]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
global.xlink: remove Blendmode cheatsheet link
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "texwindow.h"
29
30 #include <gtk/gtk.h>
31
32 #include "debugging/debugging.h"
33 #include "warnings.h"
34
35 #include "defaults.h"
36 #include "ifilesystem.h"
37 #include "iundo.h"
38 #include "igl.h"
39 #include "iarchive.h"
40 #include "moduleobserver.h"
41
42 #include <set>
43 #include <string>
44 #include <vector>
45
46 #include <uilib/uilib.h>
47
48 #include "signal/signal.h"
49 #include "math/vector.h"
50 #include "texturelib.h"
51 #include "string/string.h"
52 #include "shaderlib.h"
53 #include "os/file.h"
54 #include "os/path.h"
55 #include "stream/memstream.h"
56 #include "stream/textfilestream.h"
57 #include "stream/stringstream.h"
58 #include "cmdlib.h"
59 #include "texmanip.h"
60 #include "textures.h"
61 #include "convert.h"
62
63 #include "gtkutil/menu.h"
64 #include "gtkutil/nonmodal.h"
65 #include "gtkutil/cursor.h"
66 #include "gtkutil/widget.h"
67 #include "gtkutil/glwidget.h"
68 #include "gtkutil/messagebox.h"
69
70 #include "error.h"
71 #include "map.h"
72 #include "qgl.h"
73 #include "select.h"
74 #include "brush_primit.h"
75 #include "brushmanip.h"
76 #include "patchmanip.h"
77 #include "plugin.h"
78 #include "qe3.h"
79 #include "gtkdlgs.h"
80 #include "gtkmisc.h"
81 #include "mainframe.h"
82 #include "findtexturedialog.h"
83 #include "surfacedialog.h"
84 #include "patchdialog.h"
85 #include "groupdialog.h"
86 #include "preferences.h"
87 #include "shaders.h"
88 #include "commands.h"
89
90 bool TextureBrowser_showWads(){
91         return !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) );
92 }
93
94 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser );
95
96 bool string_equal_start( const char* string, StringRange start ){
97         return string_equal_n( string, start.first, start.last - start.first );
98 }
99
100 typedef std::set<CopiedString> TextureGroups;
101
102 void TextureGroups_addWad( TextureGroups& groups, const char* archive ){
103         if ( extension_equal( path_get_extension( archive ), "wad" ) ) {
104 #if 1
105                 groups.insert( archive );
106 #else
107                 CopiedString archiveBaseName( path_get_filename_start( archive ), path_get_filename_base_end( archive ) );
108                 groups.insert( archiveBaseName );
109 #endif
110         }
111 }
112
113 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addWad> TextureGroupsAddWadCaller;
114
115 namespace
116 {
117 bool g_TextureBrowser_shaderlistOnly = false;
118 bool g_TextureBrowser_fixedSize = true;
119 bool g_TextureBrowser_filterMissing = false;
120 bool g_TextureBrowser_filterFallback = true;
121 bool g_TextureBrowser_enableAlpha = true;
122 }
123
124 CopiedString g_notex;
125 CopiedString g_shadernotex;
126
127 bool isMissing(const char* name);
128
129 bool isNotex(const char* name);
130
131 bool isMissing(const char* name){
132         if ( string_equal( g_notex.c_str(), name ) ) {
133                 return true;
134         }
135         if ( string_equal( g_shadernotex.c_str(), name ) ) {
136                 return true;
137         }
138         return false;
139 }
140
141 bool isNotex(const char* name){
142         if ( string_equal_suffix( name, "/" DEFAULT_NOTEX_BASENAME ) ) {
143                 return true;
144         }
145         if ( string_equal_suffix( name, "/" DEFAULT_SHADERNOTEX_BASENAME ) ) {
146                 return true;
147         }
148         return false;
149 }
150
151 void TextureGroups_addShader( TextureGroups& groups, const char* shaderName ){
152         const char* texture = path_make_relative( shaderName, "textures/" );
153
154         // hide notex / shadernotex images
155         if ( g_TextureBrowser_filterFallback ) {
156                 if ( isNotex( shaderName ) ) {
157                         return;
158                 }
159                 if ( isNotex( texture ) ) {
160                         return;
161                 }
162         }
163
164         if ( texture != shaderName ) {
165                 const char* last = path_remove_directory( texture );
166                 if ( !string_empty( last ) ) {
167                         groups.insert( CopiedString( StringRange( texture, --last ) ) );
168                 }
169         }
170 }
171
172 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addShader> TextureGroupsAddShaderCaller;
173
174 void TextureGroups_addDirectory( TextureGroups& groups, const char* directory ){
175         groups.insert( directory );
176 }
177
178 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addDirectory> TextureGroupsAddDirectoryCaller;
179
180 class DeferredAdjustment
181 {
182 gdouble m_value;
183 guint m_handler;
184
185 typedef void ( *ValueChangedFunction )( void* data, gdouble value );
186
187 ValueChangedFunction m_function;
188 void* m_data;
189
190 static gboolean deferred_value_changed( gpointer data ){
191         reinterpret_cast<DeferredAdjustment*>( data )->m_function(
192                 reinterpret_cast<DeferredAdjustment*>( data )->m_data,
193                 reinterpret_cast<DeferredAdjustment*>( data )->m_value
194                 );
195         reinterpret_cast<DeferredAdjustment*>( data )->m_handler = 0;
196         reinterpret_cast<DeferredAdjustment*>( data )->m_value = 0;
197         return FALSE;
198 }
199
200 public:
201 DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){
202 }
203
204 void flush(){
205         if ( m_handler != 0 ) {
206                 g_source_remove( m_handler );
207                 deferred_value_changed( this );
208         }
209 }
210
211 void value_changed( gdouble value ){
212         m_value = value;
213         if ( m_handler == 0 ) {
214                 m_handler = g_idle_add( deferred_value_changed, this );
215         }
216 }
217
218 static void adjustment_value_changed(ui::Adjustment adjustment, DeferredAdjustment* self ){
219         self->value_changed( gtk_adjustment_get_value(adjustment) );
220 }
221 };
222
223
224 class TextureBrowser;
225
226 typedef ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw> TextureBrowserQueueDrawCaller;
227
228 void TextureBrowser_scrollChanged( void* data, gdouble value );
229
230
231 enum StartupShaders
232 {
233         STARTUPSHADERS_NONE = 0,
234         STARTUPSHADERS_COMMON,
235 };
236
237 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer );
238
239 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
240
241 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer );
242
243 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
244
245 void TextureBrowser_showTexturesExport( const Callback<void(bool)> & importer );
246
247 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showTexturesExport> TextureBrowserShowTexturesExport;
248
249 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer );
250
251 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
252
253 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer );
254
255 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
256
257 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer );
258
259 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowserFilterMissingExport;
260
261 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer );
262
263 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowserFilterFallbackExport;
264
265 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer );
266
267 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowserEnableAlphaExport;
268
269 class TextureBrowser
270 {
271 public:
272 int width, height;
273 int originy;
274 int m_nTotalHeight;
275
276 CopiedString shader;
277
278 ui::Window m_parent{ui::null};
279 ui::GLArea m_gl_widget{ui::null};
280 ui::Widget m_texture_scroll{ui::null};
281 ui::TreeView m_treeViewTree{ui::New};
282 ui::TreeView m_treeViewTags{ui::null};
283 ui::Frame m_tag_frame{ui::null};
284 ui::ListStore m_assigned_store{ui::null};
285 ui::ListStore m_available_store{ui::null};
286 ui::TreeView m_assigned_tree{ui::null};
287 ui::TreeView m_available_tree{ui::null};
288 ui::Widget m_scr_win_tree{ui::null};
289 ui::Widget m_scr_win_tags{ui::null};
290 ui::Widget m_tag_notebook{ui::null};
291 ui::Button m_search_button{ui::null};
292 ui::Widget m_shader_info_item{ui::null};
293
294 std::set<CopiedString> m_all_tags;
295 ui::ListStore m_all_tags_list{ui::null};
296 std::vector<CopiedString> m_copied_tags;
297 std::set<CopiedString> m_found_shaders;
298
299 ToggleItem m_hideunused_item;
300 ToggleItem m_hidenotex_item;
301 ToggleItem m_showshaders_item;
302 ToggleItem m_showtextures_item;
303 ToggleItem m_showshaderlistonly_item;
304 ToggleItem m_fixedsize_item;
305 ToggleItem m_filternotex_item;
306 ToggleItem m_enablealpha_item;
307
308 guint m_sizeHandler;
309 guint m_exposeHandler;
310
311 bool m_heightChanged;
312 bool m_originInvalid;
313
314 DeferredAdjustment m_scrollAdjustment;
315 FreezePointer m_freezePointer;
316
317 Vector3 color_textureback;
318 // the increment step we use against the wheel mouse
319 std::size_t m_mouseWheelScrollIncrement;
320 std::size_t m_textureScale;
321 // make the texture increments match the grid changes
322 bool m_showShaders;
323 bool m_showTextures;
324 bool m_showTextureScrollbar;
325 StartupShaders m_startupShaders;
326 // if true, the texture window will only display in-use shaders
327 // if false, all the shaders in memory are displayed
328 bool m_hideUnused;
329 bool m_rmbSelected;
330 bool m_searchedTags;
331 bool m_tags;
332 // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true.
333 int m_uniformTextureSize;
334 int m_uniformTextureMinSize;
335
336 // Return the display width of a texture in the texture browser
337 /*void getTextureWH( qtexture_t* tex, int *width, int *height ){
338         if ( !g_TextureBrowser_fixedSize ) {
339                 // Don't use uniform size
340                 *width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
341                 *height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
342
343         }
344         else if ( tex->width >= tex->height ) {
345                 // Texture is square, or wider than it is tall
346                 if ( tex->width >= m_uniformTextureSize ){
347                         *width = m_uniformTextureSize;
348                         *height = (int)( m_uniformTextureSize * ( (float)tex->height / tex->width ) );
349                 }
350                 else if ( tex->width <= m_uniformTextureMinSize ){
351                         *width = m_uniformTextureMinSize;
352                         *height = (int)( m_uniformTextureMinSize * ( (float)tex->height / tex->width ) );
353                 }
354                 else {
355                         *width = tex->width;
356                         *height = tex->height;
357                 }
358         }
359         else {
360                 // Texture taller than it is wide
361                 if ( tex->height >= m_uniformTextureSize ){
362                         *height = m_uniformTextureSize;
363                         *width = (int)( m_uniformTextureSize * ( (float)tex->width / tex->height ) );
364                 }
365                 else if ( tex->height <= m_uniformTextureMinSize ){
366                         *height = m_uniformTextureMinSize;
367                         *width = (int)( m_uniformTextureMinSize * ( (float)tex->width / tex->height ) );
368                 }
369                 else {
370                         *width = tex->width;
371                         *height = tex->height;
372                 }
373         }
374 }
375
376 */
377 void getTextureWH( qtexture_t* tex, int &W, int &H ){
378                 // Don't use uniform size
379                 W = (int)( tex->width * ( (float)m_textureScale / 100 ) );
380                 H = (int)( tex->height * ( (float)m_textureScale / 100 ) );
381                 if ( W < 1 ) W = 1;
382                 if ( H < 1 ) H = 1;
383
384         if ( g_TextureBrowser_fixedSize ){
385                 if      ( W >= H ) {
386                         // Texture is square, or wider than it is tall
387                         if ( W >= m_uniformTextureSize ){
388                                 H = m_uniformTextureSize * H / W;
389                                 W = m_uniformTextureSize;
390                         }
391                         else if ( W <= m_uniformTextureMinSize ){
392                                 H = m_uniformTextureMinSize * H / W;
393                                 W = m_uniformTextureMinSize;
394                         }
395                 }
396                 else {
397                         // Texture taller than it is wide
398                         if ( H >= m_uniformTextureSize ){
399                                 W = m_uniformTextureSize * W / H;
400                                 H = m_uniformTextureSize;
401                         }
402                         else if ( H <= m_uniformTextureMinSize ){
403                                 W = m_uniformTextureMinSize * W / H;
404                                 H = m_uniformTextureMinSize;
405                         }
406                 }
407         }
408 }
409
410 TextureBrowser() :
411         m_texture_scroll( ui::null ),
412         m_hideunused_item( TextureBrowserHideUnusedExport() ),
413         m_hidenotex_item( TextureBrowserFilterFallbackExport() ),
414         m_showshaders_item( TextureBrowserShowShadersExport() ),
415         m_showtextures_item( TextureBrowserShowTexturesExport() ),
416         m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ),
417         m_fixedsize_item( TextureBrowserFixedSizeExport() ),
418         m_filternotex_item( TextureBrowserFilterMissingExport() ),
419         m_enablealpha_item( TextureBrowserEnableAlphaExport() ),
420         m_heightChanged( true ),
421         m_originInvalid( true ),
422         m_scrollAdjustment( TextureBrowser_scrollChanged, this ),
423         color_textureback( 0.25f, 0.25f, 0.25f ),
424         m_mouseWheelScrollIncrement( 64 ),
425         m_textureScale( 50 ),
426         m_showShaders( true ),
427         m_showTextures( true ),
428         m_showTextureScrollbar( true ),
429         m_startupShaders( STARTUPSHADERS_NONE ),
430         m_hideUnused( false ),
431         m_rmbSelected( false ),
432         m_searchedTags( false ),
433         m_tags( false ),
434         m_uniformTextureSize( 160 ),
435         m_uniformTextureMinSize( 48 ){
436 }
437 };
438
439 void ( *TextureBrowser_textureSelected )( const char* shader );
440
441
442 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser );
443
444
445 const char* TextureBrowser_getComonShadersName(){
446         const char* value = g_pGameDescription->getKeyValue( "common_shaders_name" );
447         if ( !string_empty( value ) ) {
448                 return value;
449         }
450         return "Common";
451 }
452
453 const char* TextureBrowser_getComonShadersDir(){
454         const char* value = g_pGameDescription->getKeyValue( "common_shaders_dir" );
455         if ( !string_empty( value ) ) {
456                 return value;
457         }
458         return "common/";
459 }
460
461 inline int TextureBrowser_fontHeight( TextureBrowser& textureBrowser ){
462         return GlobalOpenGL().m_font->getPixelHeight();
463 }
464
465 const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ){
466         return textureBrowser.shader.c_str();
467 }
468
469 void TextureBrowser_SetStatus( TextureBrowser& textureBrowser, const char* name ){
470         IShader* shader = QERApp_Shader_ForName( name );
471         qtexture_t* q = shader->getTexture();
472         StringOutputStream strTex( 256 );
473         strTex << name << " W: " << Unsigned( q->width ) << " H: " << Unsigned( q->height );
474         shader->DecRef();
475         g_pParentWnd->SetStatusText( g_pParentWnd->m_texture_status, strTex.c_str() );
476 }
477
478 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name );
479
480 void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ){
481         textureBrowser.shader = shader;
482         TextureBrowser_SetStatus( textureBrowser, shader );
483         TextureBrowser_Focus( textureBrowser, shader );
484
485         if ( FindTextureDialog_isOpen() ) {
486                 FindTextureDialog_selectTexture( shader );
487         }
488
489         // disable the menu item "shader info" if no shader was selected
490         IShader* ishader = QERApp_Shader_ForName( shader );
491         CopiedString filename = ishader->getShaderFileName();
492
493         if ( filename.empty() ) {
494                 if ( textureBrowser.m_shader_info_item != NULL ) {
495                         gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
496                 }
497         }
498         else {
499                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, TRUE );
500         }
501
502         ishader->DecRef();
503 }
504
505
506 CopiedString g_TextureBrowser_currentDirectory;
507
508 /*
509    ============================================================================
510
511    TEXTURE LAYOUT
512
513    TTimo: now based on a rundown through all the shaders
514    NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
515    otherwise we may need to rely on a list instead of an array storage
516    ============================================================================
517  */
518
519 class TextureLayout
520 {
521 public:
522 // texture layout functions
523 // TTimo: now based on shaders
524 int current_x, current_y, current_row;
525 };
526
527 void Texture_StartPos( TextureLayout& layout ){
528         layout.current_x = 8;
529         layout.current_y = -8;
530         layout.current_row = 0;
531 }
532
533 void Texture_NextPos( TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y ){
534         qtexture_t* q = current_texture;
535
536         int nWidth, nHeight;
537         textureBrowser.getTextureWH( q, nWidth, nHeight );
538         if ( layout.current_x + nWidth > textureBrowser.width - 8 && layout.current_row ) { // go to the next row unless the texture is the first on the row
539                 layout.current_x = 8;
540                 layout.current_y -= layout.current_row + TextureBrowser_fontHeight( textureBrowser ) + 4;//+4
541                 layout.current_row = 0;
542         }
543
544         *x = layout.current_x;
545         *y = layout.current_y;
546
547         // Is our texture larger than the row? If so, grow the
548         // row height to match it
549
550         if ( layout.current_row < nHeight ) {
551                 layout.current_row = nHeight;
552         }
553
554         // never go less than 96, or the names get all crunched up
555         layout.current_x += nWidth < 96 ? 96 : nWidth;
556         layout.current_x += 8;
557 }
558
559 bool TextureSearch_IsShown( const char* name ){
560         std::set<CopiedString>::iterator iter;
561
562         iter = GlobalTextureBrowser().m_found_shaders.find( name );
563
564         if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
565                 return false;
566         }
567         else {
568                 return true;
569         }
570 }
571
572 // if texture_showinuse jump over non in-use textures
573 bool Texture_IsShown( IShader* shader, bool show_shaders, bool show_textures, bool hideUnused ){
574         // filter missing shaders
575         // ugly: filter on built-in fallback name after substitution
576         if ( g_TextureBrowser_filterMissing ) {
577                 if ( isMissing( shader->getTexture()->name ) ) {
578                         return false;
579                 }
580         }
581         // filter the fallback (notex/shadernotex) for missing shaders or editor image
582         if ( g_TextureBrowser_filterFallback ) {
583                 if ( isNotex( shader->getName() ) ) {
584                         return false;
585                 }
586                 if ( isNotex( shader->getTexture()->name ) ) {
587                         return false;
588                 }
589         }
590
591         if ( g_TextureBrowser_currentDirectory == "Untagged" ) {
592                 std::set<CopiedString>::iterator iter;
593
594                 iter = GlobalTextureBrowser().m_found_shaders.find( shader->getName() );
595
596                 if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
597                         return false;
598                 }
599                 else {
600                         return true;
601                 }
602         }
603
604         if ( !shader_equal_prefix( shader->getName(), "textures/" ) ) {
605                 return false;
606         }
607
608         if ( !show_shaders && !shader->IsDefault() ) {
609                 return false;
610         }
611
612         if ( !show_textures && shader->IsDefault() ) {
613                 return false;
614         }
615
616         if ( hideUnused && !shader->IsInUse() ) {
617                 return false;
618         }
619
620         if ( GlobalTextureBrowser().m_searchedTags ) {
621                 if ( !TextureSearch_IsShown( shader->getName() ) ) {
622                         return false;
623                 }
624                 else {
625                         return true;
626                 }
627         }
628         else {
629                 if ( !shader_equal_prefix( shader_get_textureName( shader->getName() ), g_TextureBrowser_currentDirectory.c_str() ) ) {
630                         return false;
631                 }
632         }
633
634         return true;
635 }
636
637 void TextureBrowser_heightChanged( TextureBrowser& textureBrowser ){
638         textureBrowser.m_heightChanged = true;
639
640         TextureBrowser_updateScroll( textureBrowser );
641         TextureBrowser_queueDraw( textureBrowser );
642 }
643
644 void TextureBrowser_evaluateHeight( TextureBrowser& textureBrowser ){
645         if ( textureBrowser.m_heightChanged ) {
646                 textureBrowser.m_heightChanged = false;
647
648                 textureBrowser.m_nTotalHeight = 0;
649
650                 TextureLayout layout;
651                 Texture_StartPos( layout );
652                 for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
653                 {
654                         IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
655
656                         if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
657                                 continue;
658                         }
659
660                         int x, y;
661                         Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
662                         int nWidth, nHeight;
663                         textureBrowser.getTextureWH( shader->getTexture(), nWidth, nHeight );
664                         textureBrowser.m_nTotalHeight = std::max( textureBrowser.m_nTotalHeight, abs( layout.current_y ) + TextureBrowser_fontHeight( textureBrowser ) + nHeight + 4 );
665                 }
666         }
667 }
668
669 int TextureBrowser_TotalHeight( TextureBrowser& textureBrowser ){
670         TextureBrowser_evaluateHeight( textureBrowser );
671         return textureBrowser.m_nTotalHeight;
672 }
673
674 inline const int& min_int( const int& left, const int& right ){
675         return std::min( left, right );
676 }
677
678 void TextureBrowser_clampOriginY( TextureBrowser& textureBrowser ){
679         if ( textureBrowser.originy > 0 ) {
680                 textureBrowser.originy = 0;
681         }
682         int lower = min_int( textureBrowser.height - TextureBrowser_TotalHeight( textureBrowser ), 0 );
683         if ( textureBrowser.originy < lower ) {
684                 textureBrowser.originy = lower;
685         }
686 }
687
688 int TextureBrowser_getOriginY( TextureBrowser& textureBrowser ){
689         if ( textureBrowser.m_originInvalid ) {
690                 textureBrowser.m_originInvalid = false;
691                 TextureBrowser_clampOriginY( textureBrowser );
692                 TextureBrowser_updateScroll( textureBrowser );
693         }
694         return textureBrowser.originy;
695 }
696
697 void TextureBrowser_setOriginY( TextureBrowser& textureBrowser, int originy ){
698         textureBrowser.originy = originy;
699         TextureBrowser_clampOriginY( textureBrowser );
700         TextureBrowser_updateScroll( textureBrowser );
701         TextureBrowser_queueDraw( textureBrowser );
702 }
703
704
705 Signal0 g_activeShadersChangedCallbacks;
706
707 void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handler ){
708         g_activeShadersChangedCallbacks.connectLast( handler );
709 }
710
711 void TextureBrowser_constructTreeStore();
712
713 class ShadersObserver : public ModuleObserver
714 {
715 Signal0 m_realiseCallbacks;
716 public:
717 void realise(){
718         m_realiseCallbacks();
719         /* texturebrowser tree update on vfs restart */
720 //      TextureBrowser_constructTreeStore();
721 }
722
723 void unrealise(){
724 }
725
726 void insert( const SignalHandler& handler ){
727         m_realiseCallbacks.connectLast( handler );
728 }
729 };
730
731 namespace
732 {
733 ShadersObserver g_ShadersObserver;
734 }
735
736 void TextureBrowser_addShadersRealiseCallback( const SignalHandler& handler ){
737         g_ShadersObserver.insert( handler );
738 }
739
740 void TextureBrowser_activeShadersChanged( TextureBrowser& textureBrowser ){
741         TextureBrowser_heightChanged( textureBrowser );
742         textureBrowser.m_originInvalid = true;
743
744         g_activeShadersChangedCallbacks();
745 }
746
747 struct TextureBrowser_ShowScrollbar {
748         static void Export(const TextureBrowser &self, const Callback<void(bool)> &returnz) {
749                 returnz(self.m_showTextureScrollbar);
750         }
751
752         static void Import(TextureBrowser &self, bool value) {
753                 self.m_showTextureScrollbar = value;
754                 if (self.m_texture_scroll) {
755                         self.m_texture_scroll.visible(self.m_showTextureScrollbar);
756                         TextureBrowser_updateScroll(self);
757                 }
758         }
759 };
760
761
762 /*
763    ==============
764    TextureBrowser_ShowDirectory
765    relies on texture_directory global for the directory to use
766    1) Load the shaders for the given directory
767    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
768    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
769    available through the IShaders interface
770    NOTE: for texture window layout:
771    all shaders are stored with alphabetical order after load
772    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
773    ( the GL textures are not flushed though)
774    ==============
775  */
776
777 bool endswith( const char *haystack, const char *needle ){
778         size_t lh = strlen( haystack );
779         size_t ln = strlen( needle );
780         if ( lh < ln ) {
781                 return false;
782         }
783         return !memcmp( haystack + ( lh - ln ), needle, ln );
784 }
785
786 bool texture_name_ignore( const char* name ){
787         StringOutputStream strTemp( string_length( name ) );
788         strTemp << LowerCase( name );
789
790         return
791                 endswith( strTemp.c_str(), ".specular" ) ||
792                 endswith( strTemp.c_str(), ".glow" ) ||
793                 endswith( strTemp.c_str(), ".bump" ) ||
794                 endswith( strTemp.c_str(), ".diffuse" ) ||
795                 endswith( strTemp.c_str(), ".blend" ) ||
796                 endswith( strTemp.c_str(), ".alpha" ) ||
797                 endswith( strTemp.c_str(), "_alpha" ) ||
798                 /* Quetoo */
799                 endswith( strTemp.c_str(), "_h" ) ||
800                 endswith( strTemp.c_str(), "_local" ) ||
801                 endswith( strTemp.c_str(), "_nm" ) ||
802                 endswith( strTemp.c_str(), "_s" ) ||
803                 /* DarkPlaces */
804                 endswith( strTemp.c_str(), "_bump" ) ||
805                 endswith( strTemp.c_str(), "_glow" ) ||
806                 endswith( strTemp.c_str(), "_gloss" ) ||
807                 endswith( strTemp.c_str(), "_luma" ) ||
808                 endswith( strTemp.c_str(), "_norm" ) ||
809                 endswith( strTemp.c_str(), "_pants" ) ||
810                 endswith( strTemp.c_str(), "_shirt" ) ||
811                 endswith( strTemp.c_str(), "_reflect" ) ||
812                 /* Unvanquished */
813                 endswith( strTemp.c_str(), "_d" ) ||
814                 endswith( strTemp.c_str(), "_n" ) ||
815                 endswith( strTemp.c_str(), "_p" ) ||
816                 endswith( strTemp.c_str(), "_g" ) ||
817                 endswith( strTemp.c_str(), "_a" ) ||
818                 0;
819 }
820
821 class LoadShaderVisitor : public Archive::Visitor
822 {
823 public:
824 void visit( const char* name ){
825         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
826         shader->DecRef();
827 }
828 };
829
830 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
831
832 ui::Widget g_page_textures{ui::null};
833
834 void TextureBrowser_toggleShow(){
835         GroupDialog_showPage( g_page_textures );
836 }
837
838
839 void TextureBrowser_updateTitle(){
840         GroupDialog_updatePageTitle( g_page_textures );
841 }
842
843
844 class TextureCategoryLoadShader
845 {
846 const char* m_directory;
847 std::size_t& m_count;
848 public:
849 using func = void(const char *);
850
851 TextureCategoryLoadShader( const char* directory, std::size_t& count )
852         : m_directory( directory ), m_count( count ){
853         m_count = 0;
854 }
855
856 void operator()( const char* name ) const {
857         if ( shader_equal_prefix( name, "textures/" )
858                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
859                 ++m_count;
860                 // request the shader, this will load the texture if needed
861                 // this Shader_ForName call is a kind of hack
862                 IShader *pFoo = QERApp_Shader_ForName( name );
863                 pFoo->DecRef();
864         }
865 }
866 };
867
868 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
869         StringOutputStream name( 256 );
870         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
871
872         if ( texture_name_ignore( name.c_str() ) ) {
873                 return;
874         }
875
876         if ( !shader_valid( name.c_str() ) ) {
877                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
878                 return;
879         }
880
881         // if a texture is already in use to represent a shader, ignore it
882         IShader* shader = QERApp_Shader_ForName( name.c_str() );
883         shader->DecRef();
884 }
885
886 typedef ConstPointerCaller<char, void(const char*), TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
887
888 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
889 {
890 const char* m_dirstring;
891 public:
892 LoadTexturesByTypeVisitor( const char* dirstring )
893         : m_dirstring( dirstring ){
894 }
895
896 void visit( const char* minor, const _QERPlugImageTable& table ) const {
897         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
898 }
899 };
900
901 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
902         if ( TextureBrowser_showWads() ) {
903                 Archive* archive = GlobalFileSystem().getArchive( directory );
904                 ASSERT_NOTNULL( archive );
905                 LoadShaderVisitor visitor;
906                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
907         }
908         else
909         {
910                 g_TextureBrowser_currentDirectory = directory;
911                 TextureBrowser_heightChanged( textureBrowser );
912
913                 std::size_t shaders_count;
914                 GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
915                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
916
917                 if ( g_pGameDescription->mGameType != "doom3" ) {
918                         // load remaining texture files
919
920                         StringOutputStream dirstring( 64 );
921                         dirstring << "textures/" << directory;
922
923                         Radiant_getImageModules().foreachModule( LoadTexturesByTypeVisitor( dirstring.c_str() ) );
924                 }
925         }
926
927         // we'll display the newly loaded textures + all the ones already in use
928         TextureBrowser_SetHideUnused( textureBrowser, false );
929
930         TextureBrowser_updateTitle();
931 }
932
933 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
934         g_TextureBrowser_currentDirectory = directory;
935         TextureBrowser_heightChanged( textureBrowser );
936
937         std::size_t shaders_count;
938         GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
939         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
940
941         if ( g_pGameDescription->mGameType != "doom3" ) {
942                 // load remaining texture files
943                 StringOutputStream dirstring( 64 );
944                 dirstring << "textures/" << directory;
945
946                 {
947                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
948                         Radiant_getImageModules().foreachModule( visitor );
949                 }
950         }
951
952         // we'll display the newly loaded textures + all the ones already in use
953         TextureBrowser_SetHideUnused( textureBrowser, false );
954 }
955
956
957 bool TextureBrowser_hideUnused();
958
959 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer ){
960         importer( TextureBrowser_hideUnused() );
961 }
962
963 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
964
965 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer ){
966         importer( GlobalTextureBrowser().m_showShaders );
967 }
968
969 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
970
971 void TextureBrowser_showTexturesExport( const Callback<void(bool)> & importer ){
972         importer( GlobalTextureBrowser().m_showTextures );
973 }
974
975 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showTexturesExport> TextureBrowserShowTexturesExport;
976
977 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer ){
978         importer( g_TextureBrowser_shaderlistOnly );
979 }
980
981 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
982
983 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer ){
984         importer( g_TextureBrowser_fixedSize );
985 }
986
987 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
988
989 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer ){
990         importer( g_TextureBrowser_filterMissing );
991 }
992
993 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowser_filterMissingExport;
994
995 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer ){
996         importer( g_TextureBrowser_filterFallback );
997 }
998
999 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowser_filterFallbackExport;
1000
1001 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer ){
1002         importer( g_TextureBrowser_enableAlpha );
1003 }
1004
1005 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowser_enableAlphaExport;
1006
1007 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
1008         if ( hideUnused ) {
1009                 textureBrowser.m_hideUnused = true;
1010         }
1011         else
1012         {
1013                 textureBrowser.m_hideUnused = false;
1014         }
1015
1016         textureBrowser.m_hideunused_item.update();
1017
1018         TextureBrowser_heightChanged( textureBrowser );
1019         textureBrowser.m_originInvalid = true;
1020 }
1021
1022 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
1023         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
1024                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getComonShadersDir() );
1025         }
1026 }
1027
1028
1029 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
1030 // it might need to be split in parts or moved out .. dunno
1031 // scroll origin so the specified texture is completely on screen
1032 // if current texture is not displayed, nothing is changed
1033 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
1034         TextureLayout layout;
1035         // scroll origin so the texture is completely on screen
1036         Texture_StartPos( layout );
1037
1038         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1039         {
1040                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1041
1042                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1043                         continue;
1044                 }
1045
1046                 int x, y;
1047                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1048                 qtexture_t* q = shader->getTexture();
1049                 if ( !q ) {
1050                         break;
1051                 }
1052
1053                 // we have found when texdef->name and the shader name match
1054                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
1055                 if ( shader_equal( name, shader->getName() ) ) {
1056                         //int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) ) + 2 * TextureBrowser_fontHeight( textureBrowser );
1057                         int textureWidth, textureHeight;
1058                         textureBrowser.getTextureWH( q, textureWidth, textureHeight );
1059                         textureHeight += 2 * TextureBrowser_fontHeight( textureBrowser );
1060
1061
1062                         int originy = TextureBrowser_getOriginY( textureBrowser );
1063                         if ( y > originy ) {
1064                                 originy = y + 4;
1065                         }
1066
1067                         if ( y - textureHeight < originy - textureBrowser.height ) {
1068                                 originy = ( y - textureHeight ) + textureBrowser.height;
1069                         }
1070
1071                         TextureBrowser_setOriginY( textureBrowser, originy );
1072                         return;
1073                 }
1074         }
1075 }
1076
1077 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
1078         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
1079
1080         TextureLayout layout;
1081         Texture_StartPos( layout );
1082         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1083         {
1084                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1085
1086                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1087                         continue;
1088                 }
1089
1090                 int x, y;
1091                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1092                 qtexture_t  *q = shader->getTexture();
1093                 if ( !q ) {
1094                         break;
1095                 }
1096
1097                 int nWidth, nHeight;
1098                 textureBrowser.getTextureWH( q, nWidth, nHeight );
1099                 if ( mx > x && mx - x < nWidth
1100                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
1101                         return shader;
1102                 }
1103         }
1104
1105         return 0;
1106 }
1107
1108 /*
1109    ==============
1110    SelectTexture
1111
1112    By mouse click
1113    ==============
1114  */
1115 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
1116         IShader* shader = Texture_At( textureBrowser, mx, my );
1117         if ( shader != 0 ) {
1118                 if ( bShift ) {
1119                         if ( shader->IsDefault() ) {
1120                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
1121                         }
1122                         else{
1123                                 ViewShader( shader->getShaderFileName(), shader->getName() );
1124                         }
1125                 }
1126                 else
1127                 {
1128                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
1129                         TextureBrowser_textureSelected( shader->getName() );
1130
1131                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
1132                                 UndoableCommand undo( "textureNameSetSelected" );
1133                                 Select_SetShader( shader->getName() );
1134                         }
1135                 }
1136         }
1137 }
1138
1139 /*
1140    ============================================================================
1141
1142    MOUSE ACTIONS
1143
1144    ============================================================================
1145  */
1146
1147 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
1148         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
1149         if ( y != 0 ) {
1150                 int scale = 1;
1151
1152                 if ( state & GDK_SHIFT_MASK ) {
1153                         scale = 4;
1154                 }
1155
1156                 int originy = TextureBrowser_getOriginY( textureBrowser );
1157                 originy += y * scale;
1158                 TextureBrowser_setOriginY( textureBrowser, originy );
1159         }
1160 }
1161
1162 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
1163         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser );
1164 }
1165
1166 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
1167         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_parent );
1168 }
1169
1170 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
1171         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
1172 }
1173
1174 /*
1175    ============================================================================
1176
1177    DRAWING
1178
1179    ============================================================================
1180  */
1181
1182 /*
1183    ============
1184    Texture_Draw
1185    TTimo: relying on the shaders list to display the textures
1186    we must query all qtexture_t* to manage and display through the IShaders interface
1187    this allows a plugin to completely override the texture system
1188    ============
1189  */
1190 void Texture_Draw( TextureBrowser& textureBrowser ){
1191         int originy = TextureBrowser_getOriginY( textureBrowser );
1192
1193         glClearColor( textureBrowser.color_textureback[0],
1194                                   textureBrowser.color_textureback[1],
1195                                   textureBrowser.color_textureback[2],
1196                                   0 );
1197         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1198         glMatrixMode( GL_PROJECTION );
1199         glLoadIdentity();
1200
1201         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1202         glDisable( GL_DEPTH_TEST );
1203
1204         //glDisable( GL_BLEND );
1205         if ( g_TextureBrowser_enableAlpha ) {
1206                 glEnable( GL_BLEND );
1207                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1208         }
1209         else {
1210                 glDisable( GL_BLEND );
1211         }
1212
1213         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1214         glEnable( GL_TEXTURE_2D );
1215
1216         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1217
1218         int last_y = 0, last_height = 0;
1219
1220         TextureLayout layout;
1221         Texture_StartPos( layout );
1222         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1223         {
1224                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1225
1226                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1227                         continue;
1228                 }
1229
1230                 int x, y;
1231                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1232                 qtexture_t *q = shader->getTexture();
1233                 if ( !q ) {
1234                         break;
1235                 }
1236
1237                 int nWidth, nHeight;
1238                 textureBrowser.getTextureWH( q, nWidth, nHeight );
1239
1240                 if ( y != last_y ) {
1241                         last_y = y;
1242                         last_height = 0;
1243                 }
1244                 last_height = std::max( nHeight, last_height );
1245
1246                 // Is this texture visible?
1247                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1248                          && ( y > originy - textureBrowser.height ) ) {
1249                         // borders rules:
1250                         // if it's the current texture, draw a thick red line, else:
1251                         // shaders have a white border, simple textures don't
1252                         // if !texture_showinuse: (some textures displayed may not be in use)
1253                         // draw an additional square around with 0.5 1 0.5 color
1254                         glLineWidth( 1 );
1255                         const float xf = (float)x;
1256                         const float yf = (float)( y - TextureBrowser_fontHeight( textureBrowser ) );
1257                         float xfMax = xf + 1.5 + nWidth;
1258                         float xfMin = xf - 1.5;
1259                         float yfMax = yf + 1.5;
1260                         float yfMin = yf - nHeight - 1.5;
1261
1262                         //selected texture
1263                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1264                                 glLineWidth( 2 );
1265                                 if ( textureBrowser.m_rmbSelected ) {
1266                                         glColor3f( 0,0,1 );
1267                                 }
1268                                 else {
1269                                         glColor3f( 1,0,0 );
1270                                 }
1271                                 xfMax += .5;
1272                                 xfMin -= .5;
1273                                 yfMax += .5;
1274                                 yfMin -= .5;
1275                                 glDisable( GL_TEXTURE_2D );
1276                                 glBegin( GL_LINE_LOOP );
1277                                 glVertex2f( xfMin ,yfMax );
1278                                 glVertex2f( xfMin ,yfMin );
1279                                 glVertex2f( xfMax ,yfMin );
1280                                 glVertex2f( xfMax ,yfMax );
1281                                 glEnd();
1282                                 glEnable( GL_TEXTURE_2D );
1283                         }
1284                         // highlight in-use textures
1285                         else if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1286                                 glColor3f( 0.5,1,0.5 );
1287                                 glDisable( GL_TEXTURE_2D );
1288                                 glBegin( GL_LINE_LOOP );
1289                                 glVertex2f( xfMin ,yfMax );
1290                                 glVertex2f( xfMin ,yfMin );
1291                                 glVertex2f( xfMax ,yfMin );
1292                                 glVertex2f( xfMax ,yfMax );
1293                                 glEnd();
1294                                 glEnable( GL_TEXTURE_2D );
1295                         }
1296                         // shader white border:
1297                         else if ( !shader->IsDefault() ) {
1298                                 glColor3f( 1, 1, 1 );
1299                                 glDisable( GL_TEXTURE_2D );
1300                                 glBegin( GL_LINE_LOOP );
1301                                 glVertex2f( xfMin ,yfMax );
1302                                 glVertex2f( xfMin ,yfMin );
1303                                 glVertex2f( xfMax ,yfMin );
1304                                 glVertex2f( xfMax ,yfMax );
1305                                 glEnd();
1306                         }
1307
1308                         // shader stipple:
1309                         if ( !shader->IsDefault() ) {
1310                                 glEnable( GL_LINE_STIPPLE );
1311                                 glLineStipple( 1, 0xF000 );
1312                                 glBegin( GL_LINE_LOOP );
1313                                 glColor3f( 0, 0, 0 );
1314                                 glVertex2f( xfMin ,yfMax );
1315                                 glVertex2f( xfMin ,yfMin );
1316                                 glVertex2f( xfMax ,yfMin );
1317                                 glVertex2f( xfMax ,yfMax );
1318                                 glEnd();
1319                                 glDisable( GL_LINE_STIPPLE );
1320                                 glEnable( GL_TEXTURE_2D );
1321                         }
1322
1323                         // draw checkerboard for transparent textures
1324                         if ( g_TextureBrowser_enableAlpha )
1325                         {
1326                                 glDisable( GL_TEXTURE_2D );
1327                                 glBegin( GL_QUADS );
1328                                 int font_height = TextureBrowser_fontHeight( textureBrowser );
1329                                 for ( int i = 0; i < nHeight; i += 8 )
1330                                         for ( int j = 0; j < nWidth; j += 8 )
1331                                         {
1332                                                 unsigned char color = (i + j) / 8 % 2 ? 0x66 : 0x99;
1333                                                 glColor3ub( color, color, color );
1334                                                 int left = j;
1335                                                 int right = std::min(j+8, nWidth);
1336                                                 int top = i;
1337                                                 int bottom = std::min(i+8, nHeight);
1338                                                 glVertex2i(x + right, y - nHeight - font_height + top);
1339                                                 glVertex2i(x + left,  y - nHeight - font_height + top);
1340                                                 glVertex2i(x + left,  y - nHeight - font_height + bottom);
1341                                                 glVertex2i(x + right, y - nHeight - font_height + bottom);
1342                                         }
1343                                 glEnd();
1344                                 glEnable( GL_TEXTURE_2D );
1345                         }
1346
1347                         // Draw the texture
1348                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1349                         GlobalOpenGL_debugAssertNoErrors();
1350                         glColor3f( 1,1,1 );
1351                         glBegin( GL_QUADS );
1352                         glTexCoord2i( 0,0 );
1353                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1354                         glTexCoord2i( 1,0 );
1355                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1356                         glTexCoord2i( 1,1 );
1357                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1358                         glTexCoord2i( 0,1 );
1359                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1360                         glEnd();
1361
1362                         // draw the texture name
1363                         glDisable( GL_TEXTURE_2D );
1364                         glColor3f( 1,1,1 );
1365
1366                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 2 );//+5
1367
1368                         // don't draw the directory name
1369                         const char* name = shader->getName();
1370                         name += strlen( name );
1371                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1372                                 name--;
1373
1374                         GlobalOpenGL().drawString( name );
1375                         glEnable( GL_TEXTURE_2D );
1376                 }
1377
1378                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1379         }
1380
1381
1382         // reset the current texture
1383         glBindTexture( GL_TEXTURE_2D, 0 );
1384         //qglFinish();
1385 }
1386
1387 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1388         if ( textureBrowser.m_gl_widget ) {
1389                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1390         }
1391 }
1392
1393
1394 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1395         textureBrowser.m_textureScale = scale;
1396
1397         textureBrowser.m_heightChanged = true;
1398         textureBrowser.m_originInvalid = true;
1399         g_activeShadersChangedCallbacks();
1400
1401         TextureBrowser_queueDraw( textureBrowser );
1402 }
1403
1404 void TextureBrowser_setUniformSize( TextureBrowser& textureBrowser, std::size_t scale ){
1405         textureBrowser.m_uniformTextureSize = scale;
1406
1407         textureBrowser.m_heightChanged = true;
1408         textureBrowser.m_originInvalid = true;
1409         g_activeShadersChangedCallbacks();
1410
1411         TextureBrowser_queueDraw( textureBrowser );
1412 }
1413
1414 void TextureBrowser_setUniformMinSize( TextureBrowser& textureBrowser, std::size_t scale ){
1415         textureBrowser.m_uniformTextureMinSize = scale;
1416
1417         textureBrowser.m_heightChanged = true;
1418         textureBrowser.m_originInvalid = true;
1419         g_activeShadersChangedCallbacks();
1420
1421         TextureBrowser_queueDraw( textureBrowser );
1422 }
1423
1424 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1425         int originy = TextureBrowser_getOriginY( textureBrowser );
1426
1427         if ( bUp ) {
1428                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1429         }
1430         else
1431         {
1432                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1433         }
1434
1435         TextureBrowser_setOriginY( textureBrowser, originy );
1436 }
1437
1438 XmlTagBuilder TagBuilder;
1439
1440 enum
1441 {
1442         TAG_COLUMN,
1443         N_COLUMNS
1444 };
1445
1446 void BuildStoreAssignedTags( ui::ListStore store, const char* shader, TextureBrowser* textureBrowser ){
1447         GtkTreeIter iter;
1448
1449         store.clear();
1450
1451         std::vector<CopiedString> assigned_tags;
1452         TagBuilder.GetShaderTags( shader, assigned_tags );
1453
1454         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1455         {
1456                 store.append(TAG_COLUMN, assigned_tags[i].c_str());
1457         }
1458 }
1459
1460 void BuildStoreAvailableTags(   ui::ListStore storeAvailable,
1461                                                                 ui::ListStore storeAssigned,
1462                                                                 const std::set<CopiedString>& allTags,
1463                                                                 TextureBrowser* textureBrowser ){
1464         GtkTreeIter iterAssigned;
1465         GtkTreeIter iterAvailable;
1466         std::set<CopiedString>::const_iterator iterAll;
1467         gchar* tag_assigned;
1468
1469         storeAvailable.clear();
1470
1471         bool row = gtk_tree_model_get_iter_first(storeAssigned, &iterAssigned ) != 0;
1472
1473         if ( !row ) { // does the shader have tags assigned?
1474                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1475                 {
1476                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1477                 }
1478         }
1479         else
1480         {
1481                 while ( row ) // available tags = all tags - assigned tags
1482                 {
1483                         gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1484
1485                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1486                         {
1487                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1488                                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1489                                 }
1490                                 else
1491                                 {
1492                                         row = gtk_tree_model_iter_next(storeAssigned, &iterAssigned ) != 0;
1493
1494                                         if ( row ) {
1495                                                 gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1496                                         }
1497                                 }
1498                         }
1499                 }
1500         }
1501 }
1502
1503 gboolean TextureBrowser_button_press( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1504         if ( event->type == GDK_BUTTON_PRESS ) {
1505                 if ( event->button == 3 ) {
1506                         if ( GlobalTextureBrowser().m_tags ) {
1507                                 textureBrowser->m_rmbSelected = true;
1508                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1509
1510                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1511                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1512                                 textureBrowser->m_heightChanged = true;
1513                                 textureBrowser->m_tag_frame.show();
1514
1515                 ui::process();
1516
1517                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1518                         }
1519                         else
1520                         {
1521                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1522                         }
1523                 }
1524                 else if ( event->button == 1 ) {
1525                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1526
1527                         if ( GlobalTextureBrowser().m_tags ) {
1528                                 textureBrowser->m_rmbSelected = false;
1529                                 textureBrowser->m_tag_frame.hide();
1530                         }
1531                 }
1532         }
1533         else if ( event->type == GDK_2BUTTON_PRESS && event->button == 1 ) {
1534                 #define GARUX_DISABLE_2BUTTON
1535                 #ifndef GARUX_DISABLE_2BUTTON
1536                 CopiedString texName = textureBrowser->shader;
1537                 const char* sh = textureBrowser->shader.c_str();
1538                 char* dir = strrchr( sh, '/' );
1539                 if( dir != NULL ){
1540                         *(dir + 1) = '\0';
1541                         dir = strchr( sh, '/' );
1542                         if( dir != NULL ){
1543                                 dir++;
1544                                 if( *dir != '\0'){
1545                                         ScopeDisableScreenUpdates disableScreenUpdates( dir, "Loading Textures" );
1546                                         TextureBrowser_ShowDirectory( *textureBrowser, dir );
1547                                         TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1548                                         TextureBrowser_queueDraw( *textureBrowser );
1549                                 }
1550                         }
1551                 }
1552                 #endif
1553         }
1554         else if ( event->type == GDK_2BUTTON_PRESS && event->button == 3 ) {
1555                 ScopeDisableScreenUpdates disableScreenUpdates( TextureBrowser_getComonShadersDir(), "Loading Textures" );
1556                 TextureBrowser_ShowDirectory( *textureBrowser, TextureBrowser_getComonShadersDir() );
1557                 TextureBrowser_queueDraw( *textureBrowser );
1558         }
1559         return FALSE;
1560 }
1561
1562 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1563         if ( event->type == GDK_BUTTON_RELEASE ) {
1564                 if ( event->button == 3 ) {
1565                         if ( !GlobalTextureBrowser().m_tags ) {
1566                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1567                         }
1568                 }
1569         }
1570         return FALSE;
1571 }
1572
1573 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1574         return FALSE;
1575 }
1576
1577 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1578         if ( event->direction == GDK_SCROLL_UP ) {
1579                 TextureBrowser_MouseWheel( *textureBrowser, true );
1580         }
1581         else if ( event->direction == GDK_SCROLL_DOWN ) {
1582                 TextureBrowser_MouseWheel( *textureBrowser, false );
1583         }
1584         return FALSE;
1585 }
1586
1587 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1588         //globalOutputStream() << "vertical scroll\n";
1589         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1590 }
1591
1592 static void TextureBrowser_verticalScroll(ui::Adjustment adjustment, TextureBrowser* textureBrowser ){
1593         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1594 }
1595
1596 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1597         if ( textureBrowser.m_showTextureScrollbar ) {
1598                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1599
1600                 totalHeight = std::max( totalHeight, textureBrowser.height );
1601
1602         auto vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1603
1604                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1605                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1606                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1607                 gtk_adjustment_set_step_increment(vadjustment, 20);
1608                 gtk_adjustment_set_lower(vadjustment, 0);
1609                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1610
1611                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1612         }
1613 }
1614
1615 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1616         textureBrowser->width = allocation->width;
1617         textureBrowser->height = allocation->height;
1618         TextureBrowser_heightChanged( *textureBrowser );
1619         textureBrowser->m_originInvalid = true;
1620         TextureBrowser_queueDraw( *textureBrowser );
1621         return FALSE;
1622 }
1623
1624 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1625         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1626                 GlobalOpenGL_debugAssertNoErrors();
1627                 TextureBrowser_evaluateHeight( *textureBrowser );
1628                 Texture_Draw( *textureBrowser );
1629                 GlobalOpenGL_debugAssertNoErrors();
1630                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1631         }
1632         return FALSE;
1633 }
1634
1635
1636 TextureBrowser g_TextureBrowser;
1637
1638 TextureBrowser& GlobalTextureBrowser(){
1639         return g_TextureBrowser;
1640 }
1641
1642 bool TextureBrowser_hideUnused(){
1643         return g_TextureBrowser.m_hideUnused;
1644 }
1645
1646 void TextureBrowser_ToggleHideUnused(){
1647         if ( g_TextureBrowser.m_hideUnused ) {
1648                 TextureBrowser_SetHideUnused( g_TextureBrowser, false );
1649         }
1650         else
1651         {
1652                 TextureBrowser_SetHideUnused( g_TextureBrowser, true );
1653         }
1654 }
1655
1656 void TextureGroups_constructTreeModel( TextureGroups groups, ui::TreeStore store ){
1657         // put the information from the old textures menu into a treeview
1658         GtkTreeIter iter, child;
1659
1660         TextureGroups::const_iterator i = groups.begin();
1661         while ( i != groups.end() )
1662         {
1663                 const char* dirName = ( *i ).c_str();
1664                 const char* firstUnderscore = strchr( dirName, '_' );
1665                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1666
1667                 TextureGroups::const_iterator next = i;
1668                 ++next;
1669                 if ( firstUnderscore != 0
1670                          && next != groups.end()
1671                          && string_equal_start( ( *next ).c_str(), dirRoot ) ) {
1672                         gtk_tree_store_append( store, &iter, NULL );
1673                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1674
1675                         // keep going...
1676                         while ( i != groups.end() && string_equal_start( ( *i ).c_str(), dirRoot ) )
1677                         {
1678                                 gtk_tree_store_append( store, &child, &iter );
1679                                 gtk_tree_store_set( store, &child, 0, ( *i ).c_str(), -1 );
1680                                 ++i;
1681                         }
1682                 }
1683                 else
1684                 {
1685                         gtk_tree_store_append( store, &iter, NULL );
1686                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1687                         ++i;
1688                 }
1689         }
1690 }
1691
1692 TextureGroups TextureGroups_constructTreeView(){
1693         TextureGroups groups;
1694
1695         if ( TextureBrowser_showWads() ) {
1696                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1697         }
1698         else
1699         {
1700                 // scan texture dirs and pak files only if not restricting to shaderlist
1701                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1702                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1703                 }
1704
1705                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1706         }
1707
1708         return groups;
1709 }
1710
1711 void TextureBrowser_constructTreeStore(){
1712         TextureGroups groups = TextureGroups_constructTreeView();
1713         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1714         TextureGroups_constructTreeModel( groups, store );
1715
1716         gtk_tree_view_set_model(g_TextureBrowser.m_treeViewTree, store);
1717
1718         g_object_unref( G_OBJECT( store ) );
1719 }
1720
1721 void TextureBrowser_constructTreeStoreTags(){
1722         TextureGroups groups;
1723         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1724     auto model = g_TextureBrowser.m_all_tags_list;
1725
1726         gtk_tree_view_set_model(g_TextureBrowser.m_treeViewTags, model );
1727
1728         g_object_unref( G_OBJECT( store ) );
1729 }
1730
1731 void TreeView_onRowActivated( ui::TreeView treeview, ui::TreePath path, ui::TreeViewColumn col, gpointer userdata ){
1732         GtkTreeIter iter;
1733
1734     auto model = gtk_tree_view_get_model(treeview );
1735
1736         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1737                 gchar dirName[1024];
1738
1739                 gchar* buffer;
1740                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1741                 strcpy( dirName, buffer );
1742                 g_free( buffer );
1743
1744                 g_TextureBrowser.m_searchedTags = false;
1745
1746                 if ( !TextureBrowser_showWads() ) {
1747                         strcat( dirName, "/" );
1748                 }
1749
1750                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1751                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1752                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1753                 //deactivate, so SPACE and RETURN wont be broken for 2d
1754                 gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( treeview ) ) ), NULL );
1755         }
1756 }
1757
1758 void TextureBrowser_createTreeViewTree(){
1759         gtk_tree_view_set_enable_search(g_TextureBrowser.m_treeViewTree, FALSE );
1760
1761         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_treeViewTree, FALSE );
1762         g_TextureBrowser.m_treeViewTree.connect( "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1763
1764         auto renderer = ui::CellRendererText(ui::New);
1765         gtk_tree_view_insert_column_with_attributes(g_TextureBrowser.m_treeViewTree, -1, "", renderer, "text", 0, NULL );
1766
1767         TextureBrowser_constructTreeStore();
1768 }
1769
1770 void TextureBrowser_addTag();
1771
1772 void TextureBrowser_renameTag();
1773
1774 void TextureBrowser_deleteTag();
1775
1776 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1777         ui::Widget menu = ui::Menu(ui::New);
1778
1779         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1780         menuitem.connect( "activate", (GCallback)TextureBrowser_addTag, treeview );
1781         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1782
1783         menuitem = ui::MenuItem( "Rename tag" );
1784         menuitem.connect( "activate", (GCallback)TextureBrowser_renameTag, treeview );
1785         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1786
1787         menuitem = ui::MenuItem( "Delete tag" );
1788         menuitem.connect( "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1789         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1790
1791         gtk_widget_show_all( menu );
1792
1793         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1794                                         ( event != NULL ) ? event->button : 0,
1795                                         gdk_event_get_time( (GdkEvent*)event ) );
1796 }
1797
1798 gboolean TreeViewTags_onButtonPressed( ui::TreeView treeview, GdkEventButton *event ){
1799         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1800                 GtkTreePath *path;
1801         auto selection = gtk_tree_view_get_selection(treeview );
1802
1803                 if ( gtk_tree_view_get_path_at_pos(treeview, event->x, event->y, &path, NULL, NULL, NULL ) ) {
1804                         gtk_tree_selection_unselect_all( selection );
1805                         gtk_tree_selection_select_path( selection, path );
1806                         gtk_tree_path_free( path );
1807                 }
1808
1809                 TextureBrowser_createContextMenu( treeview, event );
1810                 return TRUE;
1811         }
1812         return FALSE;
1813 }
1814
1815 void TextureBrowser_createTreeViewTags(){
1816         g_TextureBrowser.m_treeViewTags = ui::TreeView(ui::New);
1817         gtk_tree_view_set_enable_search(g_TextureBrowser.m_treeViewTags, FALSE );
1818
1819         g_TextureBrowser.m_treeViewTags.connect( "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1820
1821         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_treeViewTags, FALSE );
1822
1823         auto renderer = ui::CellRendererText(ui::New);
1824         gtk_tree_view_insert_column_with_attributes(g_TextureBrowser.m_treeViewTags, -1, "", renderer, "text", 0, NULL );
1825
1826         TextureBrowser_constructTreeStoreTags();
1827 }
1828
1829 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1830         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1831
1832         if ( g_Layout_enableDetachableMenus.m_value ) {
1833                 menu_tearoff( menu );
1834         }
1835
1836         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1837         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1838                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1839         }
1840
1841         // hide notex and shadernotex on texture browser: no one wants to apply them
1842         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1843
1844         menu_separator( menu );
1845
1846
1847         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1848         if ( g_pGameDescription->mGameType == "doom3" || !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1849                 g_TextureBrowser.m_showShaders = true;
1850         }
1851         else
1852         {
1853                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1854                 create_check_menu_item_with_mnemonic( menu, "Show textures", "ToggleShowTextures" );
1855                 menu_separator( menu );
1856         }
1857
1858         if ( g_TextureBrowser.m_tags ) {
1859                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1860         }
1861         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1862                 create_check_menu_item_with_mnemonic( menu, "ShaderList Only", "ToggleShowShaderlistOnly" );
1863         }
1864
1865         menu_separator( menu );
1866         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1867         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1868
1869         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1870                 menu_separator( menu );
1871                 g_TextureBrowser.m_shader_info_item = ui::Widget(create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo"  ));
1872                 gtk_widget_set_sensitive( g_TextureBrowser.m_shader_info_item, FALSE );
1873         }
1874
1875
1876         return textures_menu_item;
1877 }
1878
1879 void Popup_View_Menu( GtkWidget *widget, GtkMenu *menu ){
1880         gtk_menu_popup( menu, NULL, NULL, NULL, NULL, 1, gtk_get_current_event_time() );
1881 }
1882
1883 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1884         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1885
1886         if ( g_Layout_enableDetachableMenus.m_value ) {
1887                 menu_tearoff( menu );
1888         }
1889
1890         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1891         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1892
1893         return textures_menu_item;
1894 }
1895
1896 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1897         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1898
1899         if ( g_Layout_enableDetachableMenus.m_value ) {
1900                 menu_tearoff( menu );
1901         }
1902
1903         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1904         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1905         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1906         menu_separator( menu );
1907         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1908         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1909
1910         return textures_menu_item;
1911 }
1912
1913 gboolean TextureBrowser_tagMoveHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter iter, GSList** selected ){
1914         g_assert( selected != NULL );
1915
1916     auto rowref = gtk_tree_row_reference_new( model, path );
1917         *selected = g_slist_append( *selected, rowref );
1918
1919         return FALSE;
1920 }
1921
1922 void TextureBrowser_assignTags(){
1923         GSList* selected = NULL;
1924         GSList* node;
1925         gchar* tag_assigned;
1926
1927     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
1928
1929         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1930
1931         if ( selected != NULL ) {
1932                 for ( node = selected; node != NULL; node = node->next )
1933                 {
1934             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1935
1936                         if ( path ) {
1937                                 GtkTreeIter iter;
1938
1939                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_available_store, &iter, path ) ) {
1940                                         gtk_tree_model_get(g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, &tag_assigned, -1 );
1941                                         if ( !TagBuilder.CheckShaderTag( g_TextureBrowser.shader.c_str() ) ) {
1942                                                 // create a custom shader/texture entry
1943                                                 IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
1944                                                 CopiedString filename = ishader->getShaderFileName();
1945
1946                                                 if ( filename.empty() ) {
1947                                                         // it's a texture
1948                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE );
1949                                                 }
1950                                                 else {
1951                                                         // it's a shader
1952                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, SHADER );
1953                                                 }
1954                                                 ishader->DecRef();
1955                                         }
1956                                         TagBuilder.AddShaderTag( g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
1957
1958                                         gtk_list_store_remove( g_TextureBrowser.m_available_store, &iter );
1959                                         g_TextureBrowser.m_assigned_store.append(TAG_COLUMN, tag_assigned);
1960                                 }
1961                         }
1962                 }
1963
1964                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1965
1966                 // Save changes
1967                 TagBuilder.SaveXmlDoc();
1968         }
1969         g_slist_free( selected );
1970 }
1971
1972 void TextureBrowser_removeTags(){
1973         GSList* selected = NULL;
1974         GSList* node;
1975         gchar* tag;
1976
1977     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_assigned_tree );
1978
1979         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1980
1981         if ( selected != NULL ) {
1982                 for ( node = selected; node != NULL; node = node->next )
1983                 {
1984             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1985
1986                         if ( path ) {
1987                                 GtkTreeIter iter;
1988
1989                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_assigned_store, &iter, path ) ) {
1990                                         gtk_tree_model_get(g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, &tag, -1 );
1991                                         TagBuilder.DeleteShaderTag( g_TextureBrowser.shader.c_str(), tag );
1992                                         gtk_list_store_remove( g_TextureBrowser.m_assigned_store, &iter );
1993                                 }
1994                         }
1995                 }
1996
1997                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1998
1999                 // Update the "available tags list"
2000                 BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2001
2002                 // Save changes
2003                 TagBuilder.SaveXmlDoc();
2004         }
2005         g_slist_free( selected );
2006 }
2007
2008 void TextureBrowser_buildTagList(){
2009         g_TextureBrowser.m_all_tags_list.clear();
2010
2011         std::set<CopiedString>::iterator iter;
2012
2013         for ( iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter )
2014         {
2015                 g_TextureBrowser.m_all_tags_list.append(TAG_COLUMN, (*iter).c_str());
2016         }
2017 }
2018
2019 void TextureBrowser_searchTags(){
2020         GSList* selected = NULL;
2021         GSList* node;
2022         gchar* tag;
2023         char buffer[256];
2024         char tags_searched[256];
2025
2026     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2027
2028         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2029
2030         if ( selected != NULL ) {
2031                 strcpy( buffer, "/root/*/*[tag='" );
2032                 strcpy( tags_searched, "[TAGS] " );
2033
2034                 for ( node = selected; node != NULL; node = node->next )
2035                 {
2036             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2037
2038                         if ( path ) {
2039                                 GtkTreeIter iter;
2040
2041                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_all_tags_list, &iter, path ) ) {
2042                                         gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iter, TAG_COLUMN, &tag, -1 );
2043
2044                                         strcat( buffer, tag );
2045                                         strcat( tags_searched, tag );
2046                                         if ( node != g_slist_last( node ) ) {
2047                                                 strcat( buffer, "' and tag='" );
2048                                                 strcat( tags_searched, ", " );
2049                                         }
2050                                 }
2051                         }
2052                 }
2053
2054                 strcat( buffer, "']" );
2055
2056                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2057
2058                 g_TextureBrowser.m_found_shaders.clear(); // delete old list
2059                 TagBuilder.TagSearch( buffer, g_TextureBrowser.m_found_shaders );
2060
2061                 if ( !g_TextureBrowser.m_found_shaders.empty() ) { // found something
2062                         size_t shaders_found = g_TextureBrowser.m_found_shaders.size();
2063
2064                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
2065                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
2066
2067                         std::set<CopiedString>::iterator iter;
2068
2069                         for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
2070                         {
2071                                 std::string path = ( *iter ).c_str();
2072                                 size_t pos = path.find_last_of( "/", path.size() );
2073                                 std::string name = path.substr( pos + 1, path.size() );
2074                                 path = path.substr( 0, pos + 1 );
2075                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2076                         }
2077                 }
2078                 g_TextureBrowser.m_searchedTags = true;
2079                 g_TextureBrowser_currentDirectory = tags_searched;
2080
2081                 g_TextureBrowser.m_nTotalHeight = 0;
2082                 TextureBrowser_setOriginY( g_TextureBrowser, 0 );
2083                 TextureBrowser_heightChanged( g_TextureBrowser );
2084                 TextureBrowser_updateTitle();
2085         }
2086         g_slist_free( selected );
2087 }
2088
2089 void TextureBrowser_toggleSearchButton(){
2090         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ) );
2091
2092         if ( page == 0 ) { // tag page
2093                 gtk_widget_show_all( g_TextureBrowser.m_search_button );
2094         }
2095         else {
2096                 g_TextureBrowser.m_search_button.hide();
2097         }
2098 }
2099
2100 void TextureBrowser_constructTagNotebook(){
2101         g_TextureBrowser.m_tag_notebook = ui::Widget::from(gtk_notebook_new());
2102         ui::Widget labelTags = ui::Label( "Tags" );
2103         ui::Widget labelTextures = ui::Label( "Textures" );
2104
2105         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tree, labelTextures );
2106         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tags, labelTags );
2107
2108         g_TextureBrowser.m_tag_notebook.connect( "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
2109
2110         gtk_widget_show_all( g_TextureBrowser.m_tag_notebook );
2111 }
2112
2113 void TextureBrowser_constructSearchButton(){
2114         auto image = ui::Widget::from(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
2115         g_TextureBrowser.m_search_button = ui::Button(ui::New);
2116         g_TextureBrowser.m_search_button.connect( "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
2117         gtk_widget_set_tooltip_text(g_TextureBrowser.m_search_button, "Search with selected tags");
2118         g_TextureBrowser.m_search_button.add(image);
2119 }
2120
2121 void TextureBrowser_checkTagFile(){
2122         const char SHADERTAG_FILE[] = "shadertags.xml";
2123         CopiedString default_filename, rc_filename;
2124         StringOutputStream stream( 256 );
2125
2126         stream << LocalRcPath_get();
2127         stream << SHADERTAG_FILE;
2128         rc_filename = stream.c_str();
2129
2130         if ( file_exists( rc_filename.c_str() ) ) {
2131                 g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
2132
2133                 if ( g_TextureBrowser.m_tags ) {
2134                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
2135                 }
2136         }
2137         else
2138         {
2139                 // load default tagfile
2140                 stream.clear();
2141                 stream << g_pGameDescription->mGameToolsPath.c_str();
2142                 stream << SHADERTAG_FILE;
2143                 default_filename = stream.c_str();
2144
2145                 if ( file_exists( default_filename.c_str() ) ) {
2146                         g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
2147
2148                         if ( g_TextureBrowser.m_tags ) {
2149                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
2150                         }
2151                 }
2152                 else
2153                 {
2154                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
2155                 }
2156         }
2157 }
2158
2159 void TextureBrowser_SetNotex(){
2160         IShader* notex = QERApp_Shader_ForName( DEFAULT_NOTEX_NAME );
2161         IShader* shadernotex = QERApp_Shader_ForName( DEFAULT_SHADERNOTEX_NAME );
2162
2163         g_notex = notex->getTexture()->name;
2164         g_shadernotex = shadernotex->getTexture()->name;
2165
2166         notex->DecRef();
2167         shadernotex->DecRef();
2168 }
2169
2170 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
2171         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
2172         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
2173         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
2174         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
2175
2176         TextureBrowser_checkTagFile();
2177         TextureBrowser_SetNotex();
2178
2179         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_activeShadersChanged>( g_TextureBrowser ) );
2180
2181         g_TextureBrowser.m_parent = toplevel;
2182
2183         auto table = ui::Table(3, 3, FALSE);
2184         auto vbox = ui::VBox(FALSE, 0);
2185         table.attach(vbox, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2186         vbox.show();
2187
2188         // ui::Widget menu_bar{ui::null};
2189         auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
2190
2191         { // menu bar
2192                 // menu_bar = ui::Widget::from(gtk_menu_bar_new());
2193                 auto menu_view = ui::Menu(ui::New);
2194                 // auto view_item = TextureBrowser_constructViewMenu( menu_view );
2195                 TextureBrowser_constructViewMenu( menu_view );
2196                 gtk_menu_set_title( menu_view, "View" );
2197                 // gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2198                 // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2199
2200                 //gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( toolbar ), 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0 );
2201                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( toolbar ), FALSE, FALSE, 0 );
2202
2203                 //view menu button
2204                 {
2205                         auto button = toolbar_append_button( toolbar, "View", "texbro_view.png" );
2206                         button.dimensions( 22, 22 );
2207                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_view );
2208
2209                         //to show detached menu over floating tex bro
2210                         gtk_menu_attach_to_widget( GTK_MENU( menu_view ), GTK_WIDGET( button ), NULL );
2211                 }
2212                 {
2213                         auto button = toolbar_append_button( toolbar, "Find / Replace...", "texbro_gtk-find-and-replace.png", "FindReplaceTextures" );
2214                         button.dimensions( 22, 22 );
2215                 }
2216                 {
2217                         auto button = toolbar_append_button( toolbar, "Flush & Reload Shaders", "texbro_refresh.png", "RefreshShaders" );
2218                         button.dimensions( 22, 22 );
2219                 }
2220                 toolbar.show();
2221
2222 /*
2223                 auto menu_tools = ui::Menu(ui::New);
2224                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2225                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2226                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2227 */
2228                 // table.attach(menu_bar, {0, 3, 0, 1}, {GTK_FILL, GTK_SHRINK});
2229                 // menu_bar.show();
2230         }
2231         { // Texture TreeView
2232                 g_TextureBrowser.m_scr_win_tree = ui::ScrolledWindow(ui::New);
2233                 gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tree ), 0 );
2234
2235                 // vertical only scrolling for treeview
2236                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2237
2238                 g_TextureBrowser.m_scr_win_tree.show();
2239
2240                 TextureBrowser_createTreeViewTree();
2241
2242                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), g_TextureBrowser.m_treeViewTree  );
2243                 g_TextureBrowser.m_treeViewTree.show();
2244         }
2245         { // gl_widget scrollbar
2246                 auto w = ui::Widget::from(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2247                 table.attach(w, {2, 3, 1, 2}, {GTK_SHRINK, GTK_FILL});
2248                 w.show();
2249                 g_TextureBrowser.m_texture_scroll = w;
2250
2251                 auto vadjustment = ui::Adjustment::from(gtk_range_get_adjustment( GTK_RANGE( g_TextureBrowser.m_texture_scroll ) ));
2252                 vadjustment.connect( "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &g_TextureBrowser );
2253
2254                 g_TextureBrowser.m_texture_scroll.visible(g_TextureBrowser.m_showTextureScrollbar);
2255         }
2256         { // gl_widget
2257                 g_TextureBrowser.m_gl_widget = glwidget_new( FALSE );
2258                 g_object_ref( g_TextureBrowser.m_gl_widget._handle );
2259
2260                 gtk_widget_set_events( g_TextureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
2261                 gtk_widget_set_can_focus( g_TextureBrowser.m_gl_widget, true );
2262
2263                 table.attach(g_TextureBrowser.m_gl_widget, {1, 2, 1, 2});
2264                 g_TextureBrowser.m_gl_widget.show();
2265
2266                 g_TextureBrowser.m_sizeHandler = g_TextureBrowser.m_gl_widget.connect( "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &g_TextureBrowser );
2267                 g_TextureBrowser.m_exposeHandler = g_TextureBrowser.m_gl_widget.on_render( G_CALLBACK( TextureBrowser_expose ), &g_TextureBrowser );
2268
2269                 g_TextureBrowser.m_gl_widget.connect( "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &g_TextureBrowser );
2270                 g_TextureBrowser.m_gl_widget.connect( "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &g_TextureBrowser );
2271                 g_TextureBrowser.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &g_TextureBrowser );
2272                 g_TextureBrowser.m_gl_widget.connect( "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &g_TextureBrowser );
2273         }
2274
2275         // tag stuff
2276         if ( g_TextureBrowser.m_tags ) {
2277                 { // fill tag GtkListStore
2278                         g_TextureBrowser.m_all_tags_list = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2279             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_all_tags_list );
2280                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2281
2282                         TagBuilder.GetAllTags( g_TextureBrowser.m_all_tags );
2283                         TextureBrowser_buildTagList();
2284                 }
2285                 { // tag menu bar
2286                         auto menu_tags = ui::Menu(ui::New);
2287                         // auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2288                         TextureBrowser_constructTagsMenu( menu_tags );
2289                         // gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2290                         // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2291
2292                         auto button = toolbar_append_button( toolbar, "Tags", "texbro_tags.png" );
2293                         button.dimensions( 22, 22 );
2294                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_tags );
2295                 }
2296                 { // Tag TreeView
2297                         g_TextureBrowser.m_scr_win_tags = ui::ScrolledWindow(ui::New);
2298                         gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), 0 );
2299
2300                         // vertical only scrolling for treeview
2301                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2302
2303                         TextureBrowser_createTreeViewTags();
2304
2305             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2306                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2307
2308                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), g_TextureBrowser.m_treeViewTags  );
2309                         g_TextureBrowser.m_treeViewTags.show();
2310                 }
2311                 { // Texture/Tag notebook
2312                         TextureBrowser_constructTagNotebook();
2313                         vbox.pack_start( g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2314                 }
2315                 { // Tag search button
2316                         TextureBrowser_constructSearchButton();
2317                         vbox.pack_end(g_TextureBrowser.m_search_button, FALSE, FALSE, 0);
2318                 }
2319                 auto frame_table = ui::Table(3, 3, FALSE);
2320                 { // Tag frame
2321
2322                         g_TextureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2323                         gtk_frame_set_label_align( GTK_FRAME( g_TextureBrowser.m_tag_frame ), 0.5, 0.5 );
2324                         gtk_frame_set_shadow_type( GTK_FRAME( g_TextureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2325
2326                         table.attach(g_TextureBrowser.m_tag_frame, {1, 3, 2, 3}, {GTK_FILL, GTK_SHRINK});
2327
2328                         frame_table.show();
2329
2330                         g_TextureBrowser.m_tag_frame.add(frame_table);
2331                 }
2332                 { // assigned tag list
2333                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2334                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2335                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2336
2337                         g_TextureBrowser.m_assigned_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2338
2339             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_assigned_store );
2340                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2341
2342                         auto renderer = ui::CellRendererText(ui::New);
2343
2344                         g_TextureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel::from(g_TextureBrowser.m_assigned_store._handle));
2345                         g_TextureBrowser.m_assigned_store.unref();
2346                         g_TextureBrowser.m_assigned_tree.connect( "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2347                         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_assigned_tree, FALSE );
2348
2349             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_assigned_tree );
2350                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2351
2352             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2353                         gtk_tree_view_append_column(g_TextureBrowser.m_assigned_tree, column );
2354                         g_TextureBrowser.m_assigned_tree.show();
2355
2356                         scrolled_win.show();
2357                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), g_TextureBrowser.m_assigned_tree  );
2358
2359                         frame_table.attach(scrolled_win, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2360                 }
2361                 { // available tag list
2362                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2363                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2364                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2365
2366                         g_TextureBrowser.m_available_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2367             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_available_store );
2368                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2369
2370                         auto renderer = ui::CellRendererText(ui::New);
2371
2372                         g_TextureBrowser.m_available_tree = ui::TreeView(ui::TreeModel::from(g_TextureBrowser.m_available_store._handle));
2373                         g_TextureBrowser.m_available_store.unref();
2374                         g_TextureBrowser.m_available_tree.connect( "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2375                         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_available_tree, FALSE );
2376
2377             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
2378                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2379
2380             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2381                         gtk_tree_view_append_column(g_TextureBrowser.m_available_tree, column );
2382                         g_TextureBrowser.m_available_tree.show();
2383
2384                         scrolled_win.show();
2385                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), g_TextureBrowser.m_available_tree  );
2386
2387                         frame_table.attach(scrolled_win, {2, 3, 1, 3}, {GTK_FILL, GTK_FILL});
2388                 }
2389                 { // tag arrow buttons
2390                         auto m_btn_left = ui::Button(ui::New);
2391                         auto m_btn_right = ui::Button(ui::New);
2392                         auto m_arrow_left = ui::Widget::from(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2393                         auto m_arrow_right = ui::Widget::from(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2394                         m_btn_left.add(m_arrow_left);
2395                         m_btn_right.add(m_arrow_right);
2396
2397                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2398                         m_arrow_left.dimensions(-1, 68);
2399                         m_arrow_right.dimensions(-1, 68);
2400
2401                         frame_table.attach(m_btn_left, {1, 2, 1, 2}, {GTK_SHRINK, GTK_EXPAND});
2402                         frame_table.attach(m_btn_right, {1, 2, 2, 3}, {GTK_SHRINK, GTK_EXPAND});
2403
2404                         m_btn_left.connect( "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2405                         m_btn_right.connect( "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2406
2407                         m_btn_left.show();
2408                         m_btn_right.show();
2409                         m_arrow_left.show();
2410                         m_arrow_right.show();
2411                 }
2412                 { // tag fram labels
2413                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2414                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2415
2416                         frame_table.attach(m_lbl_assigned, {0, 1, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2417                         frame_table.attach(m_lbl_unassigned, {2, 3, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2418
2419                         m_lbl_assigned.show();
2420                         m_lbl_unassigned.show();
2421                 }
2422         }
2423         else { // no tag support, show the texture tree only
2424                 vbox.pack_start( g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2425         }
2426
2427         // TODO do we need this?
2428         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2429
2430         return table;
2431 }
2432
2433 void TextureBrowser_destroyWindow(){
2434         GlobalShaderSystem().setActiveShadersChangedNotify( Callback<void()>() );
2435
2436         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_sizeHandler );
2437         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_exposeHandler );
2438
2439         g_TextureBrowser.m_gl_widget.unref();
2440 }
2441
2442 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2443         return textureBrowser.color_textureback;
2444 }
2445
2446 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2447         textureBrowser.color_textureback = colour;
2448         TextureBrowser_queueDraw( textureBrowser );
2449 }
2450
2451 void TextureBrowser_selectionHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
2452         g_assert( selected != NULL );
2453
2454         gchar* name;
2455         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2456         *selected = g_slist_append( *selected, name );
2457 }
2458
2459 void TextureBrowser_shaderInfo(){
2460         const char* name = TextureBrowser_GetSelectedShader( g_TextureBrowser );
2461         IShader* shader = QERApp_Shader_ForName( name );
2462
2463         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2464
2465         shader->DecRef();
2466 }
2467
2468 void TextureBrowser_addTag(){
2469         CopiedString tag;
2470
2471         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2472
2473         if ( result == eIDOK && !tag.empty() ) {
2474                 GtkTreeIter iter;
2475                 g_TextureBrowser.m_all_tags.insert( tag.c_str() );
2476                 gtk_list_store_append( g_TextureBrowser.m_available_store, &iter );
2477                 gtk_list_store_set( g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2478
2479                 // Select the currently added tag in the available list
2480         auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
2481                 gtk_tree_selection_select_iter( selection, &iter );
2482
2483                 g_TextureBrowser.m_all_tags_list.append(TAG_COLUMN, tag.c_str());
2484         }
2485 }
2486
2487 void TextureBrowser_renameTag(){
2488         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2489            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2490            we need to count the number of selected rows first and use
2491            gtk_tree_selection_selected_foreach() then to go through the list of selected
2492            rows (which always containins a single row).
2493          */
2494
2495         GSList* selected = NULL;
2496
2497     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2498         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2499
2500         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2501                 CopiedString newTag;
2502                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2503
2504                 if ( result == eIDOK && !newTag.empty() ) {
2505                         GtkTreeIter iterList;
2506                         gchar* rowTag;
2507                         gchar* oldTag = (char*)selected->data;
2508
2509                         bool row = gtk_tree_model_get_iter_first(g_TextureBrowser.m_all_tags_list, &iterList ) != 0;
2510
2511                         while ( row )
2512                         {
2513                                 gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, &rowTag, -1 );
2514
2515                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2516                                         gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2517                                 }
2518                                 row = gtk_tree_model_iter_next(g_TextureBrowser.m_all_tags_list, &iterList ) != 0;
2519                         }
2520
2521                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2522
2523                         g_TextureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2524                         g_TextureBrowser.m_all_tags.insert( newTag );
2525
2526                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2527                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2528                 }
2529         }
2530         else
2531         {
2532                 ui::alert( g_TextureBrowser.m_parent, "Select a single tag for renaming." );
2533         }
2534 }
2535
2536 void TextureBrowser_deleteTag(){
2537         GSList* selected = NULL;
2538
2539     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2540         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2541
2542         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2543                 auto result = ui::alert( g_TextureBrowser.m_parent, "Are you sure you want to delete the selected tag?", "Delete Tag", ui::alert_type::YESNO, ui::alert_icon::Question );
2544
2545                 if ( result == ui::alert_response::YES ) {
2546                         GtkTreeIter iterSelected;
2547                         gchar *rowTag;
2548
2549                         gchar* tagSelected = (char*)selected->data;
2550
2551                         bool row = gtk_tree_model_get_iter_first(g_TextureBrowser.m_all_tags_list, &iterSelected ) != 0;
2552
2553                         while ( row )
2554                         {
2555                                 gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iterSelected, TAG_COLUMN, &rowTag, -1 );
2556
2557                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2558                                         gtk_list_store_remove( g_TextureBrowser.m_all_tags_list, &iterSelected );
2559                                         break;
2560                                 }
2561                                 row = gtk_tree_model_iter_next(g_TextureBrowser.m_all_tags_list, &iterSelected ) != 0;
2562                         }
2563
2564                         TagBuilder.DeleteTag( tagSelected );
2565                         g_TextureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2566
2567                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2568                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2569                 }
2570         }
2571         else {
2572                 ui::alert( g_TextureBrowser.m_parent, "Select a single tag for deletion." );
2573         }
2574 }
2575
2576 void TextureBrowser_copyTag(){
2577         g_TextureBrowser.m_copied_tags.clear();
2578         TagBuilder.GetShaderTags( g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags );
2579 }
2580
2581 void TextureBrowser_pasteTag(){
2582         IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
2583         CopiedString shader = g_TextureBrowser.shader.c_str();
2584
2585         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2586                 CopiedString shaderFile = ishader->getShaderFileName();
2587                 if ( shaderFile.empty() ) {
2588                         // it's a texture
2589                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2590                 }
2591                 else
2592                 {
2593                         // it's a shader
2594                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2595                 }
2596
2597                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2598                 {
2599                         TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2600                 }
2601         }
2602         else
2603         {
2604                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2605                 {
2606                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str() ) ) {
2607                                 // the tag doesn't exist - let's add it
2608                                 TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2609                         }
2610                 }
2611         }
2612
2613         ishader->DecRef();
2614
2615         TagBuilder.SaveXmlDoc();
2616         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser );
2617         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2618 }
2619
2620 void TextureBrowser_RefreshShaders(){
2621
2622         /* When shaders are refreshed, forces reloading the textures as well.
2623         Previously it would at best only display shaders, at worst mess up some textured objects. */
2624
2625     auto selection = gtk_tree_view_get_selection(GlobalTextureBrowser().m_treeViewTree);
2626         GtkTreeModel* model = NULL;
2627         GtkTreeIter iter;
2628         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2629         {
2630                 gchar dirName[1024];
2631
2632                 gchar* buffer;
2633                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2634                 strcpy( dirName, buffer );
2635                 g_free( buffer );
2636                 if ( !TextureBrowser_showWads() ) {
2637                         strcat( dirName, "/" );
2638                 }
2639
2640                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2641                 GlobalShaderSystem().refresh();
2642                 /* texturebrowser tree update on vfs restart */
2643                 TextureBrowser_constructTreeStore();
2644                 UpdateAllWindows();
2645
2646                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2647                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2648         }
2649
2650         else{
2651                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2652                 GlobalShaderSystem().refresh();
2653                 /* texturebrowser tree update on vfs restart */
2654                 TextureBrowser_constructTreeStore();
2655                 UpdateAllWindows();
2656         }
2657 }
2658
2659 void TextureBrowser_ToggleShowShaders(){
2660         g_TextureBrowser.m_showShaders ^= 1;
2661         g_TextureBrowser.m_showshaders_item.update();
2662
2663         g_TextureBrowser.m_heightChanged = true;
2664         g_TextureBrowser.m_originInvalid = true;
2665         g_activeShadersChangedCallbacks();
2666
2667         TextureBrowser_queueDraw( g_TextureBrowser );
2668 }
2669
2670 void TextureBrowser_ToggleShowTextures(){
2671         g_TextureBrowser.m_showTextures ^= 1;
2672         g_TextureBrowser.m_showtextures_item.update();
2673
2674         g_TextureBrowser.m_heightChanged = true;
2675         g_TextureBrowser.m_originInvalid = true;
2676         g_activeShadersChangedCallbacks();
2677
2678         TextureBrowser_queueDraw( g_TextureBrowser );
2679 }
2680
2681 void TextureBrowser_ToggleShowShaderListOnly(){
2682         g_TextureBrowser_shaderlistOnly ^= 1;
2683         g_TextureBrowser.m_showshaderlistonly_item.update();
2684
2685         TextureBrowser_constructTreeStore();
2686 }
2687
2688 void TextureBrowser_showAll(){
2689         g_TextureBrowser_currentDirectory = "";
2690         g_TextureBrowser.m_searchedTags = false;
2691 //      TextureBrowser_SetHideUnused( g_TextureBrowser, false );
2692         TextureBrowser_ToggleHideUnused();
2693         //TextureBrowser_heightChanged( g_TextureBrowser );
2694         TextureBrowser_updateTitle();
2695 }
2696
2697 void TextureBrowser_showUntagged(){
2698         auto result = ui::alert( g_TextureBrowser.m_parent, "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", ui::alert_type::YESNO, ui::alert_icon::Warning );
2699
2700         if ( result == ui::alert_response::YES ) {
2701                 g_TextureBrowser.m_found_shaders.clear();
2702                 TagBuilder.GetUntagged( g_TextureBrowser.m_found_shaders );
2703                 std::set<CopiedString>::iterator iter;
2704
2705                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2706
2707                 for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
2708                 {
2709                         std::string path = ( *iter ).c_str();
2710                         size_t pos = path.find_last_of( "/", path.size() );
2711                         std::string name = path.substr( pos + 1, path.size() );
2712                         path = path.substr( 0, pos + 1 );
2713                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2714                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2715                 }
2716
2717                 g_TextureBrowser_currentDirectory = "Untagged";
2718                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2719                 TextureBrowser_heightChanged( g_TextureBrowser );
2720                 TextureBrowser_updateTitle();
2721         }
2722 }
2723
2724 void TextureBrowser_FixedSize(){
2725         g_TextureBrowser_fixedSize ^= 1;
2726         GlobalTextureBrowser().m_fixedsize_item.update();
2727         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2728 }
2729
2730 void TextureBrowser_FilterMissing(){
2731         g_TextureBrowser_filterMissing ^= 1;
2732         GlobalTextureBrowser().m_filternotex_item.update();
2733         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2734         TextureBrowser_RefreshShaders();
2735 }
2736
2737 void TextureBrowser_FilterFallback(){
2738         g_TextureBrowser_filterFallback ^= 1;
2739         GlobalTextureBrowser().m_hidenotex_item.update();
2740         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2741         TextureBrowser_RefreshShaders();
2742 }
2743
2744 void TextureBrowser_EnableAlpha(){
2745         g_TextureBrowser_enableAlpha ^= 1;
2746         GlobalTextureBrowser().m_enablealpha_item.update();
2747         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2748 }
2749
2750 void TextureBrowser_exportTitle( const Callback<void(const char *)> & importer ){
2751         StringOutputStream buffer( 64 );
2752         buffer << "Textures: ";
2753         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2754                 buffer << g_TextureBrowser_currentDirectory.c_str();
2755         }
2756         else
2757         {
2758                 buffer << "all";
2759         }
2760         importer( buffer.c_str() );
2761 }
2762
2763 struct TextureScale {
2764         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2765                 switch (self.m_textureScale) {
2766                         case 10:
2767                                 returnz(0);
2768                                 break;
2769                         case 25:
2770                                 returnz(1);
2771                                 break;
2772                         case 50:
2773                                 returnz(2);
2774                                 break;
2775                         case 100:
2776                                 returnz(3);
2777                                 break;
2778                         case 200:
2779                                 returnz(4);
2780                                 break;
2781                 }
2782         }
2783
2784         static void Import(TextureBrowser &self, int value) {
2785                 switch (value) {
2786                         case 0:
2787                                 TextureBrowser_setScale(self, 10);
2788                                 break;
2789                         case 1:
2790                                 TextureBrowser_setScale(self, 25);
2791                                 break;
2792                         case 2:
2793                                 TextureBrowser_setScale(self, 50);
2794                                 break;
2795                         case 3:
2796                                 TextureBrowser_setScale(self, 100);
2797                                 break;
2798                         case 4:
2799                                 TextureBrowser_setScale(self, 200);
2800                                 break;
2801                 }
2802         }
2803 };
2804
2805 struct UniformTextureSize {
2806         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2807                 returnz(g_TextureBrowser.m_uniformTextureSize);
2808         }
2809
2810         static void Import(TextureBrowser &self, int value) {
2811                 if (value > 16)
2812                         TextureBrowser_setUniformSize(self, value);
2813         }
2814 };
2815
2816 struct UniformTextureMinSize {
2817         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2818                 returnz(g_TextureBrowser.m_uniformTextureMinSize);
2819         }
2820
2821         static void Import(TextureBrowser &self, int value) {
2822                 if (value > 16)
2823                         TextureBrowser_setUniformSize(self, value);
2824         }
2825 };
2826
2827 void TextureBrowser_constructPreferences( PreferencesPage& page ){
2828         page.appendCheckBox(
2829                 "", "Texture scrollbar",
2830                 make_property<TextureBrowser_ShowScrollbar>(GlobalTextureBrowser())
2831                 );
2832         {
2833                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
2834                 page.appendCombo(
2835                         "Texture Thumbnail Scale",
2836                         STRING_ARRAY_RANGE( texture_scale ),
2837                         make_property<TextureScale>(GlobalTextureBrowser())
2838                         );
2839         }
2840         page.appendSpinner( "Thumbnails Max Size", GlobalTextureBrowser().m_uniformTextureSize, GlobalTextureBrowser().m_uniformTextureSize, 16, 8192 );
2841         page.appendSpinner( "Thumbnails Min Size", GlobalTextureBrowser().m_uniformTextureMinSize, GlobalTextureBrowser().m_uniformTextureMinSize, 16, 8192 );
2842         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
2843         {
2844                 const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() };
2845                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
2846         }
2847 }
2848
2849 void TextureBrowser_constructPage( PreferenceGroup& group ){
2850         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
2851         TextureBrowser_constructPreferences( page );
2852 }
2853
2854 void TextureBrowser_registerPreferencesPage(){
2855         PreferencesDialog_addSettingsPage( makeCallbackF(TextureBrowser_constructPage) );
2856 }
2857
2858
2859 #include "preferencesystem.h"
2860 #include "stringio.h"
2861
2862
2863 void TextureClipboard_textureSelected( const char* shader );
2864
2865 void TextureBrowser_Construct(){
2866         GlobalCommands_insert( "ShaderInfo", makeCallbackF(TextureBrowser_shaderInfo) );
2867         GlobalCommands_insert( "ShowUntagged", makeCallbackF(TextureBrowser_showUntagged) );
2868         GlobalCommands_insert( "AddTag", makeCallbackF(TextureBrowser_addTag) );
2869         GlobalCommands_insert( "RenameTag", makeCallbackF(TextureBrowser_renameTag) );
2870         GlobalCommands_insert( "DeleteTag", makeCallbackF(TextureBrowser_deleteTag) );
2871         GlobalCommands_insert( "CopyTag", makeCallbackF(TextureBrowser_copyTag) );
2872         GlobalCommands_insert( "PasteTag", makeCallbackF(TextureBrowser_pasteTag) );
2873         GlobalCommands_insert( "RefreshShaders", makeCallbackF(VFS_Refresh) );
2874         GlobalToggles_insert( "ShowInUse", makeCallbackF(TextureBrowser_ToggleHideUnused), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
2875         GlobalCommands_insert( "ShowAllTextures", makeCallbackF(TextureBrowser_showAll), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
2876         GlobalCommands_insert( "ToggleTextures", makeCallbackF(TextureBrowser_toggleShow), Accelerator( 'T' ) );
2877         GlobalToggles_insert( "ToggleShowShaders", makeCallbackF(TextureBrowser_ToggleShowShaders), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaders_item ) );
2878         GlobalToggles_insert( "ToggleShowTextures", makeCallbackF(TextureBrowser_ToggleShowTextures), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showtextures_item ) );
2879         GlobalToggles_insert( "ToggleShowShaderlistOnly", makeCallbackF(TextureBrowser_ToggleShowShaderListOnly),
2880  ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaderlistonly_item ) );
2881         GlobalToggles_insert( "FixedSize", makeCallbackF(TextureBrowser_FixedSize), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_fixedsize_item ) );
2882         GlobalToggles_insert( "FilterMissing", makeCallbackF(TextureBrowser_FilterMissing), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_filternotex_item ) );
2883         GlobalToggles_insert( "FilterFallback", makeCallbackF(TextureBrowser_FilterFallback), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_hidenotex_item ) );
2884         GlobalToggles_insert( "EnableAlpha", makeCallbackF(TextureBrowser_EnableAlpha), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_enablealpha_item ) );
2885
2886         GlobalPreferenceSystem().registerPreference( "TextureScale", make_property_string<TextureScale>(g_TextureBrowser) );
2887         GlobalPreferenceSystem().registerPreference( "UniformTextureSize", make_property_string<UniformTextureSize>(g_TextureBrowser) );
2888         GlobalPreferenceSystem().registerPreference( "UniformTextureMinSize", make_property_string<UniformTextureMinSize>(g_TextureBrowser) );
2889         GlobalPreferenceSystem().registerPreference( "TextureScrollbar", make_property_string<TextureBrowser_ShowScrollbar>(GlobalTextureBrowser()));
2890         GlobalPreferenceSystem().registerPreference( "ShowShaders", make_property_string( GlobalTextureBrowser().m_showShaders ) );
2891         GlobalPreferenceSystem().registerPreference( "ShowTextures", make_property_string( GlobalTextureBrowser().m_showTextures ) );
2892         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", make_property_string( g_TextureBrowser_shaderlistOnly ) );
2893         GlobalPreferenceSystem().registerPreference( "FixedSize", make_property_string( g_TextureBrowser_fixedSize ) );
2894         GlobalPreferenceSystem().registerPreference( "FilterMissing", make_property_string( g_TextureBrowser_filterMissing ) );
2895         GlobalPreferenceSystem().registerPreference( "EnableAlpha", make_property_string( g_TextureBrowser_enableAlpha ) );
2896         GlobalPreferenceSystem().registerPreference( "LoadShaders", make_property_string( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ) );
2897         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", make_property_string( GlobalTextureBrowser().m_mouseWheelScrollIncrement ) );
2898         GlobalPreferenceSystem().registerPreference( "SI_Colors0", make_property_string( GlobalTextureBrowser().color_textureback ) );
2899
2900         g_TextureBrowser.shader = texdef_name_default();
2901
2902         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw>( g_TextureBrowser ) );
2903
2904         TextureBrowser_registerPreferencesPage();
2905
2906         GlobalShaderSystem().attach( g_ShadersObserver );
2907
2908         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
2909 }
2910
2911 void TextureBrowser_Destroy(){
2912         GlobalShaderSystem().detach( g_ShadersObserver );
2913
2914         Textures_setModeChangedNotify( Callback<void()>() );
2915 }
2916
2917 ui::Widget TextureBrowser_getGLWidget(){
2918         return GlobalTextureBrowser().m_gl_widget;
2919 }