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