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