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