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