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