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