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