a86575bff925ed257672d70c8d88058f07c0c97b
[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 ImportExportCallback<bool>::Import_t& importer );
230 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
231
232 void TextureBrowser_showShadersExport( const ImportExportCallback<bool>::Import_t& importer );
233 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
234
235 void TextureBrowser_showShaderlistOnly( const ImportExportCallback<bool>::Import_t& importer );
236 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
237
238 void TextureBrowser_fixedSize( const ImportExportCallback<bool>::Import_t& importer );
239 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
240
241 void TextureBrowser_filterMissing( const ImportExportCallback<bool>::Import_t& importer );
242 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_filterMissing> TextureBrowserFilterMissingExport;
243
244 void TextureBrowser_filterFallback( const ImportExportCallback<bool>::Import_t& importer );
245 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_filterFallback> TextureBrowserFilterFallbackExport;
246
247 void TextureBrowser_enableAlpha( const ImportExportCallback<bool>::Import_t& importer );
248 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), 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 void TextureBrowser_importShowScrollbar( TextureBrowser& textureBrowser, bool value ){
675         textureBrowser.m_showTextureScrollbar = value;
676         if ( textureBrowser.m_texture_scroll != 0 ) {
677                 textureBrowser.m_texture_scroll.visible(textureBrowser.m_showTextureScrollbar);
678                 TextureBrowser_updateScroll( textureBrowser );
679         }
680 }
681 typedef ReferenceCaller<TextureBrowser, void(bool), TextureBrowser_importShowScrollbar> TextureBrowserImportShowScrollbarCaller;
682
683
684 /*
685    ==============
686    TextureBrowser_ShowDirectory
687    relies on texture_directory global for the directory to use
688    1) Load the shaders for the given directory
689    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
690    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
691    available through the IShaders interface
692    NOTE: for texture window layout:
693    all shaders are stored with alphabetical order after load
694    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
695    ( the GL textures are not flushed though)
696    ==============
697  */
698
699 bool endswith( const char *haystack, const char *needle ){
700         size_t lh = strlen( haystack );
701         size_t ln = strlen( needle );
702         if ( lh < ln ) {
703                 return false;
704         }
705         return !memcmp( haystack + ( lh - ln ), needle, ln );
706 }
707
708 bool texture_name_ignore( const char* name ){
709         StringOutputStream strTemp( string_length( name ) );
710         strTemp << LowerCase( name );
711
712         return
713                 endswith( strTemp.c_str(), ".specular" ) ||
714                 endswith( strTemp.c_str(), ".glow" ) ||
715                 endswith( strTemp.c_str(), ".bump" ) ||
716                 endswith( strTemp.c_str(), ".diffuse" ) ||
717                 endswith( strTemp.c_str(), ".blend" ) ||
718                 endswith( strTemp.c_str(), ".alpha" ) ||
719                 endswith( strTemp.c_str(), "_norm" ) ||
720                 endswith( strTemp.c_str(), "_bump" ) ||
721                 endswith( strTemp.c_str(), "_glow" ) ||
722                 endswith( strTemp.c_str(), "_gloss" ) ||
723                 endswith( strTemp.c_str(), "_pants" ) ||
724                 endswith( strTemp.c_str(), "_shirt" ) ||
725                 endswith( strTemp.c_str(), "_reflect" ) ||
726                 endswith( strTemp.c_str(), "_alpha" ) ||
727                 0;
728 }
729
730 class LoadShaderVisitor : public Archive::Visitor
731 {
732 public:
733 void visit( const char* name ){
734         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
735         shader->DecRef();
736 }
737 };
738
739 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
740
741 ui::Widget g_page_textures{ui::null};
742
743 void TextureBrowser_toggleShow(){
744         GroupDialog_showPage( g_page_textures );
745 }
746
747
748 void TextureBrowser_updateTitle(){
749         GroupDialog_updatePageTitle( g_page_textures );
750 }
751
752
753
754 class TextureCategoryLoadShader
755 {
756 const char* m_directory;
757 std::size_t& m_count;
758 public:
759 using func = void(const char *);
760
761 TextureCategoryLoadShader( const char* directory, std::size_t& count )
762         : m_directory( directory ), m_count( count ){
763         m_count = 0;
764 }
765 void operator()( const char* name ) const {
766         if ( shader_equal_prefix( name, "textures/" )
767                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
768                 ++m_count;
769                 // request the shader, this will load the texture if needed
770                 // this Shader_ForName call is a kind of hack
771                 IShader *pFoo = QERApp_Shader_ForName( name );
772                 pFoo->DecRef();
773         }
774 }
775 };
776
777 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
778         StringOutputStream name( 256 );
779         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
780
781         if ( texture_name_ignore( name.c_str() ) ) {
782                 return;
783         }
784
785         if ( !shader_valid( name.c_str() ) ) {
786                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
787                 return;
788         }
789
790         // if a texture is already in use to represent a shader, ignore it
791         IShader* shader = QERApp_Shader_ForName( name.c_str() );
792         shader->DecRef();
793 }
794 typedef ConstPointerCaller<char, void(const char*), TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
795
796 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
797 {
798 const char* m_dirstring;
799 public:
800 LoadTexturesByTypeVisitor( const char* dirstring )
801         : m_dirstring( dirstring ){
802 }
803 void visit( const char* minor, const _QERPlugImageTable& table ) const {
804         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
805 }
806 };
807
808 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
809         if ( TextureBrowser_showWads() ) {
810                 Archive* archive = GlobalFileSystem().getArchive( directory );
811                 ASSERT_NOTNULL( archive );
812                 LoadShaderVisitor visitor;
813                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
814         }
815         else
816         {
817                 g_TextureBrowser_currentDirectory = directory;
818                 TextureBrowser_heightChanged( textureBrowser );
819
820                 std::size_t shaders_count;
821                 GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
822                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
823
824                 if ( g_pGameDescription->mGameType != "doom3" ) {
825                         // load remaining texture files
826
827                         StringOutputStream dirstring( 64 );
828                         dirstring << "textures/" << directory;
829
830                         Radiant_getImageModules().foreachModule( LoadTexturesByTypeVisitor( dirstring.c_str() ) );
831                 }
832         }
833
834         // we'll display the newly loaded textures + all the ones already in use
835         TextureBrowser_SetHideUnused( textureBrowser, false );
836
837         TextureBrowser_updateTitle();
838 }
839
840 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
841         g_TextureBrowser_currentDirectory = directory;
842         TextureBrowser_heightChanged( textureBrowser );
843
844         std::size_t shaders_count;
845         GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
846         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
847
848         if ( g_pGameDescription->mGameType != "doom3" ) {
849                 // load remaining texture files
850                 StringOutputStream dirstring( 64 );
851                 dirstring << "textures/" << directory;
852
853                 {
854                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
855                         Radiant_getImageModules().foreachModule( visitor );
856                 }
857         }
858
859         // we'll display the newly loaded textures + all the ones already in use
860         TextureBrowser_SetHideUnused( textureBrowser, false );
861 }
862
863
864 bool TextureBrowser_hideUnused();
865
866 void TextureBrowser_hideUnusedExport( const ImportExportCallback<bool>::Import_t& importer ){
867         importer( TextureBrowser_hideUnused() );
868 }
869 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
870
871 void TextureBrowser_showShadersExport( const ImportExportCallback<bool>::Import_t& importer ){
872         importer( GlobalTextureBrowser().m_showShaders );
873 }
874 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
875
876 void TextureBrowser_showShaderlistOnly( const ImportExportCallback<bool>::Import_t& importer ){
877         importer( g_TextureBrowser_shaderlistOnly );
878 }
879 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
880
881 void TextureBrowser_fixedSize( const ImportExportCallback<bool>::Import_t& importer ){
882         importer( g_TextureBrowser_fixedSize );
883 }
884 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
885
886 void TextureBrowser_filterMissing( const ImportExportCallback<bool>::Import_t& importer ){
887         importer( g_TextureBrowser_filterMissing );
888 }
889 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_filterMissing> TextureBrowser_filterMissingExport;
890
891 void TextureBrowser_filterFallback( const ImportExportCallback<bool>::Import_t& importer ){
892         importer( g_TextureBrowser_filterFallback );
893 }
894 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_filterFallback> TextureBrowser_filterFallbackExport;
895
896 void TextureBrowser_enableAlpha( const ImportExportCallback<bool>::Import_t& importer ){
897         importer( g_TextureBrowser_enableAlpha );
898 }
899 typedef FreeCaller<void(const ImportExportCallback<bool>::Import_t&), TextureBrowser_enableAlpha> TextureBrowser_enableAlphaExport;
900
901 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
902         if ( hideUnused ) {
903                 textureBrowser.m_hideUnused = true;
904         }
905         else
906         {
907                 textureBrowser.m_hideUnused = false;
908         }
909
910         textureBrowser.m_hideunused_item.update();
911
912         TextureBrowser_heightChanged( textureBrowser );
913         textureBrowser.m_originInvalid = true;
914 }
915
916 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
917         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
918                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getComonShadersDir() );
919         }
920 }
921
922
923 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
924 // it might need to be split in parts or moved out .. dunno
925 // scroll origin so the specified texture is completely on screen
926 // if current texture is not displayed, nothing is changed
927 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
928         TextureLayout layout;
929         // scroll origin so the texture is completely on screen
930         Texture_StartPos( layout );
931
932         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
933         {
934                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
935
936                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
937                         continue;
938                 }
939
940                 int x, y;
941                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
942                 qtexture_t* q = shader->getTexture();
943                 if ( !q ) {
944                         break;
945                 }
946
947                 // we have found when texdef->name and the shader name match
948                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
949                 if ( shader_equal( name, shader->getName() ) ) {
950                         int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) )
951                                                                 + 2 * TextureBrowser_fontHeight( textureBrowser );
952
953                         int originy = TextureBrowser_getOriginY( textureBrowser );
954                         if ( y > originy ) {
955                                 originy = y;
956                         }
957
958                         if ( y - textureHeight < originy - textureBrowser.height ) {
959                                 originy = ( y - textureHeight ) + textureBrowser.height;
960                         }
961
962                         TextureBrowser_setOriginY( textureBrowser, originy );
963                         return;
964                 }
965         }
966 }
967
968 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
969         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
970
971         TextureLayout layout;
972         Texture_StartPos( layout );
973         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
974         {
975                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
976
977                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
978                         continue;
979                 }
980
981                 int x, y;
982                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
983                 qtexture_t  *q = shader->getTexture();
984                 if ( !q ) {
985                         break;
986                 }
987
988                 int nWidth = textureBrowser.getTextureWidth( q );
989                 int nHeight = textureBrowser.getTextureHeight( q );
990                 if ( mx > x && mx - x < nWidth
991                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
992                         return shader;
993                 }
994         }
995
996         return 0;
997 }
998
999 /*
1000    ==============
1001    SelectTexture
1002
1003    By mouse click
1004    ==============
1005  */
1006 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
1007         IShader* shader = Texture_At( textureBrowser, mx, my );
1008         if ( shader != 0 ) {
1009                 if ( bShift ) {
1010                         if ( shader->IsDefault() ) {
1011                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
1012                         }
1013                         else{
1014                                 ViewShader( shader->getShaderFileName(), shader->getName() );
1015                         }
1016                 }
1017                 else
1018                 {
1019                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
1020                         TextureBrowser_textureSelected( shader->getName() );
1021
1022                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
1023                                 UndoableCommand undo( "textureNameSetSelected" );
1024                                 Select_SetShader( shader->getName() );
1025                         }
1026                 }
1027         }
1028 }
1029
1030 /*
1031    ============================================================================
1032
1033    MOUSE ACTIONS
1034
1035    ============================================================================
1036  */
1037
1038 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
1039         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
1040         if ( y != 0 ) {
1041                 int scale = 1;
1042
1043                 if ( state & GDK_SHIFT_MASK ) {
1044                         scale = 4;
1045                 }
1046
1047                 int originy = TextureBrowser_getOriginY( textureBrowser );
1048                 originy += y * scale;
1049                 TextureBrowser_setOriginY( textureBrowser, originy );
1050         }
1051 }
1052
1053 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
1054         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser );
1055 }
1056
1057 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
1058         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_parent );
1059 }
1060
1061 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
1062         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
1063 }
1064
1065 /*
1066    ============================================================================
1067
1068    DRAWING
1069
1070    ============================================================================
1071  */
1072
1073 /*
1074    ============
1075    Texture_Draw
1076    TTimo: relying on the shaders list to display the textures
1077    we must query all qtexture_t* to manage and display through the IShaders interface
1078    this allows a plugin to completely override the texture system
1079    ============
1080  */
1081 void Texture_Draw( TextureBrowser& textureBrowser ){
1082         int originy = TextureBrowser_getOriginY( textureBrowser );
1083
1084         glClearColor( textureBrowser.color_textureback[0],
1085                                   textureBrowser.color_textureback[1],
1086                                   textureBrowser.color_textureback[2],
1087                                   0 );
1088         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1089         glMatrixMode( GL_PROJECTION );
1090         glLoadIdentity();
1091
1092         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1093         glDisable( GL_DEPTH_TEST );
1094         if ( g_TextureBrowser_enableAlpha ) {
1095                 glEnable( GL_BLEND );
1096                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1097         }
1098         else {
1099                 glDisable( GL_BLEND );
1100         }
1101         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1102         glEnable( GL_TEXTURE_2D );
1103
1104         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1105
1106         int last_y = 0, last_height = 0;
1107
1108         TextureLayout layout;
1109         Texture_StartPos( layout );
1110         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1111         {
1112                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1113
1114                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1115                         continue;
1116                 }
1117
1118                 int x, y;
1119                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1120                 qtexture_t *q = shader->getTexture();
1121                 if ( !q ) {
1122                         break;
1123                 }
1124
1125                 int nWidth = textureBrowser.getTextureWidth( q );
1126                 int nHeight = textureBrowser.getTextureHeight( q );
1127
1128                 if ( y != last_y ) {
1129                         last_y = y;
1130                         last_height = 0;
1131                 }
1132                 last_height = std::max( nHeight, last_height );
1133
1134                 // Is this texture visible?
1135                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1136                          && ( y > originy - textureBrowser.height ) ) {
1137                         // borders rules:
1138                         // if it's the current texture, draw a thick red line, else:
1139                         // shaders have a white border, simple textures don't
1140                         // if !texture_showinuse: (some textures displayed may not be in use)
1141                         // draw an additional square around with 0.5 1 0.5 color
1142                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1143                                 glLineWidth( 3 );
1144                                 if ( textureBrowser.m_rmbSelected ) {
1145                                         glColor3f( 0,0,1 );
1146                                 }
1147                                 else {
1148                                         glColor3f( 1,0,0 );
1149                                 }
1150                                 glDisable( GL_TEXTURE_2D );
1151
1152                                 glBegin( GL_LINE_LOOP );
1153                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1154                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1155                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1156                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1157                                 glEnd();
1158
1159                                 glEnable( GL_TEXTURE_2D );
1160                                 glLineWidth( 1 );
1161                         }
1162                         else
1163                         {
1164                                 glLineWidth( 1 );
1165                                 // shader border:
1166                                 if ( !shader->IsDefault() ) {
1167                                         glColor3f( 1,1,1 );
1168                                         glDisable( GL_TEXTURE_2D );
1169
1170                                         glBegin( GL_LINE_LOOP );
1171                                         glVertex2i( x - 1,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1172                                         glVertex2i( x - 1,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1173                                         glVertex2i( x + 1 + nWidth,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1174                                         glVertex2i( x + 1 + nWidth,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1175                                         glEnd();
1176                                         glEnable( GL_TEXTURE_2D );
1177                                 }
1178
1179                                 // highlight in-use textures
1180                                 if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1181                                         glColor3f( 0.5,1,0.5 );
1182                                         glDisable( GL_TEXTURE_2D );
1183                                         glBegin( GL_LINE_LOOP );
1184                                         glVertex2i( x - 3,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1185                                         glVertex2i( x - 3,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1186                                         glVertex2i( x + 3 + nWidth,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1187                                         glVertex2i( x + 3 + nWidth,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1188                                         glEnd();
1189                                         glEnable( GL_TEXTURE_2D );
1190                                 }
1191                         }
1192
1193                         // draw checkerboard for transparent textures
1194                         if ( g_TextureBrowser_enableAlpha )
1195                         {
1196                                 glDisable( GL_TEXTURE_2D );
1197                                 glBegin( GL_QUADS );
1198                                 int font_height = TextureBrowser_fontHeight( textureBrowser );
1199                                 for ( int i = 0; i < nHeight; i += 8 )
1200                                         for ( int j = 0; j < nWidth; j += 8 )
1201                                         {
1202                                                 unsigned char color = (i + j) / 8 % 2 ? 0x66 : 0x99;
1203                                                 glColor3ub( color, color, color );
1204                                                 int left = j;
1205                                                 int right = std::min(j+8, nWidth);
1206                                                 int top = i;
1207                                                 int bottom = std::min(i+8, nHeight);
1208                                                 glVertex2i(x + right, y - nHeight - font_height + top);
1209                                                 glVertex2i(x + left,  y - nHeight - font_height + top);
1210                                                 glVertex2i(x + left,  y - nHeight - font_height + bottom);
1211                                                 glVertex2i(x + right, y - nHeight - font_height + bottom);
1212                                         }
1213                                 glEnd();
1214                                 glEnable( GL_TEXTURE_2D );
1215                         }
1216
1217                         // Draw the texture
1218                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1219                         GlobalOpenGL_debugAssertNoErrors();
1220                         glColor3f( 1,1,1 );
1221                         glBegin( GL_QUADS );
1222                         glTexCoord2i( 0,0 );
1223                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1224                         glTexCoord2i( 1,0 );
1225                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1226                         glTexCoord2i( 1,1 );
1227                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1228                         glTexCoord2i( 0,1 );
1229                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1230                         glEnd();
1231
1232                         // draw the texture name
1233                         glDisable( GL_TEXTURE_2D );
1234                         glColor3f( 1,1,1 );
1235
1236                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 5 );
1237
1238                         // don't draw the directory name
1239                         const char* name = shader->getName();
1240                         name += strlen( name );
1241                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1242                                 name--;
1243
1244                         GlobalOpenGL().drawString( name );
1245                         glEnable( GL_TEXTURE_2D );
1246                 }
1247
1248                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1249         }
1250
1251
1252         // reset the current texture
1253         glBindTexture( GL_TEXTURE_2D, 0 );
1254         //qglFinish();
1255 }
1256
1257 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1258         if ( textureBrowser.m_gl_widget ) {
1259                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1260         }
1261 }
1262
1263
1264 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1265         textureBrowser.m_textureScale = scale;
1266
1267         TextureBrowser_queueDraw( textureBrowser );
1268 }
1269
1270 void TextureBrowser_setUniformSize( TextureBrowser& textureBrowser, std::size_t scale ){
1271         textureBrowser.m_uniformTextureSize = scale;
1272
1273         TextureBrowser_queueDraw( textureBrowser );
1274 }
1275
1276
1277 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1278         int originy = TextureBrowser_getOriginY( textureBrowser );
1279
1280         if ( bUp ) {
1281                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1282         }
1283         else
1284         {
1285                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1286         }
1287
1288         TextureBrowser_setOriginY( textureBrowser, originy );
1289 }
1290
1291 XmlTagBuilder TagBuilder;
1292
1293 enum
1294 {
1295         TAG_COLUMN,
1296         N_COLUMNS
1297 };
1298
1299 void BuildStoreAssignedTags( ui::ListStore store, const char* shader, TextureBrowser* textureBrowser ){
1300         GtkTreeIter iter;
1301
1302         store.clear();
1303
1304         std::vector<CopiedString> assigned_tags;
1305         TagBuilder.GetShaderTags( shader, assigned_tags );
1306
1307         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1308         {
1309                 store.append(TAG_COLUMN, assigned_tags[i].c_str());
1310         }
1311 }
1312
1313 void BuildStoreAvailableTags(   ui::ListStore storeAvailable,
1314                                                                 ui::ListStore storeAssigned,
1315                                                                 const std::set<CopiedString>& allTags,
1316                                                                 TextureBrowser* textureBrowser ){
1317         GtkTreeIter iterAssigned;
1318         GtkTreeIter iterAvailable;
1319         std::set<CopiedString>::const_iterator iterAll;
1320         gchar* tag_assigned;
1321
1322         storeAvailable.clear();
1323
1324         bool row = gtk_tree_model_get_iter_first(storeAssigned, &iterAssigned ) != 0;
1325
1326         if ( !row ) { // does the shader have tags assigned?
1327                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1328                 {
1329                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1330                 }
1331         }
1332         else
1333         {
1334                 while ( row ) // available tags = all tags - assigned tags
1335                 {
1336                         gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1337
1338                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1339                         {
1340                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1341                                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1342                                 }
1343                                 else
1344                                 {
1345                                         row = gtk_tree_model_iter_next(storeAssigned, &iterAssigned ) != 0;
1346
1347                                         if ( row ) {
1348                                                 gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1349                                         }
1350                                 }
1351                         }
1352                 }
1353         }
1354 }
1355
1356 gboolean TextureBrowser_button_press( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1357         if ( event->type == GDK_BUTTON_PRESS ) {
1358                 if ( event->button == 3 ) {
1359                         if ( GlobalTextureBrowser().m_tags ) {
1360                                 textureBrowser->m_rmbSelected = true;
1361                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1362
1363                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1364                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1365                                 textureBrowser->m_heightChanged = true;
1366                                 textureBrowser->m_tag_frame.show();
1367
1368                 ui::process();
1369
1370                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1371                         }
1372                         else
1373                         {
1374                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1375                         }
1376                 }
1377                 else if ( event->button == 1 ) {
1378                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1379
1380                         if ( GlobalTextureBrowser().m_tags ) {
1381                                 textureBrowser->m_rmbSelected = false;
1382                                 textureBrowser->m_tag_frame.hide();
1383                         }
1384                 }
1385         }
1386         return FALSE;
1387 }
1388
1389 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1390         if ( event->type == GDK_BUTTON_RELEASE ) {
1391                 if ( event->button == 3 ) {
1392                         if ( !GlobalTextureBrowser().m_tags ) {
1393                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1394                         }
1395                 }
1396         }
1397         return FALSE;
1398 }
1399
1400 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1401         return FALSE;
1402 }
1403
1404 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1405         if ( event->direction == GDK_SCROLL_UP ) {
1406                 TextureBrowser_MouseWheel( *textureBrowser, true );
1407         }
1408         else if ( event->direction == GDK_SCROLL_DOWN ) {
1409                 TextureBrowser_MouseWheel( *textureBrowser, false );
1410         }
1411         return FALSE;
1412 }
1413
1414 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1415         //globalOutputStream() << "vertical scroll\n";
1416         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1417 }
1418
1419 static void TextureBrowser_verticalScroll( GtkAdjustment *adjustment, TextureBrowser* textureBrowser ){
1420         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1421 }
1422
1423 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1424         if ( textureBrowser.m_showTextureScrollbar ) {
1425                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1426
1427                 totalHeight = std::max( totalHeight, textureBrowser.height );
1428
1429         auto vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1430
1431                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1432                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1433                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1434                 gtk_adjustment_set_step_increment(vadjustment, 20);
1435                 gtk_adjustment_set_lower(vadjustment, 0);
1436                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1437
1438                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1439         }
1440 }
1441
1442 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1443         textureBrowser->width = allocation->width;
1444         textureBrowser->height = allocation->height;
1445         TextureBrowser_heightChanged( *textureBrowser );
1446         textureBrowser->m_originInvalid = true;
1447         TextureBrowser_queueDraw( *textureBrowser );
1448         return FALSE;
1449 }
1450
1451 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1452         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1453                 GlobalOpenGL_debugAssertNoErrors();
1454                 TextureBrowser_evaluateHeight( *textureBrowser );
1455                 Texture_Draw( *textureBrowser );
1456                 GlobalOpenGL_debugAssertNoErrors();
1457                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1458         }
1459         return FALSE;
1460 }
1461
1462
1463 TextureBrowser g_TextureBrowser;
1464
1465 TextureBrowser& GlobalTextureBrowser(){
1466         return g_TextureBrowser;
1467 }
1468
1469 bool TextureBrowser_hideUnused(){
1470         return g_TextureBrowser.m_hideUnused;
1471 }
1472
1473 void TextureBrowser_ToggleHideUnused(){
1474         if ( g_TextureBrowser.m_hideUnused ) {
1475                 TextureBrowser_SetHideUnused( g_TextureBrowser, false );
1476         }
1477         else
1478         {
1479                 TextureBrowser_SetHideUnused( g_TextureBrowser, true );
1480         }
1481 }
1482
1483 void TextureGroups_constructTreeModel( TextureGroups groups, ui::TreeStore store ){
1484         // put the information from the old textures menu into a treeview
1485         GtkTreeIter iter, child;
1486
1487         TextureGroups::const_iterator i = groups.begin();
1488         while ( i != groups.end() )
1489         {
1490                 const char* dirName = ( *i ).c_str();
1491                 const char* firstUnderscore = strchr( dirName, '_' );
1492                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1493
1494                 TextureGroups::const_iterator next = i;
1495                 ++next;
1496                 if ( firstUnderscore != 0
1497                          && next != groups.end()
1498                          && string_equal_start( ( *next ).c_str(), dirRoot ) ) {
1499                         gtk_tree_store_append( store, &iter, NULL );
1500                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1501
1502                         // keep going...
1503                         while ( i != groups.end() && string_equal_start( ( *i ).c_str(), dirRoot ) )
1504                         {
1505                                 gtk_tree_store_append( store, &child, &iter );
1506                                 gtk_tree_store_set( store, &child, 0, ( *i ).c_str(), -1 );
1507                                 ++i;
1508                         }
1509                 }
1510                 else
1511                 {
1512                         gtk_tree_store_append( store, &iter, NULL );
1513                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1514                         ++i;
1515                 }
1516         }
1517 }
1518
1519 TextureGroups TextureGroups_constructTreeView(){
1520         TextureGroups groups;
1521
1522         if ( TextureBrowser_showWads() ) {
1523                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1524         }
1525         else
1526         {
1527                 // scan texture dirs and pak files only if not restricting to shaderlist
1528                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1529                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1530                 }
1531
1532                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1533         }
1534
1535         return groups;
1536 }
1537
1538 void TextureBrowser_constructTreeStore(){
1539         TextureGroups groups = TextureGroups_constructTreeView();
1540         auto store = ui::TreeStore(gtk_tree_store_new( 1, G_TYPE_STRING ));
1541         TextureGroups_constructTreeModel( groups, store );
1542
1543         gtk_tree_view_set_model(g_TextureBrowser.m_treeViewTree, store);
1544
1545         g_object_unref( G_OBJECT( store ) );
1546 }
1547
1548 void TextureBrowser_constructTreeStoreTags(){
1549         TextureGroups groups;
1550         auto store = ui::TreeStore(gtk_tree_store_new( 1, G_TYPE_STRING ));
1551     auto model = g_TextureBrowser.m_all_tags_list;
1552
1553         gtk_tree_view_set_model(g_TextureBrowser.m_treeViewTags, model );
1554
1555         g_object_unref( G_OBJECT( store ) );
1556 }
1557
1558 void TreeView_onRowActivated( ui::TreeView treeview, GtkTreePath* path, ui::TreeViewColumn col, gpointer userdata ){
1559         GtkTreeIter iter;
1560
1561     auto model = gtk_tree_view_get_model(treeview );
1562
1563         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1564                 gchar dirName[1024];
1565
1566                 gchar* buffer;
1567                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1568                 strcpy( dirName, buffer );
1569                 g_free( buffer );
1570
1571                 g_TextureBrowser.m_searchedTags = false;
1572
1573                 if ( !TextureBrowser_showWads() ) {
1574                         strcat( dirName, "/" );
1575                 }
1576
1577                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1578                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1579                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1580         }
1581 }
1582
1583 void TextureBrowser_createTreeViewTree(){
1584         g_TextureBrowser.m_treeViewTree = ui::TreeView(ui::New);
1585         gtk_tree_view_set_enable_search(g_TextureBrowser.m_treeViewTree, FALSE );
1586
1587         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_treeViewTree, FALSE );
1588         g_TextureBrowser.m_treeViewTree.connect( "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1589
1590         auto renderer = ui::CellRendererText(ui::New);
1591         gtk_tree_view_insert_column_with_attributes(g_TextureBrowser.m_treeViewTree, -1, "", renderer, "text", 0, NULL );
1592
1593         TextureBrowser_constructTreeStore();
1594 }
1595
1596 void TextureBrowser_addTag();
1597 void TextureBrowser_renameTag();
1598 void TextureBrowser_deleteTag();
1599
1600 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1601         ui::Widget menu = ui::Menu(ui::New);
1602
1603         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1604         menuitem.connect( "activate", (GCallback)TextureBrowser_addTag, treeview );
1605         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1606
1607         menuitem = ui::MenuItem( "Rename tag" );
1608         menuitem.connect( "activate", (GCallback)TextureBrowser_renameTag, treeview );
1609         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1610
1611         menuitem = ui::MenuItem( "Delete tag" );
1612         menuitem.connect( "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1613         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1614
1615         gtk_widget_show_all( menu );
1616
1617         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1618                                         ( event != NULL ) ? event->button : 0,
1619                                         gdk_event_get_time( (GdkEvent*)event ) );
1620 }
1621
1622 gboolean TreeViewTags_onButtonPressed( ui::TreeView treeview, GdkEventButton *event ){
1623         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1624                 GtkTreePath *path;
1625         auto selection = gtk_tree_view_get_selection(treeview );
1626
1627                 if ( gtk_tree_view_get_path_at_pos(treeview, event->x, event->y, &path, NULL, NULL, NULL ) ) {
1628                         gtk_tree_selection_unselect_all( selection );
1629                         gtk_tree_selection_select_path( selection, path );
1630                         gtk_tree_path_free( path );
1631                 }
1632
1633                 TextureBrowser_createContextMenu( treeview, event );
1634                 return TRUE;
1635         }
1636         return FALSE;
1637 }
1638
1639 void TextureBrowser_createTreeViewTags(){
1640         g_TextureBrowser.m_treeViewTags = ui::TreeView(ui::New);
1641         gtk_tree_view_set_enable_search(g_TextureBrowser.m_treeViewTags, FALSE );
1642
1643         g_TextureBrowser.m_treeViewTags.connect( "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1644
1645         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_treeViewTags, FALSE );
1646
1647         auto renderer = ui::CellRendererText(ui::New);
1648         gtk_tree_view_insert_column_with_attributes(g_TextureBrowser.m_treeViewTags, -1, "", renderer, "text", 0, NULL );
1649
1650         TextureBrowser_constructTreeStoreTags();
1651 }
1652
1653 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1654         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1655
1656         if ( g_Layout_enableDetachableMenus.m_value ) {
1657                 menu_tearoff( menu );
1658         }
1659
1660         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1661         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1662                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1663         }
1664
1665         // hide notex and shadernotex on texture browser: no one wants to apply them
1666         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1667
1668         menu_separator( menu );
1669
1670         create_menu_item_with_mnemonic( menu, "Show All", "ShowAllTextures" );
1671
1672         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1673         if ( g_pGameDescription->mGameType == "doom3" || !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1674                 g_TextureBrowser.m_showShaders = true;
1675         }
1676         else
1677         {
1678                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1679         }
1680
1681         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1682                 create_check_menu_item_with_mnemonic( menu, "Shaders Only", "ToggleShowShaderlistOnly" );
1683         }
1684         if ( g_TextureBrowser.m_tags ) {
1685                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1686         }
1687
1688         menu_separator( menu );
1689         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1690         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1691
1692         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1693                 menu_separator( menu );
1694                 g_TextureBrowser.m_shader_info_item = ui::Widget(create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo"  ));
1695                 gtk_widget_set_sensitive( g_TextureBrowser.m_shader_info_item, FALSE );
1696         }
1697
1698
1699         return textures_menu_item;
1700 }
1701
1702 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1703         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1704
1705         if ( g_Layout_enableDetachableMenus.m_value ) {
1706                 menu_tearoff( menu );
1707         }
1708
1709         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1710         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1711
1712         return textures_menu_item;
1713 }
1714
1715 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1716         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1717
1718         if ( g_Layout_enableDetachableMenus.m_value ) {
1719                 menu_tearoff( menu );
1720         }
1721
1722         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1723         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1724         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1725         menu_separator( menu );
1726         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1727         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1728
1729         return textures_menu_item;
1730 }
1731
1732 gboolean TextureBrowser_tagMoveHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
1733         g_assert( selected != NULL );
1734
1735     auto rowref = gtk_tree_row_reference_new( model, path );
1736         *selected = g_slist_append( *selected, rowref );
1737
1738         return FALSE;
1739 }
1740
1741 void TextureBrowser_assignTags(){
1742         GSList* selected = NULL;
1743         GSList* node;
1744         gchar* tag_assigned;
1745
1746     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
1747
1748         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1749
1750         if ( selected != NULL ) {
1751                 for ( node = selected; node != NULL; node = node->next )
1752                 {
1753             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1754
1755                         if ( path ) {
1756                                 GtkTreeIter iter;
1757
1758                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_available_store, &iter, path ) ) {
1759                                         gtk_tree_model_get(g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, &tag_assigned, -1 );
1760                                         if ( !TagBuilder.CheckShaderTag( g_TextureBrowser.shader.c_str() ) ) {
1761                                                 // create a custom shader/texture entry
1762                                                 IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
1763                                                 CopiedString filename = ishader->getShaderFileName();
1764
1765                                                 if ( filename.empty() ) {
1766                                                         // it's a texture
1767                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE );
1768                                                 }
1769                                                 else {
1770                                                         // it's a shader
1771                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, SHADER );
1772                                                 }
1773                                                 ishader->DecRef();
1774                                         }
1775                                         TagBuilder.AddShaderTag( g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
1776
1777                                         gtk_list_store_remove( g_TextureBrowser.m_available_store, &iter );
1778                                         g_TextureBrowser.m_assigned_store.append(TAG_COLUMN, tag_assigned);
1779                                 }
1780                         }
1781                 }
1782
1783                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1784
1785                 // Save changes
1786                 TagBuilder.SaveXmlDoc();
1787         }
1788         g_slist_free( selected );
1789 }
1790
1791 void TextureBrowser_removeTags(){
1792         GSList* selected = NULL;
1793         GSList* node;
1794         gchar* tag;
1795
1796     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_assigned_tree );
1797
1798         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1799
1800         if ( selected != NULL ) {
1801                 for ( node = selected; node != NULL; node = node->next )
1802                 {
1803             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1804
1805                         if ( path ) {
1806                                 GtkTreeIter iter;
1807
1808                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_assigned_store, &iter, path ) ) {
1809                                         gtk_tree_model_get(g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, &tag, -1 );
1810                                         TagBuilder.DeleteShaderTag( g_TextureBrowser.shader.c_str(), tag );
1811                                         gtk_list_store_remove( g_TextureBrowser.m_assigned_store, &iter );
1812                                 }
1813                         }
1814                 }
1815
1816                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1817
1818                 // Update the "available tags list"
1819                 BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
1820
1821                 // Save changes
1822                 TagBuilder.SaveXmlDoc();
1823         }
1824         g_slist_free( selected );
1825 }
1826
1827 void TextureBrowser_buildTagList(){
1828         g_TextureBrowser.m_all_tags_list.clear();
1829
1830         std::set<CopiedString>::iterator iter;
1831
1832         for ( iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter )
1833         {
1834                 g_TextureBrowser.m_all_tags_list.append(TAG_COLUMN, (*iter).c_str());
1835         }
1836 }
1837
1838 void TextureBrowser_searchTags(){
1839         GSList* selected = NULL;
1840         GSList* node;
1841         gchar* tag;
1842         char buffer[256];
1843         char tags_searched[256];
1844
1845     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
1846
1847         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1848
1849         if ( selected != NULL ) {
1850                 strcpy( buffer, "/root/*/*[tag='" );
1851                 strcpy( tags_searched, "[TAGS] " );
1852
1853                 for ( node = selected; node != NULL; node = node->next )
1854                 {
1855             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1856
1857                         if ( path ) {
1858                                 GtkTreeIter iter;
1859
1860                                 if ( gtk_tree_model_get_iter(g_TextureBrowser.m_all_tags_list, &iter, path ) ) {
1861                                         gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iter, TAG_COLUMN, &tag, -1 );
1862
1863                                         strcat( buffer, tag );
1864                                         strcat( tags_searched, tag );
1865                                         if ( node != g_slist_last( node ) ) {
1866                                                 strcat( buffer, "' and tag='" );
1867                                                 strcat( tags_searched, ", " );
1868                                         }
1869                                 }
1870                         }
1871                 }
1872
1873                 strcat( buffer, "']" );
1874
1875                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1876
1877                 g_TextureBrowser.m_found_shaders.clear(); // delete old list
1878                 TagBuilder.TagSearch( buffer, g_TextureBrowser.m_found_shaders );
1879
1880                 if ( !g_TextureBrowser.m_found_shaders.empty() ) { // found something
1881                         size_t shaders_found = g_TextureBrowser.m_found_shaders.size();
1882
1883                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
1884                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
1885
1886                         std::set<CopiedString>::iterator iter;
1887
1888                         for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
1889                         {
1890                                 std::string path = ( *iter ).c_str();
1891                                 size_t pos = path.find_last_of( "/", path.size() );
1892                                 std::string name = path.substr( pos + 1, path.size() );
1893                                 path = path.substr( 0, pos + 1 );
1894                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
1895                         }
1896                 }
1897                 g_TextureBrowser.m_searchedTags = true;
1898                 g_TextureBrowser_currentDirectory = tags_searched;
1899
1900                 g_TextureBrowser.m_nTotalHeight = 0;
1901                 TextureBrowser_setOriginY( g_TextureBrowser, 0 );
1902                 TextureBrowser_heightChanged( g_TextureBrowser );
1903                 TextureBrowser_updateTitle();
1904         }
1905         g_slist_free( selected );
1906 }
1907
1908 void TextureBrowser_toggleSearchButton(){
1909         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ) );
1910
1911         if ( page == 0 ) { // tag page
1912                 gtk_widget_show_all( g_TextureBrowser.m_search_button );
1913         }
1914         else {
1915                 g_TextureBrowser.m_search_button.hide();
1916         }
1917 }
1918
1919 void TextureBrowser_constructTagNotebook(){
1920         g_TextureBrowser.m_tag_notebook = ui::Widget(gtk_notebook_new());
1921         ui::Widget labelTags = ui::Label( "Tags" );
1922         ui::Widget labelTextures = ui::Label( "Textures" );
1923
1924         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tree, labelTextures );
1925         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tags, labelTags );
1926
1927         g_TextureBrowser.m_tag_notebook.connect( "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
1928
1929         gtk_widget_show_all( g_TextureBrowser.m_tag_notebook );
1930 }
1931
1932 void TextureBrowser_constructSearchButton(){
1933         ui::Widget image = ui::Widget(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
1934         g_TextureBrowser.m_search_button = ui::Button(ui::New);
1935         g_TextureBrowser.m_search_button.connect( "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
1936         gtk_widget_set_tooltip_text(g_TextureBrowser.m_search_button, "Search with selected tags");
1937         g_TextureBrowser.m_search_button.add(image);
1938 }
1939
1940 void TextureBrowser_checkTagFile(){
1941         const char SHADERTAG_FILE[] = "shadertags.xml";
1942         CopiedString default_filename, rc_filename;
1943         StringOutputStream stream( 256 );
1944
1945         stream << LocalRcPath_get();
1946         stream << SHADERTAG_FILE;
1947         rc_filename = stream.c_str();
1948
1949         if ( file_exists( rc_filename.c_str() ) ) {
1950                 g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
1951
1952                 if ( g_TextureBrowser.m_tags ) {
1953                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
1954                 }
1955         }
1956         else
1957         {
1958                 // load default tagfile
1959                 stream.clear();
1960                 stream << g_pGameDescription->mGameToolsPath.c_str();
1961                 stream << SHADERTAG_FILE;
1962                 default_filename = stream.c_str();
1963
1964                 if ( file_exists( default_filename.c_str() ) ) {
1965                         g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
1966
1967                         if ( g_TextureBrowser.m_tags ) {
1968                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
1969                         }
1970                 }
1971                 else
1972                 {
1973                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
1974                 }
1975         }
1976 }
1977
1978 void TextureBrowser_SetNotex(){
1979         StringOutputStream name( 256 );
1980         name << GlobalRadiant().getAppPath() << "bitmaps/" NOTEX_BASENAME ".png";
1981         g_notex = name.c_str();
1982
1983         name = StringOutputStream(256);
1984         name << GlobalRadiant().getAppPath() << "bitmaps/" SHADERNOTEX_BASENAME " .png";
1985         g_shadernotex = name.c_str();
1986 }
1987
1988 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
1989         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
1990         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
1991         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
1992         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
1993
1994         TextureBrowser_checkTagFile();
1995         TextureBrowser_SetNotex();
1996
1997         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_activeShadersChanged>( g_TextureBrowser ) );
1998
1999         g_TextureBrowser.m_parent = toplevel;
2000
2001         auto table = ui::Table(3, 3, FALSE);
2002         auto vbox = ui::VBox(FALSE, 0);
2003         table.attach(vbox, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2004         vbox.show();
2005
2006         ui::Widget menu_bar{ui::null};
2007
2008         { // menu bar
2009                 menu_bar = ui::Widget(gtk_menu_bar_new());
2010                 auto menu_view = ui::Menu(ui::New);
2011                 auto view_item = TextureBrowser_constructViewMenu( menu_view );
2012                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2013                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2014
2015                 auto menu_tools = ui::Menu(ui::New);
2016                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2017                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2018                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2019
2020                 table.attach(menu_bar, {0, 3, 0, 1}, {GTK_FILL, GTK_SHRINK});
2021                 menu_bar.show();
2022         }
2023         { // Texture TreeView
2024                 g_TextureBrowser.m_scr_win_tree = ui::ScrolledWindow(ui::New);
2025                 gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tree ), 0 );
2026
2027                 // vertical only scrolling for treeview
2028                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2029
2030                 g_TextureBrowser.m_scr_win_tree.show();
2031
2032                 TextureBrowser_createTreeViewTree();
2033
2034                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), g_TextureBrowser.m_treeViewTree  );
2035                 g_TextureBrowser.m_treeViewTree.show();
2036         }
2037         { // gl_widget scrollbar
2038                 ui::Widget w = ui::Widget(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2039                 table.attach(w, {2, 3, 1, 2}, {GTK_SHRINK, GTK_FILL});
2040                 w.show();
2041                 g_TextureBrowser.m_texture_scroll = w;
2042
2043                 auto vadjustment = ui::Adjustment(gtk_range_get_adjustment( GTK_RANGE( g_TextureBrowser.m_texture_scroll ) ));
2044                 vadjustment.connect( "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &g_TextureBrowser );
2045
2046                 g_TextureBrowser.m_texture_scroll.visible(g_TextureBrowser.m_showTextureScrollbar);
2047         }
2048         { // gl_widget
2049                 g_TextureBrowser.m_gl_widget = glwidget_new( FALSE );
2050                 g_object_ref( g_TextureBrowser.m_gl_widget._handle );
2051
2052                 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 );
2053                 gtk_widget_set_can_focus( g_TextureBrowser.m_gl_widget, true );
2054
2055                 table.attach(g_TextureBrowser.m_gl_widget, {1, 2, 1, 2});
2056                 g_TextureBrowser.m_gl_widget.show();
2057
2058                 g_TextureBrowser.m_sizeHandler = g_TextureBrowser.m_gl_widget.connect( "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &g_TextureBrowser );
2059                 g_TextureBrowser.m_exposeHandler = g_TextureBrowser.m_gl_widget.on_render( G_CALLBACK( TextureBrowser_expose ), &g_TextureBrowser );
2060
2061                 g_TextureBrowser.m_gl_widget.connect( "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &g_TextureBrowser );
2062                 g_TextureBrowser.m_gl_widget.connect( "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &g_TextureBrowser );
2063                 g_TextureBrowser.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &g_TextureBrowser );
2064                 g_TextureBrowser.m_gl_widget.connect( "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &g_TextureBrowser );
2065         }
2066
2067         // tag stuff
2068         if ( g_TextureBrowser.m_tags ) {
2069                 { // fill tag GtkListStore
2070                         g_TextureBrowser.m_all_tags_list = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2071             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_all_tags_list );
2072                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2073
2074                         TagBuilder.GetAllTags( g_TextureBrowser.m_all_tags );
2075                         TextureBrowser_buildTagList();
2076                 }
2077                 { // tag menu bar
2078                         auto menu_tags = ui::Menu(ui::New);
2079                         auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2080                         gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2081                         gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2082                 }
2083                 { // Tag TreeView
2084                         g_TextureBrowser.m_scr_win_tags = ui::ScrolledWindow(ui::New);
2085                         gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), 0 );
2086
2087                         // vertical only scrolling for treeview
2088                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2089
2090                         TextureBrowser_createTreeViewTags();
2091
2092             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2093                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2094
2095                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), g_TextureBrowser.m_treeViewTags  );
2096                         g_TextureBrowser.m_treeViewTags.show();
2097                 }
2098                 { // Texture/Tag notebook
2099                         TextureBrowser_constructTagNotebook();
2100                         vbox.pack_start( g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2101                 }
2102                 { // Tag search button
2103                         TextureBrowser_constructSearchButton();
2104                         vbox.pack_end(g_TextureBrowser.m_search_button, FALSE, FALSE, 0);
2105                 }
2106                 auto frame_table = ui::Table(3, 3, FALSE);
2107                 { // Tag frame
2108
2109                         g_TextureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2110                         gtk_frame_set_label_align( GTK_FRAME( g_TextureBrowser.m_tag_frame ), 0.5, 0.5 );
2111                         gtk_frame_set_shadow_type( GTK_FRAME( g_TextureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2112
2113                         table.attach(g_TextureBrowser.m_tag_frame, {1, 3, 2, 3}, {GTK_FILL, GTK_SHRINK});
2114
2115                         frame_table.show();
2116
2117                         g_TextureBrowser.m_tag_frame.add(frame_table);
2118                 }
2119                 { // assigned tag list
2120                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2121                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2122                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2123
2124                         g_TextureBrowser.m_assigned_store = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2125
2126             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_assigned_store );
2127                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2128
2129                         auto renderer = ui::CellRendererText(ui::New);
2130
2131                         g_TextureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel(g_TextureBrowser.m_assigned_store ));
2132                         g_TextureBrowser.m_assigned_store.unref();
2133                         g_TextureBrowser.m_assigned_tree.connect( "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2134                         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_assigned_tree, FALSE );
2135
2136             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_assigned_tree );
2137                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2138
2139             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2140                         gtk_tree_view_append_column(g_TextureBrowser.m_assigned_tree, column );
2141                         g_TextureBrowser.m_assigned_tree.show();
2142
2143                         scrolled_win.show();
2144                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), g_TextureBrowser.m_assigned_tree  );
2145
2146                         frame_table.attach(scrolled_win, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2147                 }
2148                 { // available tag list
2149                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2150                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2151                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2152
2153                         g_TextureBrowser.m_available_store = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2154             auto sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_available_store );
2155                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2156
2157                         auto renderer = ui::CellRendererText(ui::New);
2158
2159                         g_TextureBrowser.m_available_tree = ui::TreeView(ui::TreeModel(g_TextureBrowser.m_available_store ));
2160                         g_TextureBrowser.m_available_store.unref();
2161                         g_TextureBrowser.m_available_tree.connect( "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2162                         gtk_tree_view_set_headers_visible(g_TextureBrowser.m_available_tree, FALSE );
2163
2164             auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
2165                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2166
2167             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2168                         gtk_tree_view_append_column(g_TextureBrowser.m_available_tree, column );
2169                         g_TextureBrowser.m_available_tree.show();
2170
2171                         scrolled_win.show();
2172                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), g_TextureBrowser.m_available_tree  );
2173
2174                         frame_table.attach(scrolled_win, {2, 3, 1, 3}, {GTK_FILL, GTK_FILL});
2175                 }
2176                 { // tag arrow buttons
2177                         auto m_btn_left = ui::Button(ui::New);
2178                         auto m_btn_right = ui::Button(ui::New);
2179                         auto m_arrow_left = ui::Widget(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2180                         auto m_arrow_right = ui::Widget(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2181                         m_btn_left.add(m_arrow_left);
2182                         m_btn_right.add(m_arrow_right);
2183
2184                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2185                         m_arrow_left.dimensions(-1, 68);
2186                         m_arrow_right.dimensions(-1, 68);
2187
2188                         frame_table.attach(m_btn_left, {1, 2, 1, 2}, {GTK_SHRINK, GTK_EXPAND});
2189                         frame_table.attach(m_btn_right, {1, 2, 2, 3}, {GTK_SHRINK, GTK_EXPAND});
2190
2191                         m_btn_left.connect( "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2192                         m_btn_right.connect( "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2193
2194                         m_btn_left.show();
2195                         m_btn_right.show();
2196                         m_arrow_left.show();
2197                         m_arrow_right.show();
2198                 }
2199                 { // tag fram labels
2200                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2201                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2202
2203                         frame_table.attach(m_lbl_assigned, {0, 1, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2204                         frame_table.attach(m_lbl_unassigned, {2, 3, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2205
2206                         m_lbl_assigned.show();
2207                         m_lbl_unassigned.show();
2208                 }
2209         }
2210         else { // no tag support, show the texture tree only
2211                 vbox.pack_start( g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2212         }
2213
2214         // TODO do we need this?
2215         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2216
2217         return table;
2218 }
2219
2220 void TextureBrowser_destroyWindow(){
2221         GlobalShaderSystem().setActiveShadersChangedNotify( Callback<void()>() );
2222
2223         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_sizeHandler );
2224         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_exposeHandler );
2225
2226         g_TextureBrowser.m_gl_widget.unref();
2227 }
2228
2229 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2230         return textureBrowser.color_textureback;
2231 }
2232
2233 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2234         textureBrowser.color_textureback = colour;
2235         TextureBrowser_queueDraw( textureBrowser );
2236 }
2237
2238 void TextureBrowser_selectionHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
2239         g_assert( selected != NULL );
2240
2241         gchar* name;
2242         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2243         *selected = g_slist_append( *selected, name );
2244 }
2245
2246 void TextureBrowser_shaderInfo(){
2247         const char* name = TextureBrowser_GetSelectedShader( g_TextureBrowser );
2248         IShader* shader = QERApp_Shader_ForName( name );
2249
2250         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2251
2252         shader->DecRef();
2253 }
2254
2255 void TextureBrowser_addTag(){
2256         CopiedString tag;
2257
2258         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2259
2260         if ( result == eIDOK && !tag.empty() ) {
2261                 GtkTreeIter iter;
2262                 g_TextureBrowser.m_all_tags.insert( tag.c_str() );
2263                 gtk_list_store_append( g_TextureBrowser.m_available_store, &iter );
2264                 gtk_list_store_set( g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2265
2266                 // Select the currently added tag in the available list
2267         auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_available_tree );
2268                 gtk_tree_selection_select_iter( selection, &iter );
2269
2270                 g_TextureBrowser.m_all_tags_list.append(TAG_COLUMN, tag.c_str());
2271         }
2272 }
2273
2274 void TextureBrowser_renameTag(){
2275         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2276            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2277            we need to count the number of selected rows first and use
2278            gtk_tree_selection_selected_foreach() then to go through the list of selected
2279            rows (which always containins a single row).
2280          */
2281
2282         GSList* selected = NULL;
2283
2284     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2285         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2286
2287         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2288                 CopiedString newTag;
2289                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2290
2291                 if ( result == eIDOK && !newTag.empty() ) {
2292                         GtkTreeIter iterList;
2293                         gchar* rowTag;
2294                         gchar* oldTag = (char*)selected->data;
2295
2296                         bool row = gtk_tree_model_get_iter_first(g_TextureBrowser.m_all_tags_list, &iterList ) != 0;
2297
2298                         while ( row )
2299                         {
2300                                 gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, &rowTag, -1 );
2301
2302                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2303                                         gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2304                                 }
2305                                 row = gtk_tree_model_iter_next(g_TextureBrowser.m_all_tags_list, &iterList ) != 0;
2306                         }
2307
2308                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2309
2310                         g_TextureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2311                         g_TextureBrowser.m_all_tags.insert( newTag );
2312
2313                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2314                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2315                 }
2316         }
2317         else
2318         {
2319                 g_TextureBrowser.m_parent.alert( "Select a single tag for renaming." );
2320         }
2321 }
2322
2323 void TextureBrowser_deleteTag(){
2324         GSList* selected = NULL;
2325
2326     auto selection = gtk_tree_view_get_selection(g_TextureBrowser.m_treeViewTags );
2327         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2328
2329         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2330                 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 );
2331
2332                 if ( result == ui::alert_response::YES ) {
2333                         GtkTreeIter iterSelected;
2334                         gchar *rowTag;
2335
2336                         gchar* tagSelected = (char*)selected->data;
2337
2338                         bool row = gtk_tree_model_get_iter_first(g_TextureBrowser.m_all_tags_list, &iterSelected ) != 0;
2339
2340                         while ( row )
2341                         {
2342                                 gtk_tree_model_get(g_TextureBrowser.m_all_tags_list, &iterSelected, TAG_COLUMN, &rowTag, -1 );
2343
2344                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2345                                         gtk_list_store_remove( g_TextureBrowser.m_all_tags_list, &iterSelected );
2346                                         break;
2347                                 }
2348                                 row = gtk_tree_model_iter_next(g_TextureBrowser.m_all_tags_list, &iterSelected ) != 0;
2349                         }
2350
2351                         TagBuilder.DeleteTag( tagSelected );
2352                         g_TextureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2353
2354                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2355                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2356                 }
2357         }
2358         else {
2359                 g_TextureBrowser.m_parent.alert( "Select a single tag for deletion." );
2360         }
2361 }
2362
2363 void TextureBrowser_copyTag(){
2364         g_TextureBrowser.m_copied_tags.clear();
2365         TagBuilder.GetShaderTags( g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags );
2366 }
2367
2368 void TextureBrowser_pasteTag(){
2369         IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
2370         CopiedString shader = g_TextureBrowser.shader.c_str();
2371
2372         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2373                 CopiedString shaderFile = ishader->getShaderFileName();
2374                 if ( shaderFile.empty() ) {
2375                         // it's a texture
2376                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2377                 }
2378                 else
2379                 {
2380                         // it's a shader
2381                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2382                 }
2383
2384                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2385                 {
2386                         TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2387                 }
2388         }
2389         else
2390         {
2391                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2392                 {
2393                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str() ) ) {
2394                                 // the tag doesn't exist - let's add it
2395                                 TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2396                         }
2397                 }
2398         }
2399
2400         ishader->DecRef();
2401
2402         TagBuilder.SaveXmlDoc();
2403         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser );
2404         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2405 }
2406
2407 void TextureBrowser_RefreshShaders(){
2408         ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2409         GlobalShaderSystem().refresh();
2410         UpdateAllWindows();
2411     auto selection = gtk_tree_view_get_selection(GlobalTextureBrowser().m_treeViewTree);
2412         GtkTreeModel* model = NULL;
2413         GtkTreeIter iter;
2414         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2415         {
2416                 gchar dirName[1024];
2417
2418                 gchar* buffer;
2419                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2420                 strcpy( dirName, buffer );
2421                 g_free( buffer );
2422                 if ( !TextureBrowser_showWads() ) {
2423                         strcat( dirName, "/" );
2424                 }
2425                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2426                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2427         }
2428 }
2429
2430 void TextureBrowser_ToggleShowShaders(){
2431         g_TextureBrowser.m_showShaders ^= 1;
2432         g_TextureBrowser.m_showshaders_item.update();
2433         TextureBrowser_queueDraw( g_TextureBrowser );
2434 }
2435
2436 void TextureBrowser_ToggleShowShaderListOnly(){
2437         g_TextureBrowser_shaderlistOnly ^= 1;
2438         g_TextureBrowser.m_showshaderlistonly_item.update();
2439
2440         TextureBrowser_constructTreeStore();
2441 }
2442
2443 void TextureBrowser_showAll(){
2444         g_TextureBrowser_currentDirectory = "";
2445         g_TextureBrowser.m_searchedTags = false;
2446         TextureBrowser_heightChanged( g_TextureBrowser );
2447         TextureBrowser_updateTitle();
2448 }
2449
2450 void TextureBrowser_showUntagged(){
2451         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 );
2452
2453         if ( result == ui::alert_response::YES ) {
2454                 g_TextureBrowser.m_found_shaders.clear();
2455                 TagBuilder.GetUntagged( g_TextureBrowser.m_found_shaders );
2456                 std::set<CopiedString>::iterator iter;
2457
2458                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2459
2460                 for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
2461                 {
2462                         std::string path = ( *iter ).c_str();
2463                         size_t pos = path.find_last_of( "/", path.size() );
2464                         std::string name = path.substr( pos + 1, path.size() );
2465                         path = path.substr( 0, pos + 1 );
2466                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2467                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2468                 }
2469
2470                 g_TextureBrowser_currentDirectory = "Untagged";
2471                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2472                 TextureBrowser_heightChanged( g_TextureBrowser );
2473                 TextureBrowser_updateTitle();
2474         }
2475 }
2476
2477 void TextureBrowser_FixedSize(){
2478         g_TextureBrowser_fixedSize ^= 1;
2479         GlobalTextureBrowser().m_fixedsize_item.update();
2480         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2481 }
2482
2483 void TextureBrowser_FilterMissing(){
2484         g_TextureBrowser_filterMissing ^= 1;
2485         GlobalTextureBrowser().m_filternotex_item.update();
2486         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2487         TextureBrowser_RefreshShaders();
2488 }
2489
2490 void TextureBrowser_FilterFallback(){
2491         g_TextureBrowser_filterFallback ^= 1;
2492         GlobalTextureBrowser().m_hidenotex_item.update();
2493         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2494         TextureBrowser_RefreshShaders();
2495 }
2496
2497 void TextureBrowser_EnableAlpha(){
2498         g_TextureBrowser_enableAlpha ^= 1;
2499         GlobalTextureBrowser().m_enablealpha_item.update();
2500         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2501 }
2502
2503 void TextureBrowser_exportTitle( const ImportExportCallback<const char *>::Import_t& importer ){
2504         StringOutputStream buffer( 64 );
2505         buffer << "Textures: ";
2506         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2507                 buffer << g_TextureBrowser_currentDirectory.c_str();
2508         }
2509         else
2510         {
2511                 buffer << "all";
2512         }
2513         importer( buffer.c_str() );
2514 }
2515
2516
2517 void TextureScaleImport( TextureBrowser& textureBrowser, int value ){
2518         switch ( value )
2519         {
2520         case 0:
2521                 TextureBrowser_setScale( textureBrowser, 10 );
2522                 break;
2523         case 1:
2524                 TextureBrowser_setScale( textureBrowser, 25 );
2525                 break;
2526         case 2:
2527                 TextureBrowser_setScale( textureBrowser, 50 );
2528                 break;
2529         case 3:
2530                 TextureBrowser_setScale( textureBrowser, 100 );
2531                 break;
2532         case 4:
2533                 TextureBrowser_setScale( textureBrowser, 200 );
2534                 break;
2535         }
2536 }
2537 typedef ReferenceCaller<TextureBrowser, void(int), TextureScaleImport> TextureScaleImportCaller;
2538
2539 void TextureScaleExport( TextureBrowser& textureBrowser, const ImportExportCallback<int>::Import_t& importer ){
2540         switch ( textureBrowser.m_textureScale )
2541         {
2542         case 10:
2543                 importer( 0 );
2544                 break;
2545         case 25:
2546                 importer( 1 );
2547                 break;
2548         case 50:
2549                 importer( 2 );
2550                 break;
2551         case 100:
2552                 importer( 3 );
2553                 break;
2554         case 200:
2555                 importer( 4 );
2556                 break;
2557         }
2558 }
2559 typedef ReferenceCaller<TextureBrowser, void(const ImportExportCallback<int>::Import_t&), TextureScaleExport> TextureScaleExportCaller;
2560
2561
2562 void UniformTextureSizeImport( TextureBrowser& textureBrowser, int value ){
2563
2564         if ( value > 16 )
2565                 TextureBrowser_setUniformSize( textureBrowser, value );
2566 }
2567 typedef ReferenceCaller<TextureBrowser, void(int), UniformTextureSizeImport> UniformTextureSizeImportCaller;
2568
2569 void TextureBrowser_constructPreferences( PreferencesPage& page ){
2570         page.appendCheckBox(
2571                 "", "Texture scrollbar",
2572                 {TextureBrowserImportShowScrollbarCaller( GlobalTextureBrowser() ),
2573                 BoolExportCaller( GlobalTextureBrowser().m_showTextureScrollbar )}
2574                 );
2575         {
2576                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
2577                 page.appendCombo(
2578                         "Texture Thumbnail Scale",
2579                         STRING_ARRAY_RANGE( texture_scale ),
2580                         {ImportExportCallback<int>::Import_t( TextureScaleImportCaller( GlobalTextureBrowser() ) ),
2581                         ImportExportCallback<int>::Export_t( TextureScaleExportCaller( GlobalTextureBrowser() ) )}
2582                         );
2583         }
2584         page.appendSpinner(
2585                 "Texture Thumbnail Size",
2586                 GlobalTextureBrowser().m_uniformTextureSize,
2587                 GlobalTextureBrowser().m_uniformTextureSize,
2588                 16, 8192
2589         );
2590         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
2591         {
2592                 const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() };
2593                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
2594         }
2595 }
2596 void TextureBrowser_constructPage( PreferenceGroup& group ){
2597         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
2598         TextureBrowser_constructPreferences( page );
2599 }
2600 void TextureBrowser_registerPreferencesPage(){
2601         PreferencesDialog_addSettingsPage( makeCallbackF(TextureBrowser_constructPage) );
2602 }
2603
2604
2605 #include "preferencesystem.h"
2606 #include "stringio.h"
2607
2608 typedef ReferenceCaller<TextureBrowser, void(std::size_t), TextureBrowser_setScale> TextureBrowserSetScaleCaller;
2609
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",
2634                                                                                                  makeSizeStringImportCallback( TextureBrowserSetScaleCaller( g_TextureBrowser ) ),
2635                                                                                                  SizeExportStringCaller( g_TextureBrowser.m_textureScale )
2636                                                                                                  );
2637         GlobalPreferenceSystem().registerPreference( "UniformTextureSize",
2638                                                                                                  makeIntStringImportCallback(UniformTextureSizeImportCaller(g_TextureBrowser)),
2639                                                                                                  IntExportStringCaller(g_TextureBrowser.m_uniformTextureSize) );
2640         GlobalPreferenceSystem().registerPreference( "TextureScrollbar",
2641                                                                                                  makeBoolStringImportCallback( TextureBrowserImportShowScrollbarCaller( g_TextureBrowser ) ),
2642                                                                                                  BoolExportStringCaller( GlobalTextureBrowser().m_showTextureScrollbar )
2643                                                                                                  );
2644         GlobalPreferenceSystem().registerPreference( "ShowShaders", BoolImportStringCaller( GlobalTextureBrowser().m_showShaders ), BoolExportStringCaller( GlobalTextureBrowser().m_showShaders ) );
2645         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", BoolImportStringCaller( g_TextureBrowser_shaderlistOnly ), BoolExportStringCaller( g_TextureBrowser_shaderlistOnly ) );
2646         GlobalPreferenceSystem().registerPreference( "FixedSize", BoolImportStringCaller( g_TextureBrowser_fixedSize ), BoolExportStringCaller( g_TextureBrowser_fixedSize ) );
2647         GlobalPreferenceSystem().registerPreference( "FilterMissing", BoolImportStringCaller( g_TextureBrowser_filterMissing ), BoolExportStringCaller( g_TextureBrowser_filterMissing ) );
2648         GlobalPreferenceSystem().registerPreference( "EnableAlpha", BoolImportStringCaller( g_TextureBrowser_enableAlpha ), BoolExportStringCaller( g_TextureBrowser_enableAlpha ) );
2649         GlobalPreferenceSystem().registerPreference( "LoadShaders", IntImportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ), IntExportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ) );
2650         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", SizeImportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ), SizeExportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ) );
2651         GlobalPreferenceSystem().registerPreference( "SI_Colors0", Vector3ImportStringCaller( GlobalTextureBrowser().color_textureback ), Vector3ExportStringCaller( GlobalTextureBrowser().color_textureback ) );
2652
2653         g_TextureBrowser.shader = texdef_name_default();
2654
2655         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw>( g_TextureBrowser ) );
2656
2657         TextureBrowser_registerPreferencesPage();
2658
2659         GlobalShaderSystem().attach( g_ShadersObserver );
2660
2661         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
2662 }
2663 void TextureBrowser_Destroy(){
2664         GlobalShaderSystem().detach( g_ShadersObserver );
2665
2666         Textures_setModeChangedNotify( Callback<void()>() );
2667 }