summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichele Calgaro <michele.calgaro@yahoo.it>2021-05-23 20:48:35 +0900
committerMichele Calgaro <michele.calgaro@yahoo.it>2021-05-29 15:16:28 +0900
commit8b78a8791bc539bcffe7159f9d9714d577cb3d7d (patch)
tree1328291f966f19a22d7b13657d3f01a588eb1083
parent95834e2bdc5e01ae1bd21ac0dfa4fa1d2417fae9 (diff)
downloadkoffice-8b78a8791bc539bcffe7159f9d9714d577cb3d7d.tar.gz
koffice-8b78a8791bc539bcffe7159f9d9714d577cb3d7d.zip
Renaming of files in preparation for code style tools.
Signed-off-by: Michele Calgaro <michele.calgaro@yahoo.it>
-rw-r--r--chalk/Makefile.am12
-rw-r--r--chalk/chalk_part_init.cc23
-rw-r--r--chalk/chalk_part_init.cpp23
-rw-r--r--chalk/chalkcolor/Makefile.am12
-rw-r--r--chalk/chalkcolor/colorspaces/Makefile.am4
-rw-r--r--chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cpp (renamed from chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/colorspaces/kis_lab_colorspace.cpp (renamed from chalk/chalkcolor/colorspaces/kis_lab_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cpp (renamed from chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_abstract_colorspace.cpp (renamed from chalk/chalkcolor/kis_abstract_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_basic_histogram_producers.cpp (renamed from chalk/chalkcolor/kis_basic_histogram_producers.cc)0
-rw-r--r--chalk/chalkcolor/kis_color.cpp (renamed from chalk/chalkcolor/kis_color.cc)0
-rw-r--r--chalk/chalkcolor/kis_color_conversions.cpp (renamed from chalk/chalkcolor/kis_color_conversions.cc)0
-rw-r--r--chalk/chalkcolor/kis_colorspace.cpp (renamed from chalk/chalkcolor/kis_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_colorspace_factory_registry.cpp (renamed from chalk/chalkcolor/kis_colorspace_factory_registry.cc)0
-rw-r--r--chalk/chalkcolor/kis_colorspace_iface.cpp (renamed from chalk/chalkcolor/kis_colorspace_iface.cc)0
-rw-r--r--chalk/chalkcolor/kis_composite_op.cpp (renamed from chalk/chalkcolor/kis_composite_op.cc)0
-rw-r--r--chalk/chalkcolor/kis_f16half_base_colorspace.cpp (renamed from chalk/chalkcolor/kis_f16half_base_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_f32_base_colorspace.cpp (renamed from chalk/chalkcolor/kis_f32_base_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_histogram_producer.cpp (renamed from chalk/chalkcolor/kis_histogram_producer.cc)0
-rw-r--r--chalk/chalkcolor/kis_profile.cc208
-rw-r--r--chalk/chalkcolor/kis_profile.cpp208
-rw-r--r--chalk/chalkcolor/kis_u16_base_colorspace.cpp (renamed from chalk/chalkcolor/kis_u16_base_colorspace.cc)0
-rw-r--r--chalk/chalkcolor/kis_u8_base_colorspace.cpp (renamed from chalk/chalkcolor/kis_u8_base_colorspace.cc)0
-rw-r--r--chalk/colorspaces/cmyk_u16/Makefile.am4
-rw-r--r--chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cc61
-rw-r--r--chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cpp61
-rw-r--r--chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cpp (renamed from chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cc)0
-rw-r--r--chalk/colorspaces/cmyk_u8/Makefile.am2
-rw-r--r--chalk/colorspaces/cmyk_u8/cmyk_plugin.cc66
-rw-r--r--chalk/colorspaces/cmyk_u8/cmyk_plugin.cpp66
-rw-r--r--chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cpp (renamed from chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cc)0
-rw-r--r--chalk/colorspaces/gray_u16/Makefile.am4
-rw-r--r--chalk/colorspaces/gray_u16/gray_u16_plugin.cc63
-rw-r--r--chalk/colorspaces/gray_u16/gray_u16_plugin.cpp63
-rw-r--r--chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cpp (renamed from chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cc)0
-rw-r--r--chalk/colorspaces/gray_u8/Makefile.am4
-rw-r--r--chalk/colorspaces/gray_u8/gray_plugin.cc77
-rw-r--r--chalk/colorspaces/gray_u8/gray_plugin.cpp77
-rw-r--r--chalk/colorspaces/gray_u8/kis_gray_colorspace.cpp (renamed from chalk/colorspaces/gray_u8/kis_gray_colorspace.cc)0
-rw-r--r--chalk/colorspaces/lms_f32/Makefile.am4
-rw-r--r--chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cpp (renamed from chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cc)0
-rw-r--r--chalk/colorspaces/lms_f32/lms_f32_plugin.cc64
-rw-r--r--chalk/colorspaces/lms_f32/lms_f32_plugin.cpp64
-rw-r--r--chalk/colorspaces/rgb_f16half/Makefile.am4
-rw-r--r--chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cpp (renamed from chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cc)0
-rw-r--r--chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cc63
-rw-r--r--chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cpp63
-rw-r--r--chalk/colorspaces/rgb_f16half/tests/Makefile.am2
-rw-r--r--chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cpp (renamed from chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cc)0
-rw-r--r--chalk/colorspaces/rgb_f32/Makefile.am4
-rw-r--r--chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cpp (renamed from chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cc)0
-rw-r--r--chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.h2
-rw-r--r--chalk/colorspaces/rgb_f32/rgb_f32_plugin.cc63
-rw-r--r--chalk/colorspaces/rgb_f32/rgb_f32_plugin.cpp63
-rw-r--r--chalk/colorspaces/rgb_f32/tests/Makefile.am2
-rw-r--r--chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cpp (renamed from chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cc)0
-rw-r--r--chalk/colorspaces/rgb_u16/Makefile.am4
-rw-r--r--chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cpp (renamed from chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cc)0
-rw-r--r--chalk/colorspaces/rgb_u16/rgb_u16_plugin.cc61
-rw-r--r--chalk/colorspaces/rgb_u16/rgb_u16_plugin.cpp61
-rw-r--r--chalk/colorspaces/rgb_u16/tests/Makefile.am2
-rw-r--r--chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cpp (renamed from chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cc)0
-rw-r--r--chalk/colorspaces/rgb_u8/Makefile.am4
-rw-r--r--chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cpp (renamed from chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cc)0
-rw-r--r--chalk/colorspaces/rgb_u8/rgb_plugin.cc74
-rw-r--r--chalk/colorspaces/rgb_u8/rgb_plugin.cpp74
-rw-r--r--chalk/colorspaces/wet/Makefile.am4
-rw-r--r--chalk/colorspaces/wet/kis_texture_filter.cc43
-rw-r--r--chalk/colorspaces/wet/kis_texture_filter.cpp43
-rw-r--r--chalk/colorspaces/wet/kis_texture_painter.cpp (renamed from chalk/colorspaces/wet/kis_texture_painter.cc)0
-rw-r--r--chalk/colorspaces/wet/kis_wet_colorspace.cpp (renamed from chalk/colorspaces/wet/kis_wet_colorspace.cc)0
-rw-r--r--chalk/colorspaces/wet/kis_wet_palette_widget.cpp (renamed from chalk/colorspaces/wet/kis_wet_palette_widget.cc)0
-rw-r--r--chalk/colorspaces/wet/kis_wetness_visualisation_filter.cc77
-rw-r--r--chalk/colorspaces/wet/kis_wetness_visualisation_filter.cpp77
-rw-r--r--chalk/colorspaces/wet/kis_wetop.cpp (renamed from chalk/colorspaces/wet/kis_wetop.cc)0
-rw-r--r--chalk/colorspaces/wet/wet_plugin.cc128
-rw-r--r--chalk/colorspaces/wet/wet_plugin.cpp128
-rw-r--r--chalk/colorspaces/wet/wetphysicsfilter.cpp (renamed from chalk/colorspaces/wet/wetphysicsfilter.cc)0
-rw-r--r--chalk/colorspaces/wetsticky/Makefile.am2
-rw-r--r--chalk/colorspaces/wetsticky/brushop/Makefile.am4
-rw-r--r--chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cpp (renamed from chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cc)0
-rw-r--r--chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cc56
-rw-r--r--chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cpp56
-rw-r--r--chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cpp (renamed from chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cc)0
-rw-r--r--chalk/colorspaces/wetsticky/kis_ws_engine_filter.cpp (renamed from chalk/colorspaces/wetsticky/kis_ws_engine_filter.cc)0
-rw-r--r--chalk/colorspaces/wetsticky/wet_sticky_plugin.cc60
-rw-r--r--chalk/colorspaces/wetsticky/wet_sticky_plugin.cpp60
-rw-r--r--chalk/colorspaces/ycbcr_u16/Makefile.am4
-rw-r--r--chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cpp (renamed from chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cc)0
-rw-r--r--chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cc60
-rw-r--r--chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cpp60
-rw-r--r--chalk/colorspaces/ycbcr_u8/Makefile.am4
-rw-r--r--chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cpp (renamed from chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cc)0
-rw-r--r--chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cc62
-rw-r--r--chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cpp62
-rw-r--r--chalk/core/Makefile.am28
-rwxr-xr-xchalk/core/createdcop.py2
-rw-r--r--chalk/core/kis_adjustment_layer.cpp (renamed from chalk/core/kis_adjustment_layer.cc)0
-rw-r--r--chalk/core/kis_alpha_mask.cpp (renamed from chalk/core/kis_alpha_mask.cc)0
-rw-r--r--chalk/core/kis_autobrush_resource.cpp (renamed from chalk/core/kis_autobrush_resource.cc)0
-rw-r--r--chalk/core/kis_autogradient_resource.cc221
-rw-r--r--chalk/core/kis_autogradient_resource.cpp221
-rw-r--r--chalk/core/kis_background.cpp (renamed from chalk/core/kis_background.cc)0
-rw-r--r--chalk/core/kis_boundary.cpp (renamed from chalk/core/kis_boundary.cc)0
-rw-r--r--chalk/core/kis_brush.cpp (renamed from chalk/core/kis_brush.cc)0
-rw-r--r--chalk/core/kis_command.cpp (renamed from chalk/core/kis_command.cc)0
-rw-r--r--chalk/core/kis_convolution_painter.cpp (renamed from chalk/core/kis_convolution_painter.cc)0
-rw-r--r--chalk/core/kis_exif_info.cpp (renamed from chalk/core/kis_exif_info.cc)0
-rw-r--r--chalk/core/kis_exif_value.cpp (renamed from chalk/core/kis_exif_value.cc)0
-rw-r--r--chalk/core/kis_fill_painter.cpp (renamed from chalk/core/kis_fill_painter.cc)0
-rw-r--r--chalk/core/kis_filter.cpp (renamed from chalk/core/kis_filter.cc)0
-rw-r--r--chalk/core/kis_filter_config_widget.cpp (renamed from chalk/core/kis_filter_config_widget.cc)0
-rw-r--r--chalk/core/kis_filter_configuration.cpp (renamed from chalk/core/kis_filter_configuration.cc)0
-rw-r--r--chalk/core/kis_filter_registry.cpp (renamed from chalk/core/kis_filter_registry.cc)0
-rw-r--r--chalk/core/kis_filter_strategy.cpp (renamed from chalk/core/kis_filter_strategy.cc)0
-rw-r--r--chalk/core/kis_gradient.cc639
-rw-r--r--chalk/core/kis_gradient.cpp639
-rw-r--r--chalk/core/kis_gradient_painter.cpp (renamed from chalk/core/kis_gradient_painter.cc)0
-rw-r--r--chalk/core/kis_group_layer.cpp (renamed from chalk/core/kis_group_layer.cc)0
-rw-r--r--chalk/core/kis_histogram.cpp (renamed from chalk/core/kis_histogram.cc)0
-rw-r--r--chalk/core/kis_image.cpp (renamed from chalk/core/kis_image.cc)0
-rw-r--r--chalk/core/kis_image_iface.cpp (renamed from chalk/core/kis_image_iface.cc)0
-rw-r--r--chalk/core/kis_imagepipe_brush.cpp (renamed from chalk/core/kis_imagepipe_brush.cc)0
-rw-r--r--chalk/core/kis_iterator.cpp (renamed from chalk/core/kis_iterator.cc)0
-rw-r--r--chalk/core/kis_iterators_pixel.cpp (renamed from chalk/core/kis_iterators_pixel.cc)0
-rw-r--r--chalk/core/kis_layer.cpp (renamed from chalk/core/kis_layer.cc)0
-rw-r--r--chalk/core/kis_meta_registry.cpp (renamed from chalk/core/kis_meta_registry.cc)0
-rw-r--r--chalk/core/kis_nameserver.cpp (renamed from chalk/core/kis_nameserver.cc)0
-rw-r--r--chalk/core/kis_paint_device.cpp (renamed from chalk/core/kis_paint_device.cc)0
-rw-r--r--chalk/core/kis_paint_device_iface.cpp (renamed from chalk/core/kis_paint_device_iface.cc)0
-rw-r--r--chalk/core/kis_paint_layer.cpp (renamed from chalk/core/kis_paint_layer.cc)0
-rw-r--r--chalk/core/kis_painter.cpp (renamed from chalk/core/kis_painter.cc)0
-rw-r--r--chalk/core/kis_paintop.cpp (renamed from chalk/core/kis_paintop.cc)0
-rw-r--r--chalk/core/kis_paintop_registry.cpp (renamed from chalk/core/kis_paintop_registry.cc)0
-rw-r--r--chalk/core/kis_palette.cpp (renamed from chalk/core/kis_palette.cc)0
-rw-r--r--chalk/core/kis_pattern.cc335
-rw-r--r--chalk/core/kis_pattern.cpp335
-rw-r--r--chalk/core/kis_rect.cpp (renamed from chalk/core/kis_rect.cc)0
-rw-r--r--chalk/core/kis_resource.cpp (renamed from chalk/core/kis_resource.cc)0
-rw-r--r--chalk/core/kis_rotate_visitor.cpp (renamed from chalk/core/kis_rotate_visitor.cc)0
-rw-r--r--chalk/core/kis_scale_visitor.cpp (renamed from chalk/core/kis_scale_visitor.cc)0
-rw-r--r--chalk/core/kis_selected_transaction.cpp (renamed from chalk/core/kis_selected_transaction.cc)0
-rw-r--r--chalk/core/kis_selection.cpp (renamed from chalk/core/kis_selection.cc)0
-rw-r--r--chalk/core/kis_strategy_move.cpp (renamed from chalk/core/kis_strategy_move.cc)0
-rw-r--r--chalk/core/kis_thread_pool.cpp (renamed from chalk/core/kis_thread_pool.cc)0
-rw-r--r--chalk/core/kis_transaction.cpp (renamed from chalk/core/kis_transaction.cc)0
-rw-r--r--chalk/core/kis_transform_worker.cpp (renamed from chalk/core/kis_transform_worker.cc)0
-rw-r--r--chalk/core/kis_vec.cc67
-rw-r--r--chalk/core/kis_vec.cpp67
-rw-r--r--chalk/core/tests/Makefile.am2
-rw-r--r--chalk/core/tests/kis_filter_configuration_tester.cpp (renamed from chalk/core/tests/kis_filter_configuration_tester.cc)0
-rw-r--r--chalk/core/tiles/Makefile.am6
-rw-r--r--chalk/core/tiles/kis_memento.cpp (renamed from chalk/core/tiles/kis_memento.cc)0
-rw-r--r--chalk/core/tiles/kis_tile.cpp (renamed from chalk/core/tiles/kis_tile.cc)0
-rw-r--r--chalk/core/tiles/kis_tiled_random_accessor.cpp (renamed from chalk/core/tiles/kis_tiled_random_accessor.cc)0
-rw-r--r--chalk/core/tiles/kis_tileddatamanager.cpp (renamed from chalk/core/tiles/kis_tileddatamanager.cc)0
-rw-r--r--chalk/core/tiles/kis_tiledhlineiterator.cpp (renamed from chalk/core/tiles/kis_tiledhlineiterator.cc)0
-rw-r--r--chalk/core/tiles/kis_tilediterator.cpp (renamed from chalk/core/tiles/kis_tilediterator.cc)0
-rw-r--r--chalk/core/tiles/kis_tiledrectiterator.cpp (renamed from chalk/core/tiles/kis_tiledrectiterator.cc)0
-rw-r--r--chalk/core/tiles/kis_tiledvlineiterator.cpp (renamed from chalk/core/tiles/kis_tiledvlineiterator.cc)0
-rw-r--r--chalk/core/tiles/kis_tilemanager.cpp (renamed from chalk/core/tiles/kis_tilemanager.cc)0
-rw-r--r--chalk/doc/DESIGN.obsolete2
-rw-r--r--chalk/doc/brush.txt2
-rw-r--r--chalk/main.cc43
-rw-r--r--chalk/main.cpp43
-rw-r--r--chalk/plugins/filters/blur/Makefile.am2
-rw-r--r--chalk/plugins/filters/blur/blur.cpp (renamed from chalk/plugins/filters/blur/blur.cc)0
-rw-r--r--chalk/plugins/filters/blur/kis_blur_filter.cpp (renamed from chalk/plugins/filters/blur/kis_blur_filter.cc)0
-rw-r--r--chalk/plugins/filters/blur/kis_wdg_blur.cpp (renamed from chalk/plugins/filters/blur/kis_wdg_blur.cc)0
-rw-r--r--chalk/plugins/filters/bumpmap/Makefile.am2
-rw-r--r--chalk/plugins/filters/bumpmap/bumpmap.cpp (renamed from chalk/plugins/filters/bumpmap/bumpmap.cc)0
-rw-r--r--chalk/plugins/filters/cimg/Makefile.am6
-rw-r--r--chalk/plugins/filters/cimg/kis_cimg_filter.cpp (renamed from chalk/plugins/filters/cimg/kis_cimg_filter.cc)0
-rw-r--r--chalk/plugins/filters/cimg/kis_cimg_plugin.cpp (renamed from chalk/plugins/filters/cimg/kis_cimg_plugin.cc)0
-rw-r--r--chalk/plugins/filters/cimg/kis_cimgconfig_widget.cpp (renamed from chalk/plugins/filters/cimg/kis_cimgconfig_widget.cc)0
-rw-r--r--chalk/plugins/filters/colors/Makefile.am2
-rw-r--r--chalk/plugins/filters/colors/colors.cpp (renamed from chalk/plugins/filters/colors/colors.cc)0
-rw-r--r--chalk/plugins/filters/colors/kis_color_to_alpha.cpp (renamed from chalk/plugins/filters/colors/kis_color_to_alpha.cc)0
-rw-r--r--chalk/plugins/filters/colors/kis_minmax_filters.cpp (renamed from chalk/plugins/filters/colors/kis_minmax_filters.cc)0
-rw-r--r--chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cpp (renamed from chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cc)0
-rw-r--r--chalk/plugins/filters/colorsfilters/Makefile.am6
-rw-r--r--chalk/plugins/filters/colorsfilters/colorsfilters.cpp (renamed from chalk/plugins/filters/colorsfilters/colorsfilters.cc)0
-rw-r--r--chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cpp (renamed from chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cc)0
-rw-r--r--chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cpp (renamed from chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cc)0
-rw-r--r--chalk/plugins/filters/convolutionfilters/Makefile.am8
-rw-r--r--chalk/plugins/filters/convolutionfilters/convolutionfilters.cpp (renamed from chalk/plugins/filters/convolutionfilters/convolutionfilters.cc)0
-rw-r--r--chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cpp (renamed from chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cc)0
-rw-r--r--chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cpp (renamed from chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cc)0
-rw-r--r--chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cpp (renamed from chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cc)0
-rw-r--r--chalk/plugins/filters/cubismfilter/Makefile.am6
-rw-r--r--chalk/plugins/filters/cubismfilter/kis_cubism_filter.cpp (renamed from chalk/plugins/filters/cubismfilter/kis_cubism_filter.cc)0
-rw-r--r--chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cpp (renamed from chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/cubismfilter/kis_polygon.cpp (renamed from chalk/plugins/filters/cubismfilter/kis_polygon.cc)0
-rw-r--r--chalk/plugins/filters/embossfilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/embossfilter/kis_emboss_filter.cpp (renamed from chalk/plugins/filters/embossfilter/kis_emboss_filter.cc)0
-rw-r--r--chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cpp (renamed from chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/example/Makefile.am2
-rw-r--r--chalk/plugins/filters/example/example.cpp (renamed from chalk/plugins/filters/example/example.cc)0
-rw-r--r--chalk/plugins/filters/fastcolortransfer/Makefile.am2
-rw-r--r--chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cpp (renamed from chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cc)0
-rw-r--r--chalk/plugins/filters/lenscorrectionfilter/Makefile.am2
-rw-r--r--chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cpp (renamed from chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cc)0
-rw-r--r--chalk/plugins/filters/levelfilter/Makefile.am6
-rw-r--r--chalk/plugins/filters/levelfilter/kgradientslider.cpp (renamed from chalk/plugins/filters/levelfilter/kgradientslider.cc)0
-rw-r--r--chalk/plugins/filters/levelfilter/kis_level_filter.cpp (renamed from chalk/plugins/filters/levelfilter/kis_level_filter.cc)0
-rw-r--r--chalk/plugins/filters/levelfilter/levelfilter.cpp (renamed from chalk/plugins/filters/levelfilter/levelfilter.cc)0
-rw-r--r--chalk/plugins/filters/noisefilter/Makefile.am2
-rw-r--r--chalk/plugins/filters/noisefilter/noisefilter.cpp (renamed from chalk/plugins/filters/noisefilter/noisefilter.cc)0
-rw-r--r--chalk/plugins/filters/oilpaintfilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cpp (renamed from chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cc)0
-rw-r--r--chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cpp (renamed from chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/pixelizefilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cpp (renamed from chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cc)0
-rw-r--r--chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cpp (renamed from chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/raindropsfilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cpp (renamed from chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cc)0
-rw-r--r--chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cpp (renamed from chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/randompickfilter/Makefile.am2
-rw-r--r--chalk/plugins/filters/randompickfilter/randompickfilter.cpp (renamed from chalk/plugins/filters/randompickfilter/randompickfilter.cc)0
-rw-r--r--chalk/plugins/filters/roundcorners/Makefile.am4
-rw-r--r--chalk/plugins/filters/roundcorners/kis_round_corners_filter.cpp (renamed from chalk/plugins/filters/roundcorners/kis_round_corners_filter.cc)0
-rw-r--r--chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cpp (renamed from chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/smalltilesfilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cpp (renamed from chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cc)0
-rw-r--r--chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cpp (renamed from chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/sobelfilter/Makefile.am4
-rw-r--r--chalk/plugins/filters/sobelfilter/kis_sobel_filter.cpp (renamed from chalk/plugins/filters/sobelfilter/kis_sobel_filter.cc)0
-rw-r--r--chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cpp (renamed from chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cc)0
-rw-r--r--chalk/plugins/filters/threadtest/Makefile.am2
-rw-r--r--chalk/plugins/filters/threadtest/threadtest.cpp (renamed from chalk/plugins/filters/threadtest/threadtest.cc)0
-rw-r--r--chalk/plugins/filters/unsharp/Makefile.am2
-rw-r--r--chalk/plugins/filters/unsharp/kis_unsharp_filter.cpp (renamed from chalk/plugins/filters/unsharp/kis_unsharp_filter.cc)0
-rw-r--r--chalk/plugins/filters/unsharp/kis_wdg_unsharp.cpp (renamed from chalk/plugins/filters/unsharp/kis_wdg_unsharp.cc)0
-rw-r--r--chalk/plugins/filters/unsharp/unsharp.cpp (renamed from chalk/plugins/filters/unsharp/unsharp.cc)0
-rw-r--r--chalk/plugins/filters/wavefilter/Makefile.am2
-rw-r--r--chalk/plugins/filters/wavefilter/wavefilter.cpp (renamed from chalk/plugins/filters/wavefilter/wavefilter.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/Makefile.am14
-rw-r--r--chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cc70
-rw-r--r--chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cpp70
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_brushop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_brushop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_convolveop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_convolveop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_eraseop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_eraseop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_penop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_penop.cc)0
-rw-r--r--chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cpp (renamed from chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cc)0
-rw-r--r--chalk/plugins/tools/defaulttools/Makefile.am26
-rw-r--r--chalk/plugins/tools/defaulttools/default_tools.cc88
-rw-r--r--chalk/plugins/tools/defaulttools/default_tools.cpp88
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_brush.cc167
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_brush.cpp167
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cpp (renamed from chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cc)0
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_duplicate.cc255
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_duplicate.cpp255
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_ellipse.cc186
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_ellipse.cpp186
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_fill.cc233
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_fill.cpp233
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_gradient.cc309
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_gradient.cpp309
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_line.cc254
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_line.cpp254
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_move.cpp (renamed from chalk/plugins/tools/defaulttools/kis_tool_move.cc)0
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_pan.cpp (renamed from chalk/plugins/tools/defaulttools/kis_tool_pan.cc)0
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_rectangle.cc187
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_rectangle.cpp187
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_text.cpp (renamed from chalk/plugins/tools/defaulttools/kis_tool_text.cc)0
-rw-r--r--chalk/plugins/tools/defaulttools/kis_tool_zoom.cpp (renamed from chalk/plugins/tools/defaulttools/kis_tool_zoom.cc)0
-rw-r--r--chalk/plugins/tools/selectiontools/Makefile.am8
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_move_selection.cpp (renamed from chalk/plugins/tools/selectiontools/kis_tool_move_selection.cc)0
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_brush.cc168
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_brush.cpp168
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cpp (renamed from chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cc)0
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cc321
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cpp321
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cc156
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cpp156
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_outline.cpp (renamed from chalk/plugins/tools/selectiontools/kis_tool_select_outline.cc)0
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cpp (renamed from chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cc)0
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cc323
-rw-r--r--chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cpp323
-rw-r--r--chalk/plugins/tools/selectiontools/selection_tools.cc77
-rw-r--r--chalk/plugins/tools/selectiontools/selection_tools.cpp77
-rw-r--r--chalk/plugins/tools/tool_crop/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_crop/kis_tool_crop.cc925
-rw-r--r--chalk/plugins/tools/tool_crop/kis_tool_crop.cpp925
-rw-r--r--chalk/plugins/tools/tool_crop/tool_crop.cc62
-rw-r--r--chalk/plugins/tools/tool_crop/tool_crop.cpp62
-rw-r--r--chalk/plugins/tools/tool_curves/Makefile.am16
-rw-r--r--chalk/plugins/tools/tool_curves/kis_curve_framework.cpp (renamed from chalk/plugins/tools/tool_curves/kis_curve_framework.cc)0
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier.cc366
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier.cpp366
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cc115
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cpp115
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cc104
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cpp104
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_curve.cc593
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_curve.cpp593
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_example.cc108
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_example.cpp108
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_moutline.cc809
-rw-r--r--chalk/plugins/tools/tool_curves/kis_tool_moutline.cpp809
-rw-r--r--chalk/plugins/tools/tool_curves/tool_curves.cc67
-rw-r--r--chalk/plugins/tools/tool_curves/tool_curves.cpp67
-rw-r--r--chalk/plugins/tools/tool_filter/Makefile.am6
-rw-r--r--chalk/plugins/tools/tool_filter/kis_filterop.cpp (renamed from chalk/plugins/tools/tool_filter/kis_filterop.cc)0
-rw-r--r--chalk/plugins/tools/tool_filter/kis_tool_filter.cc154
-rw-r--r--chalk/plugins/tools/tool_filter/kis_tool_filter.cpp154
-rw-r--r--chalk/plugins/tools/tool_filter/tool_filter.cc68
-rw-r--r--chalk/plugins/tools/tool_filter/tool_filter.cpp68
-rw-r--r--chalk/plugins/tools/tool_perspectivegrid/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cc499
-rw-r--r--chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cpp499
-rw-r--r--chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cc62
-rw-r--r--chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cpp62
-rw-r--r--chalk/plugins/tools/tool_perspectivetransform/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cc742
-rw-r--r--chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cpp742
-rw-r--r--chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cc63
-rw-r--r--chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cpp63
-rw-r--r--chalk/plugins/tools/tool_polygon/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_polygon/kis_tool_polygon.cc252
-rw-r--r--chalk/plugins/tools/tool_polygon/kis_tool_polygon.cpp252
-rw-r--r--chalk/plugins/tools/tool_polygon/tool_polygon.cc62
-rw-r--r--chalk/plugins/tools/tool_polygon/tool_polygon.cpp62
-rw-r--r--chalk/plugins/tools/tool_polyline/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_polyline/kis_tool_polyline.cc271
-rw-r--r--chalk/plugins/tools/tool_polyline/kis_tool_polyline.cpp271
-rw-r--r--chalk/plugins/tools/tool_polyline/tool_polyline.cc64
-rw-r--r--chalk/plugins/tools/tool_polyline/tool_polyline.cpp64
-rw-r--r--chalk/plugins/tools/tool_selectsimilar/Makefile.am2
-rw-r--r--chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cpp (renamed from chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cc)0
-rw-r--r--chalk/plugins/tools/tool_selectsimilar/selectsimilar.cpp (renamed from chalk/plugins/tools/tool_selectsimilar/selectsimilar.cc)0
-rw-r--r--chalk/plugins/tools/tool_star/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_star/kis_tool_star.cc245
-rw-r--r--chalk/plugins/tools/tool_star/kis_tool_star.cpp245
-rw-r--r--chalk/plugins/tools/tool_star/tool_star.cc62
-rw-r--r--chalk/plugins/tools/tool_star/tool_star.cpp62
-rw-r--r--chalk/plugins/tools/tool_transform/Makefile.am4
-rw-r--r--chalk/plugins/tools/tool_transform/kis_tool_transform.cc916
-rw-r--r--chalk/plugins/tools/tool_transform/kis_tool_transform.cpp916
-rw-r--r--chalk/plugins/tools/tool_transform/tool_transform.cc64
-rw-r--r--chalk/plugins/tools/tool_transform/tool_transform.cpp64
-rw-r--r--chalk/plugins/viewplugins/colorrange/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/colorrange/colorrange.cpp (renamed from chalk/plugins/viewplugins/colorrange/colorrange.cc)0
-rw-r--r--chalk/plugins/viewplugins/colorrange/dlg_colorrange.cc351
-rw-r--r--chalk/plugins/viewplugins/colorrange/dlg_colorrange.cpp351
-rw-r--r--chalk/plugins/viewplugins/colorspaceconversion/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cc155
-rw-r--r--chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cpp155
-rw-r--r--chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cc91
-rw-r--r--chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cpp91
-rw-r--r--chalk/plugins/viewplugins/dropshadow/Makefile.am4
-rw-r--r--chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cc117
-rw-r--r--chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cpp117
-rw-r--r--chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cpp (renamed from chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cc)0
-rw-r--r--chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cpp (renamed from chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cc)0
-rw-r--r--chalk/plugins/viewplugins/filtersgallery/Makefile.am4
-rw-r--r--chalk/plugins/viewplugins/filtersgallery/filters_gallery.cpp (renamed from chalk/plugins/viewplugins/filtersgallery/filters_gallery.cc)0
-rw-r--r--chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cpp (renamed from chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/histogram/dlg_histogram.cc68
-rw-r--r--chalk/plugins/viewplugins/histogram/dlg_histogram.cpp68
-rw-r--r--chalk/plugins/viewplugins/histogram/histogram.cpp (renamed from chalk/plugins/viewplugins/histogram/histogram.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram/kis_histogram_widget.cpp (renamed from chalk/plugins/viewplugins/histogram/kis_histogram_widget.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram_docker/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/histogram_docker/histogramdocker.cpp (renamed from chalk/plugins/viewplugins/histogram_docker/histogramdocker.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cpp (renamed from chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cpp (renamed from chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cc)0
-rw-r--r--chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cpp (renamed from chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cc)0
-rw-r--r--chalk/plugins/viewplugins/history_docker/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/history_docker/historydocker.cpp (renamed from chalk/plugins/viewplugins/history_docker/historydocker.cc)0
-rw-r--r--chalk/plugins/viewplugins/imagesize/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/imagesize/dlg_imagesize.cc277
-rw-r--r--chalk/plugins/viewplugins/imagesize/dlg_imagesize.cpp277
-rw-r--r--chalk/plugins/viewplugins/imagesize/dlg_layersize.cc261
-rw-r--r--chalk/plugins/viewplugins/imagesize/dlg_layersize.cpp261
-rw-r--r--chalk/plugins/viewplugins/imagesize/imagesize.cc190
-rw-r--r--chalk/plugins/viewplugins/imagesize/imagesize.cpp190
-rw-r--r--chalk/plugins/viewplugins/modify_selection/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cc76
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cpp76
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cc76
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cpp76
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cc81
-rw-r--r--chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cpp81
-rw-r--r--chalk/plugins/viewplugins/modify_selection/modify_selection.cc158
-rw-r--r--chalk/plugins/viewplugins/modify_selection/modify_selection.cpp158
-rw-r--r--chalk/plugins/viewplugins/performancetest/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/performancetest/dlg_perftest.cc110
-rw-r--r--chalk/plugins/viewplugins/performancetest/dlg_perftest.cpp110
-rw-r--r--chalk/plugins/viewplugins/performancetest/perftest.cc1198
-rw-r--r--chalk/plugins/viewplugins/performancetest/perftest.cpp1198
-rw-r--r--chalk/plugins/viewplugins/rotateimage/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cc147
-rw-r--r--chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cpp147
-rw-r--r--chalk/plugins/viewplugins/rotateimage/rotateimage.cc134
-rw-r--r--chalk/plugins/viewplugins/rotateimage/rotateimage.cpp134
-rw-r--r--chalk/plugins/viewplugins/scripting/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/scripting/scripting.cpp (renamed from chalk/plugins/viewplugins/scripting/scripting.cc)0
-rw-r--r--chalk/plugins/viewplugins/selectopaque/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/selectopaque/selectopaque.cpp (renamed from chalk/plugins/viewplugins/selectopaque/selectopaque.cc)0
-rw-r--r--chalk/plugins/viewplugins/separate_channels/Makefile.am4
-rw-r--r--chalk/plugins/viewplugins/separate_channels/dlg_separate.cc110
-rw-r--r--chalk/plugins/viewplugins/separate_channels/dlg_separate.cpp110
-rw-r--r--chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cpp (renamed from chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cc)0
-rw-r--r--chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cpp (renamed from chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cc)0
-rw-r--r--chalk/plugins/viewplugins/shearimage/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/shearimage/dlg_shearimage.cc96
-rw-r--r--chalk/plugins/viewplugins/shearimage/dlg_shearimage.cpp96
-rw-r--r--chalk/plugins/viewplugins/shearimage/shearimage.cc113
-rw-r--r--chalk/plugins/viewplugins/shearimage/shearimage.cpp113
-rw-r--r--chalk/plugins/viewplugins/substrate/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/substrate/dlg_substrate.cc59
-rw-r--r--chalk/plugins/viewplugins/substrate/dlg_substrate.cpp59
-rw-r--r--chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cpp (renamed from chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cc)0
-rw-r--r--chalk/plugins/viewplugins/substrate/substrate.cpp (renamed from chalk/plugins/viewplugins/substrate/substrate.cc)0
-rw-r--r--chalk/plugins/viewplugins/variations/Makefile.am2
-rw-r--r--chalk/plugins/viewplugins/variations/dlg_variations.cc58
-rw-r--r--chalk/plugins/viewplugins/variations/dlg_variations.cpp58
-rw-r--r--chalk/plugins/viewplugins/variations/variations.cpp (renamed from chalk/plugins/viewplugins/variations/variations.cc)0
-rw-r--r--chalk/sdk/Makefile.am2
-rw-r--r--chalk/sdk/kis_progress_subject.cpp (renamed from chalk/sdk/kis_progress_subject.cc)0
-rw-r--r--chalk/ui/Makefile.am44
-rw-r--r--chalk/ui/imageviewer.cpp (renamed from chalk/ui/imageviewer.cc)0
-rw-r--r--chalk/ui/kcurve.cpp (renamed from chalk/ui/kcurve.cc)0
-rw-r--r--chalk/ui/kis_autobrush.cpp (renamed from chalk/ui/kis_autobrush.cc)0
-rw-r--r--chalk/ui/kis_autogradient.cpp (renamed from chalk/ui/kis_autogradient.cc)0
-rw-r--r--chalk/ui/kis_birdeye_box.cpp (renamed from chalk/ui/kis_birdeye_box.cc)0
-rw-r--r--chalk/ui/kis_boundary_painter.cpp (renamed from chalk/ui/kis_boundary_painter.cc)0
-rw-r--r--chalk/ui/kis_brush_chooser.cpp (renamed from chalk/ui/kis_brush_chooser.cc)0
-rw-r--r--chalk/ui/kis_canvas.cpp (renamed from chalk/ui/kis_canvas.cc)0
-rw-r--r--chalk/ui/kis_canvas_painter.cpp (renamed from chalk/ui/kis_canvas_painter.cc)0
-rw-r--r--chalk/ui/kis_clipboard.cpp (renamed from chalk/ui/kis_clipboard.cc)0
-rw-r--r--chalk/ui/kis_cmb_composite.cc88
-rw-r--r--chalk/ui/kis_cmb_composite.cpp88
-rw-r--r--chalk/ui/kis_cmb_idlist.cc97
-rw-r--r--chalk/ui/kis_cmb_idlist.cpp97
-rw-r--r--chalk/ui/kis_color_cup.cpp (renamed from chalk/ui/kis_color_cup.cc)0
-rw-r--r--chalk/ui/kis_config.cpp (renamed from chalk/ui/kis_config.cc)0
-rw-r--r--chalk/ui/kis_controlframe.cc343
-rw-r--r--chalk/ui/kis_controlframe.cpp343
-rw-r--r--chalk/ui/kis_cursor.cc374
-rw-r--r--chalk/ui/kis_cursor.cpp374
-rw-r--r--chalk/ui/kis_custom_brush.cpp (renamed from chalk/ui/kis_custom_brush.cc)0
-rw-r--r--chalk/ui/kis_custom_image_widget.cpp (renamed from chalk/ui/kis_custom_image_widget.cc)0
-rw-r--r--chalk/ui/kis_custom_palette.cpp (renamed from chalk/ui/kis_custom_palette.cc)0
-rw-r--r--chalk/ui/kis_custom_pattern.cpp (renamed from chalk/ui/kis_custom_pattern.cc)0
-rw-r--r--chalk/ui/kis_dlg_adj_layer_props.cpp (renamed from chalk/ui/kis_dlg_adj_layer_props.cc)0
-rw-r--r--chalk/ui/kis_dlg_adjustment_layer.cpp (renamed from chalk/ui/kis_dlg_adjustment_layer.cc)0
-rw-r--r--chalk/ui/kis_dlg_apply_profile.cpp (renamed from chalk/ui/kis_dlg_apply_profile.cc)0
-rw-r--r--chalk/ui/kis_dlg_image_properties.cpp (renamed from chalk/ui/kis_dlg_image_properties.cc)0
-rw-r--r--chalk/ui/kis_dlg_layer_properties.cpp (renamed from chalk/ui/kis_dlg_layer_properties.cc)0
-rw-r--r--chalk/ui/kis_dlg_new_layer.cpp (renamed from chalk/ui/kis_dlg_new_layer.cc)0
-rw-r--r--chalk/ui/kis_dlg_preferences.cc821
-rw-r--r--chalk/ui/kis_dlg_preferences.cpp821
-rw-r--r--chalk/ui/kis_doc.cpp (renamed from chalk/ui/kis_doc.cc)0
-rw-r--r--chalk/ui/kis_doc_iface.cpp (renamed from chalk/ui/kis_doc_iface.cc)0
-rw-r--r--chalk/ui/kis_double_widget.cc147
-rw-r--r--chalk/ui/kis_double_widget.cpp147
-rw-r--r--chalk/ui/kis_factory.cc153
-rw-r--r--chalk/ui/kis_factory.cpp153
-rw-r--r--chalk/ui/kis_filter_manager.cpp (renamed from chalk/ui/kis_filter_manager.cc)0
-rw-r--r--chalk/ui/kis_filters_listview.cpp (renamed from chalk/ui/kis_filters_listview.cc)0
-rw-r--r--chalk/ui/kis_gradient_chooser.cpp (renamed from chalk/ui/kis_gradient_chooser.cc)0
-rw-r--r--chalk/ui/kis_gradient_slider_widget.cpp (renamed from chalk/ui/kis_gradient_slider_widget.cc)0
-rw-r--r--chalk/ui/kis_histogram_view.cpp (renamed from chalk/ui/kis_histogram_view.cc)0
-rw-r--r--chalk/ui/kis_icon_item.cpp (renamed from chalk/ui/kis_icon_item.cc)0
-rw-r--r--chalk/ui/kis_iconwidget.cpp (renamed from chalk/ui/kis_iconwidget.cc)0
-rw-r--r--chalk/ui/kis_import_catcher.cpp (renamed from chalk/ui/kis_import_catcher.cc)0
-rw-r--r--chalk/ui/kis_input_device.cpp (renamed from chalk/ui/kis_input_device.cc)0
-rw-r--r--chalk/ui/kis_int_spinbox.cpp (renamed from chalk/ui/kis_int_spinbox.cc)0
-rw-r--r--chalk/ui/kis_itemchooser.cpp (renamed from chalk/ui/kis_itemchooser.cc)0
-rw-r--r--chalk/ui/kis_label_cursor_pos.cpp (renamed from chalk/ui/kis_label_cursor_pos.cc)0
-rw-r--r--chalk/ui/kis_label_progress.cpp (renamed from chalk/ui/kis_label_progress.cc)0
-rw-r--r--chalk/ui/kis_label_zoom.cpp (renamed from chalk/ui/kis_label_zoom.cc)0
-rw-r--r--chalk/ui/kis_layerbox.cc675
-rw-r--r--chalk/ui/kis_layerbox.cpp675
-rw-r--r--chalk/ui/kis_layerlist.cpp (renamed from chalk/ui/kis_layerlist.cc)0
-rw-r--r--chalk/ui/kis_multi_bool_filter_widget.cpp (renamed from chalk/ui/kis_multi_bool_filter_widget.cc)0
-rw-r--r--chalk/ui/kis_multi_double_filter_widget.cpp (renamed from chalk/ui/kis_multi_double_filter_widget.cc)0
-rw-r--r--chalk/ui/kis_multi_integer_filter_widget.cpp (renamed from chalk/ui/kis_multi_integer_filter_widget.cc)0
-rw-r--r--chalk/ui/kis_opengl_canvas.cpp (renamed from chalk/ui/kis_opengl_canvas.cc)0
-rw-r--r--chalk/ui/kis_opengl_canvas_painter.cpp (renamed from chalk/ui/kis_opengl_canvas_painter.cc)0
-rw-r--r--chalk/ui/kis_opengl_image_context.cpp (renamed from chalk/ui/kis_opengl_image_context.cc)0
-rw-r--r--chalk/ui/kis_paintop_box.cc249
-rw-r--r--chalk/ui/kis_paintop_box.cpp249
-rw-r--r--chalk/ui/kis_palette_view.cpp (renamed from chalk/ui/kis_palette_view.cc)0
-rw-r--r--chalk/ui/kis_palette_widget.cpp (renamed from chalk/ui/kis_palette_widget.cc)0
-rw-r--r--chalk/ui/kis_part_layer.cpp (renamed from chalk/ui/kis_part_layer.cc)0
-rw-r--r--chalk/ui/kis_part_layer_handler.cpp (renamed from chalk/ui/kis_part_layer_handler.cc)0
-rw-r--r--chalk/ui/kis_pattern_chooser.cpp (renamed from chalk/ui/kis_pattern_chooser.cc)0
-rw-r--r--chalk/ui/kis_previewdialog.cc46
-rw-r--r--chalk/ui/kis_previewdialog.cpp46
-rw-r--r--chalk/ui/kis_previewwidget.cc409
-rw-r--r--chalk/ui/kis_previewwidget.cpp409
-rw-r--r--chalk/ui/kis_qpaintdevice_canvas.cpp (renamed from chalk/ui/kis_qpaintdevice_canvas.cc)0
-rw-r--r--chalk/ui/kis_qpaintdevice_canvas_painter.cpp (renamed from chalk/ui/kis_qpaintdevice_canvas_painter.cc)0
-rw-r--r--chalk/ui/kis_resource_mediator.cpp (renamed from chalk/ui/kis_resource_mediator.cc)0
-rw-r--r--chalk/ui/kis_resourceserver.cc199
-rw-r--r--chalk/ui/kis_resourceserver.cpp199
-rw-r--r--chalk/ui/kis_ruler.cpp (renamed from chalk/ui/kis_ruler.cc)0
-rw-r--r--chalk/ui/kis_selection_manager.cpp (renamed from chalk/ui/kis_selection_manager.cc)0
-rw-r--r--chalk/ui/kis_selection_options.cpp (renamed from chalk/ui/kis_selection_options.cc)0
-rw-r--r--chalk/ui/kis_text_brush.cpp (renamed from chalk/ui/kis_text_brush.cc)0
-rw-r--r--chalk/ui/kis_tool.cpp (renamed from chalk/ui/kis_tool.cc)0
-rw-r--r--chalk/ui/kis_tool_dummy.cpp (renamed from chalk/ui/kis_tool_dummy.cc)0
-rw-r--r--chalk/ui/kis_tool_freehand.cc354
-rw-r--r--chalk/ui/kis_tool_freehand.cpp354
-rw-r--r--chalk/ui/kis_tool_manager.cpp (renamed from chalk/ui/kis_tool_manager.cc)0
-rw-r--r--chalk/ui/kis_tool_non_paint.cpp (renamed from chalk/ui/kis_tool_non_paint.cc)0
-rw-r--r--chalk/ui/kis_tool_paint.cpp (renamed from chalk/ui/kis_tool_paint.cc)0
-rw-r--r--chalk/ui/kis_tool_registry.cpp (renamed from chalk/ui/kis_tool_registry.cc)0
-rw-r--r--chalk/ui/kis_tool_shape.cpp (renamed from chalk/ui/kis_tool_shape.cc)0
-rw-r--r--chalk/ui/kis_view.cpp (renamed from chalk/ui/kis_view.cc)0
-rw-r--r--chalk/ui/kis_view_iface.cpp (renamed from chalk/ui/kis_view_iface.cc)0
-rw-r--r--doc/chalk/developers-plugins.docbook8
-rw-r--r--example/Makefile.am8
-rw-r--r--example/example_factory.cpp (renamed from example/example_factory.cc)0
-rw-r--r--example/example_part.cpp (renamed from example/example_part.cc)0
-rw-r--r--example/example_view.cpp (renamed from example/example_view.cc)0
-rw-r--r--example/main.cpp (renamed from example/main.cc)0
-rw-r--r--filters/Makefile.am2
-rw-r--r--filters/chalk/gmagick/Makefile.am4
-rw-r--r--filters/chalk/gmagick/kis_image_magick_converter.cpp (renamed from filters/chalk/gmagick/kis_image_magick_converter.cc)0
-rw-r--r--filters/chalk/jpeg/Makefile.am6
-rw-r--r--filters/chalk/jpeg/kis_jpeg_converter.cpp (renamed from filters/chalk/jpeg/kis_jpeg_converter.cc)0
-rw-r--r--filters/chalk/jpeg/kis_jpeg_export.cpp (renamed from filters/chalk/jpeg/kis_jpeg_export.cc)0
-rw-r--r--filters/chalk/jpeg/kis_jpeg_import.cpp (renamed from filters/chalk/jpeg/kis_jpeg_import.cc)0
-rw-r--r--filters/chalk/magick/Makefile.am4
-rw-r--r--filters/chalk/magick/kis_image_magick_converter.cpp (renamed from filters/chalk/magick/kis_image_magick_converter.cc)0
-rw-r--r--filters/chalk/png/Makefile.am4
-rw-r--r--filters/chalk/png/kis_png_converter.cpp (renamed from filters/chalk/png/kis_png_converter.cc)0
-rw-r--r--filters/chalk/png/kis_png_export.cpp (renamed from filters/chalk/png/kis_png_export.cc)0
-rw-r--r--filters/chalk/png/kis_png_import.cpp (renamed from filters/chalk/png/kis_png_import.cc)0
-rw-r--r--filters/chalk/tiff/Makefile.am8
-rw-r--r--filters/chalk/tiff/kis_tiff_converter.cpp (renamed from filters/chalk/tiff/kis_tiff_converter.cc)0
-rw-r--r--filters/chalk/tiff/kis_tiff_export.cpp (renamed from filters/chalk/tiff/kis_tiff_export.cc)0
-rw-r--r--filters/chalk/tiff/kis_tiff_import.cpp (renamed from filters/chalk/tiff/kis_tiff_import.cc)0
-rw-r--r--filters/chalk/tiff/kis_tiff_reader.cpp (renamed from filters/chalk/tiff/kis_tiff_reader.cc)0
-rw-r--r--filters/chalk/tiff/kis_tiff_stream.cpp (renamed from filters/chalk/tiff/kis_tiff_stream.cc)0
-rw-r--r--filters/chalk/tiff/kis_tiff_ycbcr_reader.cpp (renamed from filters/chalk/tiff/kis_tiff_ycbcr_reader.cc)0
-rw-r--r--filters/chalk/xcf/xcf/xcf-load.cpp (renamed from filters/chalk/xcf/xcf/xcf-load.cc)0
-rw-r--r--filters/chalk/xcf/xcf/xcf-read.cpp (renamed from filters/chalk/xcf/xcf/xcf-read.cc)0
-rw-r--r--filters/chalk/xcf/xcf/xcf-save.cpp (renamed from filters/chalk/xcf/xcf/xcf-save.cc)0
-rw-r--r--filters/chalk/xcf/xcf/xcf-seek.cpp (renamed from filters/chalk/xcf/xcf/xcf-seek.cc)0
-rw-r--r--filters/chalk/xcf/xcf/xcf-write.cpp (renamed from filters/chalk/xcf/xcf/xcf-write.cc)0
-rw-r--r--filters/generic_wrapper/Makefile.am2
-rw-r--r--filters/generic_wrapper/generic_filter.cpp (renamed from filters/generic_wrapper/generic_filter.cc)0
-rw-r--r--filters/karbon/ai/Makefile.am16
-rw-r--r--filters/karbon/ai/ai3handler.cpp (renamed from filters/karbon/ai/ai3handler.cc)0
-rw-r--r--filters/karbon/ai/ai88handler.cpp (renamed from filters/karbon/ai/ai88handler.cc)0
-rw-r--r--filters/karbon/ai/aicolor.cpp (renamed from filters/karbon/ai/aicolor.cc)0
-rw-r--r--filters/karbon/ai/aielement.cpp (renamed from filters/karbon/ai/aielement.cc)0
-rw-r--r--filters/karbon/ai/aiimport.cpp (renamed from filters/karbon/ai/aiimport.cc)0
-rw-r--r--filters/karbon/ai/ailexer.cpp (renamed from filters/karbon/ai/ailexer.cc)0
-rw-r--r--filters/karbon/ai/aiparserbase.cpp (renamed from filters/karbon/ai/aiparserbase.cc)0
-rw-r--r--filters/karbon/ai/karbonaiparserbase.cpp (renamed from filters/karbon/ai/karbonaiparserbase.cc)0
-rw-r--r--filters/karbon/applixgraphics/Makefile.am4
-rw-r--r--filters/karbon/applixgraphics/applixgraphicimport.cpp (renamed from filters/karbon/applixgraphics/applixgraphicimport.cc)0
-rw-r--r--filters/karbon/eps/Makefile.am6
-rw-r--r--filters/karbon/eps/epsexport.cpp (renamed from filters/karbon/eps/epsexport.cc)0
-rw-r--r--filters/karbon/eps/epsexportdlg.cpp (renamed from filters/karbon/eps/epsexportdlg.cc)0
-rw-r--r--filters/karbon/eps/epsimport.cpp (renamed from filters/karbon/eps/epsimport.cc)0
-rw-r--r--filters/karbon/eps/pscommentlexer.cpp (renamed from filters/karbon/eps/pscommentlexer.cc)0
-rw-r--r--filters/karbon/kontour/Makefile.am2
-rw-r--r--filters/karbon/msod/Makefile.am2
-rw-r--r--filters/karbon/msod/msod.cpp (renamed from filters/karbon/msod/msod.cc)0
-rw-r--r--filters/karbon/msod/msodimport.cpp (renamed from filters/karbon/msod/msodimport.cc)0
-rw-r--r--filters/karbon/oodraw/Makefile.am2
-rw-r--r--filters/karbon/oodraw/oodrawimport.cpp (renamed from filters/karbon/oodraw/oodrawimport.cc)0
-rw-r--r--filters/karbon/png/Makefile.am2
-rw-r--r--filters/karbon/png/pngexport.cpp (renamed from filters/karbon/png/pngexport.cc)0
-rw-r--r--filters/karbon/svg/Makefile.am4
-rw-r--r--filters/karbon/svg/svgexport.cpp (renamed from filters/karbon/svg/svgexport.cc)0
-rw-r--r--filters/karbon/svg/svgimport.cpp (renamed from filters/karbon/svg/svgimport.cc)0
-rw-r--r--filters/karbon/wmf/Makefile.am4
-rw-r--r--filters/karbon/wmf/wmfexport.cpp (renamed from filters/karbon/wmf/wmfexport.cc)0
-rw-r--r--filters/karbon/wmf/wmfimport.cpp (renamed from filters/karbon/wmf/wmfimport.cc)0
-rw-r--r--filters/karbon/wmf/wmfimportparser.cpp (renamed from filters/karbon/wmf/wmfimportparser.cc)0
-rw-r--r--filters/karbon/xaml/Makefile.am4
-rw-r--r--filters/karbon/xaml/xamlexport.cpp (renamed from filters/karbon/xaml/xamlexport.cc)0
-rw-r--r--filters/karbon/xaml/xamlimport.cpp (renamed from filters/karbon/xaml/xamlimport.cc)0
-rw-r--r--filters/karbon/xcf/Makefile.am2
-rw-r--r--filters/karbon/xcf/xcfexport.cpp (renamed from filters/karbon/xcf/xcfexport.cc)0
-rw-r--r--filters/karbon/xfig/xfigimport.cpp (renamed from filters/karbon/xfig/xfigimport.cc)0
-rw-r--r--filters/karbon/xfig/xfigimport_factory.cpp (renamed from filters/karbon/xfig/xfigimport_factory.cc)0
-rw-r--r--filters/kchart/svg/Makefile.am2
-rw-r--r--filters/kchart/svg/svgexport.cpp (renamed from filters/kchart/svg/svgexport.cc)0
-rw-r--r--filters/kformula/latex/Makefile.am4
-rw-r--r--filters/kformula/latex/latexexport.cpp (renamed from filters/kformula/latex/latexexport.cc)0
-rw-r--r--filters/kformula/mathml/Makefile.am4
-rw-r--r--filters/kformula/mathml/mathmlexport.cpp (renamed from filters/kformula/mathml/mathmlexport.cc)0
-rw-r--r--filters/kformula/mathml/mathmlimport.cpp (renamed from filters/kformula/mathml/mathmlimport.cc)0
-rw-r--r--filters/kformula/png/Makefile.am4
-rw-r--r--filters/kformula/png/pngexport.cpp (renamed from filters/kformula/png/pngexport.cc)0
-rw-r--r--filters/kformula/png/pngexportdia.cpp (renamed from filters/kformula/png/pngexportdia.cc)0
-rw-r--r--filters/kformula/svg/Makefile.am4
-rw-r--r--filters/kformula/svg/svgexport.cpp (renamed from filters/kformula/svg/svgexport.cc)0
-rw-r--r--filters/kpresenter/kword/Makefile.am2
-rw-r--r--filters/kpresenter/kword/kprkword.cpp (renamed from filters/kpresenter/kword/kprkword.cc)0
-rw-r--r--filters/kpresenter/ooimpress/Makefile.am4
-rw-r--r--filters/kpresenter/ooimpress/ooimpressexport.cpp (renamed from filters/kpresenter/ooimpress/ooimpressexport.cc)0
-rw-r--r--filters/kpresenter/ooimpress/ooimpressimport.cpp (renamed from filters/kpresenter/ooimpress/ooimpressimport.cc)0
-rw-r--r--filters/kpresenter/ooimpress/stylefactory.cpp (renamed from filters/kpresenter/ooimpress/stylefactory.cc)0
-rw-r--r--filters/kpresenter/powerpoint/import/Makefile.am2
-rw-r--r--filters/kpresenter/powerpoint/import/powerpointimport.cpp (renamed from filters/kpresenter/powerpoint/import/powerpointimport.cc)0
-rw-r--r--filters/kpresenter/svg/Makefile.am2
-rw-r--r--filters/kpresenter/svg/svgexport.cc100
-rw-r--r--filters/kpresenter/svg/svgexport.cpp100
-rw-r--r--filters/kpresenter/svg/svgexport.h2
-rw-r--r--filters/kspread/applixspread/Makefile.am2
-rw-r--r--filters/kspread/applixspread/applixspreadimport.cpp (renamed from filters/kspread/applixspread/applixspreadimport.cc)0
-rw-r--r--filters/kspread/applixspread/status.html2
-rw-r--r--filters/kspread/csv/DESIGN2
-rw-r--r--filters/kspread/csv/Makefile.am4
-rw-r--r--filters/kspread/csv/csvexport.cpp (renamed from filters/kspread/csv/csvexport.cc)0
-rw-r--r--filters/kspread/csv/csvimport.cpp (renamed from filters/kspread/csv/csvimport.cc)0
-rw-r--r--filters/kspread/csv/status.html2
-rw-r--r--filters/kspread/csv/xmltree.cpp (renamed from filters/kspread/csv/xmltree.cc)0
-rw-r--r--filters/kspread/dbase/Makefile.am2
-rw-r--r--filters/kspread/dbase/dbaseimport.cpp (renamed from filters/kspread/dbase/dbaseimport.cc)0
-rw-r--r--filters/kspread/excel/Makefile.am2
-rw-r--r--filters/kspread/excel/excelexport.cpp (renamed from filters/kspread/excel/excelexport.cc)0
-rw-r--r--filters/kspread/excel/import/Makefile.am2
-rw-r--r--filters/kspread/excel/import/excelimport.cpp (renamed from filters/kspread/excel/import/excelimport.cc)0
-rw-r--r--filters/kspread/gnumeric/Makefile.am4
-rw-r--r--filters/kspread/gnumeric/gnumericexport.cpp (renamed from filters/kspread/gnumeric/gnumericexport.cc)0
-rw-r--r--filters/kspread/gnumeric/gnumericimport.cpp (renamed from filters/kspread/gnumeric/gnumericimport.cc)0
-rw-r--r--filters/kspread/html/Makefile.am2
-rw-r--r--filters/kspread/html/exportdialog.cpp (renamed from filters/kspread/html/exportdialog.cc)0
-rw-r--r--filters/kspread/html/htmlexport.cpp (renamed from filters/kspread/html/htmlexport.cc)0
-rw-r--r--filters/kspread/kexi/Makefile.am4
-rw-r--r--filters/kspread/kexi/kspread_kexiimport.cpp (renamed from filters/kspread/kexi/kspread_kexiimport.cc)0
-rw-r--r--filters/kspread/kexi/kspread_kexiimportdialog.cpp (renamed from filters/kspread/kexi/kspread_kexiimportdialog.cc)0
-rw-r--r--filters/kspread/latex/export/Makefile.am12
-rw-r--r--filters/kspread/latex/export/cell.cpp (renamed from filters/kspread/latex/export/cell.cc)0
-rw-r--r--filters/kspread/latex/export/column.cpp (renamed from filters/kspread/latex/export/column.cc)0
-rw-r--r--filters/kspread/latex/export/config.cpp (renamed from filters/kspread/latex/export/config.cc)0
-rw-r--r--filters/kspread/latex/export/document.cpp (renamed from filters/kspread/latex/export/document.cc)0
-rw-r--r--filters/kspread/latex/export/fileheader.cpp (renamed from filters/kspread/latex/export/fileheader.cc)0
-rw-r--r--filters/kspread/latex/export/format.cpp (renamed from filters/kspread/latex/export/format.cc)0
-rw-r--r--filters/kspread/latex/export/formula.cpp (renamed from filters/kspread/latex/export/formula.cc)0
-rw-r--r--filters/kspread/latex/export/kspreadlatexexportdiaImpl.cpp (renamed from filters/kspread/latex/export/kspreadlatexexportdiaImpl.cc)0
-rw-r--r--filters/kspread/latex/export/latexexport.cpp (renamed from filters/kspread/latex/export/latexexport.cc)0
-rw-r--r--filters/kspread/latex/export/latexexportIface.cpp (renamed from filters/kspread/latex/export/latexexportIface.cc)0
-rw-r--r--filters/kspread/latex/export/map.cpp (renamed from filters/kspread/latex/export/map.cc)0
-rw-r--r--filters/kspread/latex/export/pen.cpp (renamed from filters/kspread/latex/export/pen.cc)0
-rw-r--r--filters/kspread/latex/export/row.cpp (renamed from filters/kspread/latex/export/row.cc)0
-rw-r--r--filters/kspread/latex/export/spreadsheet.cpp (renamed from filters/kspread/latex/export/spreadsheet.cc)0
-rw-r--r--filters/kspread/latex/export/table.cpp (renamed from filters/kspread/latex/export/table.cc)0
-rw-r--r--filters/kspread/latex/export/xmlparser.cpp (renamed from filters/kspread/latex/export/xmlparser.cc)0
-rw-r--r--filters/kspread/libkspreadexport/KSpreadBaseWorker.cpp (renamed from filters/kspread/libkspreadexport/KSpreadBaseWorker.cc)0
-rw-r--r--filters/kspread/libkspreadexport/KSpreadLeader.cpp (renamed from filters/kspread/libkspreadexport/KSpreadLeader.cc)0
-rw-r--r--filters/kspread/libkspreadexport/Makefile.am2
-rw-r--r--filters/kspread/opencalc/Makefile.am4
-rw-r--r--filters/kspread/opencalc/opencalcexport.cpp (renamed from filters/kspread/opencalc/opencalcexport.cc)0
-rw-r--r--filters/kspread/opencalc/opencalcimport.cpp (renamed from filters/kspread/opencalc/opencalcimport.cc)0
-rw-r--r--filters/kspread/opencalc/opencalcstyleexport.cpp (renamed from filters/kspread/opencalc/opencalcstyleexport.cc)0
-rw-r--r--filters/kspread/qpro/Makefile.am2
-rw-r--r--filters/kspread/qpro/libqpro/ChangeLog8
-rw-r--r--filters/kspread/qpro/libqpro/src/Makefile.am2
-rw-r--r--filters/kspread/qpro/libqpro/src/formula.cpp (renamed from filters/kspread/qpro/libqpro/src/formula.cc)0
-rw-r--r--filters/kspread/qpro/libqpro/src/record.cpp (renamed from filters/kspread/qpro/libqpro/src/record.cc)0
-rw-r--r--filters/kspread/qpro/libqpro/src/record_factory.cpp (renamed from filters/kspread/qpro/libqpro/src/record_factory.cc)0
-rw-r--r--filters/kspread/qpro/libqpro/src/stream.cpp (renamed from filters/kspread/qpro/libqpro/src/stream.cc)0
-rw-r--r--filters/kspread/qpro/libqpro/src/tablenames.cpp (renamed from filters/kspread/qpro/libqpro/src/tablenames.cc)0
-rw-r--r--filters/kspread/qpro/qproformula.cpp (renamed from filters/kspread/qpro/qproformula.cc)0
-rw-r--r--filters/kspread/qpro/qproimport.cpp (renamed from filters/kspread/qpro/qproimport.cc)0
-rw-r--r--filters/kword/abiword/ImportField.cpp (renamed from filters/kword/abiword/ImportField.cc)0
-rw-r--r--filters/kword/abiword/ImportFormatting.cpp (renamed from filters/kword/abiword/ImportFormatting.cc)0
-rw-r--r--filters/kword/abiword/ImportHelpers.cpp (renamed from filters/kword/abiword/ImportHelpers.cc)0
-rw-r--r--filters/kword/abiword/ImportStyle.cpp (renamed from filters/kword/abiword/ImportStyle.cc)0
-rw-r--r--filters/kword/abiword/Makefile.am6
-rw-r--r--filters/kword/abiword/abiwordexport.cc1261
-rw-r--r--filters/kword/abiword/abiwordexport.cpp1261
-rw-r--r--filters/kword/abiword/abiwordimport.cpp (renamed from filters/kword/abiword/abiwordimport.cc)0
-rw-r--r--filters/kword/amipro/Makefile.am4
-rw-r--r--filters/kword/amipro/amiproexport.cpp (renamed from filters/kword/amipro/amiproexport.cc)0
-rw-r--r--filters/kword/amipro/amiproimport.cpp (renamed from filters/kword/amipro/amiproimport.cc)0
-rw-r--r--filters/kword/applixword/Makefile.am2
-rw-r--r--filters/kword/applixword/applixwordimport.cpp (renamed from filters/kword/applixword/applixwordimport.cc)0
-rw-r--r--filters/kword/ascii/ExportDialog.cpp (renamed from filters/kword/ascii/ExportDialog.cc)0
-rw-r--r--filters/kword/ascii/ImportDialog.cpp (renamed from filters/kword/ascii/ImportDialog.cc)0
-rw-r--r--filters/kword/ascii/Makefile.am4
-rw-r--r--filters/kword/ascii/asciiexport.cpp (renamed from filters/kword/ascii/asciiexport.cc)0
-rw-r--r--filters/kword/ascii/asciiimport.cpp (renamed from filters/kword/ascii/asciiimport.cc)0
-rw-r--r--filters/kword/docbook/Makefile.am2
-rw-r--r--filters/kword/docbook/docbookexport.cpp (renamed from filters/kword/docbook/docbookexport.cc)0
-rw-r--r--filters/kword/html/export/ExportBasic.cpp (renamed from filters/kword/html/export/ExportBasic.cc)0
-rw-r--r--filters/kword/html/export/ExportCss.cpp (renamed from filters/kword/html/export/ExportCss.cc)0
-rw-r--r--filters/kword/html/export/ExportDialog.cpp (renamed from filters/kword/html/export/ExportDialog.cc)0
-rw-r--r--filters/kword/html/export/ExportDocStruct.cpp (renamed from filters/kword/html/export/ExportDocStruct.cc)0
-rw-r--r--filters/kword/html/export/ExportFilter.cpp (renamed from filters/kword/html/export/ExportFilter.cc)0
-rw-r--r--filters/kword/html/export/Makefile.am4
-rw-r--r--filters/kword/html/export/htmlexport.cc127
-rw-r--r--filters/kword/html/export/htmlexport.cpp127
-rw-r--r--filters/kword/latex/export/Makefile.am16
-rw-r--r--filters/kword/latex/export/anchor.cpp (renamed from filters/kword/latex/export/anchor.cc)0
-rw-r--r--filters/kword/latex/export/config.cpp (renamed from filters/kword/latex/export/config.cc)0
-rw-r--r--filters/kword/latex/export/document.cpp (renamed from filters/kword/latex/export/document.cc)0
-rw-r--r--filters/kword/latex/export/element.cpp (renamed from filters/kword/latex/export/element.cc)0
-rw-r--r--filters/kword/latex/export/fileheader.cpp (renamed from filters/kword/latex/export/fileheader.cc)0
-rw-r--r--filters/kword/latex/export/footnote.cpp (renamed from filters/kword/latex/export/footnote.cc)0
-rw-r--r--filters/kword/latex/export/format.cpp (renamed from filters/kword/latex/export/format.cc)0
-rw-r--r--filters/kword/latex/export/formula.cpp (renamed from filters/kword/latex/export/formula.cc)0
-rw-r--r--filters/kword/latex/export/key.cpp (renamed from filters/kword/latex/export/key.cc)0
-rw-r--r--filters/kword/latex/export/kwordlatexexportdia.cpp (renamed from filters/kword/latex/export/kwordlatexexportdia.cc)0
-rw-r--r--filters/kword/latex/export/latexexport.cpp (renamed from filters/kword/latex/export/latexexport.cc)0
-rw-r--r--filters/kword/latex/export/latexexportIface.cpp (renamed from filters/kword/latex/export/latexexportIface.cc)0
-rw-r--r--filters/kword/latex/export/layout.cpp (renamed from filters/kword/latex/export/layout.cc)0
-rw-r--r--filters/kword/latex/export/listeformat.cpp (renamed from filters/kword/latex/export/listeformat.cc)0
-rw-r--r--filters/kword/latex/export/listelement.cpp (renamed from filters/kword/latex/export/listelement.cc)0
-rw-r--r--filters/kword/latex/export/listepara.cpp (renamed from filters/kword/latex/export/listepara.cc)0
-rw-r--r--filters/kword/latex/export/listtable.cpp (renamed from filters/kword/latex/export/listtable.cc)0
-rw-r--r--filters/kword/latex/export/para.cpp (renamed from filters/kword/latex/export/para.cc)0
-rw-r--r--filters/kword/latex/export/pixmapFrame.cpp (renamed from filters/kword/latex/export/pixmapFrame.cc)0
-rw-r--r--filters/kword/latex/export/table.cpp (renamed from filters/kword/latex/export/table.cc)0
-rw-r--r--filters/kword/latex/export/texlauncher.cpp (renamed from filters/kword/latex/export/texlauncher.cc)0
-rw-r--r--filters/kword/latex/export/textFrame.cpp (renamed from filters/kword/latex/export/textFrame.cc)0
-rw-r--r--filters/kword/latex/export/textformat.cpp (renamed from filters/kword/latex/export/textformat.cc)0
-rw-r--r--filters/kword/latex/export/textzone.cpp (renamed from filters/kword/latex/export/textzone.cc)0
-rw-r--r--filters/kword/latex/export/variableformat.cpp (renamed from filters/kword/latex/export/variableformat.cc)0
-rw-r--r--filters/kword/latex/export/variablezone.cpp (renamed from filters/kword/latex/export/variablezone.cc)0
-rw-r--r--filters/kword/latex/export/xml2latexparser.cpp (renamed from filters/kword/latex/export/xml2latexparser.cc)0
-rw-r--r--filters/kword/latex/export/xmlparser.cpp (renamed from filters/kword/latex/export/xmlparser.cc)0
-rw-r--r--filters/kword/latex/import/Makefile.am6
-rw-r--r--filters/kword/latex/import/config.cpp (renamed from filters/kword/latex/import/config.cc)0
-rw-r--r--filters/kword/latex/import/generator/Makefile.am2
-rw-r--r--filters/kword/latex/import/generator/body.cpp (renamed from filters/kword/latex/import/generator/body.cc)0
-rw-r--r--filters/kword/latex/import/generator/document.cpp (renamed from filters/kword/latex/import/generator/document.cc)0
-rw-r--r--filters/kword/latex/import/generator/kwordgenerator.cpp (renamed from filters/kword/latex/import/generator/kwordgenerator.cc)0
-rw-r--r--filters/kword/latex/import/generator/latex.cpp (renamed from filters/kword/latex/import/generator/latex.cc)0
-rw-r--r--filters/kword/latex/import/generator/paragraph.cpp (renamed from filters/kword/latex/import/generator/paragraph.cc)0
-rw-r--r--filters/kword/latex/import/lateximport.cpp (renamed from filters/kword/latex/import/lateximport.cc)0
-rw-r--r--filters/kword/latex/import/lateximportdia.cc170
-rw-r--r--filters/kword/latex/import/lateximportdia.cpp170
-rw-r--r--filters/kword/latex/import/parser/Makefile.am16
-rw-r--r--filters/kword/latex/import/parser/command.cpp (renamed from filters/kword/latex/import/parser/command.cc)0
-rw-r--r--filters/kword/latex/import/parser/comment.cpp (renamed from filters/kword/latex/import/parser/comment.cc)0
-rw-r--r--filters/kword/latex/import/parser/element.cpp (renamed from filters/kword/latex/import/parser/element.cc)0
-rw-r--r--filters/kword/latex/import/parser/env.cpp (renamed from filters/kword/latex/import/parser/env.cc)0
-rw-r--r--filters/kword/latex/import/parser/group.cpp (renamed from filters/kword/latex/import/parser/group.cc)0
-rw-r--r--filters/kword/latex/import/parser/latexparser.cpp (renamed from filters/kword/latex/import/parser/latexparser.cc)0
-rw-r--r--filters/kword/latex/import/parser/main.cpp (renamed from filters/kword/latex/import/parser/main.cc)0
-rw-r--r--filters/kword/latex/import/parser/param.cpp (renamed from filters/kword/latex/import/parser/param.cc)0
-rw-r--r--filters/kword/latex/import/parser/texparser.l4
-rw-r--r--filters/kword/latex/import/parser/texparser.lex4
-rw-r--r--filters/kword/latex/import/parser/text.cpp (renamed from filters/kword/latex/import/parser/text.cc)0
-rw-r--r--filters/kword/libexport/KWEFBaseWorker.cpp (renamed from filters/kword/libexport/KWEFBaseWorker.cc)0
-rw-r--r--filters/kword/libexport/KWEFKWordLeader.cc1430
-rw-r--r--filters/kword/libexport/KWEFKWordLeader.cpp1430
-rw-r--r--filters/kword/libexport/KWEFStructures.cpp (renamed from filters/kword/libexport/KWEFStructures.cc)0
-rw-r--r--filters/kword/libexport/KWEFStructures.h4
-rw-r--r--filters/kword/libexport/KWEFUtil.cpp (renamed from filters/kword/libexport/KWEFUtil.cc)0
-rw-r--r--filters/kword/libexport/Makefile.am4
-rw-r--r--filters/kword/libexport/ProcessDocument.cc1063
-rw-r--r--filters/kword/libexport/ProcessDocument.cpp1063
-rw-r--r--filters/kword/libexport/TagProcessing.cc235
-rw-r--r--filters/kword/libexport/TagProcessing.cpp235
-rw-r--r--filters/kword/libexport/TagProcessing.h2
-rw-r--r--filters/kword/msword/document.cpp4
-rw-r--r--filters/kword/msword/texthandler.cpp2
-rw-r--r--filters/kword/mswrite/ImportDialog.cpp (renamed from filters/kword/mswrite/ImportDialog.cc)0
-rw-r--r--filters/kword/mswrite/Makefile.am6
-rw-r--r--filters/kword/mswrite/mswriteexport.cpp (renamed from filters/kword/mswrite/mswriteexport.cc)0
-rw-r--r--filters/kword/mswrite/mswriteimport.cpp (renamed from filters/kword/mswrite/mswriteimport.cc)0
-rw-r--r--filters/kword/mswrite/status.html2
-rw-r--r--filters/kword/oowriter/ExportFilter.cc2229
-rw-r--r--filters/kword/oowriter/ExportFilter.cpp2229
-rw-r--r--filters/kword/oowriter/ExportFilter.h2
-rw-r--r--filters/kword/oowriter/Makefile.am6
-rw-r--r--filters/kword/oowriter/conversion.cpp (renamed from filters/kword/oowriter/conversion.cc)0
-rw-r--r--filters/kword/oowriter/oowriterexport.cc90
-rw-r--r--filters/kword/oowriter/oowriterexport.cpp90
-rw-r--r--filters/kword/oowriter/oowriterimport.cpp (renamed from filters/kword/oowriter/oowriterimport.cc)0
-rw-r--r--filters/kword/palmdoc/Makefile.am4
-rw-r--r--filters/kword/palmdoc/palmdocexport.cpp (renamed from filters/kword/palmdoc/palmdocexport.cc)0
-rw-r--r--filters/kword/palmdoc/palmdocimport.cpp (renamed from filters/kword/palmdoc/palmdocimport.cc)0
-rw-r--r--filters/kword/pdf/diffs/goo_enable-final.diff24
-rw-r--r--filters/kword/pdf/diffs/goo_gfile.diff6
-rw-r--r--filters/kword/pdf/diffs/xpdf_TextOutputDev.diff6
-rw-r--r--filters/kword/pdf/diffs/xpdf_includes.diff18
-rw-r--r--filters/kword/pdf/diffs/xpdf_security_integer_overflow.diff20
-rw-r--r--filters/kword/pdf/diffs/xpdf_security_integer_overflow_2.diff40
-rw-r--r--filters/kword/pdf/xpdf/CHANGES28
-rw-r--r--filters/kword/pdf/xpdf/goo/GHash.cc238
-rw-r--r--filters/kword/pdf/xpdf/goo/GHash.cpp238
-rw-r--r--filters/kword/pdf/xpdf/goo/GList.cc89
-rw-r--r--filters/kword/pdf/xpdf/goo/GList.cpp89
-rw-r--r--filters/kword/pdf/xpdf/goo/GString.cc233
-rw-r--r--filters/kword/pdf/xpdf/goo/GString.cpp233
-rw-r--r--filters/kword/pdf/xpdf/goo/Makefile.am2
-rw-r--r--filters/kword/pdf/xpdf/goo/gfile.cc700
-rw-r--r--filters/kword/pdf/xpdf/goo/gfile.cpp700
-rw-r--r--filters/kword/pdf/xpdf/goo/gmempp.cc32
-rw-r--r--filters/kword/pdf/xpdf/goo/gmempp.cpp32
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Annot.cc139
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Annot.cpp139
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Array.cc54
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Array.cpp54
-rw-r--r--filters/kword/pdf/xpdf/xpdf/BuiltinFont.cc65
-rw-r--r--filters/kword/pdf/xpdf/xpdf/BuiltinFont.cpp65
-rw-r--r--filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cc3367
-rw-r--r--filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cpp3367
-rw-r--r--filters/kword/pdf/xpdf/xpdf/CMap.cc360
-rw-r--r--filters/kword/pdf/xpdf/xpdf/CMap.cpp360
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Catalog.cc371
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Catalog.cpp371
-rw-r--r--filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cc392
-rw-r--r--filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cpp392
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Decrypt.cc401
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Decrypt.cpp401
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Dict.cc91
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Dict.cpp91
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Error.cc38
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Error.cpp38
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FTFont.cc685
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FTFont.cpp685
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cc1824
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cpp1824
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FontFile.cc3883
-rw-r--r--filters/kword/pdf/xpdf/xpdf/FontFile.cpp3883
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Function.cc1521
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Function.cpp1521
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Gfx.cc2782
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Gfx.cpp2782
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GfxFont.cc1301
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GfxFont.cpp1301
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GfxState.cc2338
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GfxState.cpp2338
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GlobalParams.cc1112
-rw-r--r--filters/kword/pdf/xpdf/xpdf/GlobalParams.cpp1112
-rw-r--r--filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cc194
-rw-r--r--filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cpp194
-rw-r--r--filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cc3513
-rw-r--r--filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cpp3513
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Lexer.cc474
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Lexer.cpp474
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Link.cc735
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Link.cpp735
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Makefile.am16
-rw-r--r--filters/kword/pdf/xpdf/xpdf/NameToCharCode.cc116
-rw-r--r--filters/kword/pdf/xpdf/xpdf/NameToCharCode.cpp116
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Object.cc225
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Object.cpp225
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Outline.cc140
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Outline.cpp140
-rw-r--r--filters/kword/pdf/xpdf/xpdf/OutputDev.cc103
-rw-r--r--filters/kword/pdf/xpdf/xpdf/OutputDev.cpp103
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cc162
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cpp162
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PDFDoc.cc288
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PDFDoc.cpp288
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cpp (renamed from filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cc)0
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PSOutputDev.cc3325
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PSOutputDev.cpp3325
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PSTokenizer.cc135
-rw-r--r--filters/kword/pdf/xpdf/xpdf/PSTokenizer.cpp135
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Page.cc341
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Page.cpp341
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Parser.cc223
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Parser.cpp223
-rw-r--r--filters/kword/pdf/xpdf/xpdf/SFont.cc81
-rw-r--r--filters/kword/pdf/xpdf/xpdf/SFont.cpp81
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Stream.cc4544
-rw-r--r--filters/kword/pdf/xpdf/xpdf/Stream.cpp4544
-rw-r--r--filters/kword/pdf/xpdf/xpdf/T1Font.cc535
-rw-r--r--filters/kword/pdf/xpdf/xpdf/T1Font.cpp535
-rw-r--r--filters/kword/pdf/xpdf/xpdf/TTFont.cc480
-rw-r--r--filters/kword/pdf/xpdf/xpdf/TTFont.cpp480
-rw-r--r--filters/kword/pdf/xpdf/xpdf/TextOutputDev.cc1243
-rw-r--r--filters/kword/pdf/xpdf/xpdf/TextOutputDev.cpp1243
-rw-r--r--filters/kword/pdf/xpdf/xpdf/UnicodeMap.cc268
-rw-r--r--filters/kword/pdf/xpdf/xpdf/UnicodeMap.cpp268
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XOutputDev.cc3690
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XOutputDev.cpp3690
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFApp.cc386
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFApp.cpp386
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFCore.cc1913
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFCore.cpp1913
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFTree.cc929
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFTree.cpp929
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFViewer.cc2318
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPDFViewer.cpp2318
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cc84
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cpp84
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XRef.cc693
-rw-r--r--filters/kword/pdf/xpdf/xpdf/XRef.cpp693
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdffonts.cc281
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdffonts.cpp281
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdfimages.cc154
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdfimages.cpp154
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdfinfo.cc304
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdfinfo.cpp304
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftopbm.cc146
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftopbm.cpp146
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftops.cc306
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftops.cpp306
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftotext.cc322
-rw-r--r--filters/kword/pdf/xpdf/xpdf/pdftotext.cpp322
-rw-r--r--filters/kword/pdf/xpdf/xpdf/xpdf.cc289
-rw-r--r--filters/kword/pdf/xpdf/xpdf/xpdf.cpp289
-rw-r--r--filters/kword/rtf/export/ExportFilter.cpp (renamed from filters/kword/rtf/export/ExportFilter.cc)0
-rw-r--r--filters/kword/rtf/export/Makefile.am2
-rw-r--r--filters/kword/rtf/export/rtfexport.cc87
-rw-r--r--filters/kword/rtf/export/rtfexport.cpp87
-rw-r--r--filters/kword/starwriter/Makefile.am2
-rw-r--r--filters/kword/starwriter/starwriterimport.cpp (renamed from filters/kword/starwriter/starwriterimport.cc)0
-rw-r--r--filters/kword/wml/Makefile.am4
-rw-r--r--filters/kword/wml/wmlexport.cpp (renamed from filters/kword/wml/wmlexport.cc)0
-rw-r--r--filters/kword/wml/wmlimport.cpp (renamed from filters/kword/wml/wmlimport.cc)0
-rw-r--r--filters/kword/wordperfect/export/Makefile.am2
-rw-r--r--filters/kword/wordperfect/export/wp5.cpp (renamed from filters/kword/wordperfect/export/wp5.cc)0
-rw-r--r--filters/kword/wordperfect/export/wp6.cpp (renamed from filters/kword/wordperfect/export/wp6.cc)0
-rw-r--r--filters/kword/wordperfect/export/wpexport.cpp (renamed from filters/kword/wordperfect/export/wpexport.cc)0
-rw-r--r--filters/kword/wordperfect/import/DocumentElement.cpp108
-rw-r--r--filters/kword/wordperfect/import/DocumentElement.cxx108
-rw-r--r--filters/kword/wordperfect/import/DocumentElement.h97
-rw-r--r--filters/kword/wordperfect/import/DocumentElement.hxx97
-rw-r--r--filters/kword/wordperfect/import/DocumentHandler.h (renamed from filters/kword/wordperfect/import/DocumentHandler.hxx)0
-rw-r--r--filters/kword/wordperfect/import/FilterInternal.h36
-rw-r--r--filters/kword/wordperfect/import/FilterInternal.hxx36
-rw-r--r--filters/kword/wordperfect/import/FontStyle.cpp51
-rw-r--r--filters/kword/wordperfect/import/FontStyle.cxx51
-rw-r--r--filters/kword/wordperfect/import/FontStyle.h48
-rw-r--r--filters/kword/wordperfect/import/FontStyle.hxx48
-rw-r--r--filters/kword/wordperfect/import/ListStyle.cpp162
-rw-r--r--filters/kword/wordperfect/import/ListStyle.cxx162
-rw-r--r--filters/kword/wordperfect/import/ListStyle.h97
-rw-r--r--filters/kword/wordperfect/import/ListStyle.hxx97
-rw-r--r--filters/kword/wordperfect/import/Makefile.am4
-rw-r--r--filters/kword/wordperfect/import/PageSpan.cpp180
-rw-r--r--filters/kword/wordperfect/import/PageSpan.cxx180
-rw-r--r--filters/kword/wordperfect/import/PageSpan.h (renamed from filters/kword/wordperfect/import/PageSpan.hxx)0
-rw-r--r--filters/kword/wordperfect/import/SectionStyle.cpp79
-rw-r--r--filters/kword/wordperfect/import/SectionStyle.cxx79
-rw-r--r--filters/kword/wordperfect/import/SectionStyle.h47
-rw-r--r--filters/kword/wordperfect/import/SectionStyle.hxx47
-rw-r--r--filters/kword/wordperfect/import/Style.h60
-rw-r--r--filters/kword/wordperfect/import/Style.hxx60
-rw-r--r--filters/kword/wordperfect/import/TableStyle.cpp161
-rw-r--r--filters/kword/wordperfect/import/TableStyle.cxx161
-rw-r--r--filters/kword/wordperfect/import/TableStyle.h75
-rw-r--r--filters/kword/wordperfect/import/TableStyle.hxx75
-rw-r--r--filters/kword/wordperfect/import/TextRunStyle.cpp163
-rw-r--r--filters/kword/wordperfect/import/TextRunStyle.cxx163
-rw-r--r--filters/kword/wordperfect/import/TextRunStyle.h65
-rw-r--r--filters/kword/wordperfect/import/TextRunStyle.hxx65
-rw-r--r--filters/kword/wordperfect/import/WordPerfectCollector.cpp973
-rw-r--r--filters/kword/wordperfect/import/WordPerfectCollector.cxx973
-rw-r--r--filters/kword/wordperfect/import/WordPerfectCollector.h231
-rw-r--r--filters/kword/wordperfect/import/WordPerfectCollector.hxx231
-rw-r--r--filters/kword/wordperfect/import/WriterProperties.h (renamed from filters/kword/wordperfect/import/WriterProperties.hxx)0
-rw-r--r--filters/kword/wordperfect/import/wpimport.cc391
-rw-r--r--filters/kword/wordperfect/import/wpimport.cpp391
-rw-r--r--filters/liboofilter/Makefile.am2
-rw-r--r--filters/liboofilter/liststylestack.cpp (renamed from filters/liboofilter/liststylestack.cc)0
-rw-r--r--filters/liboofilter/ooutils.cpp (renamed from filters/liboofilter/ooutils.cc)0
-rw-r--r--filters/olefilters/Makefile.am2
-rw-r--r--filters/olefilters/lib/Makefile.am4
-rw-r--r--filters/olefilters/lib/filterbase.cpp (renamed from filters/olefilters/lib/filterbase.cc)0
-rw-r--r--filters/olefilters/lib/klaola.cpp (renamed from filters/olefilters/lib/klaola.cc)0
-rw-r--r--filters/olefilters/olefilter.cpp (renamed from filters/olefilters/olefilter.cc)0
-rw-r--r--filters/olefilters/powerpoint97/Makefile.am2
-rw-r--r--filters/olefilters/powerpoint97/powerpoint.cpp (renamed from filters/olefilters/powerpoint97/powerpoint.cc)0
-rw-r--r--filters/olefilters/powerpoint97/powerpointfilter.cpp (renamed from filters/olefilters/powerpoint97/powerpointfilter.cc)0
-rw-r--r--filters/olefilters/powerpoint97/pptdoc.cpp (renamed from filters/olefilters/powerpoint97/pptdoc.cc)0
-rw-r--r--filters/olefilters/powerpoint97/pptxml.cpp (renamed from filters/olefilters/powerpoint97/pptxml.cc)0
-rw-r--r--filters/xsltfilter/export/Makefile.am4
-rw-r--r--filters/xsltfilter/export/xsltexport.cpp (renamed from filters/xsltfilter/export/xsltexport.cc)0
-rw-r--r--filters/xsltfilter/export/xsltexportdia.cpp (renamed from filters/xsltfilter/export/xsltexportdia.cc)0
-rw-r--r--filters/xsltfilter/export/xsltproc.cpp (renamed from filters/xsltfilter/export/xsltproc.cc)0
-rw-r--r--filters/xsltfilter/import/Makefile.am2
-rw-r--r--filters/xsltfilter/import/xsltimport.cpp (renamed from filters/xsltfilter/import/xsltimport.cc)0
-rw-r--r--filters/xsltfilter/import/xsltimportdia.cpp (renamed from filters/xsltfilter/import/xsltimportdia.cc)0
-rw-r--r--filters/xsltfilter/import/xsltproc.cpp (renamed from filters/xsltfilter/import/xsltproc.cc)0
-rw-r--r--interfaces/Makefile.am2
-rw-r--r--interfaces/koChart.cpp (renamed from interfaces/koChart.cc)0
-rw-r--r--karbon/Makefile.am8
-rw-r--r--karbon/TODO2
-rw-r--r--karbon/commands/Makefile.am40
-rw-r--r--karbon/commands/valigncmd.cpp (renamed from karbon/commands/valigncmd.cc)0
-rw-r--r--karbon/commands/vbooleancmd.cpp (renamed from karbon/commands/vbooleancmd.cc)0
-rw-r--r--karbon/commands/vcleanupcmd.cpp (renamed from karbon/commands/vcleanupcmd.cc)0
-rw-r--r--karbon/commands/vclipartcmd.cpp (renamed from karbon/commands/vclipartcmd.cc)0
-rw-r--r--karbon/commands/vclosepathcmd.cpp (renamed from karbon/commands/vclosepathcmd.cc)0
-rw-r--r--karbon/commands/vcommand.cpp (renamed from karbon/commands/vcommand.cc)0
-rw-r--r--karbon/commands/vdeletecmd.cpp (renamed from karbon/commands/vdeletecmd.cc)0
-rw-r--r--karbon/commands/vdeletenodescmd.cpp (renamed from karbon/commands/vdeletenodescmd.cc)0
-rw-r--r--karbon/commands/vdistributecmd.cpp (renamed from karbon/commands/vdistributecmd.cc)0
-rw-r--r--karbon/commands/vfillcmd.cpp (renamed from karbon/commands/vfillcmd.cc)0
-rw-r--r--karbon/commands/vflattencmd.cpp (renamed from karbon/commands/vflattencmd.cc)0
-rw-r--r--karbon/commands/vgroupcmd.cpp (renamed from karbon/commands/vgroupcmd.cc)0
-rw-r--r--karbon/commands/vinsertcmd.cpp (renamed from karbon/commands/vinsertcmd.cc)0
-rw-r--r--karbon/commands/vlayercmd.cpp (renamed from karbon/commands/vlayercmd.cc)0
-rw-r--r--karbon/commands/vreplacingcmd.cpp (renamed from karbon/commands/vreplacingcmd.cc)0
-rw-r--r--karbon/commands/vshapecmd.cpp (renamed from karbon/commands/vshapecmd.cc)0
-rw-r--r--karbon/commands/vstrokecmd.cpp (renamed from karbon/commands/vstrokecmd.cc)0
-rw-r--r--karbon/commands/vtextcmd.cpp (renamed from karbon/commands/vtextcmd.cc)0
-rw-r--r--karbon/commands/vtransformcmd.cpp (renamed from karbon/commands/vtransformcmd.cc)0
-rw-r--r--karbon/commands/vungroupcmd.cpp (renamed from karbon/commands/vungroupcmd.cc)0
-rw-r--r--karbon/commands/vzordercmd.cpp (renamed from karbon/commands/vzordercmd.cc)0
-rw-r--r--karbon/core/Makefile.am52
-rw-r--r--karbon/core/vclipgroup.cpp (renamed from karbon/core/vclipgroup.cc)0
-rw-r--r--karbon/core/vcolor.cpp (renamed from karbon/core/vcolor.cc)0
-rw-r--r--karbon/core/vcomposite.cpp (renamed from karbon/core/vcomposite.cc)0
-rw-r--r--karbon/core/vcomposite_iface.cpp (renamed from karbon/core/vcomposite_iface.cc)0
-rw-r--r--karbon/core/vcursor.cpp (renamed from karbon/core/vcursor.cc)0
-rw-r--r--karbon/core/vdashpattern.cpp (renamed from karbon/core/vdashpattern.cc)0
-rw-r--r--karbon/core/vdocument.cpp (renamed from karbon/core/vdocument.cc)0
-rw-r--r--karbon/core/vfill.cpp (renamed from karbon/core/vfill.cc)0
-rw-r--r--karbon/core/vglobal.cpp (renamed from karbon/core/vglobal.cc)0
-rw-r--r--karbon/core/vgradient.cpp (renamed from karbon/core/vgradient.cc)0
-rw-r--r--karbon/core/vgroup.cpp (renamed from karbon/core/vgroup.cc)0
-rw-r--r--karbon/core/vgroup_iface.cpp (renamed from karbon/core/vgroup_iface.cc)0
-rw-r--r--karbon/core/vimage.cpp (renamed from karbon/core/vimage.cc)0
-rw-r--r--karbon/core/vkarbonplugin.cpp (renamed from karbon/core/vkarbonplugin.cc)0
-rw-r--r--karbon/core/vlayer.cpp (renamed from karbon/core/vlayer.cc)0
-rw-r--r--karbon/core/vlayer_iface.cpp (renamed from karbon/core/vlayer_iface.cc)0
-rw-r--r--karbon/core/vobject.cpp (renamed from karbon/core/vobject.cc)0
-rw-r--r--karbon/core/vobject_iface.cpp (renamed from karbon/core/vobject_iface.cc)0
-rw-r--r--karbon/core/vpath.cpp (renamed from karbon/core/vpath.cc)0
-rw-r--r--karbon/core/vpattern.cpp (renamed from karbon/core/vpattern.cc)0
-rw-r--r--karbon/core/vsegment.cpp (renamed from karbon/core/vsegment.cc)0
-rw-r--r--karbon/core/vselection.cpp (renamed from karbon/core/vselection.cc)0
-rw-r--r--karbon/core/vstroke.cpp (renamed from karbon/core/vstroke.cc)0
-rw-r--r--karbon/core/vtext.cpp (renamed from karbon/core/vtext.cc)0
-rw-r--r--karbon/core/vtext_iface.cpp (renamed from karbon/core/vtext_iface.cc)0
-rw-r--r--karbon/core/vvisitor.cpp (renamed from karbon/core/vvisitor.cc)0
-rw-r--r--karbon/dialogs/Makefile.am6
-rw-r--r--karbon/dialogs/vcolordlg.cpp (renamed from karbon/dialogs/vcolordlg.cc)0
-rw-r--r--karbon/dialogs/vcolortab.cpp (renamed from karbon/dialogs/vcolortab.cc)0
-rw-r--r--karbon/dialogs/vconfiguredlg.cpp (renamed from karbon/dialogs/vconfiguredlg.cc)0
-rw-r--r--karbon/dialogs/vstrokedlg.cpp (renamed from karbon/dialogs/vstrokedlg.cc)0
-rw-r--r--karbon/dockers/Makefile.am18
-rw-r--r--karbon/dockers/vcolordocker.cpp (renamed from karbon/dockers/vcolordocker.cc)0
-rw-r--r--karbon/dockers/vdocumentdocker.cpp (renamed from karbon/dockers/vdocumentdocker.cc)0
-rw-r--r--karbon/dockers/vstrokedocker.cpp (renamed from karbon/dockers/vstrokedocker.cc)0
-rw-r--r--karbon/dockers/vstyledocker.cpp (renamed from karbon/dockers/vstyledocker.cc)0
-rw-r--r--karbon/dockers/vtransformdocker.cpp (renamed from karbon/dockers/vtransformdocker.cc)0
-rw-r--r--karbon/karbon_factory.cpp (renamed from karbon/karbon_factory.cc)0
-rw-r--r--karbon/karbon_factory_init.cpp (renamed from karbon/karbon_factory_init.cc)0
-rw-r--r--karbon/karbon_part.cpp (renamed from karbon/karbon_part.cc)0
-rw-r--r--karbon/karbon_part_iface.cpp (renamed from karbon/karbon_part_iface.cc)0
-rw-r--r--karbon/karbon_resourceserver.cpp (renamed from karbon/karbon_resourceserver.cc)0
-rw-r--r--karbon/karbon_tool_factory.cpp (renamed from karbon/karbon_tool_factory.cc)0
-rw-r--r--karbon/karbon_tool_registry.cpp (renamed from karbon/karbon_tool_registry.cc)0
-rw-r--r--karbon/karbon_view.cpp (renamed from karbon/karbon_view.cc)0
-rw-r--r--karbon/karbon_view_iface.cpp (renamed from karbon/karbon_view_iface.cc)0
-rw-r--r--karbon/main.cpp (renamed from karbon/main.cc)0
-rw-r--r--karbon/plugins/flattenpath/Makefile.am2
-rw-r--r--karbon/plugins/flattenpath/flattenpathplugin.cpp (renamed from karbon/plugins/flattenpath/flattenpathplugin.cc)0
-rw-r--r--karbon/plugins/imagetool/Makefile.am2
-rw-r--r--karbon/plugins/imagetool/imagetoolplugin.cpp (renamed from karbon/plugins/imagetool/imagetoolplugin.cc)0
-rw-r--r--karbon/plugins/imagetool/vimagetool.cpp (renamed from karbon/plugins/imagetool/vimagetool.cc)0
-rw-r--r--karbon/plugins/insertknots/Makefile.am2
-rw-r--r--karbon/plugins/insertknots/insertknotsplugin.cpp (renamed from karbon/plugins/insertknots/insertknotsplugin.cc)0
-rw-r--r--karbon/plugins/roundcorners/Makefile.am2
-rw-r--r--karbon/plugins/roundcorners/roundcornersplugin.cpp (renamed from karbon/plugins/roundcorners/roundcornersplugin.cc)0
-rw-r--r--karbon/plugins/shadoweffect/Makefile.am2
-rw-r--r--karbon/plugins/shadoweffect/shadoweffectplugin.cpp (renamed from karbon/plugins/shadoweffect/shadoweffectplugin.cc)0
-rw-r--r--karbon/plugins/shadoweffect/vshadowdecorator.cpp (renamed from karbon/plugins/shadoweffect/vshadowdecorator.cc)0
-rw-r--r--karbon/plugins/whirlpinch/Makefile.am2
-rw-r--r--karbon/plugins/whirlpinch/whirlpinchplugin.cpp (renamed from karbon/plugins/whirlpinch/whirlpinchplugin.cc)0
-rw-r--r--karbon/plugins/zoomtool/Makefile.am2
-rw-r--r--karbon/plugins/zoomtool/vzoomtool.cpp (renamed from karbon/plugins/zoomtool/vzoomtool.cc)0
-rw-r--r--karbon/plugins/zoomtool/zoomtoolplugin.cpp (renamed from karbon/plugins/zoomtool/zoomtoolplugin.cc)0
-rw-r--r--karbon/render/Makefile.am6
-rw-r--r--karbon/render/vkopainter.cpp (renamed from karbon/render/vkopainter.cc)0
-rw-r--r--karbon/render/vpainterfactory.cpp (renamed from karbon/render/vpainterfactory.cc)0
-rw-r--r--karbon/render/vqpainter.cpp (renamed from karbon/render/vqpainter.cc)0
-rw-r--r--karbon/shapes/Makefile.am14
-rw-r--r--karbon/shapes/vellipse.cpp (renamed from karbon/shapes/vellipse.cc)0
-rw-r--r--karbon/shapes/vpolygon.cpp (renamed from karbon/shapes/vpolygon.cc)0
-rw-r--r--karbon/shapes/vpolyline.cpp (renamed from karbon/shapes/vpolyline.cc)0
-rw-r--r--karbon/shapes/vrectangle.cpp (renamed from karbon/shapes/vrectangle.cc)0
-rw-r--r--karbon/shapes/vsinus.cpp (renamed from karbon/shapes/vsinus.cc)0
-rw-r--r--karbon/shapes/vspiral.cpp (renamed from karbon/shapes/vspiral.cc)0
-rw-r--r--karbon/shapes/vstar.cpp (renamed from karbon/shapes/vstar.cc)0
-rw-r--r--karbon/tools/Makefile.am38
-rw-r--r--karbon/tools/vcurvefit.cpp (renamed from karbon/tools/vcurvefit.cc)0
-rw-r--r--karbon/tools/vdefaulttools.cpp (renamed from karbon/tools/vdefaulttools.cc)0
-rw-r--r--karbon/tools/vellipsetool.cpp (renamed from karbon/tools/vellipsetool.cc)0
-rw-r--r--karbon/tools/vgradienttool.cpp (renamed from karbon/tools/vgradienttool.cc)0
-rw-r--r--karbon/tools/vpatterntool.cpp (renamed from karbon/tools/vpatterntool.cc)0
-rw-r--r--karbon/tools/vpenciltool.cpp (renamed from karbon/tools/vpenciltool.cc)0
-rw-r--r--karbon/tools/vpolygontool.cpp (renamed from karbon/tools/vpolygontool.cc)0
-rw-r--r--karbon/tools/vpolylinetool.cpp (renamed from karbon/tools/vpolylinetool.cc)0
-rw-r--r--karbon/tools/vrectangletool.cpp (renamed from karbon/tools/vrectangletool.cc)0
-rw-r--r--karbon/tools/vrotatetool.cpp (renamed from karbon/tools/vrotatetool.cc)0
-rw-r--r--karbon/tools/vroundrecttool.cpp (renamed from karbon/tools/vroundrecttool.cc)0
-rw-r--r--karbon/tools/vselectnodestool.cpp (renamed from karbon/tools/vselectnodestool.cc)0
-rw-r--r--karbon/tools/vselecttool.cpp (renamed from karbon/tools/vselecttool.cc)0
-rw-r--r--karbon/tools/vshapetool.cpp (renamed from karbon/tools/vshapetool.cc)0
-rw-r--r--karbon/tools/vsheartool.cpp (renamed from karbon/tools/vsheartool.cc)0
-rw-r--r--karbon/tools/vsinustool.cpp (renamed from karbon/tools/vsinustool.cc)0
-rw-r--r--karbon/tools/vspiraltool.cpp (renamed from karbon/tools/vspiraltool.cc)0
-rw-r--r--karbon/tools/vstartool.cpp (renamed from karbon/tools/vstartool.cc)0
-rw-r--r--karbon/tools/vtexttool.cpp (renamed from karbon/tools/vtexttool.cc)0
-rw-r--r--karbon/usablity-review.txt2
-rw-r--r--karbon/visitors/Makefile.am12
-rw-r--r--karbon/visitors/vcomputeboundingbox.cpp (renamed from karbon/visitors/vcomputeboundingbox.cc)0
-rw-r--r--karbon/visitors/vdrawselection.cpp (renamed from karbon/visitors/vdrawselection.cc)0
-rw-r--r--karbon/visitors/vselectiondesc.cpp (renamed from karbon/visitors/vselectiondesc.cc)0
-rw-r--r--karbon/visitors/vselectnodes.cpp (renamed from karbon/visitors/vselectnodes.cc)0
-rw-r--r--karbon/visitors/vselectobjects.cpp (renamed from karbon/visitors/vselectobjects.cc)0
-rw-r--r--karbon/visitors/vtransformnodes.cpp (renamed from karbon/visitors/vtransformnodes.cc)0
-rw-r--r--karbon/vtool.cpp (renamed from karbon/vtool.cc)0
-rw-r--r--karbon/vtoolcontroller.cpp (renamed from karbon/vtoolcontroller.cc)0
-rw-r--r--karbon/widgets/Makefile.am34
-rw-r--r--karbon/widgets/vcanvas.cpp (renamed from karbon/widgets/vcanvas.cc)0
-rw-r--r--karbon/widgets/vcolorslider.cc149
-rw-r--r--karbon/widgets/vcolorslider.cpp149
-rw-r--r--karbon/widgets/vgradienttabwidget.cpp (renamed from karbon/widgets/vgradienttabwidget.cc)0
-rw-r--r--karbon/widgets/vgradientwidget.cpp (renamed from karbon/widgets/vgradientwidget.cc)0
-rw-r--r--karbon/widgets/vreference.cc74
-rw-r--r--karbon/widgets/vreference.cpp74
-rw-r--r--karbon/widgets/vruler.cpp (renamed from karbon/widgets/vruler.cc)0
-rw-r--r--karbon/widgets/vselecttoolbar.cc124
-rw-r--r--karbon/widgets/vselecttoolbar.cpp124
-rw-r--r--karbon/widgets/vsmallpreview.cc282
-rw-r--r--karbon/widgets/vsmallpreview.cpp282
-rw-r--r--karbon/widgets/vstatebutton.cpp (renamed from karbon/widgets/vstatebutton.cc)0
-rw-r--r--karbon/widgets/vstrokefillpreview.cpp (renamed from karbon/widgets/vstrokefillpreview.cc)0
-rw-r--r--karbon/widgets/vtoolbox.cpp (renamed from karbon/widgets/vtoolbox.cc)0
-rw-r--r--karbon/widgets/vtranslate.cpp (renamed from karbon/widgets/vtranslate.cc)0
-rw-r--r--karbon/widgets/vtypebuttonbox.cpp (renamed from karbon/widgets/vtypebuttonbox.cc)0
-rw-r--r--kchart/ChangeLog182
-rw-r--r--kchart/KChartParamsIface.cpp (renamed from kchart/KChartParamsIface.cc)0
-rw-r--r--kchart/KChartViewIface.cpp (renamed from kchart/KChartViewIface.cc)0
-rw-r--r--kchart/Makefile.am62
-rw-r--r--kchart/csvimportdialog.cpp (renamed from kchart/csvimportdialog.cc)0
-rw-r--r--kchart/kchartBackgroundPixmapConfigPage.cc548
-rw-r--r--kchart/kchartBackgroundPixmapConfigPage.cpp548
-rw-r--r--kchart/kchartColorConfigPage.cpp (renamed from kchart/kchartColorConfigPage.cc)0
-rw-r--r--kchart/kchartComboConfigPage.cpp (renamed from kchart/kchartComboConfigPage.cc)0
-rw-r--r--kchart/kchartConfigDialog.cpp (renamed from kchart/kchartConfigDialog.cc)0
-rw-r--r--kchart/kchartDataConfigPage.cc149
-rw-r--r--kchart/kchartDataConfigPage.cpp149
-rw-r--r--kchart/kchartDataEditor.cpp (renamed from kchart/kchartDataEditor.cc)0
-rw-r--r--kchart/kchartFontConfigPage.cpp (renamed from kchart/kchartFontConfigPage.cc)0
-rw-r--r--kchart/kchartHeaderFooterConfigPage.cpp (renamed from kchart/kchartHeaderFooterConfigPage.cc)0
-rw-r--r--kchart/kchartLegendConfigPage.cpp (renamed from kchart/kchartLegendConfigPage.cc)0
-rw-r--r--kchart/kchartLine3dConfigPage.cpp (renamed from kchart/kchartLine3dConfigPage.cc)0
-rw-r--r--kchart/kchartPageLayout.cpp (renamed from kchart/kchartPageLayout.cc)0
-rw-r--r--kchart/kchartParameter3dConfigPage.cpp (renamed from kchart/kchartParameter3dConfigPage.cc)0
-rw-r--r--kchart/kchartParameterConfigPage.cpp (renamed from kchart/kchartParameterConfigPage.cc)0
-rw-r--r--kchart/kchartParameterPieConfigPage.cpp (renamed from kchart/kchartParameterPieConfigPage.cc)0
-rw-r--r--kchart/kchartParameterPolarConfigPage.cpp (renamed from kchart/kchartParameterPolarConfigPage.cc)0
-rw-r--r--kchart/kchartPieConfigPage.cpp (renamed from kchart/kchartPieConfigPage.cc)0
-rw-r--r--kchart/kchartPrinterDlg.cpp (renamed from kchart/kchartPrinterDlg.cc)0
-rw-r--r--kchart/kchartSubTypeChartPage.cpp (renamed from kchart/kchartSubTypeChartPage.cc)0
-rw-r--r--kchart/kchartWizard.cpp (renamed from kchart/kchartWizard.cc)0
-rw-r--r--kchart/kchartWizardLabelsLegendPage.cpp (renamed from kchart/kchartWizardLabelsLegendPage.cc)0
-rw-r--r--kchart/kchartWizardSelectChartSubTypePage.cpp (renamed from kchart/kchartWizardSelectChartSubTypePage.cc)0
-rw-r--r--kchart/kchartWizardSelectChartTypePage.cpp (renamed from kchart/kchartWizardSelectChartTypePage.cc)0
-rw-r--r--kchart/kchartWizardSelectChartTypePage.h2
-rw-r--r--kchart/kchartWizardSelectDataFormatPage.cpp (renamed from kchart/kchartWizardSelectDataFormatPage.cc)0
-rw-r--r--kchart/kchartWizardSelectDataPage.cpp (renamed from kchart/kchartWizardSelectDataPage.cc)0
-rw-r--r--kchart/kchartWizardSetupAxesPage.cpp (renamed from kchart/kchartWizardSetupAxesPage.cc)0
-rw-r--r--kchart/kchartWizardSetupDataPage.cpp (renamed from kchart/kchartWizardSetupDataPage.cc)0
-rw-r--r--kchart/kchart_factory.cc82
-rw-r--r--kchart/kchart_factory.cpp82
-rw-r--r--kchart/kchart_factory_init.cpp (renamed from kchart/kchart_factory_init.cc)0
-rw-r--r--kchart/kchart_params.cpp (renamed from kchart/kchart_params.cc)0
-rw-r--r--kchart/kchart_part.cpp (renamed from kchart/kchart_part.cc)0
-rw-r--r--kchart/kchart_view.cpp (renamed from kchart/kchart_view.cc)0
-rw-r--r--kchart/main.cpp (renamed from kchart/main.cc)0
-rw-r--r--kexi/3rdparty/kexisql/Makefile.msvc7
-rw-r--r--kexi/3rdparty/kolibs/Makefile.am8
-rw-r--r--kexi/3rdparty/kolibs/koGlobal.cpp (renamed from kexi/3rdparty/kolibs/koGlobal.cc)0
-rw-r--r--kexi/3rdparty/kolibs/koPageLayoutDia.cpp (renamed from kexi/3rdparty/kolibs/koPageLayoutDia.cc)0
-rw-r--r--kexi/3rdparty/kolibs/koUnit.cpp (renamed from kexi/3rdparty/kolibs/koUnit.cc)0
-rw-r--r--kexi/3rdparty/kolibs/koUnitWidgets.cpp (renamed from kexi/3rdparty/kolibs/koUnitWidgets.cc)0
-rw-r--r--kexi/doc/dev/TODO-Kexi-js2
-rw-r--r--kexi/plugins/importexport/csv/kexicsvimportdialog.cpp2
-rw-r--r--kexi/plugins/importexport/csv/kexicsvimportdialog.h2
-rwxr-xr-xkexi/tools/build_tarball/build_kexi_tarball.sh2
-rw-r--r--kformula/Makefile.am10
-rw-r--r--kformula/formulastring.cpp (renamed from kformula/formulastring.cc)0
-rw-r--r--kformula/fsparser.cpp (renamed from kformula/fsparser.cc)0
-rw-r--r--kformula/kfconfig.cpp (renamed from kformula/kfconfig.cc)0
-rw-r--r--kformula/kformula_doc.cpp (renamed from kformula/kformula_doc.cc)0
-rw-r--r--kformula/kformula_factory.cpp (renamed from kformula/kformula_factory.cc)0
-rw-r--r--kformula/kformula_view.cpp (renamed from kformula/kformula_view.cc)0
-rw-r--r--kformula/kformula_view_iface.cpp (renamed from kformula/kformula_view_iface.cc)0
-rw-r--r--kformula/kformulawidget.cpp (renamed from kformula/kformulawidget.cc)0
-rw-r--r--kformula/main.cpp (renamed from kformula/main.cc)0
-rw-r--r--kivio/kiviopart/KIvioDocIface.cpp (renamed from kivio/kiviopart/KIvioDocIface.cc)0
-rw-r--r--kivio/kiviopart/KIvioLayerIface.cpp (renamed from kivio/kiviopart/KIvioLayerIface.cc)0
-rw-r--r--kivio/kiviopart/KIvioMapIface.cpp (renamed from kivio/kiviopart/KIvioMapIface.cc)0
-rw-r--r--kivio/kiviopart/KIvioPageIface.cpp (renamed from kivio/kiviopart/KIvioPageIface.cc)0
-rw-r--r--kivio/kiviopart/KIvioStencilIface.cpp (renamed from kivio/kiviopart/KIvioStencilIface.cc)0
-rw-r--r--kivio/kiviopart/KIvioViewIface.cpp (renamed from kivio/kiviopart/KIvioViewIface.cc)0
-rw-r--r--kivio/kiviopart/Makefile.am10
-rw-r--r--kivio/kiviopart/kivio_command.cpp (renamed from kivio/kiviopart/kivio_command.cc)0
-rw-r--r--kivio/kiviopart/kivio_part_init.cpp (renamed from kivio/kiviopart/kivio_part_init.cc)0
-rw-r--r--koshell/Makefile.am4
-rw-r--r--koshell/koshell_main.cpp (renamed from koshell/koshell_main.cc)0
-rw-r--r--koshell/koshell_shell.cpp (renamed from koshell/koshell_shell.cc)0
-rw-r--r--kounavail/Makefile.am4
-rw-r--r--kounavail/kounavail.cpp (renamed from kounavail/kounavail.cc)0
-rw-r--r--kplato/KPtViewIface.cpp (renamed from kplato/KPtViewIface.cc)0
-rw-r--r--kplato/Makefile.am86
-rw-r--r--kplato/TODO2
-rw-r--r--kplato/kplato.tdevelop2
-rw-r--r--kplato/kptaccount.cpp (renamed from kplato/kptaccount.cc)0
-rw-r--r--kplato/kptaccountsdialog.cpp (renamed from kplato/kptaccountsdialog.cc)0
-rw-r--r--kplato/kptaccountspanel.cpp (renamed from kplato/kptaccountspanel.cc)0
-rw-r--r--kplato/kptaccountsview.cpp (renamed from kplato/kptaccountsview.cc)0
-rw-r--r--kplato/kptaccountsviewconfigdialog.cpp (renamed from kplato/kptaccountsviewconfigdialog.cc)0
-rw-r--r--kplato/kptappointment.cpp (renamed from kplato/kptappointment.cc)0
-rw-r--r--kplato/kptcalendar.cpp (renamed from kplato/kptcalendar.cc)0
-rw-r--r--kplato/kptcalendaredit.cpp (renamed from kplato/kptcalendaredit.cc)0
-rw-r--r--kplato/kptcalendareditbase.cpp (renamed from kplato/kptcalendareditbase.cc)0
-rw-r--r--kplato/kptcalendarlistdialog.cpp (renamed from kplato/kptcalendarlistdialog.cc)0
-rw-r--r--kplato/kptcalendarlistdialogbase.cpp (renamed from kplato/kptcalendarlistdialogbase.cc)0
-rw-r--r--kplato/kptcalendarpanel.cpp (renamed from kplato/kptcalendarpanel.cc)0
-rw-r--r--kplato/kptcanvasitem.cpp (renamed from kplato/kptcanvasitem.cc)0
-rw-r--r--kplato/kptcommand.cpp (renamed from kplato/kptcommand.cc)0
-rw-r--r--kplato/kptconfig.cpp (renamed from kplato/kptconfig.cc)0
-rw-r--r--kplato/kptconfigbehaviorpanel.cpp (renamed from kplato/kptconfigbehaviorpanel.cc)0
-rw-r--r--kplato/kptconfigdialog.cpp (renamed from kplato/kptconfigdialog.cc)0
-rw-r--r--kplato/kptcontext.cpp (renamed from kplato/kptcontext.cc)0
-rw-r--r--kplato/kptdatetable.cpp (renamed from kplato/kptdatetable.cc)0
-rw-r--r--kplato/kptdatetime.cpp (renamed from kplato/kptdatetime.cc)0
-rw-r--r--kplato/kptdoublelistviewbase.cpp (renamed from kplato/kptdoublelistviewbase.cc)0
-rw-r--r--kplato/kptduration.cpp (renamed from kplato/kptduration.cc)0
-rw-r--r--kplato/kptfactory.cpp (renamed from kplato/kptfactory.cc)0
-rw-r--r--kplato/kptganttview.cpp (renamed from kplato/kptganttview.cc)0
-rw-r--r--kplato/kptintervaledit.cpp (renamed from kplato/kptintervaledit.cc)0
-rw-r--r--kplato/kptmainprojectdialog.cpp (renamed from kplato/kptmainprojectdialog.cc)0
-rw-r--r--kplato/kptmainprojectpanel.cpp (renamed from kplato/kptmainprojectpanel.cc)0
-rw-r--r--kplato/kptmilestoneprogressdialog.cpp (renamed from kplato/kptmilestoneprogressdialog.cc)0
-rw-r--r--kplato/kptmilestoneprogresspanel.cpp (renamed from kplato/kptmilestoneprogresspanel.cc)0
-rw-r--r--kplato/kptnode.cpp (renamed from kplato/kptnode.cc)0
-rw-r--r--kplato/kptpart.cpp (renamed from kplato/kptpart.cc)0
-rw-r--r--kplato/kptpertcanvas.cpp (renamed from kplato/kptpertcanvas.cc)0
-rw-r--r--kplato/kptpertview.cpp (renamed from kplato/kptpertview.cc)0
-rw-r--r--kplato/kptproject.cpp (renamed from kplato/kptproject.cc)0
-rw-r--r--kplato/kptprojectdialog.cpp (renamed from kplato/kptprojectdialog.cc)0
-rw-r--r--kplato/kptrelation.cpp (renamed from kplato/kptrelation.cc)0
-rw-r--r--kplato/kptrelationdialog.cpp (renamed from kplato/kptrelationdialog.cc)0
-rw-r--r--kplato/kptreportview.cpp (renamed from kplato/kptreportview.cc)0
-rw-r--r--kplato/kptrequestresourcespanel.cpp (renamed from kplato/kptrequestresourcespanel.cc)0
-rw-r--r--kplato/kptresource.cpp (renamed from kplato/kptresource.cc)0
-rw-r--r--kplato/kptresourceappointmentsview.cpp (renamed from kplato/kptresourceappointmentsview.cc)0
-rw-r--r--kplato/kptresourcedialog.cpp (renamed from kplato/kptresourcedialog.cc)0
-rw-r--r--kplato/kptresourcesdialog.cpp (renamed from kplato/kptresourcesdialog.cc)0
-rw-r--r--kplato/kptresourcespanel.cpp (renamed from kplato/kptresourcespanel.cc)0
-rw-r--r--kplato/kptresourceview.cpp (renamed from kplato/kptresourceview.cc)0
-rw-r--r--kplato/kptschedule.cpp (renamed from kplato/kptschedule.cc)0
-rw-r--r--kplato/kptstandardworktimedialog.cpp (renamed from kplato/kptstandardworktimedialog.cc)0
-rw-r--r--kplato/kptsummarytaskdialog.cpp (renamed from kplato/kptsummarytaskdialog.cc)0
-rw-r--r--kplato/kptsummarytaskgeneralpanel.cpp (renamed from kplato/kptsummarytaskgeneralpanel.cc)0
-rw-r--r--kplato/kpttask.cpp (renamed from kplato/kpttask.cc)0
-rw-r--r--kplato/kpttaskappointmentsview.cpp (renamed from kplato/kpttaskappointmentsview.cc)0
-rw-r--r--kplato/kpttaskcostpanel.cpp (renamed from kplato/kpttaskcostpanel.cc)0
-rw-r--r--kplato/kpttaskdefaultpanel.cpp (renamed from kplato/kpttaskdefaultpanel.cc)0
-rw-r--r--kplato/kpttaskdialog.cpp (renamed from kplato/kpttaskdialog.cc)0
-rw-r--r--kplato/kpttaskgeneralpanel.cpp (renamed from kplato/kpttaskgeneralpanel.cc)0
-rw-r--r--kplato/kpttaskprogressdialog.cpp (renamed from kplato/kpttaskprogressdialog.cc)0
-rw-r--r--kplato/kpttaskprogresspanel.cpp (renamed from kplato/kpttaskprogresspanel.cc)0
-rw-r--r--kplato/kptview.cpp (renamed from kplato/kptview.cc)0
-rw-r--r--kplato/kptwbsdefinition.cc188
-rw-r--r--kplato/kptwbsdefinition.cpp188
-rw-r--r--kplato/kptwbsdefinitiondialog.cpp (renamed from kplato/kptwbsdefinitiondialog.cc)0
-rw-r--r--kplato/kptwbsdefinitionpanel.cpp (renamed from kplato/kptwbsdefinitionpanel.cc)0
-rw-r--r--kplato/main.cpp (renamed from kplato/main.cc)0
-rw-r--r--kpresenter/KPrMSPresentationSetup.cpp2
-rw-r--r--kpresenter/KPrMarginWidget.cpp2
-rw-r--r--kpresenter/KPrSoundPlayer.cpp2
-rw-r--r--kpresenter/KPrSoundPlayer.h2
-rw-r--r--kpresenter/KPrTextObject.cpp2
-rw-r--r--kpresenter/KPrTextProperty.cpp2
-rw-r--r--kpresenter/KPrTextProperty.h2
-rw-r--r--kpresenter/KPrView.cpp2
-rw-r--r--kpresenter/KPrWebPresentation.cpp2
-rw-r--r--kspread/CHANGES2
-rw-r--r--kspread/DESIGN.html6
-rw-r--r--kspread/Doxyfile3
-rw-r--r--kspread/KSpreadAppIface.cpp (renamed from kspread/KSpreadAppIface.cc)0
-rw-r--r--kspread/KSpreadCellIface.cpp (renamed from kspread/KSpreadCellIface.cc)0
-rw-r--r--kspread/KSpreadColumnIface.cpp (renamed from kspread/KSpreadColumnIface.cc)0
-rw-r--r--kspread/KSpreadDocIface.cpp (renamed from kspread/KSpreadDocIface.cc)0
-rw-r--r--kspread/KSpreadLayoutIface.cpp (renamed from kspread/KSpreadLayoutIface.cc)0
-rw-r--r--kspread/KSpreadMapIface.cpp (renamed from kspread/KSpreadMapIface.cc)0
-rw-r--r--kspread/KSpreadRowIface.cpp (renamed from kspread/KSpreadRowIface.cc)0
-rw-r--r--kspread/KSpreadTableIface.cpp (renamed from kspread/KSpreadTableIface.cc)0
-rw-r--r--kspread/KSpreadViewIface.cpp (renamed from kspread/KSpreadViewIface.cc)0
-rw-r--r--kspread/Makefile.am46
-rw-r--r--kspread/TODO2
-rw-r--r--kspread/commands.cpp (renamed from kspread/commands.cc)0
-rw-r--r--kspread/damages.cpp (renamed from kspread/damages.cc)0
-rw-r--r--kspread/dependencies.cpp (renamed from kspread/dependencies.cc)0
-rw-r--r--kspread/dialogs/Makefile.am60
-rw-r--r--kspread/dialogs/kspread_dlg_angle.cpp (renamed from kspread/dialogs/kspread_dlg_angle.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_area.cpp (renamed from kspread/dialogs/kspread_dlg_area.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_comment.cpp (renamed from kspread/dialogs/kspread_dlg_comment.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_conditional.cpp (renamed from kspread/dialogs/kspread_dlg_conditional.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_cons.cpp (renamed from kspread/dialogs/kspread_dlg_cons.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_csv.cpp (renamed from kspread/dialogs/kspread_dlg_csv.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_database.cpp (renamed from kspread/dialogs/kspread_dlg_database.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_find.cpp (renamed from kspread/dialogs/kspread_dlg_find.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_format.cpp (renamed from kspread/dialogs/kspread_dlg_format.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_formula.cpp (renamed from kspread/dialogs/kspread_dlg_formula.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_goalseek.cpp (renamed from kspread/dialogs/kspread_dlg_goalseek.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_goto.cpp (renamed from kspread/dialogs/kspread_dlg_goto.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_insert.cpp (renamed from kspread/dialogs/kspread_dlg_insert.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_layout.cpp (renamed from kspread/dialogs/kspread_dlg_layout.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_list.cpp (renamed from kspread/dialogs/kspread_dlg_list.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_paperlayout.cpp (renamed from kspread/dialogs/kspread_dlg_paperlayout.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_pasteinsert.cpp (renamed from kspread/dialogs/kspread_dlg_pasteinsert.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_preference.cpp (renamed from kspread/dialogs/kspread_dlg_preference.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_reference.cpp (renamed from kspread/dialogs/kspread_dlg_reference.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_resize2.cpp (renamed from kspread/dialogs/kspread_dlg_resize2.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_series.cpp (renamed from kspread/dialogs/kspread_dlg_series.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_show.cpp (renamed from kspread/dialogs/kspread_dlg_show.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_showColRow.cpp (renamed from kspread/dialogs/kspread_dlg_showColRow.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_sort.cpp (renamed from kspread/dialogs/kspread_dlg_sort.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_special.cpp (renamed from kspread/dialogs/kspread_dlg_special.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_styles.cpp (renamed from kspread/dialogs/kspread_dlg_styles.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_subtotal.cpp (renamed from kspread/dialogs/kspread_dlg_subtotal.cc)0
-rw-r--r--kspread/dialogs/kspread_dlg_validity.cpp (renamed from kspread/dialogs/kspread_dlg_validity.cc)0
-rw-r--r--kspread/dialogs/link.cpp (renamed from kspread/dialogs/link.cc)0
-rw-r--r--kspread/dialogs/sheet_properties.cpp (renamed from kspread/dialogs/sheet_properties.cc)0
-rw-r--r--kspread/digest.cpp (renamed from kspread/digest.cc)0
-rw-r--r--kspread/formula.cpp (renamed from kspread/formula.cc)0
-rw-r--r--kspread/functions.cc526
-rw-r--r--kspread/functions.cpp526
-rw-r--r--kspread/kspread_autofill.cpp (renamed from kspread/kspread_autofill.cc)0
-rw-r--r--kspread/kspread_brush.cpp (renamed from kspread/kspread_brush.cc)0
-rw-r--r--kspread/kspread_canvas.cpp (renamed from kspread/kspread_canvas.cc)0
-rw-r--r--kspread/kspread_cell.cpp (renamed from kspread/kspread_cell.cc)0
-rw-r--r--kspread/kspread_cluster.cpp (renamed from kspread/kspread_cluster.cc)0
-rw-r--r--kspread/kspread_condition.cpp (renamed from kspread/kspread_condition.cc)0
-rw-r--r--kspread/kspread_doc.cpp (renamed from kspread/kspread_doc.cc)0
-rw-r--r--kspread/kspread_editors.cpp (renamed from kspread/kspread_editors.cc)0
-rw-r--r--kspread/kspread_events.cpp (renamed from kspread/kspread_events.cc)0
-rw-r--r--kspread/kspread_factory.cpp (renamed from kspread/kspread_factory.cc)0
-rw-r--r--kspread/kspread_factory_init.cpp (renamed from kspread/kspread_factory_init.cc)0
-rw-r--r--kspread/kspread_format.cpp (renamed from kspread/kspread_format.cc)0
-rw-r--r--kspread/kspread_functions_conversion.cpp (renamed from kspread/kspread_functions_conversion.cc)0
-rw-r--r--kspread/kspread_functions_database.cpp (renamed from kspread/kspread_functions_database.cc)0
-rw-r--r--kspread/kspread_functions_datetime.cpp (renamed from kspread/kspread_functions_datetime.cc)0
-rw-r--r--kspread/kspread_functions_engineering.cpp (renamed from kspread/kspread_functions_engineering.cc)0
-rw-r--r--kspread/kspread_functions_financial.cpp (renamed from kspread/kspread_functions_financial.cc)0
-rw-r--r--kspread/kspread_functions_helper.cpp (renamed from kspread/kspread_functions_helper.cc)0
-rw-r--r--kspread/kspread_functions_information.cpp (renamed from kspread/kspread_functions_information.cc)0
-rw-r--r--kspread/kspread_functions_logic.cpp (renamed from kspread/kspread_functions_logic.cc)0
-rw-r--r--kspread/kspread_functions_math.cpp (renamed from kspread/kspread_functions_math.cc)0
-rw-r--r--kspread/kspread_functions_reference.cpp (renamed from kspread/kspread_functions_reference.cc)0
-rw-r--r--kspread/kspread_functions_statistical.cpp (renamed from kspread/kspread_functions_statistical.cc)0
-rw-r--r--kspread/kspread_functions_text.cpp (renamed from kspread/kspread_functions_text.cc)0
-rw-r--r--kspread/kspread_functions_trig.cpp (renamed from kspread/kspread_functions_trig.cc)0
-rw-r--r--kspread/kspread_genvalidationstyle.cpp (renamed from kspread/kspread_genvalidationstyle.cc)0
-rw-r--r--kspread/kspread_handler.cpp (renamed from kspread/kspread_handler.cc)0
-rw-r--r--kspread/kspread_locale.cpp (renamed from kspread/kspread_locale.cc)0
-rw-r--r--kspread/kspread_map.cpp (renamed from kspread/kspread_map.cc)0
-rw-r--r--kspread/kspread_numformat.cpp (renamed from kspread/kspread_numformat.cc)0
-rw-r--r--kspread/kspread_object.cpp (renamed from kspread/kspread_object.cc)0
-rw-r--r--kspread/kspread_pen.cpp (renamed from kspread/kspread_pen.cc)0
-rw-r--r--kspread/kspread_sheet.cpp (renamed from kspread/kspread_sheet.cc)0
-rw-r--r--kspread/kspread_sheet.h4
-rw-r--r--kspread/kspread_sheetprint.cc1807
-rw-r--r--kspread/kspread_sheetprint.cpp1807
-rw-r--r--kspread/kspread_style.cpp (renamed from kspread/kspread_style.cc)0
-rw-r--r--kspread/kspread_style_manager.cpp (renamed from kspread/kspread_style_manager.cc)0
-rw-r--r--kspread/kspread_toolbox.cpp (renamed from kspread/kspread_toolbox.cc)0
-rw-r--r--kspread/kspread_undo.cpp (renamed from kspread/kspread_undo.cc)0
-rw-r--r--kspread/kspread_util.cc1218
-rw-r--r--kspread/kspread_util.cpp1218
-rw-r--r--kspread/kspread_value.cpp (renamed from kspread/kspread_value.cc)0
-rw-r--r--kspread/kspread_view.cpp (renamed from kspread/kspread_view.cc)0
-rw-r--r--kspread/main.cpp (renamed from kspread/main.cc)0
-rw-r--r--kspread/manipulator.cpp (renamed from kspread/manipulator.cc)0
-rw-r--r--kspread/manipulator_data.cpp (renamed from kspread/manipulator_data.cc)0
-rw-r--r--kspread/plugins/insertcalendar/Makefile.am6
-rw-r--r--kspread/plugins/insertcalendar/kspread_insertcalendardialog.cpp (renamed from kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc)0
-rw-r--r--kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cpp (renamed from kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc)0
-rw-r--r--kspread/plugins/scripting/Makefile.am2
-rw-r--r--kspread/plugins/scripting/scripting.cpp (renamed from kspread/plugins/scripting/scripting.cc)0
-rw-r--r--kspread/region.cpp (renamed from kspread/region.cc)0
-rw-r--r--kspread/selection.cpp (renamed from kspread/selection.cc)0
-rw-r--r--kspread/tests/Makefile.am12
-rw-r--r--kspread/tests/formula_tester.cpp (renamed from kspread/tests/formula_tester.cc)0
-rw-r--r--kspread/tests/inspector.cpp (renamed from kspread/tests/inspector.cc)0
-rw-r--r--kspread/tests/test_formula.cpp (renamed from kspread/tests/test_formula.cc)0
-rw-r--r--kspread/tests/tester.cpp (renamed from kspread/tests/tester.cc)0
-rw-r--r--kspread/tests/testrunner.cpp (renamed from kspread/tests/testrunner.cc)0
-rw-r--r--kspread/tests/value_tester.cpp (renamed from kspread/tests/value_tester.cc)0
-rw-r--r--kspread/valuecalc.cpp (renamed from kspread/valuecalc.cc)0
-rw-r--r--kspread/valueconverter.cpp (renamed from kspread/valueconverter.cc)0
-rw-r--r--kspread/valueformatter.cpp (renamed from kspread/valueformatter.cc)0
-rw-r--r--kspread/valueparser.cpp (renamed from kspread/valueparser.cc)0
-rw-r--r--kword/DEBUG2
-rw-r--r--kword/HACKING12
-rw-r--r--kword/KWCommand.cpp2
-rw-r--r--kword/KWFrameSet.cpp2
-rw-r--r--kword/defs.h2
-rw-r--r--kword/mailmerge/KWClassicSerialDataSource.cpp2
-rw-r--r--lib/Makefile.am8
-rw-r--r--lib/kformula/Makefile.am34
-rw-r--r--lib/kformula/MatrixDialog.cpp (renamed from lib/kformula/MatrixDialog.cc)0
-rw-r--r--lib/kformula/actionelement.cpp (renamed from lib/kformula/actionelement.cc)0
-rw-r--r--lib/kformula/basicelement.cpp (renamed from lib/kformula/basicelement.cc)0
-rw-r--r--lib/kformula/bracketelement.cpp (renamed from lib/kformula/bracketelement.cc)0
-rw-r--r--lib/kformula/contextstyle.cpp (renamed from lib/kformula/contextstyle.cc)0
-rw-r--r--lib/kformula/creationstrategy.cpp (renamed from lib/kformula/creationstrategy.cc)0
-rw-r--r--lib/kformula/elementtype.cpp (renamed from lib/kformula/elementtype.cc)0
-rw-r--r--lib/kformula/encloseelement.cpp (renamed from lib/kformula/encloseelement.cc)0
-rw-r--r--lib/kformula/entities.cpp (renamed from lib/kformula/entities.cc)0
-rw-r--r--lib/kformula/errorelement.cpp (renamed from lib/kformula/errorelement.cc)0
-rw-r--r--lib/kformula/fontstyle.cc891
-rw-r--r--lib/kformula/fontstyle.cpp891
-rw-r--r--lib/kformula/formulacursor.cpp (renamed from lib/kformula/formulacursor.cc)0
-rw-r--r--lib/kformula/formulaelement.cpp (renamed from lib/kformula/formulaelement.cc)0
-rw-r--r--lib/kformula/fractionelement.cpp (renamed from lib/kformula/fractionelement.cc)0
-rw-r--r--lib/kformula/glyphelement.cpp (renamed from lib/kformula/glyphelement.cc)0
-rw-r--r--lib/kformula/identifierelement.cpp (renamed from lib/kformula/identifierelement.cc)0
-rw-r--r--lib/kformula/indexelement.cpp (renamed from lib/kformula/indexelement.cc)0
-rw-r--r--lib/kformula/kformulacommand.cpp (renamed from lib/kformula/kformulacommand.cc)0
-rw-r--r--lib/kformula/kformulacompatibility.cpp (renamed from lib/kformula/kformulacompatibility.cc)0
-rw-r--r--lib/kformula/kformulaconfigpage.cpp (renamed from lib/kformula/kformulaconfigpage.cc)0
-rw-r--r--lib/kformula/kformulacontainer.cpp (renamed from lib/kformula/kformulacontainer.cc)0
-rw-r--r--lib/kformula/kformuladocument.cpp (renamed from lib/kformula/kformuladocument.cc)0
-rw-r--r--lib/kformula/kformulainputfilter.cpp (renamed from lib/kformula/kformulainputfilter.cc)0
-rw-r--r--lib/kformula/kformulamathmlread.cpp (renamed from lib/kformula/kformulamathmlread.cc)0
-rw-r--r--lib/kformula/kformulamimesource.cpp (renamed from lib/kformula/kformulamimesource.cc)0
-rw-r--r--lib/kformula/kformulaview.cpp (renamed from lib/kformula/kformulaview.cc)0
-rw-r--r--lib/kformula/kformulawidget.cpp (renamed from lib/kformula/kformulawidget.cc)0
-rw-r--r--lib/kformula/main.cpp (renamed from lib/kformula/main.cc)0
-rw-r--r--lib/kformula/matrixelement.cpp (renamed from lib/kformula/matrixelement.cc)0
-rw-r--r--lib/kformula/numberelement.cpp (renamed from lib/kformula/numberelement.cc)0
-rw-r--r--lib/kformula/oasiscreationstrategy.cpp (renamed from lib/kformula/oasiscreationstrategy.cc)0
-rw-r--r--lib/kformula/operatordictionary.cpp (renamed from lib/kformula/operatordictionary.cc)0
-rw-r--r--lib/kformula/operatorelement.cpp (renamed from lib/kformula/operatorelement.cc)0
-rw-r--r--lib/kformula/paddedelement.cpp (renamed from lib/kformula/paddedelement.cc)0
-rw-r--r--lib/kformula/phantomelement.cpp (renamed from lib/kformula/phantomelement.cc)0
-rw-r--r--lib/kformula/prototype/gensymbolfontmap.py8
-rw-r--r--lib/kformula/rootelement.cpp (renamed from lib/kformula/rootelement.cc)0
-rwxr-xr-xlib/kformula/scripts/bynames.py2
-rwxr-xr-xlib/kformula/scripts/oper-dict.py2
-rw-r--r--lib/kformula/sequenceelement.cpp (renamed from lib/kformula/sequenceelement.cc)0
-rw-r--r--lib/kformula/sequenceparser.cpp (renamed from lib/kformula/sequenceparser.cc)0
-rw-r--r--lib/kformula/spaceelement.cpp (renamed from lib/kformula/spaceelement.cc)0
-rw-r--r--lib/kformula/stringelement.cpp (renamed from lib/kformula/stringelement.cc)0
-rw-r--r--lib/kformula/styleelement.cpp (renamed from lib/kformula/styleelement.cc)0
-rw-r--r--lib/kformula/symbolaction.cpp (renamed from lib/kformula/symbolaction.cc)0
-rw-r--r--lib/kformula/symbolelement.cpp (renamed from lib/kformula/symbolelement.cc)0
-rw-r--r--lib/kformula/symbolfontmapping.cpp (renamed from lib/kformula/symbolfontmapping.cc)0
-rw-r--r--lib/kformula/symboltable.cc152
-rw-r--r--lib/kformula/symboltable.cpp152
-rw-r--r--lib/kformula/textelement.cpp (renamed from lib/kformula/textelement.cc)0
-rw-r--r--lib/kformula/tokenelement.cpp (renamed from lib/kformula/tokenelement.cc)0
-rw-r--r--lib/kformula/tokenstyleelement.cpp (renamed from lib/kformula/tokenstyleelement.cc)0
-rw-r--r--lib/kformula/unicodetable.cpp (renamed from lib/kformula/unicodetable.cc)0
-rw-r--r--lib/kofficecore/KoApplicationIface.cpp (renamed from lib/kofficecore/KoApplicationIface.cc)0
-rw-r--r--lib/kofficecore/KoDocument.cpp4
-rw-r--r--lib/kofficecore/KoDocumentChild.cpp2
-rw-r--r--lib/kofficecore/KoDocumentIface.cpp (renamed from lib/kofficecore/KoDocumentIface.cc)0
-rw-r--r--lib/kofficecore/KoMainWindowIface.cc65
-rw-r--r--lib/kofficecore/KoMainWindowIface.cpp65
-rw-r--r--lib/kofficecore/KoViewIface.cc76
-rw-r--r--lib/kofficecore/KoViewIface.cpp76
-rw-r--r--lib/kofficecore/Makefile.am6
-rw-r--r--lib/kofficecore/kofficeversion.cpp (renamed from lib/kofficecore/kofficeversion.cc)0
-rw-r--r--lib/kofficeui/KoImageResource.cpp2
-rw-r--r--lib/kopainter/Makefile.am24
-rw-r--r--lib/kopainter/koColor.cpp (renamed from lib/kopainter/koColor.cc)0
-rw-r--r--lib/kopainter/koColorChooser.cpp (renamed from lib/kopainter/koColorChooser.cc)0
-rw-r--r--lib/kopainter/koColorSlider.cpp (renamed from lib/kopainter/koColorSlider.cc)0
-rw-r--r--lib/kopainter/koFrameButton.cpp (renamed from lib/kopainter/koFrameButton.cc)0
-rw-r--r--lib/kopainter/koIconChooser.cpp (renamed from lib/kopainter/koIconChooser.cc)0
-rw-r--r--lib/kopainter/ko_cmyk_widget.cpp (renamed from lib/kopainter/ko_cmyk_widget.cc)0
-rw-r--r--lib/kopainter/ko_color_wheel.cpp (renamed from lib/kopainter/ko_color_wheel.cc)0
-rw-r--r--lib/kopainter/ko_gray_widget.cpp (renamed from lib/kopainter/ko_gray_widget.cc)0
-rw-r--r--lib/kopainter/ko_hsv_widget.cpp (renamed from lib/kopainter/ko_hsv_widget.cc)0
-rw-r--r--lib/kopainter/ko_rgb_widget.cpp (renamed from lib/kopainter/ko_rgb_widget.cc)0
-rw-r--r--lib/kopainter/kogradientmanager.cpp (renamed from lib/kopainter/kogradientmanager.cc)0
-rw-r--r--lib/kopainter/svgpathparser.cpp (renamed from lib/kopainter/svgpathparser.cc)0
-rw-r--r--lib/kopalette/Makefile.am8
-rw-r--r--lib/kopalette/kopalette.cpp (renamed from lib/kopalette/kopalette.cc)0
-rw-r--r--lib/kopalette/kopalettemanager.cpp (renamed from lib/kopalette/kopalettemanager.cc)0
-rw-r--r--lib/kopalette/kotabpalette.cpp (renamed from lib/kopalette/kotabpalette.cc)0
-rw-r--r--lib/kopalette/kotoolboxpalette.cpp (renamed from lib/kopalette/kotoolboxpalette.cc)0
-rw-r--r--lib/kotext/KoRichText.cpp2
-rw-r--r--lib/kotext/KoTextFormatter.cpp2
-rw-r--r--lib/kotext/KoTextParag.h2
-rw-r--r--lib/kotext/KoTextViewIface.cpp (renamed from lib/kotext/KoTextViewIface.cc)0
-rw-r--r--lib/kotext/Makefile.am2
-rw-r--r--lib/kotext/tests/kotextformattertest.cpp2
-rw-r--r--lib/kross/python/cxx/Config.h (renamed from lib/kross/python/cxx/Config.hxx)0
-rw-r--r--lib/kross/python/cxx/Exception.h212
-rw-r--r--lib/kross/python/cxx/Exception.hxx212
-rw-r--r--lib/kross/python/cxx/Extensions.h756
-rw-r--r--lib/kross/python/cxx/Extensions.hxx756
-rw-r--r--lib/kross/python/cxx/IndirectPythonInterface.cpp550
-rw-r--r--lib/kross/python/cxx/IndirectPythonInterface.cxx550
-rw-r--r--lib/kross/python/cxx/IndirectPythonInterface.h156
-rw-r--r--lib/kross/python/cxx/IndirectPythonInterface.hxx156
-rw-r--r--lib/kross/python/cxx/Makefile.am6
-rw-r--r--lib/kross/python/cxx/Objects.h2804
-rw-r--r--lib/kross/python/cxx/Objects.hxx2804
-rw-r--r--lib/kross/python/cxx/PyCXX.html26
-rw-r--r--lib/kross/python/cxx/README.html22
-rw-r--r--lib/kross/python/cxx/cxx_extensions.cpp1287
-rw-r--r--lib/kross/python/cxx/cxx_extensions.cxx1287
-rw-r--r--lib/kross/python/cxx/cxxsupport.cpp142
-rw-r--r--lib/kross/python/cxx/cxxsupport.cxx142
-rw-r--r--lib/kross/python/pythonconfig.h6
-rw-r--r--lib/kwmf/Makefile.am4
-rw-r--r--lib/kwmf/kowmfpaint.cpp (renamed from lib/kwmf/kowmfpaint.cc)0
-rw-r--r--lib/kwmf/kowmfread.cpp (renamed from lib/kwmf/kowmfread.cc)0
-rw-r--r--lib/kwmf/kowmfreadprivate.cpp (renamed from lib/kwmf/kowmfreadprivate.cc)0
-rw-r--r--lib/kwmf/kowmfstack.cpp (renamed from lib/kwmf/kowmfstack.cc)0
-rw-r--r--lib/kwmf/kowmfwrite.cpp (renamed from lib/kwmf/kowmfwrite.cc)0
-rw-r--r--lib/kwmf/kwmf.cpp (renamed from lib/kwmf/kwmf.cc)0
-rw-r--r--lib/kwmf/qwmf.cpp (renamed from lib/kwmf/qwmf.cc)0
-rw-r--r--tools/converter/koconverter.cpp2
-rw-r--r--tools/kthesaurus/Makefile.am4
-rw-r--r--tools/kthesaurus/main.cc87
-rw-r--r--tools/kthesaurus/main.cpp87
-rw-r--r--tools/spell/Makefile.am2
-rw-r--r--tools/spell/main.cpp (renamed from tools/spell/main.cc)0
-rw-r--r--tools/thesaurus/Makefile.am4
-rw-r--r--tools/thesaurus/main.cc817
-rw-r--r--tools/thesaurus/main.cpp817
1529 files changed, 94813 insertions, 94819 deletions
diff --git a/chalk/Makefile.am b/chalk/Makefile.am
index 0940e393d..3a8f35134 100644
--- a/chalk/Makefile.am
+++ b/chalk/Makefile.am
@@ -2,13 +2,13 @@ INCLUDES = $(KOFFICE_INCLUDES) $(KOPAINTER_INCLUDES) $(all_includes)
## The common lib, shared between the part, the plugins, and the filters
lib_LTLIBRARIES = libchalkcommon.la
-libchalkcommon_la_SOURCES = dummy.cc
+libchalkcommon_la_SOURCES = dummy.cpp
libchalkcommon_la_LDFLAGS = $(all_libraries) $(LIB_TQT) -version-info 1:0 -no-undefined
libchalkcommon_la_LIBADD = sdk/libchalksdk.la core/libchalkimage.la ui/libchalkui.la chalkcolor/libchalkcolor.la $(LCMS_LIBS) $(LIB_KOFFICEUI) $(LIB_KOPAINTER) $(LIB_KOPALETTE) $(LIB_XINPUTEXT)
## The part
kde_module_LTLIBRARIES = libchalkpart.la
-libchalkpart_la_SOURCES = chalk_part_init.cc
+libchalkpart_la_SOURCES = chalk_part_init.cpp
libchalkpart_la_LDFLAGS = $(all_libraries) $(LIB_TQT) -module $(KDE_PLUGIN)
libchalkpart_la_LIBADD = $(KOFFICE_LIBS) libchalkcommon.la ../chalk/ui/libchalkui.la
@@ -17,7 +17,7 @@ METASOURCES = AUTO
## The tdeinit loadable module and executable
tdeinit_LTLIBRARIES = chalk.la
bin_PROGRAMS =
-chalk_la_SOURCES = main.cc
+chalk_la_SOURCES = main.cpp
chalk_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT)
chalk_la_LIBADD = $(LIB_KOFFICECORE)
@@ -30,14 +30,14 @@ rc_DATA = chalk.rc chalk_readonly.rc
SUBDIRS = sdk chalkcolor core ui . dtd colorspaces plugins data pics
# Needed to compile libchalkcommon.la, which has no source files to itself
# but everything in static libs.
-dummy.cc:
- echo > dummy.cc
+dummy.cpp:
+ echo > dummy.cpp
messages: rc.cpp
$(EXTRACTRC) `find . -name \*.ui` >> rc.cpp
$(EXTRACTRC) `find . -name \*.rc` >> rc.cpp
perl extracti18n.pl > i18ndata
- $(XGETTEXT) i18ndata rc.cpp `find . -name \*.cc -o -name \*.h -o -name \*.cpp` ui/kis_aboutdata.h -o $(podir)/chalk.pot
+ $(XGETTEXT) i18ndata rc.cpp `find . -name \*.cpp -o -name \*.h -o -name \*.cpp` ui/kis_aboutdata.h -o $(podir)/chalk.pot
rm -f i18ndata
DOXYGEN_EXCLUDE = CImg.h colorspaces plugins chalkcolor/colorspaces core/tiles
diff --git a/chalk/chalk_part_init.cc b/chalk/chalk_part_init.cc
deleted file mode 100644
index b56919749..000000000
--- a/chalk/chalk_part_init.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * kis_part_init.cc - part of Krayon
- *
- * Copyright (c) 1999 Matthias Elter <elter@kde.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include "ui/kis_factory.h"
-
-
-K_EXPORT_COMPONENT_FACTORY( libchalkpart, KisFactory )
diff --git a/chalk/chalk_part_init.cpp b/chalk/chalk_part_init.cpp
new file mode 100644
index 000000000..1915112e4
--- /dev/null
+++ b/chalk/chalk_part_init.cpp
@@ -0,0 +1,23 @@
+/*
+ * kis_part_init.cpp - part of Krayon
+ *
+ * Copyright (c) 1999 Matthias Elter <elter@kde.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include "ui/kis_factory.h"
+
+
+K_EXPORT_COMPONENT_FACTORY( libchalkpart, KisFactory )
diff --git a/chalk/chalkcolor/Makefile.am b/chalk/chalkcolor/Makefile.am
index 1fee38366..d31ea1c52 100644
--- a/chalk/chalkcolor/Makefile.am
+++ b/chalk/chalkcolor/Makefile.am
@@ -11,14 +11,14 @@ CXXFLAGS += $(OPENEXR_CXXFLAGS)
lib_LTLIBRARIES = libchalkcolor.la
if have_openexr
-OPENEXR_SOURCES=kis_f16half_base_colorspace.cc
+OPENEXR_SOURCES=kis_f16half_base_colorspace.cpp
endif
-libchalkcolor_la_SOURCES = kis_color.cc kis_colorspace.cc \
- kis_colorspace_iface.cc kis_colorspace_iface.skel kis_composite_op.cc kis_profile.cc \
- kis_histogram_producer.cc kis_basic_histogram_producers.cc kis_abstract_colorspace.cc \
- kis_colorspace_factory_registry.cc kis_color_conversions.cc kis_u8_base_colorspace.cc \
- kis_u16_base_colorspace.cc kis_f32_base_colorspace.cc $(OPENEXR_SOURCES)
+libchalkcolor_la_SOURCES = kis_color.cpp kis_colorspace.cpp \
+ kis_colorspace_iface.cpp kis_colorspace_iface.skel kis_composite_op.cpp kis_profile.cpp \
+ kis_histogram_producer.cpp kis_basic_histogram_producers.cpp kis_abstract_colorspace.cpp \
+ kis_colorspace_factory_registry.cpp kis_color_conversions.cpp kis_u8_base_colorspace.cpp \
+ kis_u16_base_colorspace.cpp kis_f32_base_colorspace.cpp $(OPENEXR_SOURCES)
libchalkcolor_la_LDFLAGS = -version-info 1:0:0 -no-undefined $(all_libraries)
libchalkcolor_la_LIBADD = colorspaces/libchalkcolorspaces.la $(LCMS_LIBS) $(LIB_TDEPARTS) $(LIB_TDECORE) $(LIB_TQT) $(OPENEXR_LIBS)
diff --git a/chalk/chalkcolor/colorspaces/Makefile.am b/chalk/chalkcolor/colorspaces/Makefile.am
index 90f75d290..18bd587b1 100644
--- a/chalk/chalkcolor/colorspaces/Makefile.am
+++ b/chalk/chalkcolor/colorspaces/Makefile.am
@@ -6,8 +6,8 @@ INCLUDES = -I$(srcdir)/.. \
noinst_LTLIBRARIES = libchalkcolorspaces.la
libchalkcolorspaces_la_SOURCES = \
- kis_alpha_colorspace.cc \
- kis_lab_colorspace.cc
+ kis_alpha_colorspace.cpp \
+ kis_lab_colorspace.cpp
noinst_HEADERS = \
kis_alpha_colorspace.h \
diff --git a/chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cc b/chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cpp
index f7c1fbce3..f7c1fbce3 100644
--- a/chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cc
+++ b/chalk/chalkcolor/colorspaces/kis_alpha_colorspace.cpp
diff --git a/chalk/chalkcolor/colorspaces/kis_lab_colorspace.cc b/chalk/chalkcolor/colorspaces/kis_lab_colorspace.cpp
index c5c7ac5a0..c5c7ac5a0 100644
--- a/chalk/chalkcolor/colorspaces/kis_lab_colorspace.cc
+++ b/chalk/chalkcolor/colorspaces/kis_lab_colorspace.cpp
diff --git a/chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cc b/chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cpp
index 835ebfa1f..835ebfa1f 100644
--- a/chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cc
+++ b/chalk/chalkcolor/colorspaces/kis_xyz_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_abstract_colorspace.cc b/chalk/chalkcolor/kis_abstract_colorspace.cpp
index 7f5155348..7f5155348 100644
--- a/chalk/chalkcolor/kis_abstract_colorspace.cc
+++ b/chalk/chalkcolor/kis_abstract_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_basic_histogram_producers.cc b/chalk/chalkcolor/kis_basic_histogram_producers.cpp
index a37a1fb3f..a37a1fb3f 100644
--- a/chalk/chalkcolor/kis_basic_histogram_producers.cc
+++ b/chalk/chalkcolor/kis_basic_histogram_producers.cpp
diff --git a/chalk/chalkcolor/kis_color.cc b/chalk/chalkcolor/kis_color.cpp
index 7d6acb896..7d6acb896 100644
--- a/chalk/chalkcolor/kis_color.cc
+++ b/chalk/chalkcolor/kis_color.cpp
diff --git a/chalk/chalkcolor/kis_color_conversions.cc b/chalk/chalkcolor/kis_color_conversions.cpp
index e517c9f75..e517c9f75 100644
--- a/chalk/chalkcolor/kis_color_conversions.cc
+++ b/chalk/chalkcolor/kis_color_conversions.cpp
diff --git a/chalk/chalkcolor/kis_colorspace.cc b/chalk/chalkcolor/kis_colorspace.cpp
index c13a2e08e..c13a2e08e 100644
--- a/chalk/chalkcolor/kis_colorspace.cc
+++ b/chalk/chalkcolor/kis_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_colorspace_factory_registry.cc b/chalk/chalkcolor/kis_colorspace_factory_registry.cpp
index d9b2591ca..d9b2591ca 100644
--- a/chalk/chalkcolor/kis_colorspace_factory_registry.cc
+++ b/chalk/chalkcolor/kis_colorspace_factory_registry.cpp
diff --git a/chalk/chalkcolor/kis_colorspace_iface.cc b/chalk/chalkcolor/kis_colorspace_iface.cpp
index bde82ff3a..bde82ff3a 100644
--- a/chalk/chalkcolor/kis_colorspace_iface.cc
+++ b/chalk/chalkcolor/kis_colorspace_iface.cpp
diff --git a/chalk/chalkcolor/kis_composite_op.cc b/chalk/chalkcolor/kis_composite_op.cpp
index 4cffd7668..4cffd7668 100644
--- a/chalk/chalkcolor/kis_composite_op.cc
+++ b/chalk/chalkcolor/kis_composite_op.cpp
diff --git a/chalk/chalkcolor/kis_f16half_base_colorspace.cc b/chalk/chalkcolor/kis_f16half_base_colorspace.cpp
index d4886c5f5..d4886c5f5 100644
--- a/chalk/chalkcolor/kis_f16half_base_colorspace.cc
+++ b/chalk/chalkcolor/kis_f16half_base_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_f32_base_colorspace.cc b/chalk/chalkcolor/kis_f32_base_colorspace.cpp
index 27a6a312e..27a6a312e 100644
--- a/chalk/chalkcolor/kis_f32_base_colorspace.cc
+++ b/chalk/chalkcolor/kis_f32_base_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_histogram_producer.cc b/chalk/chalkcolor/kis_histogram_producer.cpp
index bbea95bac..bbea95bac 100644
--- a/chalk/chalkcolor/kis_histogram_producer.cc
+++ b/chalk/chalkcolor/kis_histogram_producer.cpp
diff --git a/chalk/chalkcolor/kis_profile.cc b/chalk/chalkcolor/kis_profile.cc
deleted file mode 100644
index 61b2ad327..000000000
--- a/chalk/chalkcolor/kis_profile.cc
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * kis_profile.cc - part of Krayon
- *
- * Copyright (c) 2000 Matthias Elter <elter@kde.org>
- * 2001 John Califf
- * 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <cfloat>
-#include <cmath>
-#include <config.h>
-#include LCMS_HEADER
-
-#include <tqimage.h>
-#include <tqtextstream.h>
-#include <tqfile.h>
-
-#include <kdebug.h>
-
-#include "kis_profile.h"
-#include "kis_global.h"
-
-#include "ksharedptr.h"
-
-#include <X11/Xlib.h>
-#include <X11/Xatom.h>
-#include <fixx11h.h>
-
-KisProfile::KisProfile(TQByteArray rawData)
- : m_rawData(rawData),
- m_filename( TQString() ),
- m_valid( false ),
- m_suitableForOutput(false)
-{
- m_profile = cmsOpenProfileFromMem(rawData.data(), (DWORD)rawData.size());
- init();
-}
-
-KisProfile::KisProfile(const TQString& file)
- : m_filename(file),
- m_valid( false ),
- m_suitableForOutput( false )
-{
-}
-
-KisProfile::KisProfile(const cmsHPROFILE profile)
- : m_profile(profile),
- m_filename( TQString() ),
- m_valid( true )
-{
- size_t bytesNeeded=0;
-
- // Make a raw data image ready for saving
- _cmsSaveProfileToMem(m_profile, 0, &bytesNeeded); // calc size
- if(m_rawData.resize(bytesNeeded))
- {
- _cmsSaveProfileToMem(m_profile, m_rawData.data(), &bytesNeeded); // fill buffer
- cmsHPROFILE newprofile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD) bytesNeeded);
- cmsCloseProfile(m_profile);
- m_profile = newprofile;
- }
- else
- m_rawData.resize(0);
-
- init();
-}
-
-KisProfile::~KisProfile()
-{
- cmsCloseProfile(m_profile);
-}
-
-
-bool KisProfile::load()
-{
- TQFile file(m_filename);
- file.open(IO_ReadOnly);
- m_rawData = file.readAll();
- m_profile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD)m_rawData.size());
- file.close();
-
- if (m_profile == 0) {
- kdWarning() << "Failed to load profile from " << m_filename << endl;
- }
-
- return init();
-
-}
-
-bool KisProfile::init()
-{
- if (m_profile) {
- m_colorSpaceSignature = cmsGetColorSpace(m_profile);
- m_deviceClass = cmsGetDeviceClass(m_profile);
- m_productName = cmsTakeProductName(m_profile);
- m_productDescription = cmsTakeProductDesc(m_profile);
- m_productInfo = cmsTakeProductInfo(m_profile);
- m_valid = true;
-
- // Check if the profile can convert (something->this)
-// LPMATSHAPER OutMatShaper = cmsBuildOutputMatrixShaper(m_profile);
-// if( OutMatShaper )
-// {
-// m_suitableForOutput = true;
-// }
- cmsCIEXYZTRIPLE Primaries;
-
- if (cmsTakeColorants(&Primaries, m_profile))
- {
- m_suitableForOutput = true;
- }
-
-#if 0
- // XXX: It wasn't that easy to save a little memory: thsi gives an lcms error
- // Okay, we know enough. Free the memory; we'll load it again if needed.
-
- cmsCloseProfile(m_profile);
- m_profile = 0;
-
-#endif
- return true;
- }
- return false;
-}
-
-cmsHPROFILE KisProfile::profile()
-{
-#if 0
- if (m_profile = 0) {
- TQFile file(m_filename);
- file.open(IO_ReadOnly);
- m_rawData = file.readAll();
- m_profile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD)m_rawData.size());
- file.close();
- }
-#endif
- return m_profile;
-}
-
-bool KisProfile::save()
-{
- return false;
-}
-
-KisAnnotationSP KisProfile::annotation() const
-{
- // XXX we hardcode icc, this is correct for lcms?
- // XXX productName(), or just "ICC Profile"?
- if (!m_rawData.isEmpty())
- return new KisAnnotation("icc", productName(), m_rawData);
- else
- return 0;
-}
-
-KisProfile * KisProfile::getScreenProfile (int screen)
-{
-
-#ifdef Q_WS_X11
-
- Atom type;
- int format;
- unsigned long nitems;
- unsigned long bytes_after;
- TQ_UINT8 * str;
-
- static Atom icc_atom = XInternAtom( tqt_xdisplay(), "_ICC_PROFILE", False );
-
- if ( XGetWindowProperty ( tqt_xdisplay(),
- tqt_xrootwin( screen ),
- icc_atom,
- 0,
- INT_MAX,
- False,
- XA_CARDINAL,
- &type,
- &format,
- &nitems,
- &bytes_after,
- (unsigned char **) &str)
- ) {
-
- TQByteArray bytes (nitems);
- bytes.assign((char*)str, (TQ_UINT32)nitems);
-
- return new KisProfile(bytes);
- } else {
- return NULL;
- }
-#else
- return NULL;
-
-#endif
-}
-
-
diff --git a/chalk/chalkcolor/kis_profile.cpp b/chalk/chalkcolor/kis_profile.cpp
new file mode 100644
index 000000000..df98a7506
--- /dev/null
+++ b/chalk/chalkcolor/kis_profile.cpp
@@ -0,0 +1,208 @@
+/*
+ * kis_profile.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 Matthias Elter <elter@kde.org>
+ * 2001 John Califf
+ * 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <cfloat>
+#include <cmath>
+#include <config.h>
+#include LCMS_HEADER
+
+#include <tqimage.h>
+#include <tqtextstream.h>
+#include <tqfile.h>
+
+#include <kdebug.h>
+
+#include "kis_profile.h"
+#include "kis_global.h"
+
+#include "ksharedptr.h"
+
+#include <X11/Xlib.h>
+#include <X11/Xatom.h>
+#include <fixx11h.h>
+
+KisProfile::KisProfile(TQByteArray rawData)
+ : m_rawData(rawData),
+ m_filename( TQString() ),
+ m_valid( false ),
+ m_suitableForOutput(false)
+{
+ m_profile = cmsOpenProfileFromMem(rawData.data(), (DWORD)rawData.size());
+ init();
+}
+
+KisProfile::KisProfile(const TQString& file)
+ : m_filename(file),
+ m_valid( false ),
+ m_suitableForOutput( false )
+{
+}
+
+KisProfile::KisProfile(const cmsHPROFILE profile)
+ : m_profile(profile),
+ m_filename( TQString() ),
+ m_valid( true )
+{
+ size_t bytesNeeded=0;
+
+ // Make a raw data image ready for saving
+ _cmsSaveProfileToMem(m_profile, 0, &bytesNeeded); // calc size
+ if(m_rawData.resize(bytesNeeded))
+ {
+ _cmsSaveProfileToMem(m_profile, m_rawData.data(), &bytesNeeded); // fill buffer
+ cmsHPROFILE newprofile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD) bytesNeeded);
+ cmsCloseProfile(m_profile);
+ m_profile = newprofile;
+ }
+ else
+ m_rawData.resize(0);
+
+ init();
+}
+
+KisProfile::~KisProfile()
+{
+ cmsCloseProfile(m_profile);
+}
+
+
+bool KisProfile::load()
+{
+ TQFile file(m_filename);
+ file.open(IO_ReadOnly);
+ m_rawData = file.readAll();
+ m_profile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD)m_rawData.size());
+ file.close();
+
+ if (m_profile == 0) {
+ kdWarning() << "Failed to load profile from " << m_filename << endl;
+ }
+
+ return init();
+
+}
+
+bool KisProfile::init()
+{
+ if (m_profile) {
+ m_colorSpaceSignature = cmsGetColorSpace(m_profile);
+ m_deviceClass = cmsGetDeviceClass(m_profile);
+ m_productName = cmsTakeProductName(m_profile);
+ m_productDescription = cmsTakeProductDesc(m_profile);
+ m_productInfo = cmsTakeProductInfo(m_profile);
+ m_valid = true;
+
+ // Check if the profile can convert (something->this)
+// LPMATSHAPER OutMatShaper = cmsBuildOutputMatrixShaper(m_profile);
+// if( OutMatShaper )
+// {
+// m_suitableForOutput = true;
+// }
+ cmsCIEXYZTRIPLE Primaries;
+
+ if (cmsTakeColorants(&Primaries, m_profile))
+ {
+ m_suitableForOutput = true;
+ }
+
+#if 0
+ // XXX: It wasn't that easy to save a little memory: thsi gives an lcms error
+ // Okay, we know enough. Free the memory; we'll load it again if needed.
+
+ cmsCloseProfile(m_profile);
+ m_profile = 0;
+
+#endif
+ return true;
+ }
+ return false;
+}
+
+cmsHPROFILE KisProfile::profile()
+{
+#if 0
+ if (m_profile = 0) {
+ TQFile file(m_filename);
+ file.open(IO_ReadOnly);
+ m_rawData = file.readAll();
+ m_profile = cmsOpenProfileFromMem(m_rawData.data(), (DWORD)m_rawData.size());
+ file.close();
+ }
+#endif
+ return m_profile;
+}
+
+bool KisProfile::save()
+{
+ return false;
+}
+
+KisAnnotationSP KisProfile::annotation() const
+{
+ // XXX we hardcode icc, this is correct for lcms?
+ // XXX productName(), or just "ICC Profile"?
+ if (!m_rawData.isEmpty())
+ return new KisAnnotation("icc", productName(), m_rawData);
+ else
+ return 0;
+}
+
+KisProfile * KisProfile::getScreenProfile (int screen)
+{
+
+#ifdef Q_WS_X11
+
+ Atom type;
+ int format;
+ unsigned long nitems;
+ unsigned long bytes_after;
+ TQ_UINT8 * str;
+
+ static Atom icc_atom = XInternAtom( tqt_xdisplay(), "_ICC_PROFILE", False );
+
+ if ( XGetWindowProperty ( tqt_xdisplay(),
+ tqt_xrootwin( screen ),
+ icc_atom,
+ 0,
+ INT_MAX,
+ False,
+ XA_CARDINAL,
+ &type,
+ &format,
+ &nitems,
+ &bytes_after,
+ (unsigned char **) &str)
+ ) {
+
+ TQByteArray bytes (nitems);
+ bytes.assign((char*)str, (TQ_UINT32)nitems);
+
+ return new KisProfile(bytes);
+ } else {
+ return NULL;
+ }
+#else
+ return NULL;
+
+#endif
+}
+
+
diff --git a/chalk/chalkcolor/kis_u16_base_colorspace.cc b/chalk/chalkcolor/kis_u16_base_colorspace.cpp
index a735e35ce..a735e35ce 100644
--- a/chalk/chalkcolor/kis_u16_base_colorspace.cc
+++ b/chalk/chalkcolor/kis_u16_base_colorspace.cpp
diff --git a/chalk/chalkcolor/kis_u8_base_colorspace.cc b/chalk/chalkcolor/kis_u8_base_colorspace.cpp
index 338d95d6b..338d95d6b 100644
--- a/chalk/chalkcolor/kis_u8_base_colorspace.cc
+++ b/chalk/chalkcolor/kis_u8_base_colorspace.cpp
diff --git a/chalk/colorspaces/cmyk_u16/Makefile.am b/chalk/colorspaces/cmyk_u16/Makefile.am
index 00cdd32d1..7f5ec9ca6 100644
--- a/chalk/colorspaces/cmyk_u16/Makefile.am
+++ b/chalk/colorspaces/cmyk_u16/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
$(all_includes)
lib_LTLIBRARIES = libchalk_cmyk_u16.la
-libchalk_cmyk_u16_la_SOURCES = kis_cmyk_u16_colorspace.cc
+libchalk_cmyk_u16_la_SOURCES = kis_cmyk_u16_colorspace.cpp
libchalk_cmyk_u16_la_LDFLAGS = $(all_libraries)
libchalk_cmyk_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -15,7 +15,7 @@ libchalk_cmyk_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_cmyk_u16_plugin.la
# Srcs for the plugin
-chalk_cmyk_u16_plugin_la_SOURCES = cmyk_u16_plugin.cc
+chalk_cmyk_u16_plugin_la_SOURCES = cmyk_u16_plugin.cpp
noinst_HEADERS = cmyk_u16_plugin.h kis_cmyk_u16_colorspace.h
chalk_cmyk_u16_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cc b/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cc
deleted file mode 100644
index 4b3afa299..000000000
--- a/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-* cmyk_u16_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-#include <kis_debug_areas.h>
-#include "cmyk_u16_plugin.h"
-#include "kis_cmyk_u16_colorspace.h"
-
-typedef KGenericFactory<CMYKU16Plugin> CMYKU16PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_cmyk_u16_plugin, CMYKU16PluginFactory( "chalk" ) )
-
-
-CMYKU16Plugin::CMYKU16Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(CMYKU16PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceCMYKU16 = new KisCmykU16ColorSpace(f, 0);
- KisColorSpaceFactory * csf = new KisCmykU16ColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceCMYKU16);
- f->add(csf);
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("CMYK16HISTO", i18n("CMYK16")), colorSpaceCMYKU16) );
- }
-
-}
-
-CMYKU16Plugin::~CMYKU16Plugin()
-{
-}
-
-#include "cmyk_u16_plugin.moc"
diff --git a/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cpp b/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cpp
new file mode 100644
index 000000000..4195ff225
--- /dev/null
+++ b/chalk/colorspaces/cmyk_u16/cmyk_u16_plugin.cpp
@@ -0,0 +1,61 @@
+/*
+* cmyk_u16_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+#include <kis_debug_areas.h>
+#include "cmyk_u16_plugin.h"
+#include "kis_cmyk_u16_colorspace.h"
+
+typedef KGenericFactory<CMYKU16Plugin> CMYKU16PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_cmyk_u16_plugin, CMYKU16PluginFactory( "chalk" ) )
+
+
+CMYKU16Plugin::CMYKU16Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(CMYKU16PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceCMYKU16 = new KisCmykU16ColorSpace(f, 0);
+ KisColorSpaceFactory * csf = new KisCmykU16ColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceCMYKU16);
+ f->add(csf);
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("CMYK16HISTO", i18n("CMYK16")), colorSpaceCMYKU16) );
+ }
+
+}
+
+CMYKU16Plugin::~CMYKU16Plugin()
+{
+}
+
+#include "cmyk_u16_plugin.moc"
diff --git a/chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cc b/chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cpp
index 96a6f1323..96a6f1323 100644
--- a/chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cc
+++ b/chalk/colorspaces/cmyk_u16/kis_cmyk_u16_colorspace.cpp
diff --git a/chalk/colorspaces/cmyk_u8/Makefile.am b/chalk/colorspaces/cmyk_u8/Makefile.am
index 90ab3869f..97554d249 100644
--- a/chalk/colorspaces/cmyk_u8/Makefile.am
+++ b/chalk/colorspaces/cmyk_u8/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
kde_module_LTLIBRARIES = chalkcmykplugin.la
-chalkcmykplugin_la_SOURCES = cmyk_plugin.cc kis_cmyk_colorspace.cc
+chalkcmykplugin_la_SOURCES = cmyk_plugin.cpp kis_cmyk_colorspace.cpp
noinst_HEADERS = cmyk_plugin.h kis_cmyk_colorspace.h
chalkcmykplugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/cmyk_u8/cmyk_plugin.cc b/chalk/colorspaces/cmyk_u8/cmyk_plugin.cc
deleted file mode 100644
index 7b09ecca9..000000000
--- a/chalk/colorspaces/cmyk_u8/cmyk_plugin.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * cmyk_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "cmyk_plugin.h"
-
-#include "kis_cmyk_colorspace.h"
-
-typedef KGenericFactory<CMYKPlugin> CMYKPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkcmykplugin, CMYKPluginFactory( "chalk" ) )
-
-
-CMYKPlugin::CMYKPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(CMYKPluginFactory::instance());
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceCMYK = new KisCmykColorSpace(f, 0);
- KisColorSpaceFactory * csf = new KisCmykColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceCMYK);
- f->add(csf);
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
- (KisID("CMYKHISTO", i18n("CMYK")), colorSpaceCMYK) );
- }
-
-}
-
-CMYKPlugin::~CMYKPlugin()
-{
-}
-
-#include "cmyk_plugin.moc"
diff --git a/chalk/colorspaces/cmyk_u8/cmyk_plugin.cpp b/chalk/colorspaces/cmyk_u8/cmyk_plugin.cpp
new file mode 100644
index 000000000..588e286cd
--- /dev/null
+++ b/chalk/colorspaces/cmyk_u8/cmyk_plugin.cpp
@@ -0,0 +1,66 @@
+/*
+ * cmyk_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "cmyk_plugin.h"
+
+#include "kis_cmyk_colorspace.h"
+
+typedef KGenericFactory<CMYKPlugin> CMYKPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkcmykplugin, CMYKPluginFactory( "chalk" ) )
+
+
+CMYKPlugin::CMYKPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(CMYKPluginFactory::instance());
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceCMYK = new KisCmykColorSpace(f, 0);
+ KisColorSpaceFactory * csf = new KisCmykColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceCMYK);
+ f->add(csf);
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
+ (KisID("CMYKHISTO", i18n("CMYK")), colorSpaceCMYK) );
+ }
+
+}
+
+CMYKPlugin::~CMYKPlugin()
+{
+}
+
+#include "cmyk_plugin.moc"
diff --git a/chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cc b/chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cpp
index 09c517df8..09c517df8 100644
--- a/chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cc
+++ b/chalk/colorspaces/cmyk_u8/kis_cmyk_colorspace.cpp
diff --git a/chalk/colorspaces/gray_u16/Makefile.am b/chalk/colorspaces/gray_u16/Makefile.am
index 8ee4314cd..d77d32d2a 100644
--- a/chalk/colorspaces/gray_u16/Makefile.am
+++ b/chalk/colorspaces/gray_u16/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
$(all_includes)
lib_LTLIBRARIES = libchalk_gray_u16.la
-libchalk_gray_u16_la_SOURCES = kis_gray_u16_colorspace.cc
+libchalk_gray_u16_la_SOURCES = kis_gray_u16_colorspace.cpp
libchalk_gray_u16_la_LDFLAGS = $(all_libraries)
libchalk_gray_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -16,7 +16,7 @@ libchalk_gray_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_gray_u16_plugin.la
# Srcs for the plugin
-chalk_gray_u16_plugin_la_SOURCES = gray_u16_plugin.cc
+chalk_gray_u16_plugin_la_SOURCES = gray_u16_plugin.cpp
noinst_HEADERS = gray_u16_plugin.h kis_gray_u16_colorspace.h
chalk_gray_u16_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/gray_u16/gray_u16_plugin.cc b/chalk/colorspaces/gray_u16/gray_u16_plugin.cc
deleted file mode 100644
index 5e9e17f93..000000000
--- a/chalk/colorspaces/gray_u16/gray_u16_plugin.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-* gray_u16_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-*
-* This program is free software; you can grayistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "gray_u16_plugin.h"
-#include "kis_gray_u16_colorspace.h"
-
-typedef KGenericFactory<GRAYU16Plugin> GRAYU16PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_gray_u16_plugin, GRAYU16PluginFactory( "chalk" ) )
-
-
-GRAYU16Plugin::GRAYU16Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(GRAYU16PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceGRAYU16 = new KisGrayU16ColorSpace(f, 0);
- KisColorSpaceFactory * csf = new KisGrayU16ColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceGRAYU16);
- f->add(csf);
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("GRAYA16HISTO", i18n("GRAY/Alpha16")), colorSpaceGRAYU16) );
- }
-
-}
-
-GRAYU16Plugin::~GRAYU16Plugin()
-{
-}
-
-#include "gray_u16_plugin.moc"
diff --git a/chalk/colorspaces/gray_u16/gray_u16_plugin.cpp b/chalk/colorspaces/gray_u16/gray_u16_plugin.cpp
new file mode 100644
index 000000000..7c1896f94
--- /dev/null
+++ b/chalk/colorspaces/gray_u16/gray_u16_plugin.cpp
@@ -0,0 +1,63 @@
+/*
+* gray_u16_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+*
+* This program is free software; you can grayistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "gray_u16_plugin.h"
+#include "kis_gray_u16_colorspace.h"
+
+typedef KGenericFactory<GRAYU16Plugin> GRAYU16PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_gray_u16_plugin, GRAYU16PluginFactory( "chalk" ) )
+
+
+GRAYU16Plugin::GRAYU16Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(GRAYU16PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceGRAYU16 = new KisGrayU16ColorSpace(f, 0);
+ KisColorSpaceFactory * csf = new KisGrayU16ColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceGRAYU16);
+ f->add(csf);
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("GRAYA16HISTO", i18n("GRAY/Alpha16")), colorSpaceGRAYU16) );
+ }
+
+}
+
+GRAYU16Plugin::~GRAYU16Plugin()
+{
+}
+
+#include "gray_u16_plugin.moc"
diff --git a/chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cc b/chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cpp
index 43bdf40ff..43bdf40ff 100644
--- a/chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cc
+++ b/chalk/colorspaces/gray_u16/kis_gray_u16_colorspace.cpp
diff --git a/chalk/colorspaces/gray_u8/Makefile.am b/chalk/colorspaces/gray_u8/Makefile.am
index fda7f56a3..1282ef00f 100644
--- a/chalk/colorspaces/gray_u8/Makefile.am
+++ b/chalk/colorspaces/gray_u8/Makefile.am
@@ -9,13 +9,13 @@ INCLUDES = -I$(srcdir)/../../sdk \
lib_LTLIBRARIES = libchalkgrayscale.la
-libchalkgrayscale_la_SOURCES = kis_gray_colorspace.cc
+libchalkgrayscale_la_SOURCES = kis_gray_colorspace.cpp
libchalkgrayscale_la_LDFLAGS = $(all_libraries)
libchalkgrayscale_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalkgrayplugin.la
-chalkgrayplugin_la_SOURCES = gray_plugin.cc
+chalkgrayplugin_la_SOURCES = gray_plugin.cpp
noinst_HEADERS = gray_plugin.h kis_gray_colorspace.h
chalkgrayplugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/gray_u8/gray_plugin.cc b/chalk/colorspaces/gray_u8/gray_plugin.cc
deleted file mode 100644
index 7d03d5f63..000000000
--- a/chalk/colorspaces/gray_u8/gray_plugin.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * gray_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "gray_plugin.h"
-#include "kis_gray_colorspace.h"
-
-typedef KGenericFactory<GrayPlugin> GrayPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkgrayplugin, GrayPluginFactory( "chalkcore" ) )
-
-
-GrayPlugin::GrayPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(GrayPluginFactory::instance());
-
- // This is not a gui plugin; only load it when the doc is created.
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
-
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- // .22 gamma grayscale or something like that. Taken from the lcms tutorial...
- LPGAMMATABLE Gamma = cmsBuildGamma(256, 2.2);
- cmsHPROFILE hProfile = cmsCreateGrayProfile(cmsD50_xyY(), Gamma);
- cmsFreeGamma(Gamma);
- KisProfile *defProfile = new KisProfile(hProfile);
-
- f->addProfile(defProfile);
-
- KisColorSpace * colorSpaceGrayA = new KisGrayColorSpace(f, 0);
-
- KisColorSpaceFactory * csf = new KisGrayColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceGrayA);
-
- f->add(csf);
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
- (KisID("GRAYA8HISTO", i18n("GRAY/Alpha8")), colorSpaceGrayA) );
- }
-
-}
-
-GrayPlugin::~GrayPlugin()
-{
-}
-
-#include "gray_plugin.moc"
diff --git a/chalk/colorspaces/gray_u8/gray_plugin.cpp b/chalk/colorspaces/gray_u8/gray_plugin.cpp
new file mode 100644
index 000000000..7f177eea1
--- /dev/null
+++ b/chalk/colorspaces/gray_u8/gray_plugin.cpp
@@ -0,0 +1,77 @@
+/*
+ * gray_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "gray_plugin.h"
+#include "kis_gray_colorspace.h"
+
+typedef KGenericFactory<GrayPlugin> GrayPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkgrayplugin, GrayPluginFactory( "chalkcore" ) )
+
+
+GrayPlugin::GrayPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(GrayPluginFactory::instance());
+
+ // This is not a gui plugin; only load it when the doc is created.
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ // .22 gamma grayscale or something like that. Taken from the lcms tutorial...
+ LPGAMMATABLE Gamma = cmsBuildGamma(256, 2.2);
+ cmsHPROFILE hProfile = cmsCreateGrayProfile(cmsD50_xyY(), Gamma);
+ cmsFreeGamma(Gamma);
+ KisProfile *defProfile = new KisProfile(hProfile);
+
+ f->addProfile(defProfile);
+
+ KisColorSpace * colorSpaceGrayA = new KisGrayColorSpace(f, 0);
+
+ KisColorSpaceFactory * csf = new KisGrayColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceGrayA);
+
+ f->add(csf);
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
+ (KisID("GRAYA8HISTO", i18n("GRAY/Alpha8")), colorSpaceGrayA) );
+ }
+
+}
+
+GrayPlugin::~GrayPlugin()
+{
+}
+
+#include "gray_plugin.moc"
diff --git a/chalk/colorspaces/gray_u8/kis_gray_colorspace.cc b/chalk/colorspaces/gray_u8/kis_gray_colorspace.cpp
index 989cc2c58..989cc2c58 100644
--- a/chalk/colorspaces/gray_u8/kis_gray_colorspace.cc
+++ b/chalk/colorspaces/gray_u8/kis_gray_colorspace.cpp
diff --git a/chalk/colorspaces/lms_f32/Makefile.am b/chalk/colorspaces/lms_f32/Makefile.am
index bf8c65ecc..b7eedf99a 100644
--- a/chalk/colorspaces/lms_f32/Makefile.am
+++ b/chalk/colorspaces/lms_f32/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = \
lib_LTLIBRARIES = libchalk_lms_f32.la
-libchalk_lms_f32_la_SOURCES = kis_lms_f32_colorspace.cc
+libchalk_lms_f32_la_SOURCES = kis_lms_f32_colorspace.cpp
libchalk_lms_f32_la_LDFLAGS = $(all_libraries)
libchalk_lms_f32_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -18,7 +18,7 @@ libchalk_lms_f32_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_lms_f32_plugin.la
# Srcs for the plugin
-chalk_lms_f32_plugin_la_SOURCES = lms_f32_plugin.cc
+chalk_lms_f32_plugin_la_SOURCES = lms_f32_plugin.cpp
noinst_HEADERS = lms_f32_plugin.h kis_lms_f32_colorspace.h
chalk_lms_f32_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cc b/chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cpp
index 67ad17d0e..67ad17d0e 100644
--- a/chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cc
+++ b/chalk/colorspaces/lms_f32/kis_lms_f32_colorspace.cpp
diff --git a/chalk/colorspaces/lms_f32/lms_f32_plugin.cc b/chalk/colorspaces/lms_f32/lms_f32_plugin.cc
deleted file mode 100644
index f7e581ace..000000000
--- a/chalk/colorspaces/lms_f32/lms_f32_plugin.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
-* lms_f32_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-* Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "lms_f32_plugin.h"
-#include "kis_lms_f32_colorspace.h"
-
-typedef KGenericFactory<LMSF32Plugin> LMSF32PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_lms_f32_plugin, LMSF32PluginFactory( "chalk" ) )
-
-
-LMSF32Plugin::LMSF32Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(LMSF32PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
-
- KisColorSpace * colorSpaceLMSF32 = new KisLmsF32ColorSpace(f, 0);
-
- KisColorSpaceFactory * csf = new KisLmsF32ColorSpaceFactory();
- f->add(csf);
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicF32HistogramProducer>
- (KisID("LMSF32HISTO", i18n("Float32")), colorSpaceLMSF32) );
- }
-
-}
-
-LMSF32Plugin::~LMSF32Plugin()
-{
-}
-
-#include "lms_f32_plugin.moc"
diff --git a/chalk/colorspaces/lms_f32/lms_f32_plugin.cpp b/chalk/colorspaces/lms_f32/lms_f32_plugin.cpp
new file mode 100644
index 000000000..2c83ccd6c
--- /dev/null
+++ b/chalk/colorspaces/lms_f32/lms_f32_plugin.cpp
@@ -0,0 +1,64 @@
+/*
+* lms_f32_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+* Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "lms_f32_plugin.h"
+#include "kis_lms_f32_colorspace.h"
+
+typedef KGenericFactory<LMSF32Plugin> LMSF32PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_lms_f32_plugin, LMSF32PluginFactory( "chalk" ) )
+
+
+LMSF32Plugin::LMSF32Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(LMSF32PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
+
+ KisColorSpace * colorSpaceLMSF32 = new KisLmsF32ColorSpace(f, 0);
+
+ KisColorSpaceFactory * csf = new KisLmsF32ColorSpaceFactory();
+ f->add(csf);
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicF32HistogramProducer>
+ (KisID("LMSF32HISTO", i18n("Float32")), colorSpaceLMSF32) );
+ }
+
+}
+
+LMSF32Plugin::~LMSF32Plugin()
+{
+}
+
+#include "lms_f32_plugin.moc"
diff --git a/chalk/colorspaces/rgb_f16half/Makefile.am b/chalk/colorspaces/rgb_f16half/Makefile.am
index 52f0c5836..cea86b4ca 100644
--- a/chalk/colorspaces/rgb_f16half/Makefile.am
+++ b/chalk/colorspaces/rgb_f16half/Makefile.am
@@ -13,7 +13,7 @@ CXXFLAGS += $(OPENEXR_CXXFLAGS)
lib_LTLIBRARIES = libchalk_rgb_f16half.la
-libchalk_rgb_f16half_la_SOURCES = kis_rgb_f16half_colorspace.cc
+libchalk_rgb_f16half_la_SOURCES = kis_rgb_f16half_colorspace.cpp
libchalk_rgb_f16half_la_LDFLAGS = $(all_libraries)
libchalk_rgb_f16half_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -21,7 +21,7 @@ libchalk_rgb_f16half_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_rgb_f16half_plugin.la
# Srcs for the plugin
-chalk_rgb_f16half_plugin_la_SOURCES = rgb_f16half_plugin.cc
+chalk_rgb_f16half_plugin_la_SOURCES = rgb_f16half_plugin.cpp
noinst_HEADERS = rgb_f16half_plugin.h kis_rgb_f16half_colorspace.h
chalk_rgb_f16half_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cc b/chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cpp
index fd065637e..fd065637e 100644
--- a/chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cc
+++ b/chalk/colorspaces/rgb_f16half/kis_rgb_f16half_colorspace.cpp
diff --git a/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cc b/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cc
deleted file mode 100644
index 911da6a0b..000000000
--- a/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-* rgb_f32_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "rgb_f16half_plugin.h"
-#include "kis_rgb_f16half_colorspace.h"
-
-typedef KGenericFactory<RGBF16HalfPlugin> RGBF16HalfPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_rgb_f16half_plugin, RGBF16HalfPluginFactory( "chalk" ) )
-
-
-RGBF16HalfPlugin::RGBF16HalfPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(RGBF16HalfPluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceRGBF16Half = new KisRgbF16HalfColorSpace(f, 0);
- KisColorSpaceFactory *csf = new KisRgbF16HalfColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceRGBF16Half);
- f->add(csf);
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicF16HalfHistogramProducer>
- (KisID("RGBF16HALFHISTO", i18n("Float16 Half")), colorSpaceRGBF16Half) );
- }
-
-}
-
-RGBF16HalfPlugin::~RGBF16HalfPlugin()
-{
-}
-
-#include "rgb_f16half_plugin.moc"
-
diff --git a/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cpp b/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cpp
new file mode 100644
index 000000000..32505bc88
--- /dev/null
+++ b/chalk/colorspaces/rgb_f16half/rgb_f16half_plugin.cpp
@@ -0,0 +1,63 @@
+/*
+* rgb_f32_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "rgb_f16half_plugin.h"
+#include "kis_rgb_f16half_colorspace.h"
+
+typedef KGenericFactory<RGBF16HalfPlugin> RGBF16HalfPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_rgb_f16half_plugin, RGBF16HalfPluginFactory( "chalk" ) )
+
+
+RGBF16HalfPlugin::RGBF16HalfPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(RGBF16HalfPluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceRGBF16Half = new KisRgbF16HalfColorSpace(f, 0);
+ KisColorSpaceFactory *csf = new KisRgbF16HalfColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceRGBF16Half);
+ f->add(csf);
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicF16HalfHistogramProducer>
+ (KisID("RGBF16HALFHISTO", i18n("Float16 Half")), colorSpaceRGBF16Half) );
+ }
+
+}
+
+RGBF16HalfPlugin::~RGBF16HalfPlugin()
+{
+}
+
+#include "rgb_f16half_plugin.moc"
+
diff --git a/chalk/colorspaces/rgb_f16half/tests/Makefile.am b/chalk/colorspaces/rgb_f16half/tests/Makefile.am
index cdb3f06c5..ae1cfc827 100644
--- a/chalk/colorspaces/rgb_f16half/tests/Makefile.am
+++ b/chalk/colorspaces/rgb_f16half/tests/Makefile.am
@@ -10,7 +10,7 @@ AM_CPPFLAGS = -I$(srcdir)/.. \
# $(KDE_CHECK_PLUGIN) assures a shared library is created.
check_LTLIBRARIES = tdeunittest_kis_rgb_f16half_colorspace_tester.la
-tdeunittest_kis_rgb_f16half_colorspace_tester_la_SOURCES = kis_rgb_f16half_colorspace_tester.cc
+tdeunittest_kis_rgb_f16half_colorspace_tester_la_SOURCES = kis_rgb_f16half_colorspace_tester.cpp
tdeunittest_kis_rgb_f16half_colorspace_tester_la_LIBADD = -ltdeunittest ../libchalk_rgb_f16half.la
tdeunittest_kis_rgb_f16half_colorspace_tester_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) $(all_libraries)
diff --git a/chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cc b/chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cpp
index bb2094ef5..bb2094ef5 100644
--- a/chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cc
+++ b/chalk/colorspaces/rgb_f16half/tests/kis_rgb_f16half_colorspace_tester.cpp
diff --git a/chalk/colorspaces/rgb_f32/Makefile.am b/chalk/colorspaces/rgb_f32/Makefile.am
index 0d206a3e4..0fd090c97 100644
--- a/chalk/colorspaces/rgb_f32/Makefile.am
+++ b/chalk/colorspaces/rgb_f32/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = \
lib_LTLIBRARIES = libchalk_rgb_f32.la
-libchalk_rgb_f32_la_SOURCES = kis_rgb_f32_colorspace.cc
+libchalk_rgb_f32_la_SOURCES = kis_rgb_f32_colorspace.cpp
libchalk_rgb_f32_la_LDFLAGS = $(all_libraries)
libchalk_rgb_f32_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -18,7 +18,7 @@ libchalk_rgb_f32_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_rgb_f32_plugin.la
# Srcs for the plugin
-chalk_rgb_f32_plugin_la_SOURCES = rgb_f32_plugin.cc
+chalk_rgb_f32_plugin_la_SOURCES = rgb_f32_plugin.cpp
noinst_HEADERS = rgb_f32_plugin.h kis_rgb_f32_colorspace.h
chalk_rgb_f32_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cc b/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cpp
index d4eb9eaca..d4eb9eaca 100644
--- a/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cc
+++ b/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.cpp
diff --git a/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.h b/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.h
index c6551a4ce..785009e06 100644
--- a/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.h
+++ b/chalk/colorspaces/rgb_f32/kis_rgb_f32_colorspace.h
@@ -132,7 +132,7 @@ private:
};
struct F32OpacityTest {
inline bool operator()(const float& opacity) const {
- return opacity > F32_OPACITY_TRANSPARENT + 1e-6; // #define EPSILON in the .cc
+ return opacity > F32_OPACITY_TRANSPARENT + 1e-6; // #define EPSILON in the .cpp
}
};
};
diff --git a/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cc b/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cc
deleted file mode 100644
index 7c1149711..000000000
--- a/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-* rgb_f32_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "rgb_f32_plugin.h"
-#include "kis_rgb_f32_colorspace.h"
-
-typedef KGenericFactory<RGBF32Plugin> RGBF32PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_rgb_f32_plugin, RGBF32PluginFactory( "chalk" ) )
-
-
-RGBF32Plugin::RGBF32Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(RGBF32PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
-
- KisColorSpace * colorSpaceRGBF32 = new KisRgbF32ColorSpace(f, 0);
-
- KisColorSpaceFactory * csf = new KisRgbF32ColorSpaceFactory();
- f->add(csf);
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicF32HistogramProducer>
- (KisID("RGBF32HISTO", i18n("Float32")), colorSpaceRGBF32) );
- }
-
-}
-
-RGBF32Plugin::~RGBF32Plugin()
-{
-}
-
-#include "rgb_f32_plugin.moc"
diff --git a/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cpp b/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cpp
new file mode 100644
index 000000000..adc540ac0
--- /dev/null
+++ b/chalk/colorspaces/rgb_f32/rgb_f32_plugin.cpp
@@ -0,0 +1,63 @@
+/*
+* rgb_f32_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "rgb_f32_plugin.h"
+#include "kis_rgb_f32_colorspace.h"
+
+typedef KGenericFactory<RGBF32Plugin> RGBF32PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_rgb_f32_plugin, RGBF32PluginFactory( "chalk" ) )
+
+
+RGBF32Plugin::RGBF32Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(RGBF32PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
+
+ KisColorSpace * colorSpaceRGBF32 = new KisRgbF32ColorSpace(f, 0);
+
+ KisColorSpaceFactory * csf = new KisRgbF32ColorSpaceFactory();
+ f->add(csf);
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicF32HistogramProducer>
+ (KisID("RGBF32HISTO", i18n("Float32")), colorSpaceRGBF32) );
+ }
+
+}
+
+RGBF32Plugin::~RGBF32Plugin()
+{
+}
+
+#include "rgb_f32_plugin.moc"
diff --git a/chalk/colorspaces/rgb_f32/tests/Makefile.am b/chalk/colorspaces/rgb_f32/tests/Makefile.am
index 9ad10271b..073c5da74 100644
--- a/chalk/colorspaces/rgb_f32/tests/Makefile.am
+++ b/chalk/colorspaces/rgb_f32/tests/Makefile.am
@@ -8,7 +8,7 @@ AM_CPPFLAGS = -I$(srcdir)/.. \
# $(KDE_CHECK_PLUGIN) assures a shared library is created.
check_LTLIBRARIES = tdeunittest_kis_strategy_colorspace_rgb_f32_tester.la
-tdeunittest_kis_strategy_colorspace_rgb_f32_tester_la_SOURCES = kis_strategy_colorspace_rgb_f32_tester.cc
+tdeunittest_kis_strategy_colorspace_rgb_f32_tester_la_SOURCES = kis_strategy_colorspace_rgb_f32_tester.cpp
tdeunittest_kis_strategy_colorspace_rgb_f32_tester_la_LIBADD = -ltdeunittest ../libchalk_rgb_f32.la
tdeunittest_kis_strategy_colorspace_rgb_f32_tester_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) $(all_libraries)
diff --git a/chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cc b/chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cpp
index 4a446a83b..4a446a83b 100644
--- a/chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cc
+++ b/chalk/colorspaces/rgb_f32/tests/kis_strategy_colorspace_rgb_f32_tester.cpp
diff --git a/chalk/colorspaces/rgb_u16/Makefile.am b/chalk/colorspaces/rgb_u16/Makefile.am
index 41711c558..283c54e0e 100644
--- a/chalk/colorspaces/rgb_u16/Makefile.am
+++ b/chalk/colorspaces/rgb_u16/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
$(all_includes)
lib_LTLIBRARIES = libchalk_rgb_u16.la
-libchalk_rgb_u16_la_SOURCES = kis_rgb_u16_colorspace.cc
+libchalk_rgb_u16_la_SOURCES = kis_rgb_u16_colorspace.cpp
libchalk_rgb_u16_la_LDFLAGS = $(all_libraries)
libchalk_rgb_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -16,7 +16,7 @@ libchalk_rgb_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_rgb_u16_plugin.la
# Srcs for the plugin
-chalk_rgb_u16_plugin_la_SOURCES = rgb_u16_plugin.cc
+chalk_rgb_u16_plugin_la_SOURCES = rgb_u16_plugin.cpp
noinst_HEADERS = rgb_u16_plugin.h kis_rgb_u16_colorspace.h
chalk_rgb_u16_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cc b/chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cpp
index 40198c91a..40198c91a 100644
--- a/chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cc
+++ b/chalk/colorspaces/rgb_u16/kis_rgb_u16_colorspace.cpp
diff --git a/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cc b/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cc
deleted file mode 100644
index bc362a83e..000000000
--- a/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-* rgb_u16_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-
-#include "rgb_u16_plugin.h"
-#include "kis_rgb_u16_colorspace.h"
-#include "kis_basic_histogram_producers.h"
-
-typedef KGenericFactory<RGBU16Plugin> RGBU16PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_rgb_u16_plugin, RGBU16PluginFactory( "chalk" ) )
-
-
-RGBU16Plugin::RGBU16Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(RGBU16PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry *>( parent );
-
- KisColorSpace * colorSpaceRGBU16 = new KisRgbU16ColorSpace(f, 0);
- KisColorSpaceFactory * csFactory = new KisRgbU16ColorSpaceFactory();
- f->add( csFactory );
-
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("RGB16HISTO", i18n("RGB16")), colorSpaceRGBU16) );
- }
-
-}
-
-RGBU16Plugin::~RGBU16Plugin()
-{
-}
-
-#include "rgb_u16_plugin.moc"
diff --git a/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cpp b/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cpp
new file mode 100644
index 000000000..da6e6e427
--- /dev/null
+++ b/chalk/colorspaces/rgb_u16/rgb_u16_plugin.cpp
@@ -0,0 +1,61 @@
+/*
+* rgb_u16_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+* Copyright (c) 2005 Adrian Page <adrian@pagenet.plus.com>
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+
+#include "rgb_u16_plugin.h"
+#include "kis_rgb_u16_colorspace.h"
+#include "kis_basic_histogram_producers.h"
+
+typedef KGenericFactory<RGBU16Plugin> RGBU16PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_rgb_u16_plugin, RGBU16PluginFactory( "chalk" ) )
+
+
+RGBU16Plugin::RGBU16Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(RGBU16PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry *>( parent );
+
+ KisColorSpace * colorSpaceRGBU16 = new KisRgbU16ColorSpace(f, 0);
+ KisColorSpaceFactory * csFactory = new KisRgbU16ColorSpaceFactory();
+ f->add( csFactory );
+
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("RGB16HISTO", i18n("RGB16")), colorSpaceRGBU16) );
+ }
+
+}
+
+RGBU16Plugin::~RGBU16Plugin()
+{
+}
+
+#include "rgb_u16_plugin.moc"
diff --git a/chalk/colorspaces/rgb_u16/tests/Makefile.am b/chalk/colorspaces/rgb_u16/tests/Makefile.am
index 76c4d175b..5bed7dfa6 100644
--- a/chalk/colorspaces/rgb_u16/tests/Makefile.am
+++ b/chalk/colorspaces/rgb_u16/tests/Makefile.am
@@ -8,7 +8,7 @@ AM_CPPFLAGS = -I$(srcdir)/.. \
# $(KDE_CHECK_PLUGIN) assures a shared library is created.
check_LTLIBRARIES = tdeunittest_kis_strategy_colorspace_rgb_u16_tester.la
-tdeunittest_kis_strategy_colorspace_rgb_u16_tester_la_SOURCES = kis_strategy_colorspace_rgb_u16_tester.cc
+tdeunittest_kis_strategy_colorspace_rgb_u16_tester_la_SOURCES = kis_strategy_colorspace_rgb_u16_tester.cpp
tdeunittest_kis_strategy_colorspace_rgb_u16_tester_la_LIBADD = -ltdeunittest ../libchalk_rgb_u16.la
tdeunittest_kis_strategy_colorspace_rgb_u16_tester_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) $(all_libraries)
diff --git a/chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cc b/chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cpp
index dedc28a9d..dedc28a9d 100644
--- a/chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cc
+++ b/chalk/colorspaces/rgb_u16/tests/kis_strategy_colorspace_rgb_u16_tester.cpp
diff --git a/chalk/colorspaces/rgb_u8/Makefile.am b/chalk/colorspaces/rgb_u8/Makefile.am
index c82abaa10..9b27665f0 100644
--- a/chalk/colorspaces/rgb_u8/Makefile.am
+++ b/chalk/colorspaces/rgb_u8/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
$(all_includes)
lib_LTLIBRARIES = libchalkrgb.la
-libchalkrgb_la_SOURCES = kis_rgb_colorspace.cc
+libchalkrgb_la_SOURCES = kis_rgb_colorspace.cpp
libchalkrgb_la_LDFLAGS = $(all_libraries) $(LIB_TQT)
libchalkrgb_la_LIBADD = ../../chalkcolor/libchalkcolor.la
@@ -16,7 +16,7 @@ libchalkrgb_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalkrgbplugin.la
# Srcs for the plugin
-chalkrgbplugin_la_SOURCES = rgb_plugin.cc
+chalkrgbplugin_la_SOURCES = rgb_plugin.cpp
noinst_HEADERS = rgb_plugin.h kis_rgb_colorspace.h
chalkrgbplugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
diff --git a/chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cc b/chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cpp
index 0aaea6daa..0aaea6daa 100644
--- a/chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cc
+++ b/chalk/colorspaces/rgb_u8/kis_rgb_colorspace.cpp
diff --git a/chalk/colorspaces/rgb_u8/rgb_plugin.cc b/chalk/colorspaces/rgb_u8/rgb_plugin.cc
deleted file mode 100644
index 263101259..000000000
--- a/chalk/colorspaces/rgb_u8/rgb_plugin.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
-* rgb_plugin.cc -- Part of Chalk
-*
-* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <kis_debug_areas.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "rgb_plugin.h"
-#include "kis_rgb_colorspace.h"
-
-typedef KGenericFactory<RGBPlugin> RGBPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkrgbplugin, RGBPluginFactory( "chalk" ) )
-
-
-RGBPlugin::RGBPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(RGBPluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
-
- KisProfile *defProfile = new KisProfile(cmsCreate_sRGBProfile());
- f->addProfile(defProfile);
-
-
- KisColorSpaceFactory * csFactory = new KisRgbColorSpaceFactory();
- f->add(csFactory);
-
- KisColorSpace * colorSpaceRGBA = new KisRgbColorSpace(f, 0);
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
- (KisID("RGB8HISTO", i18n("RGB8")), colorSpaceRGBA) );
- }
-
-}
-
-RGBPlugin::~RGBPlugin()
-{
-}
-
-#include "rgb_plugin.moc"
diff --git a/chalk/colorspaces/rgb_u8/rgb_plugin.cpp b/chalk/colorspaces/rgb_u8/rgb_plugin.cpp
new file mode 100644
index 000000000..33f18b17f
--- /dev/null
+++ b/chalk/colorspaces/rgb_u8/rgb_plugin.cpp
@@ -0,0 +1,74 @@
+/*
+* rgb_plugin.cpp -- Part of Chalk
+*
+* Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+*
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kis_debug_areas.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "rgb_plugin.h"
+#include "kis_rgb_colorspace.h"
+
+typedef KGenericFactory<RGBPlugin> RGBPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkrgbplugin, RGBPluginFactory( "chalk" ) )
+
+
+RGBPlugin::RGBPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(RGBPluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
+
+ KisProfile *defProfile = new KisProfile(cmsCreate_sRGBProfile());
+ f->addProfile(defProfile);
+
+
+ KisColorSpaceFactory * csFactory = new KisRgbColorSpaceFactory();
+ f->add(csFactory);
+
+ KisColorSpace * colorSpaceRGBA = new KisRgbColorSpace(f, 0);
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU8HistogramProducer>
+ (KisID("RGB8HISTO", i18n("RGB8")), colorSpaceRGBA) );
+ }
+
+}
+
+RGBPlugin::~RGBPlugin()
+{
+}
+
+#include "rgb_plugin.moc"
diff --git a/chalk/colorspaces/wet/Makefile.am b/chalk/colorspaces/wet/Makefile.am
index 6d4bacab4..bd7c307f6 100644
--- a/chalk/colorspaces/wet/Makefile.am
+++ b/chalk/colorspaces/wet/Makefile.am
@@ -17,8 +17,8 @@ INCLUDES = -I$(srcdir)/../../sdk \
kde_module_LTLIBRARIES = chalkwetplugin.la
-chalkwetplugin_la_SOURCES = kis_wet_colorspace.cc wet_plugin.cc kis_wetop.cc kis_wet_palette_widget.cc kis_wetness_visualisation_filter.cc kis_texture_painter.cc kis_texture_filter.cc wetphysicsfilter.cc wdgpressure.ui
-noinst_HEADERS = kis_wet_colorspace.h wet_plugin.h wetphysicsfilter.h kis_wetop.cc kis_wet_palette_widget.h kis_texture_painter.h kis_wetness_visualisation_filter.h kis_texture_filter.h wetphysicsfilter.h
+chalkwetplugin_la_SOURCES = kis_wet_colorspace.cpp wet_plugin.cpp kis_wetop.cpp kis_wet_palette_widget.cpp kis_wetness_visualisation_filter.cpp kis_texture_painter.cpp kis_texture_filter.cpp wetphysicsfilter.cpp wdgpressure.ui
+noinst_HEADERS = kis_wet_colorspace.h wet_plugin.h wetphysicsfilter.h kis_wetop.cpp kis_wet_palette_widget.h kis_texture_painter.h kis_wetness_visualisation_filter.h kis_texture_filter.h wetphysicsfilter.h
chalkwetplugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
chalkwetplugin_la_LIBADD = ../../libchalkcommon.la $(LIB_KOPAINTER) $(LIB_KOFFICECORE) \
diff --git a/chalk/colorspaces/wet/kis_texture_filter.cc b/chalk/colorspaces/wet/kis_texture_filter.cc
deleted file mode 100644
index 6f58cd14a..000000000
--- a/chalk/colorspaces/wet/kis_texture_filter.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * kis_texture_filter.cc -- Part of Chalk
- *
- * Copyright (c) 2005 Bart Coppens <kde@bartcoppens.be>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <kdebug.h>
-#include <kis_view.h>
-#include <kis_image.h>
-#include <kis_debug_areas.h>
-#include "kis_texture_painter.h"
-#include "kis_texture_filter.h"
-
-void WetPaintDevAction::act(KisPaintDeviceSP device, TQ_INT32 w, TQ_INT32 h) const {
- KisColorSpace * cs = device->colorSpace();
-
- if (cs->id() != KisID("WET","")) {
- kdDebug(DBG_AREA_CMS) << "You set this kind of texture on non-wet layers!.\n";
- return;
- } else {
- kdDebug(DBG_AREA_CMS) << "Wet Paint Action activated!\n";
- }
-
- // XXX if params of the painter get configurable, make them here configurable as well?
- KisTexturePainter painter(device);
- painter.createTexture(0, 0, w, h);
- painter.end();
-}
-
diff --git a/chalk/colorspaces/wet/kis_texture_filter.cpp b/chalk/colorspaces/wet/kis_texture_filter.cpp
new file mode 100644
index 000000000..f70272dbf
--- /dev/null
+++ b/chalk/colorspaces/wet/kis_texture_filter.cpp
@@ -0,0 +1,43 @@
+/*
+ * kis_texture_filter.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2005 Bart Coppens <kde@bartcoppens.be>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <kdebug.h>
+#include <kis_view.h>
+#include <kis_image.h>
+#include <kis_debug_areas.h>
+#include "kis_texture_painter.h"
+#include "kis_texture_filter.h"
+
+void WetPaintDevAction::act(KisPaintDeviceSP device, TQ_INT32 w, TQ_INT32 h) const {
+ KisColorSpace * cs = device->colorSpace();
+
+ if (cs->id() != KisID("WET","")) {
+ kdDebug(DBG_AREA_CMS) << "You set this kind of texture on non-wet layers!.\n";
+ return;
+ } else {
+ kdDebug(DBG_AREA_CMS) << "Wet Paint Action activated!\n";
+ }
+
+ // XXX if params of the painter get configurable, make them here configurable as well?
+ KisTexturePainter painter(device);
+ painter.createTexture(0, 0, w, h);
+ painter.end();
+}
+
diff --git a/chalk/colorspaces/wet/kis_texture_painter.cc b/chalk/colorspaces/wet/kis_texture_painter.cpp
index 9300e808b..9300e808b 100644
--- a/chalk/colorspaces/wet/kis_texture_painter.cc
+++ b/chalk/colorspaces/wet/kis_texture_painter.cpp
diff --git a/chalk/colorspaces/wet/kis_wet_colorspace.cc b/chalk/colorspaces/wet/kis_wet_colorspace.cpp
index b867e01ea..b867e01ea 100644
--- a/chalk/colorspaces/wet/kis_wet_colorspace.cc
+++ b/chalk/colorspaces/wet/kis_wet_colorspace.cpp
diff --git a/chalk/colorspaces/wet/kis_wet_palette_widget.cc b/chalk/colorspaces/wet/kis_wet_palette_widget.cpp
index 43cfd559a..43cfd559a 100644
--- a/chalk/colorspaces/wet/kis_wet_palette_widget.cc
+++ b/chalk/colorspaces/wet/kis_wet_palette_widget.cpp
diff --git a/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cc b/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cc
deleted file mode 100644
index f17f4e1c4..000000000
--- a/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * kis_wetness_visualisation_filter.cc -- Part of Chalk
- *
- * Copyright (c) 2005 Bart Coppens <kde@bartcoppens.be>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <kdebug.h>
-
-#include <tdelocale.h>
-#include "kis_meta_registry.h"
-#include <kis_view.h>
-#include <kis_image.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_factory.h>
-#include "kis_wet_colorspace.h"
-#include <kis_debug_areas.h>
-#include "kis_wetness_visualisation_filter.h"
-
-WetnessVisualisationFilter::WetnessVisualisationFilter(KisView* view)
- : m_view(view), m_action(0) {
- connect(&m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotTimeout()));
-}
-
-// XXX this needs to work on a per-layer basis!
-
-void WetnessVisualisationFilter::setAction(TDEToggleAction* action) {
- m_action = action;
- if (!m_action)
- return;
- KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
- KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
- Q_ASSERT(cs);
- m_action->setChecked(cs->paintWetness());
-}
-
-void WetnessVisualisationFilter::slotActivated() {
- kdDebug(DBG_AREA_CMS) << "activated" << endl;
- if (!m_action) {
- kdDebug(DBG_AREA_CMS) << "no action" << endl;
- return;
- }
- KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
- KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
- Q_ASSERT(cs);
- if (!m_action->isChecked()) {
- m_timer.stop();
- cs->setPaintWetness(false);
- } else {
- m_timer.start(500);
- cs->setPaintWetness(true);
- }
-}
-
-void WetnessVisualisationFilter::slotTimeout() {
- KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
- KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
- Q_ASSERT(cs);
- if (!cs) return;
- cs->resetPhase();
-
-}
-
-#include "kis_wetness_visualisation_filter.moc"
diff --git a/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cpp b/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cpp
new file mode 100644
index 000000000..634424469
--- /dev/null
+++ b/chalk/colorspaces/wet/kis_wetness_visualisation_filter.cpp
@@ -0,0 +1,77 @@
+/*
+ * kis_wetness_visualisation_filter.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2005 Bart Coppens <kde@bartcoppens.be>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <kdebug.h>
+
+#include <tdelocale.h>
+#include "kis_meta_registry.h"
+#include <kis_view.h>
+#include <kis_image.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_factory.h>
+#include "kis_wet_colorspace.h"
+#include <kis_debug_areas.h>
+#include "kis_wetness_visualisation_filter.h"
+
+WetnessVisualisationFilter::WetnessVisualisationFilter(KisView* view)
+ : m_view(view), m_action(0) {
+ connect(&m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotTimeout()));
+}
+
+// XXX this needs to work on a per-layer basis!
+
+void WetnessVisualisationFilter::setAction(TDEToggleAction* action) {
+ m_action = action;
+ if (!m_action)
+ return;
+ KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
+ KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
+ Q_ASSERT(cs);
+ m_action->setChecked(cs->paintWetness());
+}
+
+void WetnessVisualisationFilter::slotActivated() {
+ kdDebug(DBG_AREA_CMS) << "activated" << endl;
+ if (!m_action) {
+ kdDebug(DBG_AREA_CMS) << "no action" << endl;
+ return;
+ }
+ KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
+ KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
+ Q_ASSERT(cs);
+ if (!m_action->isChecked()) {
+ m_timer.stop();
+ cs->setPaintWetness(false);
+ } else {
+ m_timer.start(500);
+ cs->setPaintWetness(true);
+ }
+}
+
+void WetnessVisualisationFilter::slotTimeout() {
+ KisWetColorSpace* cs = dynamic_cast<KisWetColorSpace*>(
+ KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("WET", ""),"") );
+ Q_ASSERT(cs);
+ if (!cs) return;
+ cs->resetPhase();
+
+}
+
+#include "kis_wetness_visualisation_filter.moc"
diff --git a/chalk/colorspaces/wet/kis_wetop.cc b/chalk/colorspaces/wet/kis_wetop.cpp
index 15625e5d3..15625e5d3 100644
--- a/chalk/colorspaces/wet/kis_wetop.cc
+++ b/chalk/colorspaces/wet/kis_wetop.cpp
diff --git a/chalk/colorspaces/wet/wet_plugin.cc b/chalk/colorspaces/wet/wet_plugin.cc
deleted file mode 100644
index b919a2897..000000000
--- a/chalk/colorspaces/wet/wet_plugin.cc
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * wet_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqobject.h>
-#include <tqapplication.h>
-#include <tqclipboard.h>
-#include <tqdockwindow.h>
-#include <tqpoint.h>
-#include <tqlabel.h>
-#include <tqwidget.h>
-
-#include <tdeactionclasses.h>
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kopalettemanager.h>
-#include <KoMainWindow.h>
-
-#include <kis_debug_areas.h>
-#include "kis_meta_registry.h"
-#include <kis_factory.h>
-#include <kis_image.h>
-#include <kis_debug_areas.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_tool_registry.h>
-#include <kis_paintop_registry.h>
-#include <kis_canvas_subject.h>
-#include <kis_basic_histogram_producers.h>
-
-#include "wet_plugin.h"
-#include "kis_wet_palette_widget.h"
-#include "kis_wet_colorspace.h"
-#include "kis_wetop.h"
-#include "kis_wetness_visualisation_filter.h"
-#include "kis_texture_filter.h"
-#include "wetphysicsfilter.h"
-
-typedef KGenericFactory<WetPlugin> WetPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkwetplugin, WetPluginFactory( "chalkcore" ) )
-
-
-WetPlugin::WetPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(WetPluginFactory::instance());
-
- // This is not a gui plugin; only load it when the doc is created.
- if ( parent->inherits("KisColorSpaceFactoryRegistry") ) {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
-
- KisColorSpace* colorSpaceWet = new KisWetColorSpace(f, 0);
-
- KisColorSpaceFactory * csf = new KisWetColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceWet);
-
- // colorspace
- f->add(csf);
-
- // histogram producer
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("WETHISTO", i18n("Wet")), colorSpaceWet) );
-
- // wet brush op
- KisPaintOpRegistry::instance()->add(new KisWetOpFactory);
-
- // Dry filter
- KisFilterRegistry::instance()->add( new WetPhysicsFilter() );
-
- // Texture Action:
- f->addPaintDeviceAction(colorSpaceWet, new WetPaintDevAction);
- }
- else if (parent->inherits("KisView"))
- {
- setInstance(WetPluginFactory::instance());
- setXMLFile(locate("data","chalkplugins/wetplugin.rc"), true);
-
- m_view = dynamic_cast<KisView*>(parent);
- // Wetness visualisation
- WetnessVisualisationFilter * wf = new WetnessVisualisationFilter(m_view);
- wf->setAction(new TDEToggleAction(i18n("Wetness Visualisation"), 0, 0, wf,
- TQT_SLOT(slotActivated()), actionCollection(), "wetnessvisualisation"));
-
- // Create the wet palette
- KisWetPaletteWidget * w = new KisWetPaletteWidget(m_view);
- TQ_CHECK_PTR(w);
-
- w->setCaption(i18n("Watercolors"));
-
- m_view->canvasSubject()->paletteManager()->addWidget(w, "watercolor docker", chalk::COLORBOX, INT_MAX, PALETTE_DOCKER, false);
- m_view->canvasSubject()->attach(w);
- }
-
-
-}
-
-WetPlugin::~WetPlugin()
-{
-}
-
-#include "wet_plugin.moc"
diff --git a/chalk/colorspaces/wet/wet_plugin.cpp b/chalk/colorspaces/wet/wet_plugin.cpp
new file mode 100644
index 000000000..259fe5d1c
--- /dev/null
+++ b/chalk/colorspaces/wet/wet_plugin.cpp
@@ -0,0 +1,128 @@
+/*
+ * wet_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqobject.h>
+#include <tqapplication.h>
+#include <tqclipboard.h>
+#include <tqdockwindow.h>
+#include <tqpoint.h>
+#include <tqlabel.h>
+#include <tqwidget.h>
+
+#include <tdeactionclasses.h>
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kopalettemanager.h>
+#include <KoMainWindow.h>
+
+#include <kis_debug_areas.h>
+#include "kis_meta_registry.h"
+#include <kis_factory.h>
+#include <kis_image.h>
+#include <kis_debug_areas.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_tool_registry.h>
+#include <kis_paintop_registry.h>
+#include <kis_canvas_subject.h>
+#include <kis_basic_histogram_producers.h>
+
+#include "wet_plugin.h"
+#include "kis_wet_palette_widget.h"
+#include "kis_wet_colorspace.h"
+#include "kis_wetop.h"
+#include "kis_wetness_visualisation_filter.h"
+#include "kis_texture_filter.h"
+#include "wetphysicsfilter.h"
+
+typedef KGenericFactory<WetPlugin> WetPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkwetplugin, WetPluginFactory( "chalkcore" ) )
+
+
+WetPlugin::WetPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(WetPluginFactory::instance());
+
+ // This is not a gui plugin; only load it when the doc is created.
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") ) {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>(parent);
+
+ KisColorSpace* colorSpaceWet = new KisWetColorSpace(f, 0);
+
+ KisColorSpaceFactory * csf = new KisWetColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceWet);
+
+ // colorspace
+ f->add(csf);
+
+ // histogram producer
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("WETHISTO", i18n("Wet")), colorSpaceWet) );
+
+ // wet brush op
+ KisPaintOpRegistry::instance()->add(new KisWetOpFactory);
+
+ // Dry filter
+ KisFilterRegistry::instance()->add( new WetPhysicsFilter() );
+
+ // Texture Action:
+ f->addPaintDeviceAction(colorSpaceWet, new WetPaintDevAction);
+ }
+ else if (parent->inherits("KisView"))
+ {
+ setInstance(WetPluginFactory::instance());
+ setXMLFile(locate("data","chalkplugins/wetplugin.rc"), true);
+
+ m_view = dynamic_cast<KisView*>(parent);
+ // Wetness visualisation
+ WetnessVisualisationFilter * wf = new WetnessVisualisationFilter(m_view);
+ wf->setAction(new TDEToggleAction(i18n("Wetness Visualisation"), 0, 0, wf,
+ TQT_SLOT(slotActivated()), actionCollection(), "wetnessvisualisation"));
+
+ // Create the wet palette
+ KisWetPaletteWidget * w = new KisWetPaletteWidget(m_view);
+ TQ_CHECK_PTR(w);
+
+ w->setCaption(i18n("Watercolors"));
+
+ m_view->canvasSubject()->paletteManager()->addWidget(w, "watercolor docker", chalk::COLORBOX, INT_MAX, PALETTE_DOCKER, false);
+ m_view->canvasSubject()->attach(w);
+ }
+
+
+}
+
+WetPlugin::~WetPlugin()
+{
+}
+
+#include "wet_plugin.moc"
diff --git a/chalk/colorspaces/wet/wetphysicsfilter.cc b/chalk/colorspaces/wet/wetphysicsfilter.cpp
index 3a4394439..3a4394439 100644
--- a/chalk/colorspaces/wet/wetphysicsfilter.cc
+++ b/chalk/colorspaces/wet/wetphysicsfilter.cpp
diff --git a/chalk/colorspaces/wetsticky/Makefile.am b/chalk/colorspaces/wetsticky/Makefile.am
index 4ade368a8..5d4e02894 100644
--- a/chalk/colorspaces/wetsticky/Makefile.am
+++ b/chalk/colorspaces/wetsticky/Makefile.am
@@ -12,7 +12,7 @@ INCLUDES = -I$(srcdir)/../../sdk \
kde_module_LTLIBRARIES = chalkwsplugin.la
-chalkwsplugin_la_SOURCES = wet_sticky_plugin.cc kis_wet_sticky_colorspace.cc kis_ws_engine_filter.cc
+chalkwsplugin_la_SOURCES = wet_sticky_plugin.cpp kis_wet_sticky_colorspace.cpp kis_ws_engine_filter.cpp
noinst_HEADERS = wet_sticky_plugin.h kis_wet_sticky_colorspace.h kis_ws_engine_filter.h
chalkwsplugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
diff --git a/chalk/colorspaces/wetsticky/brushop/Makefile.am b/chalk/colorspaces/wetsticky/brushop/Makefile.am
index 8df4d61e3..eae064f8e 100644
--- a/chalk/colorspaces/wetsticky/brushop/Makefile.am
+++ b/chalk/colorspaces/wetsticky/brushop/Makefile.am
@@ -13,8 +13,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalkwsbrushpaintop_la_SOURCES = \
- wsbrushpaintop_plugin.cc \
- kis_wsbrushop.cc
+ wsbrushpaintop_plugin.cpp \
+ kis_wsbrushop.cpp
noinst_HEADERS= \
wsbrushpaintop_plugin.h \
diff --git a/chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cc b/chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cpp
index ed828bf51..ed828bf51 100644
--- a/chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cc
+++ b/chalk/colorspaces/wetsticky/brushop/kis_wsbrushop.cpp
diff --git a/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cc b/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cc
deleted file mode 100644
index 1f141bb4f..000000000
--- a/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * wsbrushpaintop_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_paintop_registry.h>
-#include <kis_debug_areas.h>
-#include "kis_wsbrushop.h"
-
-#include "wsbrushpaintop_plugin.h"
-
-typedef KGenericFactory<WSBrushPaintOpPlugin> WSBrushPaintOpPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkwsbrushpaintop, WSBrushPaintOpPluginFactory( "chalkcore" ) )
-
-
-WSBrushPaintOpPlugin::WSBrushPaintOpPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(WSBrushPaintOpPluginFactory::instance());
-
- // This is not a gui plugin; only load it when the doc is created.
- if ( parent->inherits("KisFactory") )
- {
- KisPaintOpRegistry::instance() -> add ( new KisWSBrushOpFactory );
- }
-
-}
-
-WSBrushPaintOpPlugin::~WSBrushPaintOpPlugin()
-{
-}
-
-#include "wsbrushpaintop_plugin.moc"
diff --git a/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cpp b/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cpp
new file mode 100644
index 000000000..97c892b2b
--- /dev/null
+++ b/chalk/colorspaces/wetsticky/brushop/wsbrushpaintop_plugin.cpp
@@ -0,0 +1,56 @@
+/*
+ * wsbrushpaintop_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_paintop_registry.h>
+#include <kis_debug_areas.h>
+#include "kis_wsbrushop.h"
+
+#include "wsbrushpaintop_plugin.h"
+
+typedef KGenericFactory<WSBrushPaintOpPlugin> WSBrushPaintOpPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkwsbrushpaintop, WSBrushPaintOpPluginFactory( "chalkcore" ) )
+
+
+WSBrushPaintOpPlugin::WSBrushPaintOpPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(WSBrushPaintOpPluginFactory::instance());
+
+ // This is not a gui plugin; only load it when the doc is created.
+ if ( parent->inherits("KisFactory") )
+ {
+ KisPaintOpRegistry::instance() -> add ( new KisWSBrushOpFactory );
+ }
+
+}
+
+WSBrushPaintOpPlugin::~WSBrushPaintOpPlugin()
+{
+}
+
+#include "wsbrushpaintop_plugin.moc"
diff --git a/chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cc b/chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cpp
index 3e47114ae..3e47114ae 100644
--- a/chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cc
+++ b/chalk/colorspaces/wetsticky/kis_wet_sticky_colorspace.cpp
diff --git a/chalk/colorspaces/wetsticky/kis_ws_engine_filter.cc b/chalk/colorspaces/wetsticky/kis_ws_engine_filter.cpp
index c53f6ea08..c53f6ea08 100644
--- a/chalk/colorspaces/wetsticky/kis_ws_engine_filter.cc
+++ b/chalk/colorspaces/wetsticky/kis_ws_engine_filter.cpp
diff --git a/chalk/colorspaces/wetsticky/wet_sticky_plugin.cc b/chalk/colorspaces/wetsticky/wet_sticky_plugin.cc
deleted file mode 100644
index 76dee20e6..000000000
--- a/chalk/colorspaces/wetsticky/wet_sticky_plugin.cc
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * wet_sticky_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_colorspace_registry.h>
-#include <kis_debug_areas.h>
-#include "wet_sticky_plugin.h"
-
-#include "kis_wet_sticky_colorspace.h"
-#include "kis_ws_engine_filter.h"
-
-typedef KGenericFactory<WetStickyPlugin> WetStickyPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkwsplugin, WetStickyPluginFactory( "chalkcore" ) )
-
-
-WetStickyPlugin::WetStickyPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(WetStickyPluginFactory::instance());
-
- // This is not a gui plugin; only load it when the doc is created.
- if ( parent->inherits("KisFactory") )
- {
- KisColorSpace * colorSpaceWS = new KisWetStickyColorSpace();
- TQ_CHECK_PTR(colorSpaceWS);
- KisColorSpaceRegistry::instance() -> add(colorSpaceWS);
- KisFilterRegistry::instance()->add(new KisWSEngineFilter());
- }
-
-}
-
-WetStickyPlugin::~WetStickyPlugin()
-{
-}
-
-#include "wet_sticky_plugin.moc"
diff --git a/chalk/colorspaces/wetsticky/wet_sticky_plugin.cpp b/chalk/colorspaces/wetsticky/wet_sticky_plugin.cpp
new file mode 100644
index 000000000..e56e4cc88
--- /dev/null
+++ b/chalk/colorspaces/wetsticky/wet_sticky_plugin.cpp
@@ -0,0 +1,60 @@
+/*
+ * wet_sticky_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_colorspace_registry.h>
+#include <kis_debug_areas.h>
+#include "wet_sticky_plugin.h"
+
+#include "kis_wet_sticky_colorspace.h"
+#include "kis_ws_engine_filter.h"
+
+typedef KGenericFactory<WetStickyPlugin> WetStickyPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkwsplugin, WetStickyPluginFactory( "chalkcore" ) )
+
+
+WetStickyPlugin::WetStickyPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(WetStickyPluginFactory::instance());
+
+ // This is not a gui plugin; only load it when the doc is created.
+ if ( parent->inherits("KisFactory") )
+ {
+ KisColorSpace * colorSpaceWS = new KisWetStickyColorSpace();
+ TQ_CHECK_PTR(colorSpaceWS);
+ KisColorSpaceRegistry::instance() -> add(colorSpaceWS);
+ KisFilterRegistry::instance()->add(new KisWSEngineFilter());
+ }
+
+}
+
+WetStickyPlugin::~WetStickyPlugin()
+{
+}
+
+#include "wet_sticky_plugin.moc"
diff --git a/chalk/colorspaces/ycbcr_u16/Makefile.am b/chalk/colorspaces/ycbcr_u16/Makefile.am
index ab8200201..e9c273b79 100644
--- a/chalk/colorspaces/ycbcr_u16/Makefile.am
+++ b/chalk/colorspaces/ycbcr_u16/Makefile.am
@@ -16,7 +16,7 @@ libchalk_ycbcr_u16_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_ycbcr_u16_plugin.la
# Srcs for the plugin
-chalk_ycbcr_u16_plugin_la_SOURCES = ycbcr_u16_plugin.cc
+chalk_ycbcr_u16_plugin_la_SOURCES = ycbcr_u16_plugin.cpp
noinst_HEADERS = ycbcr_u16_plugin.h kis_ycbcr_u16_colorspace.h
chalk_ycbcr_u16_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
@@ -24,6 +24,6 @@ chalk_ycbcr_u16_plugin_la_LIBADD = libchalk_ycbcr_u16.la ../../chalkcolor/libch
METASOURCES = AUTO
-libchalk_ycbcr_u16_la_SOURCES = kis_ycbcr_u16_colorspace.cc
+libchalk_ycbcr_u16_la_SOURCES = kis_ycbcr_u16_colorspace.cpp
.NOTPARALLEL:
diff --git a/chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cc b/chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cpp
index 4d7493b27..4d7493b27 100644
--- a/chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cc
+++ b/chalk/colorspaces/ycbcr_u16/kis_ycbcr_u16_colorspace.cpp
diff --git a/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cc b/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cc
deleted file mode 100644
index fdfb23106..000000000
--- a/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cc
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * ycbcr_u16_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-#include <kis_debug_areas.h>
-#include "ycbcr_u16_plugin.h"
-#include "kis_ycbcr_u16_colorspace.h"
-
-typedef KGenericFactory<YCbCrU16Plugin> YCbCrU16PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_ycbcr_u16_plugin, YCbCrU16PluginFactory( "chalk" ) )
-
-
-YCbCrU16Plugin::YCbCrU16Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(YCbCrU16PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceYCbCrU16 = new KisYCbCrU16ColorSpace(f, 0);
- KisColorSpaceFactory * csf = new KisYCbCrU16ColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceYCbCrU16);
- f->add(csf);
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("YCbCr16HISTO", i18n("YCbCr16")), colorSpaceYCbCrU16) );
- }
-
-}
-
-YCbCrU16Plugin::~YCbCrU16Plugin()
-{
-}
-
-#include "ycbcr_u16_plugin.moc"
diff --git a/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cpp b/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cpp
new file mode 100644
index 000000000..4371a20a4
--- /dev/null
+++ b/chalk/colorspaces/ycbcr_u16/ycbcr_u16_plugin.cpp
@@ -0,0 +1,60 @@
+/*
+ * ycbcr_u16_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+#include <kis_debug_areas.h>
+#include "ycbcr_u16_plugin.h"
+#include "kis_ycbcr_u16_colorspace.h"
+
+typedef KGenericFactory<YCbCrU16Plugin> YCbCrU16PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_ycbcr_u16_plugin, YCbCrU16PluginFactory( "chalk" ) )
+
+
+YCbCrU16Plugin::YCbCrU16Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(YCbCrU16PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceYCbCrU16 = new KisYCbCrU16ColorSpace(f, 0);
+ KisColorSpaceFactory * csf = new KisYCbCrU16ColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceYCbCrU16);
+ f->add(csf);
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("YCbCr16HISTO", i18n("YCbCr16")), colorSpaceYCbCrU16) );
+ }
+
+}
+
+YCbCrU16Plugin::~YCbCrU16Plugin()
+{
+}
+
+#include "ycbcr_u16_plugin.moc"
diff --git a/chalk/colorspaces/ycbcr_u8/Makefile.am b/chalk/colorspaces/ycbcr_u8/Makefile.am
index 82f2942df..77c8c432e 100644
--- a/chalk/colorspaces/ycbcr_u8/Makefile.am
+++ b/chalk/colorspaces/ycbcr_u8/Makefile.am
@@ -16,7 +16,7 @@ libchalk_ycbcr_u8_la_LIBADD = ../../chalkcolor/libchalkcolor.la
kde_module_LTLIBRARIES = chalk_ycbcr_u8_plugin.la
# Srcs for the plugin
-chalk_ycbcr_u8_plugin_la_SOURCES = ycbcr_u8_plugin.cc
+chalk_ycbcr_u8_plugin_la_SOURCES = ycbcr_u8_plugin.cpp
noinst_HEADERS = ycbcr_u8_plugin.h kis_ycbcr_u8_colorspace.h
chalk_ycbcr_u8_plugin_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts -llcms
@@ -25,7 +25,7 @@ chalk_ycbcr_u8_plugin_la_LIBADD = libchalk_ycbcr_u8.la ../../chalkcolor/libchal
METASOURCES = AUTO
-libchalk_ycbcr_u8_la_SOURCES = kis_ycbcr_u8_colorspace.cc
+libchalk_ycbcr_u8_la_SOURCES = kis_ycbcr_u8_colorspace.cpp
kde_services_DATA = chalk_ycbcr_u8_plugin.desktop
.NOTPARALLEL:
diff --git a/chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cc b/chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cpp
index 5cd132319..5cd132319 100644
--- a/chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cc
+++ b/chalk/colorspaces/ycbcr_u8/kis_ycbcr_u8_colorspace.cpp
diff --git a/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cc b/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cc
deleted file mode 100644
index 342074329..000000000
--- a/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * ycbcr_u8_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "ycbcr_u8_plugin.h"
-
-#include <kinstance.h>
-#include <kgenericfactory.h>
-#include <kdebug.h>
-
-#include <kis_debug_areas.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_basic_histogram_producers.h>
-#include <kis_debug_areas.h>
-
-#include "kis_ycbcr_u8_colorspace.h"
-
-typedef KGenericFactory<YCbCrU8Plugin> YCbCrU8PluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalk_ycbcr_u8_plugin, YCbCrU8PluginFactory( "chalk" ) )
-
-
-YCbCrU8Plugin::YCbCrU8Plugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(YCbCrU8PluginFactory::instance());
-
- if ( parent->inherits("KisColorSpaceFactoryRegistry") )
- {
- KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
-
- KisColorSpace * colorSpaceYCbCrU8 = new KisYCbCrU8ColorSpace(f, 0);
- KisColorSpaceFactory * csf = new KisYCbCrU8ColorSpaceFactory();
- TQ_CHECK_PTR(colorSpaceYCbCrU8);
- f->add(csf);
- KisHistogramProducerFactoryRegistry::instance()->add(
- new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
- (KisID("YCBR8HISTO", i18n("YCBR8")), colorSpaceYCbCrU8) );
- }
-
-}
-
-YCbCrU8Plugin::~YCbCrU8Plugin()
-{
-}
-
-#include "ycbcr_u8_plugin.moc"
diff --git a/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cpp b/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cpp
new file mode 100644
index 000000000..6c3ac2437
--- /dev/null
+++ b/chalk/colorspaces/ycbcr_u8/ycbcr_u8_plugin.cpp
@@ -0,0 +1,62 @@
+/*
+ * ycbcr_u8_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "ycbcr_u8_plugin.h"
+
+#include <kinstance.h>
+#include <kgenericfactory.h>
+#include <kdebug.h>
+
+#include <kis_debug_areas.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_basic_histogram_producers.h>
+#include <kis_debug_areas.h>
+
+#include "kis_ycbcr_u8_colorspace.h"
+
+typedef KGenericFactory<YCbCrU8Plugin> YCbCrU8PluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalk_ycbcr_u8_plugin, YCbCrU8PluginFactory( "chalk" ) )
+
+
+YCbCrU8Plugin::YCbCrU8Plugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(YCbCrU8PluginFactory::instance());
+
+ if ( parent->inherits("KisColorSpaceFactoryRegistry") )
+ {
+ KisColorSpaceFactoryRegistry * f = dynamic_cast<KisColorSpaceFactoryRegistry*>( parent );
+
+ KisColorSpace * colorSpaceYCbCrU8 = new KisYCbCrU8ColorSpace(f, 0);
+ KisColorSpaceFactory * csf = new KisYCbCrU8ColorSpaceFactory();
+ TQ_CHECK_PTR(colorSpaceYCbCrU8);
+ f->add(csf);
+ KisHistogramProducerFactoryRegistry::instance()->add(
+ new KisBasicHistogramProducerFactory<KisBasicU16HistogramProducer>
+ (KisID("YCBR8HISTO", i18n("YCBR8")), colorSpaceYCbCrU8) );
+ }
+
+}
+
+YCbCrU8Plugin::~YCbCrU8Plugin()
+{
+}
+
+#include "ycbcr_u8_plugin.moc"
diff --git a/chalk/core/Makefile.am b/chalk/core/Makefile.am
index 9370161af..ae67f2c08 100644
--- a/chalk/core/Makefile.am
+++ b/chalk/core/Makefile.am
@@ -13,21 +13,21 @@ CXXFLAGS += $(OPENEXR_CXXFLAGS)
lib_LTLIBRARIES = libchalkimage.la
-libchalkimage_la_SOURCES = kis_adjustment_layer.cc kis_alpha_mask.cc \
- kis_autobrush_resource.cc kis_autogradient_resource.cc kis_background.cc kis_boundary.cc \
- kis_brush.cc kis_command.cc kis_convolution_painter.cc kis_fill_painter.cc \
- kis_filter.cc kis_filter_registry.cc kis_filter_strategy.cc \
- kis_filter_configuration.cc kis_filter_config_widget.cc kis_gradient.cc kis_gradient_painter.cc \
- kis_histogram.cc kis_image.cc kis_imagepipe_brush.cc kis_iterator.cc \
- kis_iterators_pixel.cc kis_layer.cc kis_group_layer.cc kis_paint_layer.cc kis_meta_registry.cc \
- kis_nameserver.cc kis_painter.cc kis_paintop.cc kis_paintop_registry.cc kis_palette.cc \
- kis_pattern.cc kis_rect.cc kis_resource.cc kis_rotate_visitor.cc \
- kis_selected_transaction.cc kis_selection.cc kis_strategy_move.cc kis_transaction.cc \
- kis_transform_worker.cc kis_vec.cc kis_paint_device.cc kis_paint_device_iface.cc \
- kis_paint_device_iface.skel kis_image_iface.cc kis_image_iface.skel kis_basic_math_toolbox.cpp \
- kis_math_toolbox.cpp kis_exif_info.cc kis_thread_pool.cc kis_exif_value.cc \
+libchalkimage_la_SOURCES = kis_adjustment_layer.cpp kis_alpha_mask.cpp \
+ kis_autobrush_resource.cpp kis_autogradient_resource.cpp kis_background.cpp kis_boundary.cpp \
+ kis_brush.cpp kis_command.cpp kis_convolution_painter.cpp kis_fill_painter.cpp \
+ kis_filter.cpp kis_filter_registry.cpp kis_filter_strategy.cpp \
+ kis_filter_configuration.cpp kis_filter_config_widget.cpp kis_gradient.cpp kis_gradient_painter.cpp \
+ kis_histogram.cpp kis_image.cpp kis_imagepipe_brush.cpp kis_iterator.cpp \
+ kis_iterators_pixel.cpp kis_layer.cpp kis_group_layer.cpp kis_paint_layer.cpp kis_meta_registry.cpp \
+ kis_nameserver.cpp kis_painter.cpp kis_paintop.cpp kis_paintop_registry.cpp kis_palette.cpp \
+ kis_pattern.cpp kis_rect.cpp kis_resource.cpp kis_rotate_visitor.cpp \
+ kis_selected_transaction.cpp kis_selection.cpp kis_strategy_move.cpp kis_transaction.cpp \
+ kis_transform_worker.cpp kis_vec.cpp kis_paint_device.cpp kis_paint_device_iface.cpp \
+ kis_paint_device_iface.skel kis_image_iface.cpp kis_image_iface.skel kis_basic_math_toolbox.cpp \
+ kis_math_toolbox.cpp kis_exif_info.cpp kis_thread_pool.cpp kis_exif_value.cpp \
kis_filter_strategy.h kis_random_accessor.cpp kis_random_sub_accessor.cpp \
- kis_perspective_grid.cpp kis_perspectivetransform_worker.cpp kis_perspective_math.cpp kis_scale_visitor.cc
+ kis_perspective_grid.cpp kis_perspectivetransform_worker.cpp kis_perspective_math.cpp kis_scale_visitor.cpp
noinst_HEADERS = kis_rotate_visitor.h kis_selected_transaction.h \
kis_strategy_move.h kis_transform_worker.h kis_datamanager.h kis_iteratorpixeltrait.h \
diff --git a/chalk/core/createdcop.py b/chalk/core/createdcop.py
index ef7acc5ef..337d90761 100755
--- a/chalk/core/createdcop.py
+++ b/chalk/core/createdcop.py
@@ -149,7 +149,7 @@ def createDCOP(header):
classname = classname + part.capitalize()
classname_upper = classname_upper + part.upper() + "_"
ifaceheader = header[:-2] + "_iface.h"
- ifaceimplementation = header[:-2] + "_iface.cc"
+ ifaceimplementation = header[:-2] + "_iface.cpp"
ifaceclass = classname + "Iface"
#print "with: ", implementation, classname, classname_upper, ifaceheader, ifaceimplementation, ifaceclass
diff --git a/chalk/core/kis_adjustment_layer.cc b/chalk/core/kis_adjustment_layer.cpp
index 69e8b9398..69e8b9398 100644
--- a/chalk/core/kis_adjustment_layer.cc
+++ b/chalk/core/kis_adjustment_layer.cpp
diff --git a/chalk/core/kis_alpha_mask.cc b/chalk/core/kis_alpha_mask.cpp
index 152963087..152963087 100644
--- a/chalk/core/kis_alpha_mask.cc
+++ b/chalk/core/kis_alpha_mask.cpp
diff --git a/chalk/core/kis_autobrush_resource.cc b/chalk/core/kis_autobrush_resource.cpp
index 9a09fe788..9a09fe788 100644
--- a/chalk/core/kis_autobrush_resource.cc
+++ b/chalk/core/kis_autobrush_resource.cpp
diff --git a/chalk/core/kis_autogradient_resource.cc b/chalk/core/kis_autogradient_resource.cc
deleted file mode 100644
index 671e8fc2f..000000000
--- a/chalk/core/kis_autogradient_resource.cc
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
- * 2004 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "kis_gradient.h"
-#include "kis_autogradient_resource.h"
-
-// FIXME: use the same #define as in kis_gradient.cc, probably best customizable?
-#define PREVIEW_WIDTH 64
-#define PREVIEW_HEIGHT 64
-
-
-void KisAutogradientResource::createSegment( int interpolation, int colorInterpolation, double startOffset, double endOffset, double middleOffset, TQColor left, TQColor right )
-{
- pushSegment(new KisGradientSegment(interpolation, colorInterpolation, startOffset, middleOffset, endOffset, Color( left, 1 ), Color( right, 1 )));
-
-}
-
-const TQValueVector<double> KisAutogradientResource::getHandlePositions() const
-{
- TQValueVector<double> handlePositions;
-
- handlePositions.push_back(m_segments[0]->startOffset());
- for (uint i = 0; i < m_segments.count(); i++)
- {
- handlePositions.push_back(m_segments[i]->endOffset());
- }
- return handlePositions;
-}
-
-const TQValueVector<double> KisAutogradientResource::getMiddleHandlePositions() const
-{
- TQValueVector<double> middleHandlePositions;
-
- for (uint i = 0; i < m_segments.count(); i++)
- {
- middleHandlePositions.push_back(m_segments[i]->middleOffset());
- }
- return middleHandlePositions;
-}
-
-void KisAutogradientResource::moveSegmentStartOffset( KisGradientSegment* segment, double t)
-{
- TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
- if ( it != m_segments.end() )
- {
- if ( it == m_segments.begin() )
- {
- segment->setStartOffset( 0.0 );
- return;
- }
- KisGradientSegment* previousSegment = (*(it-1));
- if ( t > segment->startOffset() )
- {
- if( t > segment->middleOffset() )
- t = segment->middleOffset();
- }
- else {
- if( t < previousSegment->middleOffset() )
- t = previousSegment->middleOffset();
- }
- previousSegment->setEndOffset( t );
- segment->setStartOffset( t );
- }
-}
-
-void KisAutogradientResource::moveSegmentEndOffset( KisGradientSegment* segment, double t)
-{
- TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
- if ( it != m_segments.end() )
- {
- if ( it+1 == m_segments.end() )
- {
- segment->setEndOffset( 1.0 );
- return;
- }
- KisGradientSegment* followingSegment = (*(it+1));
- if ( t < segment->endOffset() )
- {
- if( t < segment->middleOffset() )
- t = segment->middleOffset();
- }
- else {
- if( t > followingSegment->middleOffset() )
- t = followingSegment->middleOffset();
- }
- followingSegment->setStartOffset( t );
- segment->setEndOffset( t );
- }
-}
-
-void KisAutogradientResource::moveSegmentMiddleOffset( KisGradientSegment* segment, double t)
-{
- if( segment )
- {
- if( t > segment->endOffset() )
- segment->setMiddleOffset( segment->endOffset() );
- else if( t < segment->startOffset() )
- segment->setMiddleOffset( segment->startOffset() );
- else
- segment->setMiddleOffset( t );
- }
-}
-
-void KisAutogradientResource::splitSegment( KisGradientSegment* segment )
-{
- Q_ASSERT(segment != 0);
- TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
- if ( it != m_segments.end() )
- {
- KisGradientSegment* newSegment = new KisGradientSegment(
- segment->interpolation(), segment->colorInterpolation(),
- segment ->startOffset(),
- ( segment->middleOffset() - segment->startOffset() ) / 2 + segment->startOffset(),
- segment->middleOffset(),
- segment->startColor(),
- segment->colorAt( segment->middleOffset() ) );
- m_segments.insert( it, newSegment );
- segment->setStartColor( segment->colorAt( segment->middleOffset() ) );
- segment->setStartOffset( segment->middleOffset() );
- segment->setMiddleOffset( ( segment->endOffset() - segment->startOffset() ) / 2 + segment->startOffset() );
- }
-}
-
-void KisAutogradientResource::duplicateSegment( KisGradientSegment* segment )
-{
- Q_ASSERT(segment != 0);
- TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
- if ( it != m_segments.end() )
- {
- double middlePostionPercentage = ( segment->middleOffset() - segment->startOffset() ) / segment->length();
- double center = segment->startOffset() + segment->length() / 2;
- KisGradientSegment* newSegment = new KisGradientSegment(
- segment->interpolation(), segment->colorInterpolation(),
- segment ->startOffset(),
- segment->length() / 2 * middlePostionPercentage + segment->startOffset(),
- center, segment->startColor(),
- segment->endColor() );
- m_segments.insert( it, newSegment );
- segment->setStartOffset( center );
- segment->setMiddleOffset( segment->length() * middlePostionPercentage + segment->startOffset() );
- }
-}
-
-void KisAutogradientResource::mirrorSegment( KisGradientSegment* segment )
-{
- Q_ASSERT(segment != 0);
- Color tmpColor = segment->startColor();
- segment->setStartColor( segment->endColor() );
- segment->setEndColor( tmpColor );
- segment->setMiddleOffset( segment->endOffset() - ( segment->middleOffset() - segment->startOffset() ) );
-
- if( segment->interpolation() == INTERP_SPHERE_INCREASING )
- segment->setInterpolation( INTERP_SPHERE_DECREASING );
- else if( segment->interpolation() == INTERP_SPHERE_DECREASING )
- segment->setInterpolation( INTERP_SPHERE_INCREASING );
-
- if( segment->colorInterpolation() == COLOR_INTERP_HSV_CW )
- segment->setColorInterpolation( COLOR_INTERP_HSV_CCW );
- else if( segment->colorInterpolation() == COLOR_INTERP_HSV_CCW )
- segment->setColorInterpolation( COLOR_INTERP_HSV_CW );
-}
-
-KisGradientSegment* KisAutogradientResource::removeSegment( KisGradientSegment* segment )
-{
- Q_ASSERT(segment != 0);
- if( m_segments.count() < 2 )
- return 0;
- TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
- if ( it != m_segments.end() )
- {
- double middlePostionPercentage;
- KisGradientSegment* nextSegment;
- if( it == m_segments.begin() )
- {
- nextSegment = (*(it+1));
- middlePostionPercentage = ( nextSegment->middleOffset() - nextSegment->startOffset() ) / nextSegment->length();
- nextSegment->setStartOffset( segment->startOffset() );
- nextSegment->setMiddleOffset( middlePostionPercentage * nextSegment->length() + nextSegment->startOffset() );
- }
- else
- {
- nextSegment = (*(it-1));
- middlePostionPercentage = ( nextSegment->middleOffset() - nextSegment->startOffset() ) / nextSegment->length();
- nextSegment->setEndOffset( segment->endOffset() );
- nextSegment->setMiddleOffset( middlePostionPercentage * nextSegment->length() + nextSegment->startOffset() );
- }
-
- delete segment;
- m_segments.erase( it );
- return nextSegment;
- }
- return 0;
-}
-
-bool KisAutogradientResource::removeSegmentPossible() const
-{
- if( m_segments.count() < 2 )
- return false;
- return true;
-}
-
-void KisAutogradientResource::updatePreview()
-{
- setImage( generatePreview( PREVIEW_WIDTH, PREVIEW_HEIGHT ) );
-}
diff --git a/chalk/core/kis_autogradient_resource.cpp b/chalk/core/kis_autogradient_resource.cpp
new file mode 100644
index 000000000..aaac54efd
--- /dev/null
+++ b/chalk/core/kis_autogradient_resource.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
+ * 2004 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "kis_gradient.h"
+#include "kis_autogradient_resource.h"
+
+// FIXME: use the same #define as in kis_gradient.cpp, probably best customizable?
+#define PREVIEW_WIDTH 64
+#define PREVIEW_HEIGHT 64
+
+
+void KisAutogradientResource::createSegment( int interpolation, int colorInterpolation, double startOffset, double endOffset, double middleOffset, TQColor left, TQColor right )
+{
+ pushSegment(new KisGradientSegment(interpolation, colorInterpolation, startOffset, middleOffset, endOffset, Color( left, 1 ), Color( right, 1 )));
+
+}
+
+const TQValueVector<double> KisAutogradientResource::getHandlePositions() const
+{
+ TQValueVector<double> handlePositions;
+
+ handlePositions.push_back(m_segments[0]->startOffset());
+ for (uint i = 0; i < m_segments.count(); i++)
+ {
+ handlePositions.push_back(m_segments[i]->endOffset());
+ }
+ return handlePositions;
+}
+
+const TQValueVector<double> KisAutogradientResource::getMiddleHandlePositions() const
+{
+ TQValueVector<double> middleHandlePositions;
+
+ for (uint i = 0; i < m_segments.count(); i++)
+ {
+ middleHandlePositions.push_back(m_segments[i]->middleOffset());
+ }
+ return middleHandlePositions;
+}
+
+void KisAutogradientResource::moveSegmentStartOffset( KisGradientSegment* segment, double t)
+{
+ TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
+ if ( it != m_segments.end() )
+ {
+ if ( it == m_segments.begin() )
+ {
+ segment->setStartOffset( 0.0 );
+ return;
+ }
+ KisGradientSegment* previousSegment = (*(it-1));
+ if ( t > segment->startOffset() )
+ {
+ if( t > segment->middleOffset() )
+ t = segment->middleOffset();
+ }
+ else {
+ if( t < previousSegment->middleOffset() )
+ t = previousSegment->middleOffset();
+ }
+ previousSegment->setEndOffset( t );
+ segment->setStartOffset( t );
+ }
+}
+
+void KisAutogradientResource::moveSegmentEndOffset( KisGradientSegment* segment, double t)
+{
+ TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
+ if ( it != m_segments.end() )
+ {
+ if ( it+1 == m_segments.end() )
+ {
+ segment->setEndOffset( 1.0 );
+ return;
+ }
+ KisGradientSegment* followingSegment = (*(it+1));
+ if ( t < segment->endOffset() )
+ {
+ if( t < segment->middleOffset() )
+ t = segment->middleOffset();
+ }
+ else {
+ if( t > followingSegment->middleOffset() )
+ t = followingSegment->middleOffset();
+ }
+ followingSegment->setStartOffset( t );
+ segment->setEndOffset( t );
+ }
+}
+
+void KisAutogradientResource::moveSegmentMiddleOffset( KisGradientSegment* segment, double t)
+{
+ if( segment )
+ {
+ if( t > segment->endOffset() )
+ segment->setMiddleOffset( segment->endOffset() );
+ else if( t < segment->startOffset() )
+ segment->setMiddleOffset( segment->startOffset() );
+ else
+ segment->setMiddleOffset( t );
+ }
+}
+
+void KisAutogradientResource::splitSegment( KisGradientSegment* segment )
+{
+ Q_ASSERT(segment != 0);
+ TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
+ if ( it != m_segments.end() )
+ {
+ KisGradientSegment* newSegment = new KisGradientSegment(
+ segment->interpolation(), segment->colorInterpolation(),
+ segment ->startOffset(),
+ ( segment->middleOffset() - segment->startOffset() ) / 2 + segment->startOffset(),
+ segment->middleOffset(),
+ segment->startColor(),
+ segment->colorAt( segment->middleOffset() ) );
+ m_segments.insert( it, newSegment );
+ segment->setStartColor( segment->colorAt( segment->middleOffset() ) );
+ segment->setStartOffset( segment->middleOffset() );
+ segment->setMiddleOffset( ( segment->endOffset() - segment->startOffset() ) / 2 + segment->startOffset() );
+ }
+}
+
+void KisAutogradientResource::duplicateSegment( KisGradientSegment* segment )
+{
+ Q_ASSERT(segment != 0);
+ TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
+ if ( it != m_segments.end() )
+ {
+ double middlePostionPercentage = ( segment->middleOffset() - segment->startOffset() ) / segment->length();
+ double center = segment->startOffset() + segment->length() / 2;
+ KisGradientSegment* newSegment = new KisGradientSegment(
+ segment->interpolation(), segment->colorInterpolation(),
+ segment ->startOffset(),
+ segment->length() / 2 * middlePostionPercentage + segment->startOffset(),
+ center, segment->startColor(),
+ segment->endColor() );
+ m_segments.insert( it, newSegment );
+ segment->setStartOffset( center );
+ segment->setMiddleOffset( segment->length() * middlePostionPercentage + segment->startOffset() );
+ }
+}
+
+void KisAutogradientResource::mirrorSegment( KisGradientSegment* segment )
+{
+ Q_ASSERT(segment != 0);
+ Color tmpColor = segment->startColor();
+ segment->setStartColor( segment->endColor() );
+ segment->setEndColor( tmpColor );
+ segment->setMiddleOffset( segment->endOffset() - ( segment->middleOffset() - segment->startOffset() ) );
+
+ if( segment->interpolation() == INTERP_SPHERE_INCREASING )
+ segment->setInterpolation( INTERP_SPHERE_DECREASING );
+ else if( segment->interpolation() == INTERP_SPHERE_DECREASING )
+ segment->setInterpolation( INTERP_SPHERE_INCREASING );
+
+ if( segment->colorInterpolation() == COLOR_INTERP_HSV_CW )
+ segment->setColorInterpolation( COLOR_INTERP_HSV_CCW );
+ else if( segment->colorInterpolation() == COLOR_INTERP_HSV_CCW )
+ segment->setColorInterpolation( COLOR_INTERP_HSV_CW );
+}
+
+KisGradientSegment* KisAutogradientResource::removeSegment( KisGradientSegment* segment )
+{
+ Q_ASSERT(segment != 0);
+ if( m_segments.count() < 2 )
+ return 0;
+ TQValueVector<KisGradientSegment*>::iterator it = tqFind( m_segments.begin(), m_segments.end(), segment );
+ if ( it != m_segments.end() )
+ {
+ double middlePostionPercentage;
+ KisGradientSegment* nextSegment;
+ if( it == m_segments.begin() )
+ {
+ nextSegment = (*(it+1));
+ middlePostionPercentage = ( nextSegment->middleOffset() - nextSegment->startOffset() ) / nextSegment->length();
+ nextSegment->setStartOffset( segment->startOffset() );
+ nextSegment->setMiddleOffset( middlePostionPercentage * nextSegment->length() + nextSegment->startOffset() );
+ }
+ else
+ {
+ nextSegment = (*(it-1));
+ middlePostionPercentage = ( nextSegment->middleOffset() - nextSegment->startOffset() ) / nextSegment->length();
+ nextSegment->setEndOffset( segment->endOffset() );
+ nextSegment->setMiddleOffset( middlePostionPercentage * nextSegment->length() + nextSegment->startOffset() );
+ }
+
+ delete segment;
+ m_segments.erase( it );
+ return nextSegment;
+ }
+ return 0;
+}
+
+bool KisAutogradientResource::removeSegmentPossible() const
+{
+ if( m_segments.count() < 2 )
+ return false;
+ return true;
+}
+
+void KisAutogradientResource::updatePreview()
+{
+ setImage( generatePreview( PREVIEW_WIDTH, PREVIEW_HEIGHT ) );
+}
diff --git a/chalk/core/kis_background.cc b/chalk/core/kis_background.cpp
index 506d49e8e..506d49e8e 100644
--- a/chalk/core/kis_background.cc
+++ b/chalk/core/kis_background.cpp
diff --git a/chalk/core/kis_boundary.cc b/chalk/core/kis_boundary.cpp
index a15697a7f..a15697a7f 100644
--- a/chalk/core/kis_boundary.cc
+++ b/chalk/core/kis_boundary.cpp
diff --git a/chalk/core/kis_brush.cc b/chalk/core/kis_brush.cpp
index 49ee8e581..49ee8e581 100644
--- a/chalk/core/kis_brush.cc
+++ b/chalk/core/kis_brush.cpp
diff --git a/chalk/core/kis_command.cc b/chalk/core/kis_command.cpp
index 11da634b8..11da634b8 100644
--- a/chalk/core/kis_command.cc
+++ b/chalk/core/kis_command.cpp
diff --git a/chalk/core/kis_convolution_painter.cc b/chalk/core/kis_convolution_painter.cpp
index f5ee5573f..f5ee5573f 100644
--- a/chalk/core/kis_convolution_painter.cc
+++ b/chalk/core/kis_convolution_painter.cpp
diff --git a/chalk/core/kis_exif_info.cc b/chalk/core/kis_exif_info.cpp
index 5d54ed5e7..5d54ed5e7 100644
--- a/chalk/core/kis_exif_info.cc
+++ b/chalk/core/kis_exif_info.cpp
diff --git a/chalk/core/kis_exif_value.cc b/chalk/core/kis_exif_value.cpp
index 134d4009a..134d4009a 100644
--- a/chalk/core/kis_exif_value.cc
+++ b/chalk/core/kis_exif_value.cpp
diff --git a/chalk/core/kis_fill_painter.cc b/chalk/core/kis_fill_painter.cpp
index 6b88759a4..6b88759a4 100644
--- a/chalk/core/kis_fill_painter.cc
+++ b/chalk/core/kis_fill_painter.cpp
diff --git a/chalk/core/kis_filter.cc b/chalk/core/kis_filter.cpp
index ee396596a..ee396596a 100644
--- a/chalk/core/kis_filter.cc
+++ b/chalk/core/kis_filter.cpp
diff --git a/chalk/core/kis_filter_config_widget.cc b/chalk/core/kis_filter_config_widget.cpp
index 1df05f64d..1df05f64d 100644
--- a/chalk/core/kis_filter_config_widget.cc
+++ b/chalk/core/kis_filter_config_widget.cpp
diff --git a/chalk/core/kis_filter_configuration.cc b/chalk/core/kis_filter_configuration.cpp
index b29a20b86..b29a20b86 100644
--- a/chalk/core/kis_filter_configuration.cc
+++ b/chalk/core/kis_filter_configuration.cpp
diff --git a/chalk/core/kis_filter_registry.cc b/chalk/core/kis_filter_registry.cpp
index f67e3ecc8..f67e3ecc8 100644
--- a/chalk/core/kis_filter_registry.cc
+++ b/chalk/core/kis_filter_registry.cpp
diff --git a/chalk/core/kis_filter_strategy.cc b/chalk/core/kis_filter_strategy.cpp
index 650a96812..650a96812 100644
--- a/chalk/core/kis_filter_strategy.cc
+++ b/chalk/core/kis_filter_strategy.cpp
diff --git a/chalk/core/kis_gradient.cc b/chalk/core/kis_gradient.cc
deleted file mode 100644
index 41541e80e..000000000
--- a/chalk/core/kis_gradient.cc
+++ /dev/null
@@ -1,639 +0,0 @@
-/*
- * kis_gradient.cc - part of Krayon
- *
- * Copyright (c) 2000 Matthias Elter <elter@kde.org>
- * 2001 John Califf
- * 2004 Boudewijn Rempt <boud@valdyas.org>
- * 2004 Adrian Page <adrian@pagenet.plus.com>
- * 2004 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <cfloat>
-#include <cmath>
-
-#include <tqimage.h>
-#include <tqtextstream.h>
-#include <tqfile.h>
-
-#include <koColor.h>
-#include <kogradientmanager.h>
-
-#include <kdebug.h>
-#include <tdelocale.h>
-
-#include "kis_gradient.h"
-
-#define PREVIEW_WIDTH 64
-#define PREVIEW_HEIGHT 64
-
-KisGradientSegment::RGBColorInterpolationStrategy *KisGradientSegment::RGBColorInterpolationStrategy::m_instance = 0;
-KisGradientSegment::HSVCWColorInterpolationStrategy *KisGradientSegment::HSVCWColorInterpolationStrategy::m_instance = 0;
-KisGradientSegment::HSVCCWColorInterpolationStrategy *KisGradientSegment::HSVCCWColorInterpolationStrategy::m_instance = 0;
-
-KisGradientSegment::LinearInterpolationStrategy *KisGradientSegment::LinearInterpolationStrategy::m_instance = 0;
-KisGradientSegment::CurvedInterpolationStrategy *KisGradientSegment::CurvedInterpolationStrategy::m_instance = 0;
-KisGradientSegment::SineInterpolationStrategy *KisGradientSegment::SineInterpolationStrategy::m_instance = 0;
-KisGradientSegment::SphereIncreasingInterpolationStrategy *KisGradientSegment::SphereIncreasingInterpolationStrategy::m_instance = 0;
-KisGradientSegment::SphereDecreasingInterpolationStrategy *KisGradientSegment::SphereDecreasingInterpolationStrategy::m_instance = 0;
-
-KisGradient::KisGradient(const TQString& file) : super(file)
-{
-}
-
-KisGradient::~KisGradient()
-{
- for (uint i = 0; i < m_segments.count(); i++) {
- delete m_segments[i];
- m_segments[i] = 0;
- }
-}
-
-bool KisGradient::load()
-{
- return init();
-}
-
-bool KisGradient::save()
-{
- return false;
-}
-
-TQImage KisGradient::img()
-{
- return m_img;
-}
-
-bool KisGradient::init()
-{
- KoGradientManager gradLoader;
- KoGradient* grad = gradLoader.loadGradient(filename());
-
- if( !grad )
- return false;
-
- m_segments.clear();
-
- if( grad->colorStops.count() > 1 ) {
- KoColorStop *colstop;
- for(colstop = grad->colorStops.first(); colstop; colstop = grad->colorStops.next()) {
- KoColorStop *colstopNext = grad->colorStops.next();
-
- if(colstopNext) {
- KoColor leftRgb((int)(colstop->color1 * 255 + 0.5), (int)(colstop->color2 * 255 + 0.5), (int)(colstop->color3 * 255 + 0.5));
- KoColor rightRgb((int)(colstopNext->color1 * 255 + 0.5), (int)(colstopNext->color2 * 255 + 0.5), (int)(colstopNext->color3 * 255 + 0.5));
-
- double midp = colstop->midpoint;
- midp = colstop->offset + ((colstopNext->offset - colstop->offset) * midp);
-
- Color leftColor(leftRgb.color(), colstop->opacity);
- Color rightColor(rightRgb.color(), colstopNext->opacity);
-
- KisGradientSegment *segment = new KisGradientSegment(colstop->interpolation, colstop->colorType, colstop->offset, midp, colstopNext->offset, leftColor, rightColor);
- TQ_CHECK_PTR(segment);
-
- if ( !segment->isValid() ) {
- delete segment;
- return false;
- }
-
- m_segments.push_back(segment);
- grad->colorStops.prev();
- }
- else {
- grad->colorStops.prev();
- break;
- }
- }
- }
- else
- return false;
-
- if (!m_segments.isEmpty()) {
- m_img = generatePreview(PREVIEW_WIDTH, PREVIEW_HEIGHT);
- setValid(true);
- return true;
- }
- else {
- return false;
- }
-}
-
-void KisGradient::setImage(const TQImage& img)
-{
- m_img = img;
- m_img.detach();
-
- setValid(true);
-}
-
-KisGradientSegment *KisGradient::segmentAt(double t) const
-{
- Q_ASSERT(t >= 0 || t <= 1);
- Q_ASSERT(!m_segments.empty());
-
- for(TQValueVector<KisGradientSegment *>::const_iterator it = m_segments.begin(); it!= m_segments.end(); ++it)
- {
- if (t > (*it)->startOffset() - DBL_EPSILON && t < (*it)->endOffset() + DBL_EPSILON) {
- return *it;
- }
- }
-
- return 0;
-}
-
-void KisGradient::colorAt(double t, TQColor *color, TQ_UINT8 *opacity) const
-{
- const KisGradientSegment *segment = segmentAt(t);
- Q_ASSERT(segment != 0);
-
- if (segment) {
- Color col = segment->colorAt(t);
- *color = col.color();
- *opacity = static_cast<TQ_UINT8>(col.alpha() * OPACITY_OPAQUE + 0.5);
- }
-}
-
-TQImage KisGradient::generatePreview(int width, int height) const
-{
- TQImage img(width, height, 32);
-
- for (int y = 0; y < img.height(); y++) {
- for (int x = 0; x < img.width(); x++) {
-
- int backgroundRed = 128 + 63 * ((x / 4 + y / 4) % 2);
- int backgroundGreen = backgroundRed;
- int backgroundBlue = backgroundRed;
-
- TQColor color;
- TQ_UINT8 opacity;
- double t = static_cast<double>(x) / (img.width() - 1);
-
- colorAt(t, &color, &opacity);
-
- double alpha = static_cast<double>(opacity) / OPACITY_OPAQUE;
-
- int red = static_cast<int>((1 - alpha) * backgroundRed + alpha * color.red() + 0.5);
- int green = static_cast<int>((1 - alpha) * backgroundGreen + alpha * color.green() + 0.5);
- int blue = static_cast<int>((1 - alpha) * backgroundBlue + alpha * color.blue() + 0.5);
-
- img.setPixel(x, y, tqRgb(red, green, blue));
- }
- }
-
- return img;
-}
-
-KisGradientSegment::KisGradientSegment(int interpolationType, int colorInterpolationType, double startOffset, double middleOffset, double endOffset, const Color& startColor, const Color& endColor)
-{
- m_interpolator = 0;
-
- switch (interpolationType) {
- case INTERP_LINEAR:
- m_interpolator = LinearInterpolationStrategy::instance();
- break;
- case INTERP_CURVED:
- m_interpolator = CurvedInterpolationStrategy::instance();
- break;
- case INTERP_SINE:
- m_interpolator = SineInterpolationStrategy::instance();
- break;
- case INTERP_SPHERE_INCREASING:
- m_interpolator = SphereIncreasingInterpolationStrategy::instance();
- break;
- case INTERP_SPHERE_DECREASING:
- m_interpolator = SphereDecreasingInterpolationStrategy::instance();
- break;
- }
-
- m_colorInterpolator = 0;
-
- switch (colorInterpolationType) {
- case COLOR_INTERP_RGB:
- m_colorInterpolator = RGBColorInterpolationStrategy::instance();
- break;
- case COLOR_INTERP_HSV_CCW:
- m_colorInterpolator = HSVCCWColorInterpolationStrategy::instance();
- break;
- case COLOR_INTERP_HSV_CW:
- m_colorInterpolator = HSVCWColorInterpolationStrategy::instance();
- break;
- }
-
- if (startOffset < DBL_EPSILON) {
- m_startOffset = 0;
- }
- else
- if (startOffset > 1 - DBL_EPSILON) {
- m_startOffset = 1;
- }
- else {
- m_startOffset = startOffset;
- }
-
- if (middleOffset < m_startOffset + DBL_EPSILON) {
- m_middleOffset = m_startOffset;
- }
- else
- if (middleOffset > 1 - DBL_EPSILON) {
- m_middleOffset = 1;
- }
- else {
- m_middleOffset = middleOffset;
- }
-
- if (endOffset < m_middleOffset + DBL_EPSILON) {
- m_endOffset = m_middleOffset;
- }
- else
- if (endOffset > 1 - DBL_EPSILON) {
- m_endOffset = 1;
- }
- else {
- m_endOffset = endOffset;
- }
-
- m_length = m_endOffset - m_startOffset;
-
- if (m_length < DBL_EPSILON) {
- m_middleT = 0.5;
- }
- else {
- m_middleT = (m_middleOffset - m_startOffset) / m_length;
- }
-
- m_startColor = startColor;
- m_endColor = endColor;
-}
-
-const Color& KisGradientSegment::startColor() const
-{
- return m_startColor;
-}
-
-const Color& KisGradientSegment::endColor() const
-{
- return m_endColor;
-}
-
-double KisGradientSegment::startOffset() const
-{
- return m_startOffset;
-}
-
-double KisGradientSegment::middleOffset() const
-{
- return m_middleOffset;
-}
-
-double KisGradientSegment::endOffset() const
-{
- return m_endOffset;
-}
-
-void KisGradientSegment::setStartOffset(double t)
-{
- m_startOffset = t;
- m_length = m_endOffset - m_startOffset;
-
- if (m_length < DBL_EPSILON) {
- m_middleT = 0.5;
- }
- else {
- m_middleT = (m_middleOffset - m_startOffset) / m_length;
- }
-}
-void KisGradientSegment::setMiddleOffset(double t)
-{
- m_middleOffset = t;
-
- if (m_length < DBL_EPSILON) {
- m_middleT = 0.5;
- }
- else {
- m_middleT = (m_middleOffset - m_startOffset) / m_length;
- }
-}
-
-void KisGradientSegment::setEndOffset(double t)
-{
- m_endOffset = t;
- m_length = m_endOffset - m_startOffset;
-
- if (m_length < DBL_EPSILON) {
- m_middleT = 0.5;
- }
- else {
- m_middleT = (m_middleOffset - m_startOffset) / m_length;
- }
-}
-
-int KisGradientSegment::interpolation() const
-{
- return m_interpolator->type();
-}
-
-void KisGradientSegment::setInterpolation(int interpolationType)
-{
- switch (interpolationType) {
- case INTERP_LINEAR:
- m_interpolator = LinearInterpolationStrategy::instance();
- break;
- case INTERP_CURVED:
- m_interpolator = CurvedInterpolationStrategy::instance();
- break;
- case INTERP_SINE:
- m_interpolator = SineInterpolationStrategy::instance();
- break;
- case INTERP_SPHERE_INCREASING:
- m_interpolator = SphereIncreasingInterpolationStrategy::instance();
- break;
- case INTERP_SPHERE_DECREASING:
- m_interpolator = SphereDecreasingInterpolationStrategy::instance();
- break;
- }
-}
-
-int KisGradientSegment::colorInterpolation() const
-{
- return m_colorInterpolator->type();
-}
-
-void KisGradientSegment::setColorInterpolation(int colorInterpolationType)
-{
- switch (colorInterpolationType) {
- case COLOR_INTERP_RGB:
- m_colorInterpolator = RGBColorInterpolationStrategy::instance();
- break;
- case COLOR_INTERP_HSV_CCW:
- m_colorInterpolator = HSVCCWColorInterpolationStrategy::instance();
- break;
- case COLOR_INTERP_HSV_CW:
- m_colorInterpolator = HSVCWColorInterpolationStrategy::instance();
- break;
- }
-}
-
-Color KisGradientSegment::colorAt(double t) const
-{
- Q_ASSERT(t > m_startOffset - DBL_EPSILON && t < m_endOffset + DBL_EPSILON);
-
- double segmentT;
-
- if (m_length < DBL_EPSILON) {
- segmentT = 0.5;
- }
- else {
- segmentT = (t - m_startOffset) / m_length;
- }
-
- double colorT = m_interpolator->valueAt(segmentT, m_middleT);
-
- Color color = m_colorInterpolator->colorAt(colorT, m_startColor, m_endColor);
-
- return color;
-}
-
-bool KisGradientSegment::isValid() const
-{
- if (m_interpolator == 0 || m_colorInterpolator ==0)
- return false;
- return true;
-}
-
-KisGradientSegment::RGBColorInterpolationStrategy *KisGradientSegment::RGBColorInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new RGBColorInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-Color KisGradientSegment::RGBColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
-{
- int startRed = start.color().red();
- int startGreen = start.color().green();
- int startBlue = start.color().blue();
- double startAlpha = start.alpha();
- int red = static_cast<int>(startRed + t * (end.color().red() - startRed) + 0.5);
- int green = static_cast<int>(startGreen + t * (end.color().green() - startGreen) + 0.5);
- int blue = static_cast<int>(startBlue + t * (end.color().blue() - startBlue) + 0.5);
- double alpha = startAlpha + t * (end.alpha() - startAlpha);
-
- return Color(TQColor(red, green, blue), alpha);
-}
-
-KisGradientSegment::HSVCWColorInterpolationStrategy *KisGradientSegment::HSVCWColorInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new HSVCWColorInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-Color KisGradientSegment::HSVCWColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
-{
- KoColor sc = KoColor(start.color());
- KoColor ec = KoColor(end.color());
-
- int s = static_cast<int>(sc.S() + t * (ec.S() - sc.S()) + 0.5);
- int v = static_cast<int>(sc.V() + t * (ec.V() - sc.V()) + 0.5);
- int h;
-
- if (ec.H() < sc.H()) {
- h = static_cast<int>(ec.H() + (1 - t) * (sc.H() - ec.H()) + 0.5);
- }
- else {
- h = static_cast<int>(ec.H() + (1 - t) * (360 - ec.H() + sc.H()) + 0.5);
-
- if (h > 359) {
- h -= 360;
- }
- }
-
- double alpha = start.alpha() + t * (end.alpha() - start.alpha());
-
- return Color(KoColor(h, s, v, KoColor::csHSV).color(), alpha);
-}
-
-KisGradientSegment::HSVCCWColorInterpolationStrategy *KisGradientSegment::HSVCCWColorInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new HSVCCWColorInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-Color KisGradientSegment::HSVCCWColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
-{
- KoColor sc = KoColor(start.color());
- KoColor se = KoColor(end.color());
-
- int s = static_cast<int>(sc.S() + t * (se.S() - sc.S()) + 0.5);
- int v = static_cast<int>(sc.V() + t * (se.V() - sc.V()) + 0.5);
- int h;
-
- if (sc.H() < se.H()) {
- h = static_cast<int>(sc.H() + t * (se.H() - sc.H()) + 0.5);
- }
- else {
- h = static_cast<int>(sc.H() + t * (360 - sc.H() + se.H()) + 0.5);
-
- if (h > 359) {
- h -= 360;
- }
- }
-
- double alpha = start.alpha() + t * (end.alpha() - start.alpha());
-
- return Color(KoColor(h, s, v, KoColor::csHSV).color(), alpha);
-}
-
-KisGradientSegment::LinearInterpolationStrategy *KisGradientSegment::LinearInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new LinearInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-double KisGradientSegment::LinearInterpolationStrategy::calcValueAt(double t, double middle)
-{
- Q_ASSERT(t > -DBL_EPSILON && t < 1 + DBL_EPSILON);
- Q_ASSERT(middle > -DBL_EPSILON && middle < 1 + DBL_EPSILON);
-
- double value = 0;
-
- if (t <= middle) {
- if (middle < DBL_EPSILON) {
- value = 0;
- }
- else {
- value = (t / middle) * 0.5;
- }
- }
- else {
- if (middle > 1 - DBL_EPSILON) {
- value = 1;
- }
- else {
- value = ((t - middle) / (1 - middle)) * 0.5 + 0.5;
- }
- }
-
- return value;
-}
-
-double KisGradientSegment::LinearInterpolationStrategy::valueAt(double t, double middle) const
-{
- return calcValueAt(t, middle);
-}
-
-KisGradientSegment::CurvedInterpolationStrategy::CurvedInterpolationStrategy()
-{
- m_logHalf = log(0.5);
-}
-
-KisGradientSegment::CurvedInterpolationStrategy *KisGradientSegment::CurvedInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new CurvedInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-double KisGradientSegment::CurvedInterpolationStrategy::valueAt(double t, double middle) const
-{
- Q_ASSERT(t > -DBL_EPSILON && t < 1 + DBL_EPSILON);
- Q_ASSERT(middle > -DBL_EPSILON && middle < 1 + DBL_EPSILON);
-
- double value = 0;
-
- if (middle < DBL_EPSILON) {
- middle = DBL_EPSILON;
- }
-
- value = pow(t, m_logHalf / log(middle));
-
- return value;
-}
-
-KisGradientSegment::SineInterpolationStrategy *KisGradientSegment::SineInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new SineInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-double KisGradientSegment::SineInterpolationStrategy::valueAt(double t, double middle) const
-{
- double lt = LinearInterpolationStrategy::calcValueAt(t, middle);
- double value = (sin(-M_PI_2 + M_PI * lt) + 1.0) / 2.0;
-
- return value;
-}
-
-KisGradientSegment::SphereIncreasingInterpolationStrategy *KisGradientSegment::SphereIncreasingInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new SphereIncreasingInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-double KisGradientSegment::SphereIncreasingInterpolationStrategy::valueAt(double t, double middle) const
-{
- double lt = LinearInterpolationStrategy::calcValueAt(t, middle) - 1;
- double value = sqrt(1 - lt * lt);
-
- return value;
-}
-
-KisGradientSegment::SphereDecreasingInterpolationStrategy *KisGradientSegment::SphereDecreasingInterpolationStrategy::instance()
-{
- if (m_instance == 0) {
- m_instance = new SphereDecreasingInterpolationStrategy();
- TQ_CHECK_PTR(m_instance);
- }
-
- return m_instance;
-}
-
-double KisGradientSegment::SphereDecreasingInterpolationStrategy::valueAt(double t, double middle) const
-{
- double lt = LinearInterpolationStrategy::calcValueAt(t, middle);
- double value = 1 - sqrt(1 - lt * lt);
-
- return value;
-}
-
-#include "kis_gradient.moc"
-
diff --git a/chalk/core/kis_gradient.cpp b/chalk/core/kis_gradient.cpp
new file mode 100644
index 000000000..9b240cb06
--- /dev/null
+++ b/chalk/core/kis_gradient.cpp
@@ -0,0 +1,639 @@
+/*
+ * kis_gradient.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 Matthias Elter <elter@kde.org>
+ * 2001 John Califf
+ * 2004 Boudewijn Rempt <boud@valdyas.org>
+ * 2004 Adrian Page <adrian@pagenet.plus.com>
+ * 2004 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <cfloat>
+#include <cmath>
+
+#include <tqimage.h>
+#include <tqtextstream.h>
+#include <tqfile.h>
+
+#include <koColor.h>
+#include <kogradientmanager.h>
+
+#include <kdebug.h>
+#include <tdelocale.h>
+
+#include "kis_gradient.h"
+
+#define PREVIEW_WIDTH 64
+#define PREVIEW_HEIGHT 64
+
+KisGradientSegment::RGBColorInterpolationStrategy *KisGradientSegment::RGBColorInterpolationStrategy::m_instance = 0;
+KisGradientSegment::HSVCWColorInterpolationStrategy *KisGradientSegment::HSVCWColorInterpolationStrategy::m_instance = 0;
+KisGradientSegment::HSVCCWColorInterpolationStrategy *KisGradientSegment::HSVCCWColorInterpolationStrategy::m_instance = 0;
+
+KisGradientSegment::LinearInterpolationStrategy *KisGradientSegment::LinearInterpolationStrategy::m_instance = 0;
+KisGradientSegment::CurvedInterpolationStrategy *KisGradientSegment::CurvedInterpolationStrategy::m_instance = 0;
+KisGradientSegment::SineInterpolationStrategy *KisGradientSegment::SineInterpolationStrategy::m_instance = 0;
+KisGradientSegment::SphereIncreasingInterpolationStrategy *KisGradientSegment::SphereIncreasingInterpolationStrategy::m_instance = 0;
+KisGradientSegment::SphereDecreasingInterpolationStrategy *KisGradientSegment::SphereDecreasingInterpolationStrategy::m_instance = 0;
+
+KisGradient::KisGradient(const TQString& file) : super(file)
+{
+}
+
+KisGradient::~KisGradient()
+{
+ for (uint i = 0; i < m_segments.count(); i++) {
+ delete m_segments[i];
+ m_segments[i] = 0;
+ }
+}
+
+bool KisGradient::load()
+{
+ return init();
+}
+
+bool KisGradient::save()
+{
+ return false;
+}
+
+TQImage KisGradient::img()
+{
+ return m_img;
+}
+
+bool KisGradient::init()
+{
+ KoGradientManager gradLoader;
+ KoGradient* grad = gradLoader.loadGradient(filename());
+
+ if( !grad )
+ return false;
+
+ m_segments.clear();
+
+ if( grad->colorStops.count() > 1 ) {
+ KoColorStop *colstop;
+ for(colstop = grad->colorStops.first(); colstop; colstop = grad->colorStops.next()) {
+ KoColorStop *colstopNext = grad->colorStops.next();
+
+ if(colstopNext) {
+ KoColor leftRgb((int)(colstop->color1 * 255 + 0.5), (int)(colstop->color2 * 255 + 0.5), (int)(colstop->color3 * 255 + 0.5));
+ KoColor rightRgb((int)(colstopNext->color1 * 255 + 0.5), (int)(colstopNext->color2 * 255 + 0.5), (int)(colstopNext->color3 * 255 + 0.5));
+
+ double midp = colstop->midpoint;
+ midp = colstop->offset + ((colstopNext->offset - colstop->offset) * midp);
+
+ Color leftColor(leftRgb.color(), colstop->opacity);
+ Color rightColor(rightRgb.color(), colstopNext->opacity);
+
+ KisGradientSegment *segment = new KisGradientSegment(colstop->interpolation, colstop->colorType, colstop->offset, midp, colstopNext->offset, leftColor, rightColor);
+ TQ_CHECK_PTR(segment);
+
+ if ( !segment->isValid() ) {
+ delete segment;
+ return false;
+ }
+
+ m_segments.push_back(segment);
+ grad->colorStops.prev();
+ }
+ else {
+ grad->colorStops.prev();
+ break;
+ }
+ }
+ }
+ else
+ return false;
+
+ if (!m_segments.isEmpty()) {
+ m_img = generatePreview(PREVIEW_WIDTH, PREVIEW_HEIGHT);
+ setValid(true);
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+void KisGradient::setImage(const TQImage& img)
+{
+ m_img = img;
+ m_img.detach();
+
+ setValid(true);
+}
+
+KisGradientSegment *KisGradient::segmentAt(double t) const
+{
+ Q_ASSERT(t >= 0 || t <= 1);
+ Q_ASSERT(!m_segments.empty());
+
+ for(TQValueVector<KisGradientSegment *>::const_iterator it = m_segments.begin(); it!= m_segments.end(); ++it)
+ {
+ if (t > (*it)->startOffset() - DBL_EPSILON && t < (*it)->endOffset() + DBL_EPSILON) {
+ return *it;
+ }
+ }
+
+ return 0;
+}
+
+void KisGradient::colorAt(double t, TQColor *color, TQ_UINT8 *opacity) const
+{
+ const KisGradientSegment *segment = segmentAt(t);
+ Q_ASSERT(segment != 0);
+
+ if (segment) {
+ Color col = segment->colorAt(t);
+ *color = col.color();
+ *opacity = static_cast<TQ_UINT8>(col.alpha() * OPACITY_OPAQUE + 0.5);
+ }
+}
+
+TQImage KisGradient::generatePreview(int width, int height) const
+{
+ TQImage img(width, height, 32);
+
+ for (int y = 0; y < img.height(); y++) {
+ for (int x = 0; x < img.width(); x++) {
+
+ int backgroundRed = 128 + 63 * ((x / 4 + y / 4) % 2);
+ int backgroundGreen = backgroundRed;
+ int backgroundBlue = backgroundRed;
+
+ TQColor color;
+ TQ_UINT8 opacity;
+ double t = static_cast<double>(x) / (img.width() - 1);
+
+ colorAt(t, &color, &opacity);
+
+ double alpha = static_cast<double>(opacity) / OPACITY_OPAQUE;
+
+ int red = static_cast<int>((1 - alpha) * backgroundRed + alpha * color.red() + 0.5);
+ int green = static_cast<int>((1 - alpha) * backgroundGreen + alpha * color.green() + 0.5);
+ int blue = static_cast<int>((1 - alpha) * backgroundBlue + alpha * color.blue() + 0.5);
+
+ img.setPixel(x, y, tqRgb(red, green, blue));
+ }
+ }
+
+ return img;
+}
+
+KisGradientSegment::KisGradientSegment(int interpolationType, int colorInterpolationType, double startOffset, double middleOffset, double endOffset, const Color& startColor, const Color& endColor)
+{
+ m_interpolator = 0;
+
+ switch (interpolationType) {
+ case INTERP_LINEAR:
+ m_interpolator = LinearInterpolationStrategy::instance();
+ break;
+ case INTERP_CURVED:
+ m_interpolator = CurvedInterpolationStrategy::instance();
+ break;
+ case INTERP_SINE:
+ m_interpolator = SineInterpolationStrategy::instance();
+ break;
+ case INTERP_SPHERE_INCREASING:
+ m_interpolator = SphereIncreasingInterpolationStrategy::instance();
+ break;
+ case INTERP_SPHERE_DECREASING:
+ m_interpolator = SphereDecreasingInterpolationStrategy::instance();
+ break;
+ }
+
+ m_colorInterpolator = 0;
+
+ switch (colorInterpolationType) {
+ case COLOR_INTERP_RGB:
+ m_colorInterpolator = RGBColorInterpolationStrategy::instance();
+ break;
+ case COLOR_INTERP_HSV_CCW:
+ m_colorInterpolator = HSVCCWColorInterpolationStrategy::instance();
+ break;
+ case COLOR_INTERP_HSV_CW:
+ m_colorInterpolator = HSVCWColorInterpolationStrategy::instance();
+ break;
+ }
+
+ if (startOffset < DBL_EPSILON) {
+ m_startOffset = 0;
+ }
+ else
+ if (startOffset > 1 - DBL_EPSILON) {
+ m_startOffset = 1;
+ }
+ else {
+ m_startOffset = startOffset;
+ }
+
+ if (middleOffset < m_startOffset + DBL_EPSILON) {
+ m_middleOffset = m_startOffset;
+ }
+ else
+ if (middleOffset > 1 - DBL_EPSILON) {
+ m_middleOffset = 1;
+ }
+ else {
+ m_middleOffset = middleOffset;
+ }
+
+ if (endOffset < m_middleOffset + DBL_EPSILON) {
+ m_endOffset = m_middleOffset;
+ }
+ else
+ if (endOffset > 1 - DBL_EPSILON) {
+ m_endOffset = 1;
+ }
+ else {
+ m_endOffset = endOffset;
+ }
+
+ m_length = m_endOffset - m_startOffset;
+
+ if (m_length < DBL_EPSILON) {
+ m_middleT = 0.5;
+ }
+ else {
+ m_middleT = (m_middleOffset - m_startOffset) / m_length;
+ }
+
+ m_startColor = startColor;
+ m_endColor = endColor;
+}
+
+const Color& KisGradientSegment::startColor() const
+{
+ return m_startColor;
+}
+
+const Color& KisGradientSegment::endColor() const
+{
+ return m_endColor;
+}
+
+double KisGradientSegment::startOffset() const
+{
+ return m_startOffset;
+}
+
+double KisGradientSegment::middleOffset() const
+{
+ return m_middleOffset;
+}
+
+double KisGradientSegment::endOffset() const
+{
+ return m_endOffset;
+}
+
+void KisGradientSegment::setStartOffset(double t)
+{
+ m_startOffset = t;
+ m_length = m_endOffset - m_startOffset;
+
+ if (m_length < DBL_EPSILON) {
+ m_middleT = 0.5;
+ }
+ else {
+ m_middleT = (m_middleOffset - m_startOffset) / m_length;
+ }
+}
+void KisGradientSegment::setMiddleOffset(double t)
+{
+ m_middleOffset = t;
+
+ if (m_length < DBL_EPSILON) {
+ m_middleT = 0.5;
+ }
+ else {
+ m_middleT = (m_middleOffset - m_startOffset) / m_length;
+ }
+}
+
+void KisGradientSegment::setEndOffset(double t)
+{
+ m_endOffset = t;
+ m_length = m_endOffset - m_startOffset;
+
+ if (m_length < DBL_EPSILON) {
+ m_middleT = 0.5;
+ }
+ else {
+ m_middleT = (m_middleOffset - m_startOffset) / m_length;
+ }
+}
+
+int KisGradientSegment::interpolation() const
+{
+ return m_interpolator->type();
+}
+
+void KisGradientSegment::setInterpolation(int interpolationType)
+{
+ switch (interpolationType) {
+ case INTERP_LINEAR:
+ m_interpolator = LinearInterpolationStrategy::instance();
+ break;
+ case INTERP_CURVED:
+ m_interpolator = CurvedInterpolationStrategy::instance();
+ break;
+ case INTERP_SINE:
+ m_interpolator = SineInterpolationStrategy::instance();
+ break;
+ case INTERP_SPHERE_INCREASING:
+ m_interpolator = SphereIncreasingInterpolationStrategy::instance();
+ break;
+ case INTERP_SPHERE_DECREASING:
+ m_interpolator = SphereDecreasingInterpolationStrategy::instance();
+ break;
+ }
+}
+
+int KisGradientSegment::colorInterpolation() const
+{
+ return m_colorInterpolator->type();
+}
+
+void KisGradientSegment::setColorInterpolation(int colorInterpolationType)
+{
+ switch (colorInterpolationType) {
+ case COLOR_INTERP_RGB:
+ m_colorInterpolator = RGBColorInterpolationStrategy::instance();
+ break;
+ case COLOR_INTERP_HSV_CCW:
+ m_colorInterpolator = HSVCCWColorInterpolationStrategy::instance();
+ break;
+ case COLOR_INTERP_HSV_CW:
+ m_colorInterpolator = HSVCWColorInterpolationStrategy::instance();
+ break;
+ }
+}
+
+Color KisGradientSegment::colorAt(double t) const
+{
+ Q_ASSERT(t > m_startOffset - DBL_EPSILON && t < m_endOffset + DBL_EPSILON);
+
+ double segmentT;
+
+ if (m_length < DBL_EPSILON) {
+ segmentT = 0.5;
+ }
+ else {
+ segmentT = (t - m_startOffset) / m_length;
+ }
+
+ double colorT = m_interpolator->valueAt(segmentT, m_middleT);
+
+ Color color = m_colorInterpolator->colorAt(colorT, m_startColor, m_endColor);
+
+ return color;
+}
+
+bool KisGradientSegment::isValid() const
+{
+ if (m_interpolator == 0 || m_colorInterpolator ==0)
+ return false;
+ return true;
+}
+
+KisGradientSegment::RGBColorInterpolationStrategy *KisGradientSegment::RGBColorInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new RGBColorInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+Color KisGradientSegment::RGBColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
+{
+ int startRed = start.color().red();
+ int startGreen = start.color().green();
+ int startBlue = start.color().blue();
+ double startAlpha = start.alpha();
+ int red = static_cast<int>(startRed + t * (end.color().red() - startRed) + 0.5);
+ int green = static_cast<int>(startGreen + t * (end.color().green() - startGreen) + 0.5);
+ int blue = static_cast<int>(startBlue + t * (end.color().blue() - startBlue) + 0.5);
+ double alpha = startAlpha + t * (end.alpha() - startAlpha);
+
+ return Color(TQColor(red, green, blue), alpha);
+}
+
+KisGradientSegment::HSVCWColorInterpolationStrategy *KisGradientSegment::HSVCWColorInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new HSVCWColorInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+Color KisGradientSegment::HSVCWColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
+{
+ KoColor sc = KoColor(start.color());
+ KoColor ec = KoColor(end.color());
+
+ int s = static_cast<int>(sc.S() + t * (ec.S() - sc.S()) + 0.5);
+ int v = static_cast<int>(sc.V() + t * (ec.V() - sc.V()) + 0.5);
+ int h;
+
+ if (ec.H() < sc.H()) {
+ h = static_cast<int>(ec.H() + (1 - t) * (sc.H() - ec.H()) + 0.5);
+ }
+ else {
+ h = static_cast<int>(ec.H() + (1 - t) * (360 - ec.H() + sc.H()) + 0.5);
+
+ if (h > 359) {
+ h -= 360;
+ }
+ }
+
+ double alpha = start.alpha() + t * (end.alpha() - start.alpha());
+
+ return Color(KoColor(h, s, v, KoColor::csHSV).color(), alpha);
+}
+
+KisGradientSegment::HSVCCWColorInterpolationStrategy *KisGradientSegment::HSVCCWColorInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new HSVCCWColorInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+Color KisGradientSegment::HSVCCWColorInterpolationStrategy::colorAt(double t, Color start, Color end) const
+{
+ KoColor sc = KoColor(start.color());
+ KoColor se = KoColor(end.color());
+
+ int s = static_cast<int>(sc.S() + t * (se.S() - sc.S()) + 0.5);
+ int v = static_cast<int>(sc.V() + t * (se.V() - sc.V()) + 0.5);
+ int h;
+
+ if (sc.H() < se.H()) {
+ h = static_cast<int>(sc.H() + t * (se.H() - sc.H()) + 0.5);
+ }
+ else {
+ h = static_cast<int>(sc.H() + t * (360 - sc.H() + se.H()) + 0.5);
+
+ if (h > 359) {
+ h -= 360;
+ }
+ }
+
+ double alpha = start.alpha() + t * (end.alpha() - start.alpha());
+
+ return Color(KoColor(h, s, v, KoColor::csHSV).color(), alpha);
+}
+
+KisGradientSegment::LinearInterpolationStrategy *KisGradientSegment::LinearInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new LinearInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+double KisGradientSegment::LinearInterpolationStrategy::calcValueAt(double t, double middle)
+{
+ Q_ASSERT(t > -DBL_EPSILON && t < 1 + DBL_EPSILON);
+ Q_ASSERT(middle > -DBL_EPSILON && middle < 1 + DBL_EPSILON);
+
+ double value = 0;
+
+ if (t <= middle) {
+ if (middle < DBL_EPSILON) {
+ value = 0;
+ }
+ else {
+ value = (t / middle) * 0.5;
+ }
+ }
+ else {
+ if (middle > 1 - DBL_EPSILON) {
+ value = 1;
+ }
+ else {
+ value = ((t - middle) / (1 - middle)) * 0.5 + 0.5;
+ }
+ }
+
+ return value;
+}
+
+double KisGradientSegment::LinearInterpolationStrategy::valueAt(double t, double middle) const
+{
+ return calcValueAt(t, middle);
+}
+
+KisGradientSegment::CurvedInterpolationStrategy::CurvedInterpolationStrategy()
+{
+ m_logHalf = log(0.5);
+}
+
+KisGradientSegment::CurvedInterpolationStrategy *KisGradientSegment::CurvedInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new CurvedInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+double KisGradientSegment::CurvedInterpolationStrategy::valueAt(double t, double middle) const
+{
+ Q_ASSERT(t > -DBL_EPSILON && t < 1 + DBL_EPSILON);
+ Q_ASSERT(middle > -DBL_EPSILON && middle < 1 + DBL_EPSILON);
+
+ double value = 0;
+
+ if (middle < DBL_EPSILON) {
+ middle = DBL_EPSILON;
+ }
+
+ value = pow(t, m_logHalf / log(middle));
+
+ return value;
+}
+
+KisGradientSegment::SineInterpolationStrategy *KisGradientSegment::SineInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new SineInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+double KisGradientSegment::SineInterpolationStrategy::valueAt(double t, double middle) const
+{
+ double lt = LinearInterpolationStrategy::calcValueAt(t, middle);
+ double value = (sin(-M_PI_2 + M_PI * lt) + 1.0) / 2.0;
+
+ return value;
+}
+
+KisGradientSegment::SphereIncreasingInterpolationStrategy *KisGradientSegment::SphereIncreasingInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new SphereIncreasingInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+double KisGradientSegment::SphereIncreasingInterpolationStrategy::valueAt(double t, double middle) const
+{
+ double lt = LinearInterpolationStrategy::calcValueAt(t, middle) - 1;
+ double value = sqrt(1 - lt * lt);
+
+ return value;
+}
+
+KisGradientSegment::SphereDecreasingInterpolationStrategy *KisGradientSegment::SphereDecreasingInterpolationStrategy::instance()
+{
+ if (m_instance == 0) {
+ m_instance = new SphereDecreasingInterpolationStrategy();
+ TQ_CHECK_PTR(m_instance);
+ }
+
+ return m_instance;
+}
+
+double KisGradientSegment::SphereDecreasingInterpolationStrategy::valueAt(double t, double middle) const
+{
+ double lt = LinearInterpolationStrategy::calcValueAt(t, middle);
+ double value = 1 - sqrt(1 - lt * lt);
+
+ return value;
+}
+
+#include "kis_gradient.moc"
+
diff --git a/chalk/core/kis_gradient_painter.cc b/chalk/core/kis_gradient_painter.cpp
index 7c2b00b18..7c2b00b18 100644
--- a/chalk/core/kis_gradient_painter.cc
+++ b/chalk/core/kis_gradient_painter.cpp
diff --git a/chalk/core/kis_group_layer.cc b/chalk/core/kis_group_layer.cpp
index 290d19f5c..290d19f5c 100644
--- a/chalk/core/kis_group_layer.cc
+++ b/chalk/core/kis_group_layer.cpp
diff --git a/chalk/core/kis_histogram.cc b/chalk/core/kis_histogram.cpp
index bece7c9a3..bece7c9a3 100644
--- a/chalk/core/kis_histogram.cc
+++ b/chalk/core/kis_histogram.cpp
diff --git a/chalk/core/kis_image.cc b/chalk/core/kis_image.cpp
index 1180bf4cf..1180bf4cf 100644
--- a/chalk/core/kis_image.cc
+++ b/chalk/core/kis_image.cpp
diff --git a/chalk/core/kis_image_iface.cc b/chalk/core/kis_image_iface.cpp
index 2cc16e27e..2cc16e27e 100644
--- a/chalk/core/kis_image_iface.cc
+++ b/chalk/core/kis_image_iface.cpp
diff --git a/chalk/core/kis_imagepipe_brush.cc b/chalk/core/kis_imagepipe_brush.cpp
index 5c60b5174..5c60b5174 100644
--- a/chalk/core/kis_imagepipe_brush.cc
+++ b/chalk/core/kis_imagepipe_brush.cpp
diff --git a/chalk/core/kis_iterator.cc b/chalk/core/kis_iterator.cpp
index 0e0c2d813..0e0c2d813 100644
--- a/chalk/core/kis_iterator.cc
+++ b/chalk/core/kis_iterator.cpp
diff --git a/chalk/core/kis_iterators_pixel.cc b/chalk/core/kis_iterators_pixel.cpp
index 741a20b00..741a20b00 100644
--- a/chalk/core/kis_iterators_pixel.cc
+++ b/chalk/core/kis_iterators_pixel.cpp
diff --git a/chalk/core/kis_layer.cc b/chalk/core/kis_layer.cpp
index f43570f08..f43570f08 100644
--- a/chalk/core/kis_layer.cc
+++ b/chalk/core/kis_layer.cpp
diff --git a/chalk/core/kis_meta_registry.cc b/chalk/core/kis_meta_registry.cpp
index 4bde87b22..4bde87b22 100644
--- a/chalk/core/kis_meta_registry.cc
+++ b/chalk/core/kis_meta_registry.cpp
diff --git a/chalk/core/kis_nameserver.cc b/chalk/core/kis_nameserver.cpp
index 4cb51a989..4cb51a989 100644
--- a/chalk/core/kis_nameserver.cc
+++ b/chalk/core/kis_nameserver.cpp
diff --git a/chalk/core/kis_paint_device.cc b/chalk/core/kis_paint_device.cpp
index da25caecb..da25caecb 100644
--- a/chalk/core/kis_paint_device.cc
+++ b/chalk/core/kis_paint_device.cpp
diff --git a/chalk/core/kis_paint_device_iface.cc b/chalk/core/kis_paint_device_iface.cpp
index c8afa80a3..c8afa80a3 100644
--- a/chalk/core/kis_paint_device_iface.cc
+++ b/chalk/core/kis_paint_device_iface.cpp
diff --git a/chalk/core/kis_paint_layer.cc b/chalk/core/kis_paint_layer.cpp
index a4c5412d5..a4c5412d5 100644
--- a/chalk/core/kis_paint_layer.cc
+++ b/chalk/core/kis_paint_layer.cpp
diff --git a/chalk/core/kis_painter.cc b/chalk/core/kis_painter.cpp
index f3f5c9286..f3f5c9286 100644
--- a/chalk/core/kis_painter.cc
+++ b/chalk/core/kis_painter.cpp
diff --git a/chalk/core/kis_paintop.cc b/chalk/core/kis_paintop.cpp
index 59cfef6b2..59cfef6b2 100644
--- a/chalk/core/kis_paintop.cc
+++ b/chalk/core/kis_paintop.cpp
diff --git a/chalk/core/kis_paintop_registry.cc b/chalk/core/kis_paintop_registry.cpp
index d549c3ad5..d549c3ad5 100644
--- a/chalk/core/kis_paintop_registry.cc
+++ b/chalk/core/kis_paintop_registry.cpp
diff --git a/chalk/core/kis_palette.cc b/chalk/core/kis_palette.cpp
index aa62b07a0..aa62b07a0 100644
--- a/chalk/core/kis_palette.cc
+++ b/chalk/core/kis_palette.cpp
diff --git a/chalk/core/kis_pattern.cc b/chalk/core/kis_pattern.cc
deleted file mode 100644
index 654449b80..000000000
--- a/chalk/core/kis_pattern.cc
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * kis_pattern.cc - part of Krayon
- *
- * Copyright (c) 2000 Matthias Elter <elter@kde.org>
- * 2001 John Califf
- * 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include "kis_pattern.h"
-
-#include <sys/types.h>
-#include <netinet/in.h>
-
-#include <limits.h>
-#include <stdlib.h>
-
-#include <tqpoint.h>
-#include <tqsize.h>
-#include <tqimage.h>
-#include <tqvaluevector.h>
-#include <tqmap.h>
-#include <tqfile.h>
-
-#include <kdebug.h>
-#include <tdelocale.h>
-
-#include "kis_color.h"
-#include "kis_layer.h"
-#include "kis_paint_device.h"
-
-namespace {
- struct GimpPatternHeader {
- TQ_UINT32 header_size; /* header_size = sizeof (PatternHeader) + brush name */
- TQ_UINT32 version; /* pattern file version # */
- TQ_UINT32 width; /* width of pattern */
- TQ_UINT32 height; /* height of pattern */
- TQ_UINT32 bytes; /* depth of pattern in bytes : 1, 2, 3 or 4*/
- TQ_UINT32 magic_number; /* GIMP brush magic number */
- };
-
- // Yes! This is _NOT_ what my pat.txt file says. It's really not 'GIMP', but 'GPAT'
- TQ_UINT32 const GimpPatternMagic = (('G' << 24) + ('P' << 16) + ('A' << 8) + ('T' << 0));
-}
-
-KisPattern::KisPattern(const TQString& file) : super(file), m_hasFile(true)
-{
-}
-
-KisPattern::KisPattern(KisPaintDevice* image, int x, int y, int w, int h)
- : super(""), m_hasFile(false)
-{
- // Forcefully convert to RGBA8
- // XXX profile and exposure?
- setImage(image->convertToTQImage(0, x, y, w, h));
- setName(image->name());
-}
-
-KisPattern::~KisPattern()
-{
-}
-
-bool KisPattern::load()
-{
- if (!m_hasFile)
- return true;
-
- TQFile file(filename());
- file.open(IO_ReadOnly);
- TQByteArray data = file.readAll();
- if (!data.isEmpty()) {
- TQ_INT32 startPos = m_data.size();
-
- m_data.resize(m_data.size() + data.count());
- memcpy(&m_data[startPos], data.data(), data.count());
- }
- file.close();
- return init();
-}
-
-bool KisPattern::save()
-{
- TQFile file(filename());
- file.open(IO_WriteOnly | IO_Truncate);
-
- TQTextStream stream(&file);
- // Header: header_size (24+name length),version,width,height,colourdepth of brush,magic,name
- // depth: 1 = greyscale, 2 = greyscale + A, 3 = RGB, 4 = RGBA
- // magic = "GPAT", as a single uint32, the docs are wrong here!
- // name is UTF-8 (\0-terminated! The docs say nothing about this!)
- // _All_ data in network order, it seems! (not mentioned in gimp-2.2.8/devel-docs/pat.txt!!)
- // We only save RGBA at the moment
- // Version is 1 for now...
-
- GimpPatternHeader ph;
- TQCString utf8Name = name().utf8();
- char const* name = utf8Name.data();
- int nameLength = tqstrlen(name);
-
- ph.header_size = htonl(sizeof(GimpPatternHeader) + nameLength + 1); // trailing 0
- ph.version = htonl(1);
- ph.width = htonl(width());
- ph.height = htonl(height());
- ph.bytes = htonl(4);
- ph.magic_number = htonl(GimpPatternMagic);
-
- TQByteArray bytes;
- bytes.setRawData(reinterpret_cast<char*>(&ph), sizeof(GimpPatternHeader));
- int wrote = file.writeBlock(bytes);
- bytes.resetRawData(reinterpret_cast<char*>(&ph), sizeof(GimpPatternHeader));
-
- if (wrote == -1)
- return false;
-
- wrote = file.writeBlock(name, nameLength + 1); // Trailing 0 apparantly!
- if (wrote == -1)
- return false;
-
- int k = 0;
- bytes.resize(width() * height() * 4);
- for (TQ_INT32 y = 0; y < height(); y++) {
- for (TQ_INT32 x = 0; x < width(); x++) {
- // RGBA only
- TQRgb pixel = m_img.pixel(x,y);
- bytes[k++] = static_cast<char>(tqRed(pixel));
- bytes[k++] = static_cast<char>(tqGreen(pixel));
- bytes[k++] = static_cast<char>(tqBlue(pixel));
- bytes[k++] = static_cast<char>(tqAlpha(pixel));
- }
- }
-
- wrote = file.writeBlock(bytes);
- if (wrote == -1)
- return false;
-
- file.close();
-
- return true;
-}
-
-TQImage KisPattern::img()
-{
- return m_img;
-}
-
-bool KisPattern::init()
-{
- // load Gimp patterns
- GimpPatternHeader bh;
- TQ_INT32 k;
- TQValueVector<char> name;
-
- if (sizeof(GimpPatternHeader) > m_data.size()) {
- return false;
- }
-
- memcpy(&bh, &m_data[0], sizeof(GimpPatternHeader));
- bh.header_size = ntohl(bh.header_size);
- bh.version = ntohl(bh.version);
- bh.width = ntohl(bh.width);
- bh.height = ntohl(bh.height);
- bh.bytes = ntohl(bh.bytes);
- bh.magic_number = ntohl(bh.magic_number);
-
- if (bh.header_size > m_data.size() || bh.header_size == 0) {
- return false;
- }
-
- name.resize(bh.header_size - sizeof(GimpPatternHeader));
- memcpy(&name[0], &m_data[sizeof(GimpPatternHeader)], name.size());
-
- if (name[name.size() - 1]) {
- return false;
- }
-
- setName(i18n(&name[0]));
-
- if (bh.width == 0 || bh.height == 0 || !m_img.create(bh.width, bh.height, 32)) {
- return false;
- }
-
- k = bh.header_size;
-
- if (bh.bytes == 1) {
- // Grayscale
- TQ_INT32 val;
-
- for (TQ_UINT32 y = 0; y < bh.height; y++) {
- for (TQ_UINT32 x = 0; x < bh.width; x++, k++) {
- if (static_cast<TQ_UINT32>(k) > m_data.size()) {
- kdDebug(DBG_AREA_FILE) << "failed in gray\n";
- return false;
- }
-
- val = m_data[k];
- m_img.setPixel(x, y, tqRgb(val, val, val));
- m_img.setAlphaBuffer(false);
- }
- }
- } else if (bh.bytes == 2) {
- // Grayscale + A
- TQ_INT32 val;
- TQ_INT32 alpha;
- for (TQ_UINT32 y = 0; y < bh.height; y++) {
- for (TQ_UINT32 x = 0; x < bh.width; x++, k++) {
- if (static_cast<TQ_UINT32>(k + 2) > m_data.size()) {
- kdDebug(DBG_AREA_FILE) << "failed in grayA\n";
- return false;
- }
-
- val = m_data[k];
- alpha = m_data[k++];
- m_img.setPixel(x, y, tqRgba(val, val, val, alpha));
- m_img.setAlphaBuffer(true);
- }
- }
- } else if (bh.bytes == 3) {
- // RGB without alpha
- for (TQ_UINT32 y = 0; y < bh.height; y++) {
- for (TQ_UINT32 x = 0; x < bh.width; x++) {
- if (static_cast<TQ_UINT32>(k + 3) > m_data.size()) {
- kdDebug(DBG_AREA_FILE) << "failed in RGB\n";
- return false;
- }
-
- m_img.setPixel(x, y, tqRgb(m_data[k],
- m_data[k + 1],
- m_data[k + 2]));
- k += 3;
- m_img.setAlphaBuffer(false);
- }
- }
- } else if (bh.bytes == 4) {
- // Has alpha
- for (TQ_UINT32 y = 0; y < bh.height; y++) {
- for (TQ_UINT32 x = 0; x < bh.width; x++) {
- if (static_cast<TQ_UINT32>(k + 4) > m_data.size()) {
- kdDebug(DBG_AREA_FILE) << "failed in RGBA\n";
- return false;
- }
-
- m_img.setPixel(x, y, tqRgba(m_data[k],
- m_data[k + 1],
- m_data[k + 2],
- m_data[k + 3]));
- k += 4;
- m_img.setAlphaBuffer(true);
- }
- }
- } else {
- return false;
- }
-
- if (m_img.isNull()) {
- return false;
- }
-
- setWidth(m_img.width());
- setHeight(m_img.height());
-
- setValid(true);
-
- return true;
-}
-
-KisPaintDeviceSP KisPattern::image(KisColorSpace * colorSpace) {
- // Check if there's already a pattern prepared for this colorspace
- TQMap<TQString, KisPaintDeviceSP>::const_iterator it = m_colorspaces.find(colorSpace->id().id());
- if (it != m_colorspaces.end())
- return (*it);
-
- // If not, create one
- KisPaintDeviceSP layer = new KisPaintDevice(colorSpace, "pattern");
-
- TQ_CHECK_PTR(layer);
-
- layer->convertFromTQImage(m_img,"");
-
- m_colorspaces[colorSpace->id().id()] = layer;
- return layer;
-}
-
-TQ_INT32 KisPattern::width() const
-{
- return m_width;
-}
-
-void KisPattern::setWidth(TQ_INT32 w)
-{
- m_width = w;
-}
-
-TQ_INT32 KisPattern::height() const
-{
- return m_height;
-}
-
-void KisPattern::setHeight(TQ_INT32 h)
-{
- m_height = h;
-}
-
-void KisPattern::setImage(const TQImage& img)
-{
- m_hasFile = false;
- m_img = img;
- m_img.detach();
-
- setWidth(img.width());
- setHeight(img.height());
-
- setValid(true);
-}
-
-KisPattern* KisPattern::clone() const
-{
- KisPattern* pattern = new KisPattern("");
- pattern->setImage(m_img);
- pattern->setName(name());
- return pattern;
-}
-
-#include "kis_pattern.moc"
diff --git a/chalk/core/kis_pattern.cpp b/chalk/core/kis_pattern.cpp
new file mode 100644
index 000000000..b2a529958
--- /dev/null
+++ b/chalk/core/kis_pattern.cpp
@@ -0,0 +1,335 @@
+/*
+ * kis_pattern.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 Matthias Elter <elter@kde.org>
+ * 2001 John Califf
+ * 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include "kis_pattern.h"
+
+#include <sys/types.h>
+#include <netinet/in.h>
+
+#include <limits.h>
+#include <stdlib.h>
+
+#include <tqpoint.h>
+#include <tqsize.h>
+#include <tqimage.h>
+#include <tqvaluevector.h>
+#include <tqmap.h>
+#include <tqfile.h>
+
+#include <kdebug.h>
+#include <tdelocale.h>
+
+#include "kis_color.h"
+#include "kis_layer.h"
+#include "kis_paint_device.h"
+
+namespace {
+ struct GimpPatternHeader {
+ TQ_UINT32 header_size; /* header_size = sizeof (PatternHeader) + brush name */
+ TQ_UINT32 version; /* pattern file version # */
+ TQ_UINT32 width; /* width of pattern */
+ TQ_UINT32 height; /* height of pattern */
+ TQ_UINT32 bytes; /* depth of pattern in bytes : 1, 2, 3 or 4*/
+ TQ_UINT32 magic_number; /* GIMP brush magic number */
+ };
+
+ // Yes! This is _NOT_ what my pat.txt file says. It's really not 'GIMP', but 'GPAT'
+ TQ_UINT32 const GimpPatternMagic = (('G' << 24) + ('P' << 16) + ('A' << 8) + ('T' << 0));
+}
+
+KisPattern::KisPattern(const TQString& file) : super(file), m_hasFile(true)
+{
+}
+
+KisPattern::KisPattern(KisPaintDevice* image, int x, int y, int w, int h)
+ : super(""), m_hasFile(false)
+{
+ // Forcefully convert to RGBA8
+ // XXX profile and exposure?
+ setImage(image->convertToTQImage(0, x, y, w, h));
+ setName(image->name());
+}
+
+KisPattern::~KisPattern()
+{
+}
+
+bool KisPattern::load()
+{
+ if (!m_hasFile)
+ return true;
+
+ TQFile file(filename());
+ file.open(IO_ReadOnly);
+ TQByteArray data = file.readAll();
+ if (!data.isEmpty()) {
+ TQ_INT32 startPos = m_data.size();
+
+ m_data.resize(m_data.size() + data.count());
+ memcpy(&m_data[startPos], data.data(), data.count());
+ }
+ file.close();
+ return init();
+}
+
+bool KisPattern::save()
+{
+ TQFile file(filename());
+ file.open(IO_WriteOnly | IO_Truncate);
+
+ TQTextStream stream(&file);
+ // Header: header_size (24+name length),version,width,height,colourdepth of brush,magic,name
+ // depth: 1 = greyscale, 2 = greyscale + A, 3 = RGB, 4 = RGBA
+ // magic = "GPAT", as a single uint32, the docs are wrong here!
+ // name is UTF-8 (\0-terminated! The docs say nothing about this!)
+ // _All_ data in network order, it seems! (not mentioned in gimp-2.2.8/devel-docs/pat.txt!!)
+ // We only save RGBA at the moment
+ // Version is 1 for now...
+
+ GimpPatternHeader ph;
+ TQCString utf8Name = name().utf8();
+ char const* name = utf8Name.data();
+ int nameLength = tqstrlen(name);
+
+ ph.header_size = htonl(sizeof(GimpPatternHeader) + nameLength + 1); // trailing 0
+ ph.version = htonl(1);
+ ph.width = htonl(width());
+ ph.height = htonl(height());
+ ph.bytes = htonl(4);
+ ph.magic_number = htonl(GimpPatternMagic);
+
+ TQByteArray bytes;
+ bytes.setRawData(reinterpret_cast<char*>(&ph), sizeof(GimpPatternHeader));
+ int wrote = file.writeBlock(bytes);
+ bytes.resetRawData(reinterpret_cast<char*>(&ph), sizeof(GimpPatternHeader));
+
+ if (wrote == -1)
+ return false;
+
+ wrote = file.writeBlock(name, nameLength + 1); // Trailing 0 apparantly!
+ if (wrote == -1)
+ return false;
+
+ int k = 0;
+ bytes.resize(width() * height() * 4);
+ for (TQ_INT32 y = 0; y < height(); y++) {
+ for (TQ_INT32 x = 0; x < width(); x++) {
+ // RGBA only
+ TQRgb pixel = m_img.pixel(x,y);
+ bytes[k++] = static_cast<char>(tqRed(pixel));
+ bytes[k++] = static_cast<char>(tqGreen(pixel));
+ bytes[k++] = static_cast<char>(tqBlue(pixel));
+ bytes[k++] = static_cast<char>(tqAlpha(pixel));
+ }
+ }
+
+ wrote = file.writeBlock(bytes);
+ if (wrote == -1)
+ return false;
+
+ file.close();
+
+ return true;
+}
+
+TQImage KisPattern::img()
+{
+ return m_img;
+}
+
+bool KisPattern::init()
+{
+ // load Gimp patterns
+ GimpPatternHeader bh;
+ TQ_INT32 k;
+ TQValueVector<char> name;
+
+ if (sizeof(GimpPatternHeader) > m_data.size()) {
+ return false;
+ }
+
+ memcpy(&bh, &m_data[0], sizeof(GimpPatternHeader));
+ bh.header_size = ntohl(bh.header_size);
+ bh.version = ntohl(bh.version);
+ bh.width = ntohl(bh.width);
+ bh.height = ntohl(bh.height);
+ bh.bytes = ntohl(bh.bytes);
+ bh.magic_number = ntohl(bh.magic_number);
+
+ if (bh.header_size > m_data.size() || bh.header_size == 0) {
+ return false;
+ }
+
+ name.resize(bh.header_size - sizeof(GimpPatternHeader));
+ memcpy(&name[0], &m_data[sizeof(GimpPatternHeader)], name.size());
+
+ if (name[name.size() - 1]) {
+ return false;
+ }
+
+ setName(i18n(&name[0]));
+
+ if (bh.width == 0 || bh.height == 0 || !m_img.create(bh.width, bh.height, 32)) {
+ return false;
+ }
+
+ k = bh.header_size;
+
+ if (bh.bytes == 1) {
+ // Grayscale
+ TQ_INT32 val;
+
+ for (TQ_UINT32 y = 0; y < bh.height; y++) {
+ for (TQ_UINT32 x = 0; x < bh.width; x++, k++) {
+ if (static_cast<TQ_UINT32>(k) > m_data.size()) {
+ kdDebug(DBG_AREA_FILE) << "failed in gray\n";
+ return false;
+ }
+
+ val = m_data[k];
+ m_img.setPixel(x, y, tqRgb(val, val, val));
+ m_img.setAlphaBuffer(false);
+ }
+ }
+ } else if (bh.bytes == 2) {
+ // Grayscale + A
+ TQ_INT32 val;
+ TQ_INT32 alpha;
+ for (TQ_UINT32 y = 0; y < bh.height; y++) {
+ for (TQ_UINT32 x = 0; x < bh.width; x++, k++) {
+ if (static_cast<TQ_UINT32>(k + 2) > m_data.size()) {
+ kdDebug(DBG_AREA_FILE) << "failed in grayA\n";
+ return false;
+ }
+
+ val = m_data[k];
+ alpha = m_data[k++];
+ m_img.setPixel(x, y, tqRgba(val, val, val, alpha));
+ m_img.setAlphaBuffer(true);
+ }
+ }
+ } else if (bh.bytes == 3) {
+ // RGB without alpha
+ for (TQ_UINT32 y = 0; y < bh.height; y++) {
+ for (TQ_UINT32 x = 0; x < bh.width; x++) {
+ if (static_cast<TQ_UINT32>(k + 3) > m_data.size()) {
+ kdDebug(DBG_AREA_FILE) << "failed in RGB\n";
+ return false;
+ }
+
+ m_img.setPixel(x, y, tqRgb(m_data[k],
+ m_data[k + 1],
+ m_data[k + 2]));
+ k += 3;
+ m_img.setAlphaBuffer(false);
+ }
+ }
+ } else if (bh.bytes == 4) {
+ // Has alpha
+ for (TQ_UINT32 y = 0; y < bh.height; y++) {
+ for (TQ_UINT32 x = 0; x < bh.width; x++) {
+ if (static_cast<TQ_UINT32>(k + 4) > m_data.size()) {
+ kdDebug(DBG_AREA_FILE) << "failed in RGBA\n";
+ return false;
+ }
+
+ m_img.setPixel(x, y, tqRgba(m_data[k],
+ m_data[k + 1],
+ m_data[k + 2],
+ m_data[k + 3]));
+ k += 4;
+ m_img.setAlphaBuffer(true);
+ }
+ }
+ } else {
+ return false;
+ }
+
+ if (m_img.isNull()) {
+ return false;
+ }
+
+ setWidth(m_img.width());
+ setHeight(m_img.height());
+
+ setValid(true);
+
+ return true;
+}
+
+KisPaintDeviceSP KisPattern::image(KisColorSpace * colorSpace) {
+ // Check if there's already a pattern prepared for this colorspace
+ TQMap<TQString, KisPaintDeviceSP>::const_iterator it = m_colorspaces.find(colorSpace->id().id());
+ if (it != m_colorspaces.end())
+ return (*it);
+
+ // If not, create one
+ KisPaintDeviceSP layer = new KisPaintDevice(colorSpace, "pattern");
+
+ TQ_CHECK_PTR(layer);
+
+ layer->convertFromTQImage(m_img,"");
+
+ m_colorspaces[colorSpace->id().id()] = layer;
+ return layer;
+}
+
+TQ_INT32 KisPattern::width() const
+{
+ return m_width;
+}
+
+void KisPattern::setWidth(TQ_INT32 w)
+{
+ m_width = w;
+}
+
+TQ_INT32 KisPattern::height() const
+{
+ return m_height;
+}
+
+void KisPattern::setHeight(TQ_INT32 h)
+{
+ m_height = h;
+}
+
+void KisPattern::setImage(const TQImage& img)
+{
+ m_hasFile = false;
+ m_img = img;
+ m_img.detach();
+
+ setWidth(img.width());
+ setHeight(img.height());
+
+ setValid(true);
+}
+
+KisPattern* KisPattern::clone() const
+{
+ KisPattern* pattern = new KisPattern("");
+ pattern->setImage(m_img);
+ pattern->setName(name());
+ return pattern;
+}
+
+#include "kis_pattern.moc"
diff --git a/chalk/core/kis_rect.cc b/chalk/core/kis_rect.cpp
index 175a07a97..175a07a97 100644
--- a/chalk/core/kis_rect.cc
+++ b/chalk/core/kis_rect.cpp
diff --git a/chalk/core/kis_resource.cc b/chalk/core/kis_resource.cpp
index a856cbb12..a856cbb12 100644
--- a/chalk/core/kis_resource.cc
+++ b/chalk/core/kis_resource.cpp
diff --git a/chalk/core/kis_rotate_visitor.cc b/chalk/core/kis_rotate_visitor.cpp
index abb47a056..abb47a056 100644
--- a/chalk/core/kis_rotate_visitor.cc
+++ b/chalk/core/kis_rotate_visitor.cpp
diff --git a/chalk/core/kis_scale_visitor.cc b/chalk/core/kis_scale_visitor.cpp
index a06d674d1..a06d674d1 100644
--- a/chalk/core/kis_scale_visitor.cc
+++ b/chalk/core/kis_scale_visitor.cpp
diff --git a/chalk/core/kis_selected_transaction.cc b/chalk/core/kis_selected_transaction.cpp
index 44eec6976..44eec6976 100644
--- a/chalk/core/kis_selected_transaction.cc
+++ b/chalk/core/kis_selected_transaction.cpp
diff --git a/chalk/core/kis_selection.cc b/chalk/core/kis_selection.cpp
index ea8f2be2b..ea8f2be2b 100644
--- a/chalk/core/kis_selection.cc
+++ b/chalk/core/kis_selection.cpp
diff --git a/chalk/core/kis_strategy_move.cc b/chalk/core/kis_strategy_move.cpp
index d5102c8b2..d5102c8b2 100644
--- a/chalk/core/kis_strategy_move.cc
+++ b/chalk/core/kis_strategy_move.cpp
diff --git a/chalk/core/kis_thread_pool.cc b/chalk/core/kis_thread_pool.cpp
index 128071922..128071922 100644
--- a/chalk/core/kis_thread_pool.cc
+++ b/chalk/core/kis_thread_pool.cpp
diff --git a/chalk/core/kis_transaction.cc b/chalk/core/kis_transaction.cpp
index d0a10acc3..d0a10acc3 100644
--- a/chalk/core/kis_transaction.cc
+++ b/chalk/core/kis_transaction.cpp
diff --git a/chalk/core/kis_transform_worker.cc b/chalk/core/kis_transform_worker.cpp
index 0d4a98b4c..0d4a98b4c 100644
--- a/chalk/core/kis_transform_worker.cc
+++ b/chalk/core/kis_transform_worker.cpp
diff --git a/chalk/core/kis_vec.cc b/chalk/core/kis_vec.cc
deleted file mode 100644
index fa54e1f90..000000000
--- a/chalk/core/kis_vec.cc
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * kis_vec.cc - part of KImageShop
- *
- * Copyright (c) 1999 Matthias Elter <me@kde.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "kis_vec.h"
-
-KisVector2D& KisVector2D::normalize()
-{
- double length, ilength;
-
- length = m_x*m_x + m_y*m_y;
- length = sqrt (length);
-
- if (length > epsilon)
- {
- ilength = 1/length;
- m_x *= ilength;
- m_y *= ilength;
- }
- return *this;
-}
-
-KisVector3D& KisVector3D::normalize()
-{
- double length, ilength;
-
- length = m_x*m_x + m_y*m_y + m_z*m_z;
- length = sqrt (length);
-
- if (length > epsilon)
- {
- ilength = 1/length;
- m_x *= ilength;
- m_y *= ilength;
- m_z *= ilength;
- }
- return *this;
-}
-
-KisVector3D& KisVector3D::crossProduct(const KisVector3D &v)
-{
- double x,y,z;
-
- x = m_y*v.m_z - m_z*v.m_y;
- y = m_z*v.m_x - m_x*v.m_z;
- z = m_x*v.m_y - m_y*v.m_x;
- m_x=x; m_y=y; m_z=z;
-
- return *this;
-}
-
diff --git a/chalk/core/kis_vec.cpp b/chalk/core/kis_vec.cpp
new file mode 100644
index 000000000..9bd6ada9f
--- /dev/null
+++ b/chalk/core/kis_vec.cpp
@@ -0,0 +1,67 @@
+/*
+ * kis_vec.cpp - part of KImageShop
+ *
+ * Copyright (c) 1999 Matthias Elter <me@kde.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "kis_vec.h"
+
+KisVector2D& KisVector2D::normalize()
+{
+ double length, ilength;
+
+ length = m_x*m_x + m_y*m_y;
+ length = sqrt (length);
+
+ if (length > epsilon)
+ {
+ ilength = 1/length;
+ m_x *= ilength;
+ m_y *= ilength;
+ }
+ return *this;
+}
+
+KisVector3D& KisVector3D::normalize()
+{
+ double length, ilength;
+
+ length = m_x*m_x + m_y*m_y + m_z*m_z;
+ length = sqrt (length);
+
+ if (length > epsilon)
+ {
+ ilength = 1/length;
+ m_x *= ilength;
+ m_y *= ilength;
+ m_z *= ilength;
+ }
+ return *this;
+}
+
+KisVector3D& KisVector3D::crossProduct(const KisVector3D &v)
+{
+ double x,y,z;
+
+ x = m_y*v.m_z - m_z*v.m_y;
+ y = m_z*v.m_x - m_x*v.m_z;
+ z = m_x*v.m_y - m_y*v.m_x;
+ m_x=x; m_y=y; m_z=z;
+
+ return *this;
+}
+
diff --git a/chalk/core/tests/Makefile.am b/chalk/core/tests/Makefile.am
index 973166855..9b78866a8 100644
--- a/chalk/core/tests/Makefile.am
+++ b/chalk/core/tests/Makefile.am
@@ -21,7 +21,7 @@ tdeunittest_kis_image_tester_la_LIBADD = -ltdeunittest ../../libchalkcommon.la
tdeunittest_kis_image_tester_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) $(all_libraries)
-tdeunittest_kis_filter_configuration_tester_la_SOURCES = kis_filter_configuration_tester.cc
+tdeunittest_kis_filter_configuration_tester_la_SOURCES = kis_filter_configuration_tester.cpp
tdeunittest_kis_filter_configuration_tester_la_LIBADD = -ltdeunittest ../../libchalkcommon.la
tdeunittest_kis_filter_configuration_tester_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) $(all_libraries)
diff --git a/chalk/core/tests/kis_filter_configuration_tester.cc b/chalk/core/tests/kis_filter_configuration_tester.cpp
index 135e72489..135e72489 100644
--- a/chalk/core/tests/kis_filter_configuration_tester.cc
+++ b/chalk/core/tests/kis_filter_configuration_tester.cpp
diff --git a/chalk/core/tiles/Makefile.am b/chalk/core/tiles/Makefile.am
index 7fad1ab90..9ebe93ec2 100644
--- a/chalk/core/tiles/Makefile.am
+++ b/chalk/core/tiles/Makefile.am
@@ -12,9 +12,9 @@ INCLUDES = -I$(srcdir)/../ \
noinst_LTLIBRARIES = libchalktile.la
-libchalktile_la_SOURCES = kis_tiledvlineiterator.cc kis_tiledhlineiterator.cc \
- kis_tileddatamanager.cc kis_tile.cc kis_tilediterator.cc kis_tiledrectiterator.cc \
- kis_memento.cc kis_tilemanager.cc kis_tiled_random_accessor.cc
+libchalktile_la_SOURCES = kis_tiledvlineiterator.cpp kis_tiledhlineiterator.cpp \
+ kis_tileddatamanager.cpp kis_tile.cpp kis_tilediterator.cpp kis_tiledrectiterator.cpp \
+ kis_memento.cpp kis_tilemanager.cpp kis_tiled_random_accessor.cpp
libchalktile_la_METASOURCES = AUTO
diff --git a/chalk/core/tiles/kis_memento.cc b/chalk/core/tiles/kis_memento.cpp
index 1181f70a3..1181f70a3 100644
--- a/chalk/core/tiles/kis_memento.cc
+++ b/chalk/core/tiles/kis_memento.cpp
diff --git a/chalk/core/tiles/kis_tile.cc b/chalk/core/tiles/kis_tile.cpp
index 743ca82be..743ca82be 100644
--- a/chalk/core/tiles/kis_tile.cc
+++ b/chalk/core/tiles/kis_tile.cpp
diff --git a/chalk/core/tiles/kis_tiled_random_accessor.cc b/chalk/core/tiles/kis_tiled_random_accessor.cpp
index 159faf18c..159faf18c 100644
--- a/chalk/core/tiles/kis_tiled_random_accessor.cc
+++ b/chalk/core/tiles/kis_tiled_random_accessor.cpp
diff --git a/chalk/core/tiles/kis_tileddatamanager.cc b/chalk/core/tiles/kis_tileddatamanager.cpp
index 4586903ce..4586903ce 100644
--- a/chalk/core/tiles/kis_tileddatamanager.cc
+++ b/chalk/core/tiles/kis_tileddatamanager.cpp
diff --git a/chalk/core/tiles/kis_tiledhlineiterator.cc b/chalk/core/tiles/kis_tiledhlineiterator.cpp
index cf023c1ed..cf023c1ed 100644
--- a/chalk/core/tiles/kis_tiledhlineiterator.cc
+++ b/chalk/core/tiles/kis_tiledhlineiterator.cpp
diff --git a/chalk/core/tiles/kis_tilediterator.cc b/chalk/core/tiles/kis_tilediterator.cpp
index 0f3bdf001..0f3bdf001 100644
--- a/chalk/core/tiles/kis_tilediterator.cc
+++ b/chalk/core/tiles/kis_tilediterator.cpp
diff --git a/chalk/core/tiles/kis_tiledrectiterator.cc b/chalk/core/tiles/kis_tiledrectiterator.cpp
index 8f0f7ed1d..8f0f7ed1d 100644
--- a/chalk/core/tiles/kis_tiledrectiterator.cc
+++ b/chalk/core/tiles/kis_tiledrectiterator.cpp
diff --git a/chalk/core/tiles/kis_tiledvlineiterator.cc b/chalk/core/tiles/kis_tiledvlineiterator.cpp
index 0fe8514f8..0fe8514f8 100644
--- a/chalk/core/tiles/kis_tiledvlineiterator.cc
+++ b/chalk/core/tiles/kis_tiledvlineiterator.cpp
diff --git a/chalk/core/tiles/kis_tilemanager.cc b/chalk/core/tiles/kis_tilemanager.cpp
index aa8a207c5..aa8a207c5 100644
--- a/chalk/core/tiles/kis_tilemanager.cc
+++ b/chalk/core/tiles/kis_tilemanager.cpp
diff --git a/chalk/doc/DESIGN.obsolete b/chalk/doc/DESIGN.obsolete
index a1b8e58d4..2f0d25ca6 100644
--- a/chalk/doc/DESIGN.obsolete
+++ b/chalk/doc/DESIGN.obsolete
@@ -169,7 +169,7 @@ Random head-scratchings
- I take it that the two tests that are present in chalk/test
are obsolete?
- - what with the dummmmmy.cc?
+ - what with the dummmmmy.cpp?
- which bits of the chalk/ui files are still relevant?
diff --git a/chalk/doc/brush.txt b/chalk/doc/brush.txt
index e2373258f..afadadc5b 100644
--- a/chalk/doc/brush.txt
+++ b/chalk/doc/brush.txt
@@ -4,7 +4,7 @@ Painting with brushes
when I started working on Chalk, I felt I needed examples. I used the following
sources:
-* The old Chalk brush code (http://webcvs.kde.org/cgi-bin/cvsweb.cgi/koffice/chalk/tools/kis_tool_brush.cc?rev=1.58&content-type=text/x-cvsweb-markup)
+* The old Chalk brush code (http://webcvs.kde.org/cgi-bin/cvsweb.cgi/koffice/chalk/tools/kis_tool_brush.cpp?rev=1.58&content-type=text/x-cvsweb-markup)
* Peter Jodda's Perico (http://software.jodda.de/perico.html)
* The source of the Gimp (both current and 0.99.11 -- the oldest version I could find) (http://www.gimp.org)
* David Hodson's article on Gimp brushes (http://members.ozemail.com.au/~hodsond/gimpbrush.html)
diff --git a/chalk/main.cc b/chalk/main.cc
deleted file mode 100644
index 592c1368f..000000000
--- a/chalk/main.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * main.cc - part of KImageShop
- *
- * Copyright (c) 1999 Matthias Elter <me@kde.org>
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- */
-#include <dcopclient.h>
-#include <tdecmdlineargs.h>
-#include <KoApplication.h>
-
-#include "ui/kis_aboutdata.h"
-
-static const TDECmdLineOptions options[] = {
- { "+[file(s)]", I18N_NOOP("File(s) or URL(s) to open"), 0 },
- TDECmdLineLastOption
-};
-
-extern "C" KRITA_EXPORT int kdemain(int argc, char **argv)
-{
- TDECmdLineArgs::init(argc, argv, newChalkAboutData());
- TDECmdLineArgs::addCmdLineOptions(options);
-
- KoApplication app;
-
- if (!app.start())
- return 1;
-
- return app.exec();
-}
-
diff --git a/chalk/main.cpp b/chalk/main.cpp
new file mode 100644
index 000000000..6d6b1781f
--- /dev/null
+++ b/chalk/main.cpp
@@ -0,0 +1,43 @@
+/*
+ * main.cpp - part of KImageShop
+ *
+ * Copyright (c) 1999 Matthias Elter <me@kde.org>
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ */
+#include <dcopclient.h>
+#include <tdecmdlineargs.h>
+#include <KoApplication.h>
+
+#include "ui/kis_aboutdata.h"
+
+static const TDECmdLineOptions options[] = {
+ { "+[file(s)]", I18N_NOOP("File(s) or URL(s) to open"), 0 },
+ TDECmdLineLastOption
+};
+
+extern "C" KRITA_EXPORT int kdemain(int argc, char **argv)
+{
+ TDECmdLineArgs::init(argc, argv, newChalkAboutData());
+ TDECmdLineArgs::addCmdLineOptions(options);
+
+ KoApplication app;
+
+ if (!app.start())
+ return 1;
+
+ return app.exec();
+}
+
diff --git a/chalk/plugins/filters/blur/Makefile.am b/chalk/plugins/filters/blur/Makefile.am
index d4de75452..53f86c330 100644
--- a/chalk/plugins/filters/blur/Makefile.am
+++ b/chalk/plugins/filters/blur/Makefile.am
@@ -9,7 +9,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkblurfilter_la_SOURCES = wdgblur.ui blur.cc kis_blur_filter.cc kis_wdg_blur.cc
+chalkblurfilter_la_SOURCES = wdgblur.ui blur.cpp kis_blur_filter.cpp kis_wdg_blur.cpp
kde_module_LTLIBRARIES = chalkblurfilter.la
noinst_HEADERS = blur.h kis_blur_filter.h
diff --git a/chalk/plugins/filters/blur/blur.cc b/chalk/plugins/filters/blur/blur.cpp
index 69bac7b1d..69bac7b1d 100644
--- a/chalk/plugins/filters/blur/blur.cc
+++ b/chalk/plugins/filters/blur/blur.cpp
diff --git a/chalk/plugins/filters/blur/kis_blur_filter.cc b/chalk/plugins/filters/blur/kis_blur_filter.cpp
index 8d3604974..8d3604974 100644
--- a/chalk/plugins/filters/blur/kis_blur_filter.cc
+++ b/chalk/plugins/filters/blur/kis_blur_filter.cpp
diff --git a/chalk/plugins/filters/blur/kis_wdg_blur.cc b/chalk/plugins/filters/blur/kis_wdg_blur.cpp
index d4213bb58..d4213bb58 100644
--- a/chalk/plugins/filters/blur/kis_wdg_blur.cc
+++ b/chalk/plugins/filters/blur/kis_wdg_blur.cpp
diff --git a/chalk/plugins/filters/bumpmap/Makefile.am b/chalk/plugins/filters/bumpmap/Makefile.am
index 2b208b33e..9f003aa3e 100644
--- a/chalk/plugins/filters/bumpmap/Makefile.am
+++ b/chalk/plugins/filters/bumpmap/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
-I$(srcdir)/../../../../lib/kofficecore \
$(all_includes)
-chalkbumpmap_la_SOURCES = bumpmap.cc wdgbumpmap.ui
+chalkbumpmap_la_SOURCES = bumpmap.cpp wdgbumpmap.ui
kde_module_LTLIBRARIES = chalkbumpmap.la
noinst_HEADERS = bumpmap.h
diff --git a/chalk/plugins/filters/bumpmap/bumpmap.cc b/chalk/plugins/filters/bumpmap/bumpmap.cpp
index 9d7712228..9d7712228 100644
--- a/chalk/plugins/filters/bumpmap/bumpmap.cc
+++ b/chalk/plugins/filters/bumpmap/bumpmap.cpp
diff --git a/chalk/plugins/filters/cimg/Makefile.am b/chalk/plugins/filters/cimg/Makefile.am
index 4a180a28d..d82def816 100644
--- a/chalk/plugins/filters/cimg/Makefile.am
+++ b/chalk/plugins/filters/cimg/Makefile.am
@@ -12,9 +12,9 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalkcimg_la_SOURCES = \
wdg_cimg.ui\
- kis_cimg_filter.cc\
- kis_cimg_plugin.cc\
- kis_cimgconfig_widget.cc
+ kis_cimg_filter.cpp\
+ kis_cimg_plugin.cpp\
+ kis_cimgconfig_widget.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalkcimg.la
diff --git a/chalk/plugins/filters/cimg/kis_cimg_filter.cc b/chalk/plugins/filters/cimg/kis_cimg_filter.cpp
index c8be0a6f6..c8be0a6f6 100644
--- a/chalk/plugins/filters/cimg/kis_cimg_filter.cc
+++ b/chalk/plugins/filters/cimg/kis_cimg_filter.cpp
diff --git a/chalk/plugins/filters/cimg/kis_cimg_plugin.cc b/chalk/plugins/filters/cimg/kis_cimg_plugin.cpp
index 9ed82fe26..9ed82fe26 100644
--- a/chalk/plugins/filters/cimg/kis_cimg_plugin.cc
+++ b/chalk/plugins/filters/cimg/kis_cimg_plugin.cpp
diff --git a/chalk/plugins/filters/cimg/kis_cimgconfig_widget.cc b/chalk/plugins/filters/cimg/kis_cimgconfig_widget.cpp
index ba9e61e06..ba9e61e06 100644
--- a/chalk/plugins/filters/cimg/kis_cimgconfig_widget.cc
+++ b/chalk/plugins/filters/cimg/kis_cimgconfig_widget.cpp
diff --git a/chalk/plugins/filters/colors/Makefile.am b/chalk/plugins/filters/colors/Makefile.am
index 293806496..8f54c2ed7 100644
--- a/chalk/plugins/filters/colors/Makefile.am
+++ b/chalk/plugins/filters/colors/Makefile.am
@@ -9,7 +9,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkextensioncolorsfilters_la_SOURCES = colors.cc kis_minmax_filters.cc kis_color_to_alpha.cc wdgcolortoalphabase.ui kis_wdg_color_to_alpha.cc
+chalkextensioncolorsfilters_la_SOURCES = colors.cpp kis_minmax_filters.cpp kis_color_to_alpha.cpp wdgcolortoalphabase.ui kis_wdg_color_to_alpha.cpp
kde_module_LTLIBRARIES = chalkextensioncolorsfilters.la
noinst_HEADERS = colors.h
diff --git a/chalk/plugins/filters/colors/colors.cc b/chalk/plugins/filters/colors/colors.cpp
index d3cadc68a..d3cadc68a 100644
--- a/chalk/plugins/filters/colors/colors.cc
+++ b/chalk/plugins/filters/colors/colors.cpp
diff --git a/chalk/plugins/filters/colors/kis_color_to_alpha.cc b/chalk/plugins/filters/colors/kis_color_to_alpha.cpp
index 26f428448..26f428448 100644
--- a/chalk/plugins/filters/colors/kis_color_to_alpha.cc
+++ b/chalk/plugins/filters/colors/kis_color_to_alpha.cpp
diff --git a/chalk/plugins/filters/colors/kis_minmax_filters.cc b/chalk/plugins/filters/colors/kis_minmax_filters.cpp
index eac48ad3c..eac48ad3c 100644
--- a/chalk/plugins/filters/colors/kis_minmax_filters.cc
+++ b/chalk/plugins/filters/colors/kis_minmax_filters.cpp
diff --git a/chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cc b/chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cpp
index 31b726bf0..31b726bf0 100644
--- a/chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cc
+++ b/chalk/plugins/filters/colors/kis_wdg_color_to_alpha.cpp
diff --git a/chalk/plugins/filters/colorsfilters/Makefile.am b/chalk/plugins/filters/colorsfilters/Makefile.am
index 8e0be13e1..e7459d7d1 100644
--- a/chalk/plugins/filters/colorsfilters/Makefile.am
+++ b/chalk/plugins/filters/colorsfilters/Makefile.am
@@ -7,11 +7,11 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkcolorsfilters_la_SOURCES = colorsfilters.cc \
- kis_perchannel_filter.cc \
+chalkcolorsfilters_la_SOURCES = colorsfilters.cpp \
+ kis_perchannel_filter.cpp \
wdg_perchannel.ui \
wdg_brightness_contrast.ui \
- kis_brightness_contrast_filter.cc
+ kis_brightness_contrast_filter.cpp
noinst_HEADERS = colorsfilters.h \
kis_perchannel_filter.h \
diff --git a/chalk/plugins/filters/colorsfilters/colorsfilters.cc b/chalk/plugins/filters/colorsfilters/colorsfilters.cpp
index 754bbc2c0..754bbc2c0 100644
--- a/chalk/plugins/filters/colorsfilters/colorsfilters.cc
+++ b/chalk/plugins/filters/colorsfilters/colorsfilters.cpp
diff --git a/chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cc b/chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cpp
index cbca7a08c..cbca7a08c 100644
--- a/chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cc
+++ b/chalk/plugins/filters/colorsfilters/kis_brightness_contrast_filter.cpp
diff --git a/chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cc b/chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cpp
index d479b27d6..d479b27d6 100644
--- a/chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cc
+++ b/chalk/plugins/filters/colorsfilters/kis_perchannel_filter.cpp
diff --git a/chalk/plugins/filters/convolutionfilters/Makefile.am b/chalk/plugins/filters/convolutionfilters/Makefile.am
index 6e4242f26..cd4582e94 100644
--- a/chalk/plugins/filters/convolutionfilters/Makefile.am
+++ b/chalk/plugins/filters/convolutionfilters/Makefile.am
@@ -12,10 +12,10 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkconvolutionfilters.la
chalkconvolutionfilters_la_SOURCES = kis_custom_convolution_filter_configuration_base_widget.ui \
- kis_custom_convolution_filter_configuration_widget.cc \
- kis_custom_convolution_filter.cc \
- convolutionfilters.cc \
- kis_convolution_filter.cc
+ kis_custom_convolution_filter_configuration_widget.cpp \
+ kis_custom_convolution_filter.cpp \
+ convolutionfilters.cpp \
+ kis_convolution_filter.cpp
noinst_HEADERS = convolutionfilters.h \
kis_custom_convolution_filter_configuration_widget.h \
diff --git a/chalk/plugins/filters/convolutionfilters/convolutionfilters.cc b/chalk/plugins/filters/convolutionfilters/convolutionfilters.cpp
index 8f1085654..8f1085654 100644
--- a/chalk/plugins/filters/convolutionfilters/convolutionfilters.cc
+++ b/chalk/plugins/filters/convolutionfilters/convolutionfilters.cpp
diff --git a/chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cc b/chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cpp
index 08601d600..08601d600 100644
--- a/chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cc
+++ b/chalk/plugins/filters/convolutionfilters/kis_convolution_filter.cpp
diff --git a/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cc b/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cpp
index dc73f197b..dc73f197b 100644
--- a/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cc
+++ b/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter.cpp
diff --git a/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cc b/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cpp
index fcffb3def..fcffb3def 100644
--- a/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cc
+++ b/chalk/plugins/filters/convolutionfilters/kis_custom_convolution_filter_configuration_widget.cpp
diff --git a/chalk/plugins/filters/cubismfilter/Makefile.am b/chalk/plugins/filters/cubismfilter/Makefile.am
index e281360ed..a26a8e806 100644
--- a/chalk/plugins/filters/cubismfilter/Makefile.am
+++ b/chalk/plugins/filters/cubismfilter/Makefile.am
@@ -10,9 +10,9 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkcubismfilter.la
-chalkcubismfilter_la_SOURCES = kis_cubism_filter_plugin.cc \
- kis_cubism_filter.cc \
- kis_polygon.cc
+chalkcubismfilter_la_SOURCES = kis_cubism_filter_plugin.cpp \
+ kis_cubism_filter.cpp \
+ kis_polygon.cpp
noinst_HEADERS = kis_cubism_filter_plugin.h \
kis_cubism_filter.h \
diff --git a/chalk/plugins/filters/cubismfilter/kis_cubism_filter.cc b/chalk/plugins/filters/cubismfilter/kis_cubism_filter.cpp
index 1eb2984ef..1eb2984ef 100644
--- a/chalk/plugins/filters/cubismfilter/kis_cubism_filter.cc
+++ b/chalk/plugins/filters/cubismfilter/kis_cubism_filter.cpp
diff --git a/chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cc b/chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cpp
index 7215a2e3b..7215a2e3b 100644
--- a/chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cc
+++ b/chalk/plugins/filters/cubismfilter/kis_cubism_filter_plugin.cpp
diff --git a/chalk/plugins/filters/cubismfilter/kis_polygon.cc b/chalk/plugins/filters/cubismfilter/kis_polygon.cpp
index cd2d979f2..cd2d979f2 100644
--- a/chalk/plugins/filters/cubismfilter/kis_polygon.cc
+++ b/chalk/plugins/filters/cubismfilter/kis_polygon.cpp
diff --git a/chalk/plugins/filters/embossfilter/Makefile.am b/chalk/plugins/filters/embossfilter/Makefile.am
index 8bb9cdeb1..69b5cb613 100644
--- a/chalk/plugins/filters/embossfilter/Makefile.am
+++ b/chalk/plugins/filters/embossfilter/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkembossfilter.la
-chalkembossfilter_la_SOURCES = kis_emboss_filter_plugin.cc \
- kis_emboss_filter.cc
+chalkembossfilter_la_SOURCES = kis_emboss_filter_plugin.cpp \
+ kis_emboss_filter.cpp
noinst_HEADERS = kis_emboss_filter_plugin.h \
kis_emboss_filter.h
diff --git a/chalk/plugins/filters/embossfilter/kis_emboss_filter.cc b/chalk/plugins/filters/embossfilter/kis_emboss_filter.cpp
index 0d6974e0c..0d6974e0c 100644
--- a/chalk/plugins/filters/embossfilter/kis_emboss_filter.cc
+++ b/chalk/plugins/filters/embossfilter/kis_emboss_filter.cpp
diff --git a/chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cc b/chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cpp
index bd11b115b..bd11b115b 100644
--- a/chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cc
+++ b/chalk/plugins/filters/embossfilter/kis_emboss_filter_plugin.cpp
diff --git a/chalk/plugins/filters/example/Makefile.am b/chalk/plugins/filters/example/Makefile.am
index fcb56751d..c39558f79 100644
--- a/chalk/plugins/filters/example/Makefile.am
+++ b/chalk/plugins/filters/example/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkexample_la_SOURCES = example.cc
+chalkexample_la_SOURCES = example.cpp
kde_module_LTLIBRARIES = chalkexample.la
noinst_HEADERS = example.h
diff --git a/chalk/plugins/filters/example/example.cc b/chalk/plugins/filters/example/example.cpp
index a9ade7249..a9ade7249 100644
--- a/chalk/plugins/filters/example/example.cc
+++ b/chalk/plugins/filters/example/example.cpp
diff --git a/chalk/plugins/filters/fastcolortransfer/Makefile.am b/chalk/plugins/filters/fastcolortransfer/Makefile.am
index e923ce229..e9a171840 100644
--- a/chalk/plugins/filters/fastcolortransfer/Makefile.am
+++ b/chalk/plugins/filters/fastcolortransfer/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkfastcolortransfer_la_SOURCES = wdgfastcolortransfer.ui fastcolortransfer.cc \
+chalkfastcolortransfer_la_SOURCES = wdgfastcolortransfer.ui fastcolortransfer.cpp \
kis_wdg_fastcolortransfer.cpp
kde_module_LTLIBRARIES = chalkfastcolortransfer.la
diff --git a/chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cc b/chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cpp
index c43e56900..c43e56900 100644
--- a/chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cc
+++ b/chalk/plugins/filters/fastcolortransfer/fastcolortransfer.cpp
diff --git a/chalk/plugins/filters/lenscorrectionfilter/Makefile.am b/chalk/plugins/filters/lenscorrectionfilter/Makefile.am
index a0e2e5b48..e36e7d001 100644
--- a/chalk/plugins/filters/lenscorrectionfilter/Makefile.am
+++ b/chalk/plugins/filters/lenscorrectionfilter/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalklenscorrectionfilter_la_SOURCES = lenscorrectionfilter.cc \
+chalklenscorrectionfilter_la_SOURCES = lenscorrectionfilter.cpp \
wdglenscorrectionoptions.ui kis_wdg_lens_correction.cpp
kde_module_LTLIBRARIES = chalklenscorrectionfilter.la
diff --git a/chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cc b/chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cpp
index 6b26ab11a..6b26ab11a 100644
--- a/chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cc
+++ b/chalk/plugins/filters/lenscorrectionfilter/lenscorrectionfilter.cpp
diff --git a/chalk/plugins/filters/levelfilter/Makefile.am b/chalk/plugins/filters/levelfilter/Makefile.am
index 7dc49964c..897779e1b 100644
--- a/chalk/plugins/filters/levelfilter/Makefile.am
+++ b/chalk/plugins/filters/levelfilter/Makefile.am
@@ -7,10 +7,10 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalklevelfilter_la_SOURCES = levelfilter.cc \
+chalklevelfilter_la_SOURCES = levelfilter.cpp \
wdg_level.ui \
- kis_level_filter.cc \
- kgradientslider.cc
+ kis_level_filter.cpp \
+ kgradientslider.cpp
noinst_HEADERS = levelfilter.h \
kis_level_filter.h \
diff --git a/chalk/plugins/filters/levelfilter/kgradientslider.cc b/chalk/plugins/filters/levelfilter/kgradientslider.cpp
index b36e5ce97..b36e5ce97 100644
--- a/chalk/plugins/filters/levelfilter/kgradientslider.cc
+++ b/chalk/plugins/filters/levelfilter/kgradientslider.cpp
diff --git a/chalk/plugins/filters/levelfilter/kis_level_filter.cc b/chalk/plugins/filters/levelfilter/kis_level_filter.cpp
index 84dbc035c..84dbc035c 100644
--- a/chalk/plugins/filters/levelfilter/kis_level_filter.cc
+++ b/chalk/plugins/filters/levelfilter/kis_level_filter.cpp
diff --git a/chalk/plugins/filters/levelfilter/levelfilter.cc b/chalk/plugins/filters/levelfilter/levelfilter.cpp
index 891143783..891143783 100644
--- a/chalk/plugins/filters/levelfilter/levelfilter.cc
+++ b/chalk/plugins/filters/levelfilter/levelfilter.cpp
diff --git a/chalk/plugins/filters/noisefilter/Makefile.am b/chalk/plugins/filters/noisefilter/Makefile.am
index 8c06406f7..119039f0b 100644
--- a/chalk/plugins/filters/noisefilter/Makefile.am
+++ b/chalk/plugins/filters/noisefilter/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalknoisefilter_la_SOURCES = noisefilter.cc wdgnoiseoptions.ui \
+chalknoisefilter_la_SOURCES = noisefilter.cpp wdgnoiseoptions.ui \
kis_wdg_noise.cpp
kde_module_LTLIBRARIES = chalknoisefilter.la
diff --git a/chalk/plugins/filters/noisefilter/noisefilter.cc b/chalk/plugins/filters/noisefilter/noisefilter.cpp
index d8609ba2b..d8609ba2b 100644
--- a/chalk/plugins/filters/noisefilter/noisefilter.cc
+++ b/chalk/plugins/filters/noisefilter/noisefilter.cpp
diff --git a/chalk/plugins/filters/oilpaintfilter/Makefile.am b/chalk/plugins/filters/oilpaintfilter/Makefile.am
index 032fc2f3d..6332d7baa 100644
--- a/chalk/plugins/filters/oilpaintfilter/Makefile.am
+++ b/chalk/plugins/filters/oilpaintfilter/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkoilpaintfilter.la
-chalkoilpaintfilter_la_SOURCES = kis_oilpaint_filter_plugin.cc \
- kis_oilpaint_filter.cc
+chalkoilpaintfilter_la_SOURCES = kis_oilpaint_filter_plugin.cpp \
+ kis_oilpaint_filter.cpp
noinst_HEADERS = kis_oilpaint_filter_plugin.h \
kis_oilpaint_filter.h
diff --git a/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cc b/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cpp
index de869a424..de869a424 100644
--- a/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cc
+++ b/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter.cpp
diff --git a/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cc b/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cpp
index d9c9f3e6f..d9c9f3e6f 100644
--- a/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cc
+++ b/chalk/plugins/filters/oilpaintfilter/kis_oilpaint_filter_plugin.cpp
diff --git a/chalk/plugins/filters/pixelizefilter/Makefile.am b/chalk/plugins/filters/pixelizefilter/Makefile.am
index 750941e1f..20f7bc4ae 100644
--- a/chalk/plugins/filters/pixelizefilter/Makefile.am
+++ b/chalk/plugins/filters/pixelizefilter/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkpixelizefilter.la
-chalkpixelizefilter_la_SOURCES = kis_pixelize_filter_plugin.cc \
- kis_pixelize_filter.cc
+chalkpixelizefilter_la_SOURCES = kis_pixelize_filter_plugin.cpp \
+ kis_pixelize_filter.cpp
noinst_HEADERS = kis_pixelize_filter_plugin.h \
kis_pixelize_filter.h
diff --git a/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cc b/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cpp
index a6b77df76..a6b77df76 100644
--- a/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cc
+++ b/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter.cpp
diff --git a/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cc b/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cpp
index d93cad4e1..d93cad4e1 100644
--- a/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cc
+++ b/chalk/plugins/filters/pixelizefilter/kis_pixelize_filter_plugin.cpp
diff --git a/chalk/plugins/filters/raindropsfilter/Makefile.am b/chalk/plugins/filters/raindropsfilter/Makefile.am
index 10f44c436..e6a1d4683 100644
--- a/chalk/plugins/filters/raindropsfilter/Makefile.am
+++ b/chalk/plugins/filters/raindropsfilter/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkraindropsfilter.la
-chalkraindropsfilter_la_SOURCES = kis_raindrops_filter_plugin.cc \
- kis_raindrops_filter.cc
+chalkraindropsfilter_la_SOURCES = kis_raindrops_filter_plugin.cpp \
+ kis_raindrops_filter.cpp
noinst_HEADERS = kis_raindrops_filter_plugin.h \
kis_raindrops_filter.h
diff --git a/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cc b/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cpp
index acb8c2e17..acb8c2e17 100644
--- a/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cc
+++ b/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter.cpp
diff --git a/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cc b/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cpp
index f62196cb9..f62196cb9 100644
--- a/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cc
+++ b/chalk/plugins/filters/raindropsfilter/kis_raindrops_filter_plugin.cpp
diff --git a/chalk/plugins/filters/randompickfilter/Makefile.am b/chalk/plugins/filters/randompickfilter/Makefile.am
index 65e910ff9..3be553f2a 100644
--- a/chalk/plugins/filters/randompickfilter/Makefile.am
+++ b/chalk/plugins/filters/randompickfilter/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkrandompickfilter_la_SOURCES = randompickfilter.cc wdgrandompickoptions.ui \
+chalkrandompickfilter_la_SOURCES = randompickfilter.cpp wdgrandompickoptions.ui \
kis_wdg_random_pick.cpp
kde_module_LTLIBRARIES = chalkrandompickfilter.la
diff --git a/chalk/plugins/filters/randompickfilter/randompickfilter.cc b/chalk/plugins/filters/randompickfilter/randompickfilter.cpp
index 74368802a..74368802a 100644
--- a/chalk/plugins/filters/randompickfilter/randompickfilter.cc
+++ b/chalk/plugins/filters/randompickfilter/randompickfilter.cpp
diff --git a/chalk/plugins/filters/roundcorners/Makefile.am b/chalk/plugins/filters/roundcorners/Makefile.am
index 05f2e0554..59655c047 100644
--- a/chalk/plugins/filters/roundcorners/Makefile.am
+++ b/chalk/plugins/filters/roundcorners/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalkroundcornersfilter.la
-chalkroundcornersfilter_la_SOURCES = kis_round_corners_filter_plugin.cc \
- kis_round_corners_filter.cc
+chalkroundcornersfilter_la_SOURCES = kis_round_corners_filter_plugin.cpp \
+ kis_round_corners_filter.cpp
noinst_HEADERS = kis_round_corners_filter_plugin.h \
kis_round_corners_filter.h
diff --git a/chalk/plugins/filters/roundcorners/kis_round_corners_filter.cc b/chalk/plugins/filters/roundcorners/kis_round_corners_filter.cpp
index 698961a82..698961a82 100644
--- a/chalk/plugins/filters/roundcorners/kis_round_corners_filter.cc
+++ b/chalk/plugins/filters/roundcorners/kis_round_corners_filter.cpp
diff --git a/chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cc b/chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cpp
index 14610c8e5..14610c8e5 100644
--- a/chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cc
+++ b/chalk/plugins/filters/roundcorners/kis_round_corners_filter_plugin.cpp
diff --git a/chalk/plugins/filters/smalltilesfilter/Makefile.am b/chalk/plugins/filters/smalltilesfilter/Makefile.am
index 5705eae94..da7181494 100644
--- a/chalk/plugins/filters/smalltilesfilter/Makefile.am
+++ b/chalk/plugins/filters/smalltilesfilter/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalksmalltilesfilter.la
-chalksmalltilesfilter_la_SOURCES = kis_small_tiles_filter_plugin.cc \
- kis_small_tiles_filter.cc
+chalksmalltilesfilter_la_SOURCES = kis_small_tiles_filter_plugin.cpp \
+ kis_small_tiles_filter.cpp
noinst_HEADERS = kis_small_tiles_filter_plugin.h \
kis_small_tiles_filter.h
diff --git a/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cc b/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cpp
index a0cf20f17..a0cf20f17 100644
--- a/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cc
+++ b/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter.cpp
diff --git a/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cc b/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cpp
index 6a7fe9ea8..6a7fe9ea8 100644
--- a/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cc
+++ b/chalk/plugins/filters/smalltilesfilter/kis_small_tiles_filter_plugin.cpp
diff --git a/chalk/plugins/filters/sobelfilter/Makefile.am b/chalk/plugins/filters/sobelfilter/Makefile.am
index 38893ad43..4a8e4151d 100644
--- a/chalk/plugins/filters/sobelfilter/Makefile.am
+++ b/chalk/plugins/filters/sobelfilter/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = \
kde_module_LTLIBRARIES = chalksobelfilter.la
-chalksobelfilter_la_SOURCES = kis_sobel_filter_plugin.cc \
- kis_sobel_filter.cc
+chalksobelfilter_la_SOURCES = kis_sobel_filter_plugin.cpp \
+ kis_sobel_filter.cpp
noinst_HEADERS = kis_sobel_filter_plugin.h \
kis_sobel_filter.h
diff --git a/chalk/plugins/filters/sobelfilter/kis_sobel_filter.cc b/chalk/plugins/filters/sobelfilter/kis_sobel_filter.cpp
index 623fc690b..623fc690b 100644
--- a/chalk/plugins/filters/sobelfilter/kis_sobel_filter.cc
+++ b/chalk/plugins/filters/sobelfilter/kis_sobel_filter.cpp
diff --git a/chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cc b/chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cpp
index 3b21c5477..3b21c5477 100644
--- a/chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cc
+++ b/chalk/plugins/filters/sobelfilter/kis_sobel_filter_plugin.cpp
diff --git a/chalk/plugins/filters/threadtest/Makefile.am b/chalk/plugins/filters/threadtest/Makefile.am
index 7846c3c0e..e1a7c2675 100644
--- a/chalk/plugins/filters/threadtest/Makefile.am
+++ b/chalk/plugins/filters/threadtest/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
-I$(srcdir)/../../../../lib/kofficecore \
$(all_includes)
-chalkthreadtest_la_SOURCES = threadtest.cc
+chalkthreadtest_la_SOURCES = threadtest.cpp
kde_module_LTLIBRARIES = chalkthreadtest.la
noinst_HEADERS = threadtest.h
diff --git a/chalk/plugins/filters/threadtest/threadtest.cc b/chalk/plugins/filters/threadtest/threadtest.cpp
index 8477c09c7..8477c09c7 100644
--- a/chalk/plugins/filters/threadtest/threadtest.cc
+++ b/chalk/plugins/filters/threadtest/threadtest.cpp
diff --git a/chalk/plugins/filters/unsharp/Makefile.am b/chalk/plugins/filters/unsharp/Makefile.am
index e955e3bcb..a831dbbdb 100644
--- a/chalk/plugins/filters/unsharp/Makefile.am
+++ b/chalk/plugins/filters/unsharp/Makefile.am
@@ -9,7 +9,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkunsharpfilter_la_SOURCES = wdgunsharp.ui kis_wdg_unsharp.cc unsharp.cc kis_unsharp_filter.cc
+chalkunsharpfilter_la_SOURCES = wdgunsharp.ui kis_wdg_unsharp.cpp unsharp.cpp kis_unsharp_filter.cpp
kde_module_LTLIBRARIES = chalkunsharpfilter.la
diff --git a/chalk/plugins/filters/unsharp/kis_unsharp_filter.cc b/chalk/plugins/filters/unsharp/kis_unsharp_filter.cpp
index 845262b17..845262b17 100644
--- a/chalk/plugins/filters/unsharp/kis_unsharp_filter.cc
+++ b/chalk/plugins/filters/unsharp/kis_unsharp_filter.cpp
diff --git a/chalk/plugins/filters/unsharp/kis_wdg_unsharp.cc b/chalk/plugins/filters/unsharp/kis_wdg_unsharp.cpp
index 627d105cf..627d105cf 100644
--- a/chalk/plugins/filters/unsharp/kis_wdg_unsharp.cc
+++ b/chalk/plugins/filters/unsharp/kis_wdg_unsharp.cpp
diff --git a/chalk/plugins/filters/unsharp/unsharp.cc b/chalk/plugins/filters/unsharp/unsharp.cpp
index 3d90d49ed..3d90d49ed 100644
--- a/chalk/plugins/filters/unsharp/unsharp.cc
+++ b/chalk/plugins/filters/unsharp/unsharp.cpp
diff --git a/chalk/plugins/filters/wavefilter/Makefile.am b/chalk/plugins/filters/wavefilter/Makefile.am
index 3425e7698..a6b300518 100644
--- a/chalk/plugins/filters/wavefilter/Makefile.am
+++ b/chalk/plugins/filters/wavefilter/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkwavefilter_la_SOURCES = wavefilter.cc wdgwaveoptions.ui \
+chalkwavefilter_la_SOURCES = wavefilter.cpp wdgwaveoptions.ui \
kis_wdg_wave.cpp
kde_module_LTLIBRARIES = chalkwavefilter.la
diff --git a/chalk/plugins/filters/wavefilter/wavefilter.cc b/chalk/plugins/filters/wavefilter/wavefilter.cpp
index 9f9777bf6..9f9777bf6 100644
--- a/chalk/plugins/filters/wavefilter/wavefilter.cc
+++ b/chalk/plugins/filters/wavefilter/wavefilter.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/Makefile.am b/chalk/plugins/paintops/defaultpaintops/Makefile.am
index 31acf6e0e..84e2a4088 100644
--- a/chalk/plugins/paintops/defaultpaintops/Makefile.am
+++ b/chalk/plugins/paintops/defaultpaintops/Makefile.am
@@ -18,14 +18,14 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalkdefaultpaintops_la_SOURCES = \
- defaultpaintops_plugin.cc \
- kis_airbrushop.cc \
- kis_brushop.cc \
- kis_duplicateop.cc \
- kis_eraseop.cc \
- kis_penop.cc \
+ defaultpaintops_plugin.cpp \
+ kis_airbrushop.cpp \
+ kis_brushop.cpp \
+ kis_duplicateop.cpp \
+ kis_eraseop.cpp \
+ kis_penop.cpp \
kis_dlgbrushcurvecontrol.ui \
- kis_smudgeop.cc
+ kis_smudgeop.cpp
noinst_HEADERS = defaultpaintops_plugin.h kis_airbrushop.h kis_brushop.h \
kis_duplicateop.h kis_eraseop.h kis_penop.h kis_smudgeop.h
diff --git a/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cc b/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cc
deleted file mode 100644
index 25f12b87b..000000000
--- a/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cc
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * defaultpaintops_plugin.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_paintop_registry.h>
-
-#include "kis_airbrushop.h"
-#include "kis_brushop.h"
-#include "kis_duplicateop.h"
-#include "kis_eraseop.h"
-#include "kis_smudgeop.h"
-#include "kis_penop.h"
-#include "kis_global.h"
-#include "kis_paintop_registry.h"
-
-#include "defaultpaintops_plugin.h"
-
-typedef KGenericFactory<DefaultPaintOpsPlugin> DefaultPaintOpsPluginFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkdefaultpaintops, DefaultPaintOpsPluginFactory( "chalkcore" ) )
-
-
-DefaultPaintOpsPlugin::DefaultPaintOpsPlugin(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(DefaultPaintOpsPluginFactory::instance());
-
- // This is not a gui plugin; only load it when the doc is created.
- if ( parent->inherits("KisPaintOpRegistry") )
- {
- KisPaintOpRegistry * r = dynamic_cast<KisPaintOpRegistry*>(parent);
- // Add hard-coded paint ops. Plugin paintops will add
- // themselves in the plugin initialization code.
- r->add ( new KisAirbrushOpFactory );
- r->add ( new KisBrushOpFactory );
- r->add ( new KisDuplicateOpFactory );
- r->add ( new KisEraseOpFactory );
- r->add ( new KisPenOpFactory );
- r->add ( new KisSmudgeOpFactory );
- }
-
-}
-
-DefaultPaintOpsPlugin::~DefaultPaintOpsPlugin()
-{
-}
-
-#include "defaultpaintops_plugin.moc"
diff --git a/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cpp b/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cpp
new file mode 100644
index 000000000..6e1d3f754
--- /dev/null
+++ b/chalk/plugins/paintops/defaultpaintops/defaultpaintops_plugin.cpp
@@ -0,0 +1,70 @@
+/*
+ * defaultpaintops_plugin.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_paintop_registry.h>
+
+#include "kis_airbrushop.h"
+#include "kis_brushop.h"
+#include "kis_duplicateop.h"
+#include "kis_eraseop.h"
+#include "kis_smudgeop.h"
+#include "kis_penop.h"
+#include "kis_global.h"
+#include "kis_paintop_registry.h"
+
+#include "defaultpaintops_plugin.h"
+
+typedef KGenericFactory<DefaultPaintOpsPlugin> DefaultPaintOpsPluginFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkdefaultpaintops, DefaultPaintOpsPluginFactory( "chalkcore" ) )
+
+
+DefaultPaintOpsPlugin::DefaultPaintOpsPlugin(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(DefaultPaintOpsPluginFactory::instance());
+
+ // This is not a gui plugin; only load it when the doc is created.
+ if ( parent->inherits("KisPaintOpRegistry") )
+ {
+ KisPaintOpRegistry * r = dynamic_cast<KisPaintOpRegistry*>(parent);
+ // Add hard-coded paint ops. Plugin paintops will add
+ // themselves in the plugin initialization code.
+ r->add ( new KisAirbrushOpFactory );
+ r->add ( new KisBrushOpFactory );
+ r->add ( new KisDuplicateOpFactory );
+ r->add ( new KisEraseOpFactory );
+ r->add ( new KisPenOpFactory );
+ r->add ( new KisSmudgeOpFactory );
+ }
+
+}
+
+DefaultPaintOpsPlugin::~DefaultPaintOpsPlugin()
+{
+}
+
+#include "defaultpaintops_plugin.moc"
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cc b/chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cpp
index 2a8750f33..2a8750f33 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_airbrushop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_brushop.cc b/chalk/plugins/paintops/defaultpaintops/kis_brushop.cpp
index 285b4d6fc..285b4d6fc 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_brushop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_brushop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_convolveop.cc b/chalk/plugins/paintops/defaultpaintops/kis_convolveop.cpp
index 708d792c9..708d792c9 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_convolveop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_convolveop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cc b/chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cpp
index 556a77751..556a77751 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_eraseop.cc b/chalk/plugins/paintops/defaultpaintops/kis_eraseop.cpp
index 55e3b7b84..55e3b7b84 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_eraseop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_eraseop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_penop.cc b/chalk/plugins/paintops/defaultpaintops/kis_penop.cpp
index 4a8da9a16..4a8da9a16 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_penop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_penop.cpp
diff --git a/chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cc b/chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cpp
index f15077b37..f15077b37 100644
--- a/chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cc
+++ b/chalk/plugins/paintops/defaultpaintops/kis_smudgeop.cpp
diff --git a/chalk/plugins/tools/defaulttools/Makefile.am b/chalk/plugins/tools/defaulttools/Makefile.am
index c4d790cb5..ad9e96a5b 100644
--- a/chalk/plugins/tools/defaulttools/Makefile.am
+++ b/chalk/plugins/tools/defaulttools/Makefile.am
@@ -10,19 +10,19 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalkdefaulttools_la_SOURCES = \
- default_tools.cc \
- kis_tool_colorpicker.cc \
- kis_tool_move.cc \
- kis_tool_zoom.cc \
- kis_tool_brush.cc \
- kis_tool_line.cc \
- kis_tool_duplicate.cc \
- kis_tool_fill.cc \
- kis_tool_rectangle.cc \
- kis_tool_ellipse.cc \
- kis_tool_pan.cc \
- kis_tool_text.cc \
- kis_tool_gradient.cc \
+ default_tools.cpp \
+ kis_tool_colorpicker.cpp \
+ kis_tool_move.cpp \
+ kis_tool_zoom.cpp \
+ kis_tool_brush.cpp \
+ kis_tool_line.cpp \
+ kis_tool_duplicate.cpp \
+ kis_tool_fill.cpp \
+ kis_tool_rectangle.cpp \
+ kis_tool_ellipse.cpp \
+ kis_tool_pan.cpp \
+ kis_tool_text.cpp \
+ kis_tool_gradient.cpp \
wdgcolorpicker.ui
# Install this plugin in the KDE modules directory
diff --git a/chalk/plugins/tools/defaulttools/default_tools.cc b/chalk/plugins/tools/defaulttools/default_tools.cc
deleted file mode 100644
index 17e0feff0..000000000
--- a/chalk/plugins/tools/defaulttools/default_tools.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * default_tools.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool.h>
-#include <kis_tool_registry.h>
-#include "default_tools.h"
-
-#include "kis_tool_fill.h"
-#include "kis_tool_brush.h"
-#include "kis_tool_freehand.h"
-#include "kis_tool_gradient.h"
-#include "kis_tool_rectangle.h"
-#include "kis_tool_colorpicker.h"
-#include "kis_tool_line.h"
-#include "kis_tool_text.h"
-#include "kis_tool_duplicate.h"
-#include "kis_tool_move.h"
-#include "kis_tool_zoom.h"
-#include "kis_tool_ellipse.h"
-#include "kis_tool_pan.h"
-
-
-typedef KGenericFactory<DefaultTools> DefaultToolsFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkdefaulttools, DefaultToolsFactory( "chalk" ) )
-
-
-DefaultTools::DefaultTools(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(DefaultToolsFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
-
- r->add(new KisToolFillFactory());
- r->add(new KisToolGradientFactory());
- r->add(new KisToolBrushFactory());
- r->add(new KisToolColorPickerFactory());
- r->add(new KisToolLineFactory());
- r->add(new KisToolTextFactory());
- r->add(new KisToolDuplicateFactory());
- r->add(new KisToolMoveFactory());
- r->add(new KisToolZoomFactory());
- r->add(new KisToolEllipseFactory());
- r->add(new KisToolRectangleFactory());
- r->add(new KisToolPanFactory());
-
- }
-}
-
-DefaultTools::~DefaultTools()
-{
-}
-
-#include "default_tools.moc"
diff --git a/chalk/plugins/tools/defaulttools/default_tools.cpp b/chalk/plugins/tools/defaulttools/default_tools.cpp
new file mode 100644
index 000000000..6f1bedbbf
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/default_tools.cpp
@@ -0,0 +1,88 @@
+/*
+ * default_tools.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool.h>
+#include <kis_tool_registry.h>
+#include "default_tools.h"
+
+#include "kis_tool_fill.h"
+#include "kis_tool_brush.h"
+#include "kis_tool_freehand.h"
+#include "kis_tool_gradient.h"
+#include "kis_tool_rectangle.h"
+#include "kis_tool_colorpicker.h"
+#include "kis_tool_line.h"
+#include "kis_tool_text.h"
+#include "kis_tool_duplicate.h"
+#include "kis_tool_move.h"
+#include "kis_tool_zoom.h"
+#include "kis_tool_ellipse.h"
+#include "kis_tool_pan.h"
+
+
+typedef KGenericFactory<DefaultTools> DefaultToolsFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkdefaulttools, DefaultToolsFactory( "chalk" ) )
+
+
+DefaultTools::DefaultTools(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(DefaultToolsFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+
+ r->add(new KisToolFillFactory());
+ r->add(new KisToolGradientFactory());
+ r->add(new KisToolBrushFactory());
+ r->add(new KisToolColorPickerFactory());
+ r->add(new KisToolLineFactory());
+ r->add(new KisToolTextFactory());
+ r->add(new KisToolDuplicateFactory());
+ r->add(new KisToolMoveFactory());
+ r->add(new KisToolZoomFactory());
+ r->add(new KisToolEllipseFactory());
+ r->add(new KisToolRectangleFactory());
+ r->add(new KisToolPanFactory());
+
+ }
+}
+
+DefaultTools::~DefaultTools()
+{
+}
+
+#include "default_tools.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_brush.cc b/chalk/plugins/tools/defaulttools/kis_tool_brush.cc
deleted file mode 100644
index 7c83a36b0..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_brush.cc
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * kis_tool_brush.cc - part of Chalk
- *
- * Copyright (c) 2003-2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqevent.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqwidget.h>
-#include <tqtimer.h>
-#include <tqpushbutton.h>
-#include <tqpainter.h>
-#include <tqrect.h>
-#include <tqcheckbox.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_config.h"
-#include "kis_brush.h"
-#include "kis_paintop.h"
-#include "kis_paintop_registry.h"
-#include "kis_cmb_composite.h"
-#include "kis_cursor.h"
-#include "kis_painter.h"
-#include "kis_tool_brush.h"
-#include "kis_canvas_subject.h"
-#include "kis_boundary.h"
-#include "kis_move_event.h"
-#include "kis_canvas.h"
-#include "kis_layer.h"
-
-KisToolBrush::KisToolBrush()
- : super(i18n("Brush"))
-{
- setName("tool_brush");
- setCursor(KisCursor::load("tool_freehand_cursor.png", 5, 5));
- m_rate = 100; // Conveniently hardcoded for now
- m_timer = new TQTimer(this);
- TQ_CHECK_PTR(m_timer);
-
- connect(m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(timeoutPaint()));
-
-}
-
-KisToolBrush::~KisToolBrush()
-{
- delete m_timer;
- m_timer = 0;
-}
-
-void KisToolBrush::timeoutPaint()
-{
- if (currentImage() && painter()) {
- painter()->paintAt(m_prevPos, m_prevPressure, m_prevXTilt, m_prevYTilt);
- currentImage()->activeLayer()->setDirty(painter()->dirtyRect());
- }
-}
-
-
-void KisToolBrush::update(KisCanvasSubject *subject)
-{
- super::update(subject);
-}
-
-void KisToolBrush::initPaint(KisEvent *e)
-{
- super::initPaint(e);
-
- if (!m_painter) {
- kdWarning() << "Didn't create a painter! Something is wrong!\n";
- return;
- }
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), m_painter);
- if (!op) return;
-
- m_subject->canvasController()->kiscanvas()->update(); // remove the outline
-
- painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
-
- if (op->incremental()) {
- m_timer->start( m_rate );
- }
-}
-
-
-void KisToolBrush::endPaint()
-{
- m_timer->stop();
- super::endPaint();
-}
-
-
-void KisToolBrush::setup(TDEActionCollection *collection)
-{
-
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Brush"),
- "tool_freehand", TQt::Key_B, this,
- TQT_SLOT(activate()), collection,
- name());
- m_action->setToolTip(i18n("Draw freehand"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-void KisToolBrush::move(KisMoveEvent *e) {
- KisToolFreehand::move(e);
- KisConfig cfg;
- if (m_mode != PAINT && cfg.cursorStyle() == CURSOR_STYLE_OUTLINE)
- paintOutline(e->pos());
-}
-
-void KisToolBrush::leave(TQEvent */*e*/) {
- m_subject->canvasController()->kiscanvas()->update(); // remove the outline
-}
-
-
-void KisToolBrush::slotSetPaintingMode( int mode )
-{
- if (mode == TQButton::On) {
- // Direct painting
- m_paintIncremental = true;
- }
- else {
- m_paintIncremental = false;
- }
-}
-
-
-TQWidget* KisToolBrush::createOptionWidget(TQWidget* parent)
-{
- TQWidget *widget = super::createOptionWidget(parent);
- m_chkDirect = new TQCheckBox(i18n("Paint direct"), widget, "chkDirect");
- m_chkDirect->setChecked(true);
- connect(m_chkDirect, TQT_SIGNAL(stateChanged(int)), this, TQT_SLOT(slotSetPaintingMode(int)));
-
- m_optionLayout = new TQGridLayout(NULL, 3, 2, 0, 6);
- TQ_CHECK_PTR(m_optionLayout);
-
- super::addOptionWidgetLayout(m_optionLayout);
- m_optionLayout->addWidget(m_chkDirect, 0, 0);
-
- return widget;
-}
-
-#include "kis_tool_brush.moc"
-
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_brush.cpp b/chalk/plugins/tools/defaulttools/kis_tool_brush.cpp
new file mode 100644
index 000000000..96e262022
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_brush.cpp
@@ -0,0 +1,167 @@
+/*
+ * kis_tool_brush.cpp - part of Chalk
+ *
+ * Copyright (c) 2003-2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqevent.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqwidget.h>
+#include <tqtimer.h>
+#include <tqpushbutton.h>
+#include <tqpainter.h>
+#include <tqrect.h>
+#include <tqcheckbox.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_config.h"
+#include "kis_brush.h"
+#include "kis_paintop.h"
+#include "kis_paintop_registry.h"
+#include "kis_cmb_composite.h"
+#include "kis_cursor.h"
+#include "kis_painter.h"
+#include "kis_tool_brush.h"
+#include "kis_canvas_subject.h"
+#include "kis_boundary.h"
+#include "kis_move_event.h"
+#include "kis_canvas.h"
+#include "kis_layer.h"
+
+KisToolBrush::KisToolBrush()
+ : super(i18n("Brush"))
+{
+ setName("tool_brush");
+ setCursor(KisCursor::load("tool_freehand_cursor.png", 5, 5));
+ m_rate = 100; // Conveniently hardcoded for now
+ m_timer = new TQTimer(this);
+ TQ_CHECK_PTR(m_timer);
+
+ connect(m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(timeoutPaint()));
+
+}
+
+KisToolBrush::~KisToolBrush()
+{
+ delete m_timer;
+ m_timer = 0;
+}
+
+void KisToolBrush::timeoutPaint()
+{
+ if (currentImage() && painter()) {
+ painter()->paintAt(m_prevPos, m_prevPressure, m_prevXTilt, m_prevYTilt);
+ currentImage()->activeLayer()->setDirty(painter()->dirtyRect());
+ }
+}
+
+
+void KisToolBrush::update(KisCanvasSubject *subject)
+{
+ super::update(subject);
+}
+
+void KisToolBrush::initPaint(KisEvent *e)
+{
+ super::initPaint(e);
+
+ if (!m_painter) {
+ kdWarning() << "Didn't create a painter! Something is wrong!\n";
+ return;
+ }
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), m_painter);
+ if (!op) return;
+
+ m_subject->canvasController()->kiscanvas()->update(); // remove the outline
+
+ painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
+
+ if (op->incremental()) {
+ m_timer->start( m_rate );
+ }
+}
+
+
+void KisToolBrush::endPaint()
+{
+ m_timer->stop();
+ super::endPaint();
+}
+
+
+void KisToolBrush::setup(TDEActionCollection *collection)
+{
+
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Brush"),
+ "tool_freehand", TQt::Key_B, this,
+ TQT_SLOT(activate()), collection,
+ name());
+ m_action->setToolTip(i18n("Draw freehand"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+void KisToolBrush::move(KisMoveEvent *e) {
+ KisToolFreehand::move(e);
+ KisConfig cfg;
+ if (m_mode != PAINT && cfg.cursorStyle() == CURSOR_STYLE_OUTLINE)
+ paintOutline(e->pos());
+}
+
+void KisToolBrush::leave(TQEvent */*e*/) {
+ m_subject->canvasController()->kiscanvas()->update(); // remove the outline
+}
+
+
+void KisToolBrush::slotSetPaintingMode( int mode )
+{
+ if (mode == TQButton::On) {
+ // Direct painting
+ m_paintIncremental = true;
+ }
+ else {
+ m_paintIncremental = false;
+ }
+}
+
+
+TQWidget* KisToolBrush::createOptionWidget(TQWidget* parent)
+{
+ TQWidget *widget = super::createOptionWidget(parent);
+ m_chkDirect = new TQCheckBox(i18n("Paint direct"), widget, "chkDirect");
+ m_chkDirect->setChecked(true);
+ connect(m_chkDirect, TQT_SIGNAL(stateChanged(int)), this, TQT_SLOT(slotSetPaintingMode(int)));
+
+ m_optionLayout = new TQGridLayout(NULL, 3, 2, 0, 6);
+ TQ_CHECK_PTR(m_optionLayout);
+
+ super::addOptionWidgetLayout(m_optionLayout);
+ m_optionLayout->addWidget(m_chkDirect, 0, 0);
+
+ return widget;
+}
+
+#include "kis_tool_brush.moc"
+
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cc b/chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cpp
index 40a09a91f..40a09a91f 100644
--- a/chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cc
+++ b/chalk/plugins/tools/defaulttools/kis_tool_colorpicker.cpp
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cc b/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cc
deleted file mode 100644
index 7bb4c54fd..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cc
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * kis_tool_duplicate.cc - part of Chalk
- *
- * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqbitmap.h>
-#include <tqcheckbox.h>
-#include <tqpainter.h>
-#include <tqlabel.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <knuminput.h>
-#include <tdelocale.h>
-
-#include "kis_brush.h"
-#include "kis_cursor.h"
-#include "kis_image.h"
-#include "kis_tool_duplicate.h"
-#include "kis_painter.h"
-#include "kis_vec.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas_subject.h"
-#include "kis_perspective_grid.h"
-
-#include "kis_canvas_painter.h"
-#include "kis_boundary_painter.h"
-
-KisToolDuplicate::KisToolDuplicate()
- : super(i18n("Duplicate Brush")), m_isOffsetNotUptodate(true), m_position(TQPoint(-1,-1))
-{
- setName("tool_duplicate");
- m_subject = 0;
- setCursor(KisCursor::load("tool_duplicate_cursor.png", 5, 5));
-}
-
-KisToolDuplicate::~KisToolDuplicate()
-{
-}
-
-void KisToolDuplicate::activate()
-{
- m_position = TQPoint(-1,-1);
- super::activate();
- if( m_subject->currentImg()->perspectiveGrid()->countSubGrids() != 1 )
- {
- m_perspectiveCorrection->setEnabled( false );
- m_perspectiveCorrection->setChecked( false );
- } else {
- m_perspectiveCorrection->setEnabled( true );
- }
-}
-
-void KisToolDuplicate::buttonPress(KisButtonPressEvent *e)
-{
- if (e->state() == ShiftButton) {
- m_position = e->pos();
- m_isOffsetNotUptodate = true;
- } else {
- if (m_position != TQPoint(-1, -1)) {
- super::buttonPress(e);
- }
- }
-}
-
-
-void KisToolDuplicate::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Duplicate Brush"),
- "tool_duplicate", TQt::Key_C, this,
- TQT_SLOT(activate()), collection,
- name());
- m_action->setToolTip(i18n("Duplicate parts of the image. Shift-click to select the point to duplicate from to begin."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-void KisToolDuplicate::initPaint(KisEvent *e)
-{
- if( m_position != TQPoint(-1,-1))
- {
- if(m_isOffsetNotUptodate)
- {
- m_offset = e->pos() - m_position;
- m_isOffsetNotUptodate = false;
- }
- m_paintIncremental = false;
- super::initPaint(e);
- painter()->setDuplicateOffset( m_offset );
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("duplicate", 0, painter());
- if (op && m_source) {
- op->setSource(m_source);
- painter()->setPaintOp(op);
- }
- m_positionStartPainting = e->pos();
- painter()->setDuplicateStart( e->pos() );
- }
-}
-
-void KisToolDuplicate::move(KisMoveEvent *e)
-{
-
- // Paint the outline where we will (or are) copying from
- if( m_position == TQPoint(-1,-1) )
- return;
-
- TQPoint srcPos;
- if (m_mode == PAINT) {
- // if we are in perspective correction mode, update the offset when moving
- if(m_perspectiveCorrection->isChecked())
- {
- double startM[3][3];
- double endM[3][3];
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- startM[i][j] = 0.;
- endM[i][j] = 0.;
- }
- startM[i][i] = 1.;
- endM[i][i] = 1.;
- }
-
- // First look for the grid corresponding to the start point
- KisSubPerspectiveGrid* subGridStart = *m_subject->currentImg()->perspectiveGrid()->begin();//device->image()->perspectiveGrid()->gridAt(KisPoint(srcPoint.x() +hotSpot.x(),srcPoint.y() +hotSpot.y()));
- TQRect r = TQRect(0,0, m_subject->currentImg()->width(), m_subject->currentImg()->height());
-
- if(subGridStart)
- {
- double* b = KisPerspectiveMath::computeMatrixTransfoFromPerspective( r, *subGridStart->topLeft(), *subGridStart->topRight(), *subGridStart->bottomLeft(), *subGridStart->bottomRight());
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- startM[i][j] = b[3*i+j];
- }
- }
-
- }
- // Second look for the grid corresponding to the end point
- KisSubPerspectiveGrid* subGridEnd = *m_subject->currentImg()->perspectiveGrid()->begin();// device->image()->perspectiveGrid()->gridAt(pos);
- if(subGridEnd)
- {
- double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(*subGridEnd->topLeft(), *subGridEnd->topRight(), *subGridEnd->bottomLeft(), *subGridEnd->bottomRight(), r);
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- endM[i][j] = b[3*i+j];
- }
- }
- }
- // Compute the translation in the perspective transformation space:
- KisPoint translat;
- {
- KisPoint positionStartPaintingT = KisPerspectiveMath::matProd(endM, m_positionStartPainting);
- KisPoint currentPositionT = KisPerspectiveMath::matProd(endM, e->pos() );
- KisPoint duplicateStartPoisitionT = KisPerspectiveMath::matProd(endM, m_positionStartPainting - m_offset);
- KisPoint duplicateRealPosition = KisPerspectiveMath::matProd(startM, duplicateStartPoisitionT + (currentPositionT - positionStartPaintingT) );
- KisPoint p = e->pos() - duplicateRealPosition;
- srcPos = p.floorTQPoint();
- }
-
- }else {
- srcPos = painter()->duplicateOffset().floorTQPoint();
- }
- } else {
- if(m_isOffsetNotUptodate)
- srcPos = e->pos().floorTQPoint() - m_position.floorTQPoint();
- else
- srcPos = m_offset.floorTQPoint();
- }
-
- TQ_INT32 x;
- TQ_INT32 y;
-
- // like KisPaintOp::splitCoordinate
- x = (TQ_INT32)((e->x() < 0) ? e->x() - 1 : e->x());
- y = (TQ_INT32)((e->y() < 0) ? e->y() - 1 : e->y());
- srcPos = TQPoint(x - srcPos.x(), y - srcPos.y());
-
- paintOutline(srcPos);
- super::move(e);
-}
-
-void KisToolDuplicate::paintAt(const KisPoint &pos,
- const double pressure,
- const double xtilt,
- const double ytilt)
-{
- if( m_position != TQPoint(-1,-1))
- {
- if(m_isOffsetNotUptodate)
- {
- m_offset = pos - m_position;
- m_isOffsetNotUptodate = false;
- }
- painter()->setDuplicateHealing( m_healing->isChecked() );
- painter()->setDuplicateHealingRadius( m_healingRadius->value() );
- painter()->setDuplicatePerspectiveCorrection( m_perspectiveCorrection->isChecked() );
- painter()->paintAt( pos, pressure, xtilt, ytilt);
- }
-}
-
-TQString KisToolDuplicate::quickHelp() const {
- return i18n("To start, shift-click on the place you want to duplicate from. Then you can start painting. An indication of where you are copying from will be displayed while drawing and moving the mouse.");
-}
-
-TQWidget* KisToolDuplicate::createOptionWidget(TQWidget* parent)
-{
- TQWidget* widget = KisToolPaint::createOptionWidget(parent);
- m_healing = new TQCheckBox(widget);
- m_healing->setChecked( false);
- addOptionWidgetOption(m_healing, new TQLabel(i18n("Healing"), widget ));
- m_healingRadius = new KIntNumInput(widget);
-
- KisBrush *brush = m_subject->currentBrush();
- int healingradius = 20;
- if( brush )
- {
- healingradius = 2 * TQMAX(brush->width(),brush->height());
- }
-
- m_healingRadius->setValue( healingradius );
- addOptionWidgetOption(m_healingRadius, new TQLabel(i18n("Healing radius"), widget ));
- m_perspectiveCorrection = new TQCheckBox(widget);
- addOptionWidgetOption(m_perspectiveCorrection, new TQLabel(i18n("Correct the perspective"), widget ));
- return widget;
-}
-
-#include "kis_tool_duplicate.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cpp b/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cpp
new file mode 100644
index 000000000..0f917e7f7
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_duplicate.cpp
@@ -0,0 +1,255 @@
+/*
+ * kis_tool_duplicate.cpp - part of Chalk
+ *
+ * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqbitmap.h>
+#include <tqcheckbox.h>
+#include <tqpainter.h>
+#include <tqlabel.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <knuminput.h>
+#include <tdelocale.h>
+
+#include "kis_brush.h"
+#include "kis_cursor.h"
+#include "kis_image.h"
+#include "kis_tool_duplicate.h"
+#include "kis_painter.h"
+#include "kis_vec.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas_subject.h"
+#include "kis_perspective_grid.h"
+
+#include "kis_canvas_painter.h"
+#include "kis_boundary_painter.h"
+
+KisToolDuplicate::KisToolDuplicate()
+ : super(i18n("Duplicate Brush")), m_isOffsetNotUptodate(true), m_position(TQPoint(-1,-1))
+{
+ setName("tool_duplicate");
+ m_subject = 0;
+ setCursor(KisCursor::load("tool_duplicate_cursor.png", 5, 5));
+}
+
+KisToolDuplicate::~KisToolDuplicate()
+{
+}
+
+void KisToolDuplicate::activate()
+{
+ m_position = TQPoint(-1,-1);
+ super::activate();
+ if( m_subject->currentImg()->perspectiveGrid()->countSubGrids() != 1 )
+ {
+ m_perspectiveCorrection->setEnabled( false );
+ m_perspectiveCorrection->setChecked( false );
+ } else {
+ m_perspectiveCorrection->setEnabled( true );
+ }
+}
+
+void KisToolDuplicate::buttonPress(KisButtonPressEvent *e)
+{
+ if (e->state() == ShiftButton) {
+ m_position = e->pos();
+ m_isOffsetNotUptodate = true;
+ } else {
+ if (m_position != TQPoint(-1, -1)) {
+ super::buttonPress(e);
+ }
+ }
+}
+
+
+void KisToolDuplicate::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Duplicate Brush"),
+ "tool_duplicate", TQt::Key_C, this,
+ TQT_SLOT(activate()), collection,
+ name());
+ m_action->setToolTip(i18n("Duplicate parts of the image. Shift-click to select the point to duplicate from to begin."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+void KisToolDuplicate::initPaint(KisEvent *e)
+{
+ if( m_position != TQPoint(-1,-1))
+ {
+ if(m_isOffsetNotUptodate)
+ {
+ m_offset = e->pos() - m_position;
+ m_isOffsetNotUptodate = false;
+ }
+ m_paintIncremental = false;
+ super::initPaint(e);
+ painter()->setDuplicateOffset( m_offset );
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("duplicate", 0, painter());
+ if (op && m_source) {
+ op->setSource(m_source);
+ painter()->setPaintOp(op);
+ }
+ m_positionStartPainting = e->pos();
+ painter()->setDuplicateStart( e->pos() );
+ }
+}
+
+void KisToolDuplicate::move(KisMoveEvent *e)
+{
+
+ // Paint the outline where we will (or are) copying from
+ if( m_position == TQPoint(-1,-1) )
+ return;
+
+ TQPoint srcPos;
+ if (m_mode == PAINT) {
+ // if we are in perspective correction mode, update the offset when moving
+ if(m_perspectiveCorrection->isChecked())
+ {
+ double startM[3][3];
+ double endM[3][3];
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ startM[i][j] = 0.;
+ endM[i][j] = 0.;
+ }
+ startM[i][i] = 1.;
+ endM[i][i] = 1.;
+ }
+
+ // First look for the grid corresponding to the start point
+ KisSubPerspectiveGrid* subGridStart = *m_subject->currentImg()->perspectiveGrid()->begin();//device->image()->perspectiveGrid()->gridAt(KisPoint(srcPoint.x() +hotSpot.x(),srcPoint.y() +hotSpot.y()));
+ TQRect r = TQRect(0,0, m_subject->currentImg()->width(), m_subject->currentImg()->height());
+
+ if(subGridStart)
+ {
+ double* b = KisPerspectiveMath::computeMatrixTransfoFromPerspective( r, *subGridStart->topLeft(), *subGridStart->topRight(), *subGridStart->bottomLeft(), *subGridStart->bottomRight());
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ startM[i][j] = b[3*i+j];
+ }
+ }
+
+ }
+ // Second look for the grid corresponding to the end point
+ KisSubPerspectiveGrid* subGridEnd = *m_subject->currentImg()->perspectiveGrid()->begin();// device->image()->perspectiveGrid()->gridAt(pos);
+ if(subGridEnd)
+ {
+ double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(*subGridEnd->topLeft(), *subGridEnd->topRight(), *subGridEnd->bottomLeft(), *subGridEnd->bottomRight(), r);
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ endM[i][j] = b[3*i+j];
+ }
+ }
+ }
+ // Compute the translation in the perspective transformation space:
+ KisPoint translat;
+ {
+ KisPoint positionStartPaintingT = KisPerspectiveMath::matProd(endM, m_positionStartPainting);
+ KisPoint currentPositionT = KisPerspectiveMath::matProd(endM, e->pos() );
+ KisPoint duplicateStartPoisitionT = KisPerspectiveMath::matProd(endM, m_positionStartPainting - m_offset);
+ KisPoint duplicateRealPosition = KisPerspectiveMath::matProd(startM, duplicateStartPoisitionT + (currentPositionT - positionStartPaintingT) );
+ KisPoint p = e->pos() - duplicateRealPosition;
+ srcPos = p.floorTQPoint();
+ }
+
+ }else {
+ srcPos = painter()->duplicateOffset().floorTQPoint();
+ }
+ } else {
+ if(m_isOffsetNotUptodate)
+ srcPos = e->pos().floorTQPoint() - m_position.floorTQPoint();
+ else
+ srcPos = m_offset.floorTQPoint();
+ }
+
+ TQ_INT32 x;
+ TQ_INT32 y;
+
+ // like KisPaintOp::splitCoordinate
+ x = (TQ_INT32)((e->x() < 0) ? e->x() - 1 : e->x());
+ y = (TQ_INT32)((e->y() < 0) ? e->y() - 1 : e->y());
+ srcPos = TQPoint(x - srcPos.x(), y - srcPos.y());
+
+ paintOutline(srcPos);
+ super::move(e);
+}
+
+void KisToolDuplicate::paintAt(const KisPoint &pos,
+ const double pressure,
+ const double xtilt,
+ const double ytilt)
+{
+ if( m_position != TQPoint(-1,-1))
+ {
+ if(m_isOffsetNotUptodate)
+ {
+ m_offset = pos - m_position;
+ m_isOffsetNotUptodate = false;
+ }
+ painter()->setDuplicateHealing( m_healing->isChecked() );
+ painter()->setDuplicateHealingRadius( m_healingRadius->value() );
+ painter()->setDuplicatePerspectiveCorrection( m_perspectiveCorrection->isChecked() );
+ painter()->paintAt( pos, pressure, xtilt, ytilt);
+ }
+}
+
+TQString KisToolDuplicate::quickHelp() const {
+ return i18n("To start, shift-click on the place you want to duplicate from. Then you can start painting. An indication of where you are copying from will be displayed while drawing and moving the mouse.");
+}
+
+TQWidget* KisToolDuplicate::createOptionWidget(TQWidget* parent)
+{
+ TQWidget* widget = KisToolPaint::createOptionWidget(parent);
+ m_healing = new TQCheckBox(widget);
+ m_healing->setChecked( false);
+ addOptionWidgetOption(m_healing, new TQLabel(i18n("Healing"), widget ));
+ m_healingRadius = new KIntNumInput(widget);
+
+ KisBrush *brush = m_subject->currentBrush();
+ int healingradius = 20;
+ if( brush )
+ {
+ healingradius = 2 * TQMAX(brush->width(),brush->height());
+ }
+
+ m_healingRadius->setValue( healingradius );
+ addOptionWidgetOption(m_healingRadius, new TQLabel(i18n("Healing radius"), widget ));
+ m_perspectiveCorrection = new TQCheckBox(widget);
+ addOptionWidgetOption(m_perspectiveCorrection, new TQLabel(i18n("Correct the perspective"), widget ));
+ return widget;
+}
+
+#include "kis_tool_duplicate.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cc b/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cc
deleted file mode 100644
index 919454b26..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * kis_tool_ellipse.cc - part of Krayon
- *
- * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2004 Clarence Dang <dang@kde.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqpainter.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-
-#include "kis_painter.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_tool_ellipse.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_undo_adapter.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-
-KisToolEllipse::KisToolEllipse()
- : super(i18n ("Ellipse")),
- m_dragging (false),
- m_currentImage (0)
-{
- setName("tool_ellipse");
- setCursor(KisCursor::load("tool_ellipse_cursor.png", 6, 6));
-}
-
-KisToolEllipse::~KisToolEllipse()
-{
-}
-
-void KisToolEllipse::update (KisCanvasSubject *subject)
-{
- super::update (subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg ();
-}
-
-void KisToolEllipse::buttonPress(KisButtonPressEvent *event)
-{
- if (m_currentImage && event->button() == Qt::LeftButton) {
- m_dragging = true;
- m_dragStart = m_dragCenter = m_dragEnd = event->pos();
- draw(m_dragStart, m_dragEnd);
- }
-}
-
-void KisToolEllipse::move(KisMoveEvent *event)
-{
- if (m_dragging) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- // move (alt) or resize ellipse
- if (event->state() & TQt::AltButton) {
- KisPoint trans = event->pos() - m_dragEnd;
- m_dragStart += trans;
- m_dragEnd += trans;
- } else {
- KisPoint diag = event->pos() - (event->state() & TQt::ControlButton
- ? m_dragCenter : m_dragStart);
- // circle?
- if (event->state() & TQt::ShiftButton) {
- double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
- double w = diag.x() < 0 ? -size : size;
- double h = diag.y() < 0 ? -size : size;
- diag = KisPoint(w, h);
- }
-
- // resize around center point?
- if (event->state() & TQt::ControlButton) {
- m_dragStart = m_dragCenter - diag;
- m_dragEnd = m_dragCenter + diag;
- } else {
- m_dragEnd = m_dragStart + diag;
- }
- }
- // draw new lines on canvas
- draw(m_dragStart, m_dragEnd);
- m_dragCenter = KisPoint((m_dragStart.x() + m_dragEnd.x()) / 2,
- (m_dragStart.y() + m_dragEnd.y()) / 2);
- }
-}
-
-void KisToolEllipse::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- if (m_dragging && event->button() == Qt::LeftButton) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- m_dragging = false;
-
- if (m_dragStart == m_dragEnd)
- return;
-
- if (!m_currentImage)
- return;
-
- if (!m_currentImage->activeDevice())
- return;
-
- KisPaintDeviceSP device = m_currentImage->activeDevice ();
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (i18n ("Ellipse"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBackgroundColor(m_subject->bgColor());
- painter.setFillStyle(fillStyle());
- painter.setBrush(m_subject->currentBrush());
- painter.setPattern(m_subject->currentPattern());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op); // Painter takes ownership
-
- painter.paintEllipse(m_dragStart, m_dragEnd, PRESSURE_DEFAULT/*event->pressure()*/, event->xTilt(), event->yTilt());
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- KisUndoAdapter *adapter = m_currentImage->undoAdapter();
- if (adapter) {
- adapter->addCommand(painter.endTransaction());
- }
- }
-}
-
-void KisToolEllipse::draw(const KisPoint& start, const KisPoint& end )
-{
- if (!m_subject || !m_currentImage)
- return;
-
- KisCanvasController *controller = m_subject->canvasController ();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter p (canvas);
-
- p.setRasterOp (TQt::NotROP);
- p.drawEllipse (TQRect (controller->windowToView (start).floorTQPoint(), controller->windowToView (end).floorTQPoint()));
- p.end ();
-}
-
-void KisToolEllipse::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F7));
- m_action = new TDERadioAction(i18n("&Ellipse"),
- "tool_ellipse",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- m_action->setToolTip(i18n("Draw an ellipse"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_ellipse.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cpp b/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cpp
new file mode 100644
index 000000000..0488dcb05
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_ellipse.cpp
@@ -0,0 +1,186 @@
+/*
+ * kis_tool_ellipse.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2004 Clarence Dang <dang@kde.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqpainter.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+
+#include "kis_painter.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_tool_ellipse.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_undo_adapter.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+
+KisToolEllipse::KisToolEllipse()
+ : super(i18n ("Ellipse")),
+ m_dragging (false),
+ m_currentImage (0)
+{
+ setName("tool_ellipse");
+ setCursor(KisCursor::load("tool_ellipse_cursor.png", 6, 6));
+}
+
+KisToolEllipse::~KisToolEllipse()
+{
+}
+
+void KisToolEllipse::update (KisCanvasSubject *subject)
+{
+ super::update (subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg ();
+}
+
+void KisToolEllipse::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_currentImage && event->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_dragStart = m_dragCenter = m_dragEnd = event->pos();
+ draw(m_dragStart, m_dragEnd);
+ }
+}
+
+void KisToolEllipse::move(KisMoveEvent *event)
+{
+ if (m_dragging) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ // move (alt) or resize ellipse
+ if (event->state() & TQt::AltButton) {
+ KisPoint trans = event->pos() - m_dragEnd;
+ m_dragStart += trans;
+ m_dragEnd += trans;
+ } else {
+ KisPoint diag = event->pos() - (event->state() & TQt::ControlButton
+ ? m_dragCenter : m_dragStart);
+ // circle?
+ if (event->state() & TQt::ShiftButton) {
+ double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
+ double w = diag.x() < 0 ? -size : size;
+ double h = diag.y() < 0 ? -size : size;
+ diag = KisPoint(w, h);
+ }
+
+ // resize around center point?
+ if (event->state() & TQt::ControlButton) {
+ m_dragStart = m_dragCenter - diag;
+ m_dragEnd = m_dragCenter + diag;
+ } else {
+ m_dragEnd = m_dragStart + diag;
+ }
+ }
+ // draw new lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ m_dragCenter = KisPoint((m_dragStart.x() + m_dragEnd.x()) / 2,
+ (m_dragStart.y() + m_dragEnd.y()) / 2);
+ }
+}
+
+void KisToolEllipse::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ m_dragging = false;
+
+ if (m_dragStart == m_dragEnd)
+ return;
+
+ if (!m_currentImage)
+ return;
+
+ if (!m_currentImage->activeDevice())
+ return;
+
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (i18n ("Ellipse"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBackgroundColor(m_subject->bgColor());
+ painter.setFillStyle(fillStyle());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setPattern(m_subject->currentPattern());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op); // Painter takes ownership
+
+ painter.paintEllipse(m_dragStart, m_dragEnd, PRESSURE_DEFAULT/*event->pressure()*/, event->xTilt(), event->yTilt());
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ KisUndoAdapter *adapter = m_currentImage->undoAdapter();
+ if (adapter) {
+ adapter->addCommand(painter.endTransaction());
+ }
+ }
+}
+
+void KisToolEllipse::draw(const KisPoint& start, const KisPoint& end )
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ KisCanvasController *controller = m_subject->canvasController ();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter p (canvas);
+
+ p.setRasterOp (TQt::NotROP);
+ p.drawEllipse (TQRect (controller->windowToView (start).floorTQPoint(), controller->windowToView (end).floorTQPoint()));
+ p.end ();
+}
+
+void KisToolEllipse::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F7));
+ m_action = new TDERadioAction(i18n("&Ellipse"),
+ "tool_ellipse",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ m_action->setToolTip(i18n("Draw an ellipse"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_ellipse.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_fill.cc b/chalk/plugins/tools/defaulttools/kis_tool_fill.cc
deleted file mode 100644
index df8e4f7c5..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_fill.cc
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * kis_tool_fill.cc - part of Krayon
- *
- * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kcommand.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqcheckbox.h>
-
-#include <tqcolor.h>
-
-#include "knuminput.h"
-
-#include "kis_layer.h"
-#include "kis_cursor.h"
-#include "kis_painter.h"
-#include "kis_tool_brush.h"
-#include "kis_cmb_composite.h"
-#include "kis_tool_fill.h"
-#include "kis_colorspace.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_pattern.h"
-#include "kis_fill_painter.h"
-#include "kis_progress_display_interface.h"
-#include "kis_undo_adapter.h"
-#include "kis_canvas_subject.h"
-#include "kis_selection.h"
-
-KisToolFill::KisToolFill()
- : super(i18n("Fill")), m_wasPressed(false)
-{
- setName("tool_fill");
- m_subject = 0;
- m_oldColor = 0;
- m_threshold = 15;
- m_usePattern = false;
- m_unmerged = false;
- m_fillOnlySelection = false;
-
- setCursor(KisCursor::load("tool_fill_cursor.png", 6, 6));
-}
-
-void KisToolFill::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- m_currentImage = subject->currentImg();
-
- super::update(m_subject);
-}
-
-KisToolFill::~KisToolFill()
-{
-}
-
-bool KisToolFill::flood(int startX, int startY)
-{
- KisPaintDeviceSP device = m_currentImage->activeDevice();
- if (!device) return false;
-
- if (m_fillOnlySelection) {
- TQRect rc = device->selection()->selectedRect();
- KisPaintDeviceSP filled = new KisPaintDevice(device->colorSpace(), "filled");
- KisFillPainter painter(filled);
- if (m_usePattern)
- painter.fillRect(rc.x(), rc.y(), rc.width(), rc.height(),
- m_subject->currentPattern());
- else
- painter.fillRect(rc.x(), rc.y(), rc.width(), rc.height(),
- m_subject->fgColor(), m_opacity);
- painter.end();
- KisPainter painter2(device);
- if (m_currentImage->undo()) painter2.beginTransaction(i18n("Fill"));
- painter2.bltSelection(rc.x(), rc.y() , m_compositeOp, filled, m_opacity,
- rc.x(), rc.y(), rc.width(), rc.height());
-
- device->setDirty(filled->extent());
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter2.endTransaction());
- }
- return true;
- }
-
- KisFillPainter painter(device);
- if (m_currentImage->undo()) painter.beginTransaction(i18n("Flood Fill"));
- painter.setPaintColor(m_subject->fgColor());
- painter.setOpacity(m_opacity);
- painter.setFillThreshold(m_threshold);
- painter.setCompositeOp(m_compositeOp);
- painter.setPattern(m_subject->currentPattern());
- painter.setSampleMerged(!m_unmerged);
- painter.setCareForSelection(true);
-
- KisProgressDisplayInterface *progress = m_subject->progressDisplay();
- if (progress) {
- progress->setSubject(&painter, true, true);
- }
-
- if (m_usePattern)
- painter.fillPattern(startX, startY);
- else
- painter.fillColor(startX, startY);
-
- device->setDirty(painter.dirtyRect());
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
-
- return true;
-}
-
-void KisToolFill::buttonPress(KisButtonPressEvent *e)
-{
- m_startPos = e->pos();
- m_wasPressed = true;
-}
-
-void KisToolFill::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (!m_subject) return;
- if (!m_currentImage || !m_currentImage->activeDevice()) return;
- if (e->button() != Qt::LeftButton) return;
- if(!m_wasPressed) return;
- m_wasPressed = false;
- int x, y;
- x = m_startPos.floorX();
- y = m_startPos.floorY();
- if (!m_currentImage->bounds().contains(x, y)) {
- return;
- }
- flood(x, y);
- notifyModified();
-}
-
-TQWidget* KisToolFill::createOptionWidget(TQWidget* parent)
-{
- TQWidget *widget = super::createOptionWidget(parent);
-
- m_lbThreshold = new TQLabel(i18n("Threshold: "), widget);
- m_slThreshold = new KIntNumInput( widget, "int_widget");
- m_slThreshold->setRange( 1, 100);
- m_slThreshold->setSteps( 3, 3);
- m_slThreshold->setValue(m_threshold);
- connect(m_slThreshold, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotSetThreshold(int)));
-
- m_checkUsePattern = new TQCheckBox(i18n("Use pattern"), widget);
- m_checkUsePattern->setChecked(m_usePattern);
- connect(m_checkUsePattern, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetUsePattern(bool)));
-
- m_checkSampleMerged = new TQCheckBox(i18n("Limit to current layer"), widget);
- m_checkSampleMerged->setChecked(m_unmerged);
- connect(m_checkSampleMerged, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetSampleMerged(bool)));
-
- m_checkFillSelection = new TQCheckBox(i18n("Fill entire selection"), widget);
- m_checkFillSelection->setChecked(m_fillOnlySelection);
- connect(m_checkFillSelection, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetFillSelection(bool)));
-
- addOptionWidgetOption(m_slThreshold, m_lbThreshold);
-
- addOptionWidgetOption(m_checkFillSelection);
- addOptionWidgetOption(m_checkSampleMerged);
- addOptionWidgetOption(m_checkUsePattern);
-
- return widget;
-}
-
-void KisToolFill::slotSetThreshold(int threshold)
-{
- m_threshold = threshold;
-}
-
-void KisToolFill::slotSetUsePattern(bool state)
-{
- m_usePattern = state;
-}
-
-void KisToolFill::slotSetSampleMerged(bool state)
-{
- m_unmerged = state;
-}
-
-void KisToolFill::slotSetFillSelection(bool state)
-{
- m_fillOnlySelection = state;
- m_slThreshold->setEnabled(!state);
- m_checkSampleMerged->setEnabled(!state);
-}
-
-void KisToolFill::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Fill"),
- "tool_color_fill",
- TQt::Key_F,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- m_action->setToolTip(i18n("Contiguous fill"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_fill.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_fill.cpp b/chalk/plugins/tools/defaulttools/kis_tool_fill.cpp
new file mode 100644
index 000000000..ceb78f06b
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_fill.cpp
@@ -0,0 +1,233 @@
+/*
+ * kis_tool_fill.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kcommand.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqcheckbox.h>
+
+#include <tqcolor.h>
+
+#include "knuminput.h"
+
+#include "kis_layer.h"
+#include "kis_cursor.h"
+#include "kis_painter.h"
+#include "kis_tool_brush.h"
+#include "kis_cmb_composite.h"
+#include "kis_tool_fill.h"
+#include "kis_colorspace.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_pattern.h"
+#include "kis_fill_painter.h"
+#include "kis_progress_display_interface.h"
+#include "kis_undo_adapter.h"
+#include "kis_canvas_subject.h"
+#include "kis_selection.h"
+
+KisToolFill::KisToolFill()
+ : super(i18n("Fill")), m_wasPressed(false)
+{
+ setName("tool_fill");
+ m_subject = 0;
+ m_oldColor = 0;
+ m_threshold = 15;
+ m_usePattern = false;
+ m_unmerged = false;
+ m_fillOnlySelection = false;
+
+ setCursor(KisCursor::load("tool_fill_cursor.png", 6, 6));
+}
+
+void KisToolFill::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ m_currentImage = subject->currentImg();
+
+ super::update(m_subject);
+}
+
+KisToolFill::~KisToolFill()
+{
+}
+
+bool KisToolFill::flood(int startX, int startY)
+{
+ KisPaintDeviceSP device = m_currentImage->activeDevice();
+ if (!device) return false;
+
+ if (m_fillOnlySelection) {
+ TQRect rc = device->selection()->selectedRect();
+ KisPaintDeviceSP filled = new KisPaintDevice(device->colorSpace(), "filled");
+ KisFillPainter painter(filled);
+ if (m_usePattern)
+ painter.fillRect(rc.x(), rc.y(), rc.width(), rc.height(),
+ m_subject->currentPattern());
+ else
+ painter.fillRect(rc.x(), rc.y(), rc.width(), rc.height(),
+ m_subject->fgColor(), m_opacity);
+ painter.end();
+ KisPainter painter2(device);
+ if (m_currentImage->undo()) painter2.beginTransaction(i18n("Fill"));
+ painter2.bltSelection(rc.x(), rc.y() , m_compositeOp, filled, m_opacity,
+ rc.x(), rc.y(), rc.width(), rc.height());
+
+ device->setDirty(filled->extent());
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter2.endTransaction());
+ }
+ return true;
+ }
+
+ KisFillPainter painter(device);
+ if (m_currentImage->undo()) painter.beginTransaction(i18n("Flood Fill"));
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setOpacity(m_opacity);
+ painter.setFillThreshold(m_threshold);
+ painter.setCompositeOp(m_compositeOp);
+ painter.setPattern(m_subject->currentPattern());
+ painter.setSampleMerged(!m_unmerged);
+ painter.setCareForSelection(true);
+
+ KisProgressDisplayInterface *progress = m_subject->progressDisplay();
+ if (progress) {
+ progress->setSubject(&painter, true, true);
+ }
+
+ if (m_usePattern)
+ painter.fillPattern(startX, startY);
+ else
+ painter.fillColor(startX, startY);
+
+ device->setDirty(painter.dirtyRect());
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+
+ return true;
+}
+
+void KisToolFill::buttonPress(KisButtonPressEvent *e)
+{
+ m_startPos = e->pos();
+ m_wasPressed = true;
+}
+
+void KisToolFill::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (!m_subject) return;
+ if (!m_currentImage || !m_currentImage->activeDevice()) return;
+ if (e->button() != Qt::LeftButton) return;
+ if(!m_wasPressed) return;
+ m_wasPressed = false;
+ int x, y;
+ x = m_startPos.floorX();
+ y = m_startPos.floorY();
+ if (!m_currentImage->bounds().contains(x, y)) {
+ return;
+ }
+ flood(x, y);
+ notifyModified();
+}
+
+TQWidget* KisToolFill::createOptionWidget(TQWidget* parent)
+{
+ TQWidget *widget = super::createOptionWidget(parent);
+
+ m_lbThreshold = new TQLabel(i18n("Threshold: "), widget);
+ m_slThreshold = new KIntNumInput( widget, "int_widget");
+ m_slThreshold->setRange( 1, 100);
+ m_slThreshold->setSteps( 3, 3);
+ m_slThreshold->setValue(m_threshold);
+ connect(m_slThreshold, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotSetThreshold(int)));
+
+ m_checkUsePattern = new TQCheckBox(i18n("Use pattern"), widget);
+ m_checkUsePattern->setChecked(m_usePattern);
+ connect(m_checkUsePattern, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetUsePattern(bool)));
+
+ m_checkSampleMerged = new TQCheckBox(i18n("Limit to current layer"), widget);
+ m_checkSampleMerged->setChecked(m_unmerged);
+ connect(m_checkSampleMerged, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetSampleMerged(bool)));
+
+ m_checkFillSelection = new TQCheckBox(i18n("Fill entire selection"), widget);
+ m_checkFillSelection->setChecked(m_fillOnlySelection);
+ connect(m_checkFillSelection, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetFillSelection(bool)));
+
+ addOptionWidgetOption(m_slThreshold, m_lbThreshold);
+
+ addOptionWidgetOption(m_checkFillSelection);
+ addOptionWidgetOption(m_checkSampleMerged);
+ addOptionWidgetOption(m_checkUsePattern);
+
+ return widget;
+}
+
+void KisToolFill::slotSetThreshold(int threshold)
+{
+ m_threshold = threshold;
+}
+
+void KisToolFill::slotSetUsePattern(bool state)
+{
+ m_usePattern = state;
+}
+
+void KisToolFill::slotSetSampleMerged(bool state)
+{
+ m_unmerged = state;
+}
+
+void KisToolFill::slotSetFillSelection(bool state)
+{
+ m_fillOnlySelection = state;
+ m_slThreshold->setEnabled(!state);
+ m_checkSampleMerged->setEnabled(!state);
+}
+
+void KisToolFill::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Fill"),
+ "tool_color_fill",
+ TQt::Key_F,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ m_action->setToolTip(i18n("Contiguous fill"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_fill.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_gradient.cc b/chalk/plugins/tools/defaulttools/kis_tool_gradient.cc
deleted file mode 100644
index a46fee808..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_gradient.cc
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * kis_tool_gradient.cc - part of Chalk
- *
- * Copyright (c) 2000 John Califf
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2003 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqpainter.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqcheckbox.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_canvas_subject.h"
-#include "kis_cmb_composite.h"
-#include "kis_cursor.h"
-#include "kis_double_widget.h"
-#include "kis_gradient_painter.h"
-#include "kis_move_event.h"
-#include "kis_painter.h"
-#include "kis_progress_display_interface.h"
-#include "kis_tool_gradient.h"
-#include "kis_undo_adapter.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-KisToolGradient::KisToolGradient()
- : super(i18n("Gradient")),
- m_dragging( false )
-{
- setName("tool_gradient");
- setCursor(KisCursor::load("tool_gradient_cursor.png", 6, 6));
-
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
-
- m_reverse = false;
- m_shape = KisGradientPainter::GradientShapeLinear;
- m_repeat = KisGradientPainter::GradientRepeatNone;
- m_antiAliasThreshold = 0.2;
-}
-
-KisToolGradient::~KisToolGradient()
-{
-}
-
-void KisToolGradient::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- super::update(m_subject);
-}
-
-void KisToolGradient::paint(KisCanvasPainter& gc)
-{
- if (m_dragging)
- paintLine(gc);
-}
-
-void KisToolGradient::paint(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_dragging)
- paintLine(gc);
-}
-
-void KisToolGradient::buttonPress(KisButtonPressEvent *e)
-{
- if (!m_subject || !m_subject->currentImg()) {
- return;
- }
-
- if (e->button() == Qt::LeftButton) {
- m_dragging = true;
- m_startPos = e->pos();
- m_endPos = e->pos();
- }
-}
-
-void KisToolGradient::move(KisMoveEvent *e)
-{
- if (m_dragging) {
- if (m_startPos != m_endPos) {
- paintLine();
- }
-
- if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
- m_endPos = straightLine(e->pos());
- }
- else {
- m_endPos = e->pos();
- }
-
- paintLine();
- }
-}
-
-void KisToolGradient::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_dragging && e->button() == Qt::LeftButton) {
-
- KisCanvasController *controller = m_subject->canvasController();
- KisImageSP img = m_subject->currentImg();
-
- m_dragging = false;
-
- if (m_startPos == m_endPos) {
- controller->updateCanvas();
- m_dragging = false;
- return;
- }
-
- if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
- m_endPos = straightLine(e->pos());
- }
- else {
- m_endPos = e->pos();
- }
-
- KisPaintDeviceSP device;
-
- if (img && (device = img->activeDevice())) {
-
- KisGradientPainter painter(device);
-
- if (img->undo()) painter.beginTransaction(i18n("Gradient"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setGradient(*(m_subject->currentGradient()));
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
-
- KisProgressDisplayInterface *progress = m_subject->progressDisplay();
-
- if (progress) {
- progress->setSubject(&painter, true, true);
- }
-
- bool painted = painter.paintGradient(m_startPos, m_endPos, m_shape, m_repeat, m_antiAliasThreshold, m_reverse, 0, 0, m_subject->currentImg()->width(), m_subject->currentImg()->height());
-
- if (painted) {
- // does whole thing at moment
- device->setDirty(painter.dirtyRect());
-
- notifyModified();
-
- if (img->undo()) {
- img->undoAdapter()->addCommand(painter.endTransaction());
- }
- }
-
- /* remove remains of the line drawn while moving */
- if (controller->kiscanvas()) {
- controller->kiscanvas()->update();
- }
-
- }
- }
-}
-
-KisPoint KisToolGradient::straightLine(KisPoint point)
-{
- KisPoint comparison = point - m_startPos;
- KisPoint result;
-
- if ( fabs(comparison.x()) > fabs(comparison.y())) {
- result.setX(point.x());
- result.setY(m_startPos.y());
- } else {
- result.setX( m_startPos.x() );
- result.setY( point.y() );
- }
-
- return result;
-}
-
-void KisToolGradient::paintLine()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
-
- paintLine(gc);
- }
-}
-
-void KisToolGradient::paintLine(KisCanvasPainter& gc)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
-
- KisPoint start = controller->windowToView(m_startPos);
- KisPoint end = controller->windowToView(m_endPos);
-
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::SolidLine);
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawLine(start.floorTQPoint(), end.floorTQPoint());
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-TQWidget* KisToolGradient::createOptionWidget(TQWidget* parent)
-{
- TQWidget *widget = super::createOptionWidget(parent);
- TQ_CHECK_PTR(widget);
-
- m_lbShape = new TQLabel(i18n("Shape:"), widget);
- m_lbRepeat = new TQLabel(i18n("Repeat:"), widget);
-
- m_ckReverse = new TQCheckBox(i18n("Reverse"), widget, "reverse_check");
- connect(m_ckReverse, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetReverse(bool)));
-
- m_cmbShape = new TQComboBox(false, widget, "shape_combo");
- connect(m_cmbShape, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotSetShape(int)));
- m_cmbShape->insertItem(i18n("Linear"));
- m_cmbShape->insertItem(i18n("Bi-Linear"));
- m_cmbShape->insertItem(i18n("Radial"));
- m_cmbShape->insertItem(i18n("Square"));
- m_cmbShape->insertItem(i18n("Conical"));
- m_cmbShape->insertItem(i18n("Conical Symmetric"));
-
- m_cmbRepeat = new TQComboBox(false, widget, "repeat_combo");
- connect(m_cmbRepeat, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotSetRepeat(int)));
- m_cmbRepeat->insertItem(i18n("None"));
- m_cmbRepeat->insertItem(i18n("Forwards"));
- m_cmbRepeat->insertItem(i18n("Alternating"));
-
- addOptionWidgetOption(m_cmbShape, m_lbShape);
-
- addOptionWidgetOption(m_cmbRepeat, m_lbRepeat);
-
- addOptionWidgetOption(m_ckReverse);
-
- m_lbAntiAliasThreshold = new TQLabel(i18n("Anti-alias threshold:"), widget);
-
- m_slAntiAliasThreshold = new KDoubleNumInput(widget, "threshold_slider");
- m_slAntiAliasThreshold->setRange( 0, 1);
- m_slAntiAliasThreshold->setValue(m_antiAliasThreshold);
- connect(m_slAntiAliasThreshold, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(slotSetAntiAliasThreshold(double)));
-
- addOptionWidgetOption(m_slAntiAliasThreshold, m_lbAntiAliasThreshold);
-
- return widget;
-}
-
-void KisToolGradient::slotSetShape(int shape)
-{
- m_shape = static_cast<KisGradientPainter::enumGradientShape>(shape);
-}
-
-void KisToolGradient::slotSetRepeat(int repeat)
-{
- m_repeat = static_cast<KisGradientPainter::enumGradientRepeat>(repeat);
-}
-
-void KisToolGradient::slotSetReverse(bool state)
-{
- m_reverse = state;
-}
-
-void KisToolGradient::slotSetAntiAliasThreshold(double value)
-{
- m_antiAliasThreshold = value;
-}
-
-void KisToolGradient::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Gradient"),
- "tool_gradient", TQt::Key_G, this,
- TQT_SLOT(activate()), collection,
- name());
- m_action->setToolTip(i18n("Draw a gradient"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_gradient.moc"
-
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_gradient.cpp b/chalk/plugins/tools/defaulttools/kis_tool_gradient.cpp
new file mode 100644
index 000000000..b8f72a3bb
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_gradient.cpp
@@ -0,0 +1,309 @@
+/*
+ * kis_tool_gradient.cpp - part of Chalk
+ *
+ * Copyright (c) 2000 John Califf
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2003 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqpainter.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqcheckbox.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_canvas_subject.h"
+#include "kis_cmb_composite.h"
+#include "kis_cursor.h"
+#include "kis_double_widget.h"
+#include "kis_gradient_painter.h"
+#include "kis_move_event.h"
+#include "kis_painter.h"
+#include "kis_progress_display_interface.h"
+#include "kis_tool_gradient.h"
+#include "kis_undo_adapter.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+KisToolGradient::KisToolGradient()
+ : super(i18n("Gradient")),
+ m_dragging( false )
+{
+ setName("tool_gradient");
+ setCursor(KisCursor::load("tool_gradient_cursor.png", 6, 6));
+
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+
+ m_reverse = false;
+ m_shape = KisGradientPainter::GradientShapeLinear;
+ m_repeat = KisGradientPainter::GradientRepeatNone;
+ m_antiAliasThreshold = 0.2;
+}
+
+KisToolGradient::~KisToolGradient()
+{
+}
+
+void KisToolGradient::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ super::update(m_subject);
+}
+
+void KisToolGradient::paint(KisCanvasPainter& gc)
+{
+ if (m_dragging)
+ paintLine(gc);
+}
+
+void KisToolGradient::paint(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_dragging)
+ paintLine(gc);
+}
+
+void KisToolGradient::buttonPress(KisButtonPressEvent *e)
+{
+ if (!m_subject || !m_subject->currentImg()) {
+ return;
+ }
+
+ if (e->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_startPos = e->pos();
+ m_endPos = e->pos();
+ }
+}
+
+void KisToolGradient::move(KisMoveEvent *e)
+{
+ if (m_dragging) {
+ if (m_startPos != m_endPos) {
+ paintLine();
+ }
+
+ if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
+ m_endPos = straightLine(e->pos());
+ }
+ else {
+ m_endPos = e->pos();
+ }
+
+ paintLine();
+ }
+}
+
+void KisToolGradient::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_dragging && e->button() == Qt::LeftButton) {
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisImageSP img = m_subject->currentImg();
+
+ m_dragging = false;
+
+ if (m_startPos == m_endPos) {
+ controller->updateCanvas();
+ m_dragging = false;
+ return;
+ }
+
+ if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
+ m_endPos = straightLine(e->pos());
+ }
+ else {
+ m_endPos = e->pos();
+ }
+
+ KisPaintDeviceSP device;
+
+ if (img && (device = img->activeDevice())) {
+
+ KisGradientPainter painter(device);
+
+ if (img->undo()) painter.beginTransaction(i18n("Gradient"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setGradient(*(m_subject->currentGradient()));
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+
+ KisProgressDisplayInterface *progress = m_subject->progressDisplay();
+
+ if (progress) {
+ progress->setSubject(&painter, true, true);
+ }
+
+ bool painted = painter.paintGradient(m_startPos, m_endPos, m_shape, m_repeat, m_antiAliasThreshold, m_reverse, 0, 0, m_subject->currentImg()->width(), m_subject->currentImg()->height());
+
+ if (painted) {
+ // does whole thing at moment
+ device->setDirty(painter.dirtyRect());
+
+ notifyModified();
+
+ if (img->undo()) {
+ img->undoAdapter()->addCommand(painter.endTransaction());
+ }
+ }
+
+ /* remove remains of the line drawn while moving */
+ if (controller->kiscanvas()) {
+ controller->kiscanvas()->update();
+ }
+
+ }
+ }
+}
+
+KisPoint KisToolGradient::straightLine(KisPoint point)
+{
+ KisPoint comparison = point - m_startPos;
+ KisPoint result;
+
+ if ( fabs(comparison.x()) > fabs(comparison.y())) {
+ result.setX(point.x());
+ result.setY(m_startPos.y());
+ } else {
+ result.setX( m_startPos.x() );
+ result.setY( point.y() );
+ }
+
+ return result;
+}
+
+void KisToolGradient::paintLine()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+
+ paintLine(gc);
+ }
+}
+
+void KisToolGradient::paintLine(KisCanvasPainter& gc)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+
+ KisPoint start = controller->windowToView(m_startPos);
+ KisPoint end = controller->windowToView(m_endPos);
+
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::SolidLine);
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawLine(start.floorTQPoint(), end.floorTQPoint());
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+TQWidget* KisToolGradient::createOptionWidget(TQWidget* parent)
+{
+ TQWidget *widget = super::createOptionWidget(parent);
+ TQ_CHECK_PTR(widget);
+
+ m_lbShape = new TQLabel(i18n("Shape:"), widget);
+ m_lbRepeat = new TQLabel(i18n("Repeat:"), widget);
+
+ m_ckReverse = new TQCheckBox(i18n("Reverse"), widget, "reverse_check");
+ connect(m_ckReverse, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetReverse(bool)));
+
+ m_cmbShape = new TQComboBox(false, widget, "shape_combo");
+ connect(m_cmbShape, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotSetShape(int)));
+ m_cmbShape->insertItem(i18n("Linear"));
+ m_cmbShape->insertItem(i18n("Bi-Linear"));
+ m_cmbShape->insertItem(i18n("Radial"));
+ m_cmbShape->insertItem(i18n("Square"));
+ m_cmbShape->insertItem(i18n("Conical"));
+ m_cmbShape->insertItem(i18n("Conical Symmetric"));
+
+ m_cmbRepeat = new TQComboBox(false, widget, "repeat_combo");
+ connect(m_cmbRepeat, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotSetRepeat(int)));
+ m_cmbRepeat->insertItem(i18n("None"));
+ m_cmbRepeat->insertItem(i18n("Forwards"));
+ m_cmbRepeat->insertItem(i18n("Alternating"));
+
+ addOptionWidgetOption(m_cmbShape, m_lbShape);
+
+ addOptionWidgetOption(m_cmbRepeat, m_lbRepeat);
+
+ addOptionWidgetOption(m_ckReverse);
+
+ m_lbAntiAliasThreshold = new TQLabel(i18n("Anti-alias threshold:"), widget);
+
+ m_slAntiAliasThreshold = new KDoubleNumInput(widget, "threshold_slider");
+ m_slAntiAliasThreshold->setRange( 0, 1);
+ m_slAntiAliasThreshold->setValue(m_antiAliasThreshold);
+ connect(m_slAntiAliasThreshold, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(slotSetAntiAliasThreshold(double)));
+
+ addOptionWidgetOption(m_slAntiAliasThreshold, m_lbAntiAliasThreshold);
+
+ return widget;
+}
+
+void KisToolGradient::slotSetShape(int shape)
+{
+ m_shape = static_cast<KisGradientPainter::enumGradientShape>(shape);
+}
+
+void KisToolGradient::slotSetRepeat(int repeat)
+{
+ m_repeat = static_cast<KisGradientPainter::enumGradientRepeat>(repeat);
+}
+
+void KisToolGradient::slotSetReverse(bool state)
+{
+ m_reverse = state;
+}
+
+void KisToolGradient::slotSetAntiAliasThreshold(double value)
+{
+ m_antiAliasThreshold = value;
+}
+
+void KisToolGradient::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Gradient"),
+ "tool_gradient", TQt::Key_G, this,
+ TQT_SLOT(activate()), collection,
+ name());
+ m_action->setToolTip(i18n("Draw a gradient"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_gradient.moc"
+
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_line.cc b/chalk/plugins/tools/defaulttools/kis_tool_line.cc
deleted file mode 100644
index 4e118cccb..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_line.cc
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * kis_tool_line.cc - part of Krayon
- *
- * Copyright (c) 2000 John Califf
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2003 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqwidget.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_cursor.h"
-#include "kis_painter.h"
-#include "kis_tool_line.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas_subject.h"
-#include "kis_undo_adapter.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_layer.h"
-
-KisToolLine::KisToolLine()
- : super(i18n("Line")),
- m_dragging( false )
-{
- setName("tool_line");
- setCursor(KisCursor::load("tool_line_cursor.png", 6, 6));
-
- m_painter = 0;
- m_currentImage = 0;
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
-}
-
-KisToolLine::~KisToolLine()
-{
-}
-
-void KisToolLine::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- m_currentImage = subject->currentImg();
-
- super::update(m_subject);
-}
-
-
-void KisToolLine::paint(KisCanvasPainter& gc)
-{
- if (m_dragging)
- paintLine(gc, TQRect());
-}
-
-void KisToolLine::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- if (m_dragging)
- paintLine(gc, rc);
-}
-
-void KisToolLine::buttonPress(KisButtonPressEvent *e)
-{
- if (!m_subject || !m_currentImage) return;
-
- if (!m_subject->currentBrush()) return;
-
- if (e->button() == Qt::LeftButton) {
- m_dragging = true;
- //KisCanvasController *controller = m_subject->canvasController();
- m_startPos = e->pos(); //controller->windowToView(e->pos());
- m_endPos = e->pos(); //controller->windowToView(e->pos());
- }
-}
-
-void KisToolLine::move(KisMoveEvent *e)
-{
- if (m_dragging) {
- if (m_startPos != m_endPos)
- paintLine();
- //KisCanvasController *controller = m_subject->canvasController();
-
- if (e->state() & TQt::AltButton) {
- KisPoint trans = e->pos() - m_endPos;
- m_startPos += trans;
- m_endPos += trans;
- } else if (e->state() & TQt::ShiftButton)
- m_endPos = straightLine(e->pos());
- else
- m_endPos = e->pos();//controller->windowToView(e->pos());
- paintLine();
- }
-}
-
-void KisToolLine::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_dragging && e->button() == Qt::LeftButton) {
- m_dragging = false;
- KisCanvasController *controller = m_subject->canvasController();
- KisImageSP img = m_subject->currentImg();
-
- if (m_startPos == m_endPos) {
- controller->updateCanvas();
- m_dragging = false;
- return;
- }
-
- if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
- m_endPos = straightLine(e->pos());
- }
- else {
- m_endPos = e->pos();
- }
-
- KisPaintDeviceSP device;
- if (m_currentImage &&
- (device = m_currentImage->activeDevice()) &&
- m_subject &&
- m_subject->currentBrush())
- {
- delete m_painter;
- m_painter = new KisPainter( device );
- TQ_CHECK_PTR(m_painter);
-
- if (m_currentImage->undo()) m_painter->beginTransaction(i18n("Line"));
-
- m_painter->setPaintColor(m_subject->fgColor());
- m_painter->setBrush(m_subject->currentBrush());
- m_painter->setOpacity(m_opacity);
- m_painter->setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), m_painter);
- m_painter->setPaintOp(op); // Painter takes ownership
- m_painter->paintLine(m_startPos, PRESSURE_DEFAULT, 0, 0, m_endPos, PRESSURE_DEFAULT, 0, 0);
- device->setDirty( m_painter->dirtyRect() );
- notifyModified();
-
- /* remove remains of the line drawn while moving */
- if (controller->kiscanvas()) {
- controller->kiscanvas()->update();
- }
-
- if (m_currentImage->undo() && m_painter) {
- m_currentImage->undoAdapter()->addCommand(m_painter->endTransaction());
- }
- delete m_painter;
- m_painter = 0;
- } else {
- if (m_painter)
- controller->updateCanvas(m_painter->dirtyRect()); // Removes the last remaining line.
- }
- }
-
-}
-
-KisPoint KisToolLine::straightLine(KisPoint point)
-{
- KisPoint comparison = point - m_startPos;
- KisPoint result;
-
- if ( fabs(comparison.x()) > fabs(comparison.y())) {
- result.setX(point.x());
- result.setY(m_startPos.y());
- } else {
- result.setX( m_startPos.x() );
- result.setY( point.y() );
- }
-
- return result;
-}
-
-void KisToolLine::paintLine()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintLine(gc, rc);
- }
-}
-
-void KisToolLine::paintLine(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::SolidLine);
- KisPoint start;
- KisPoint end;
-
-// Q_ASSERT(controller);
- start = controller->windowToView(m_startPos);
- end = controller->windowToView(m_endPos);
-// start.setX(start.x() - controller->horzValue());
-// start.setY(start.y() - controller->vertValue());
-// end.setX(end.x() - controller->horzValue());
-// end.setY(end.y() - controller->vertValue());
-// end.setX((end.x() - start.x()));
-// end.setY((end.y() - start.y()));
-// start *= m_subject->zoomFactor();
-// end *= m_subject->zoomFactor();
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawLine(start.floorTQPoint(), end.floorTQPoint());
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolLine::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Line"),
- "tool_line", TQt::Key_L, this,
- TQT_SLOT(activate()), collection,
- name());
- m_action->setToolTip(i18n("Draw a line"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-TQString KisToolLine::quickHelp() const {
- return i18n("Alt+Drag will move the origin of the currently displayed line around, Shift+Drag will force you to draw straight lines");
-}
-
-#include "kis_tool_line.moc"
-
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_line.cpp b/chalk/plugins/tools/defaulttools/kis_tool_line.cpp
new file mode 100644
index 000000000..87cb93907
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_line.cpp
@@ -0,0 +1,254 @@
+/*
+ * kis_tool_line.cpp - part of Krayon
+ *
+ * Copyright (c) 2000 John Califf
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2003 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqwidget.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_cursor.h"
+#include "kis_painter.h"
+#include "kis_tool_line.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas_subject.h"
+#include "kis_undo_adapter.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_layer.h"
+
+KisToolLine::KisToolLine()
+ : super(i18n("Line")),
+ m_dragging( false )
+{
+ setName("tool_line");
+ setCursor(KisCursor::load("tool_line_cursor.png", 6, 6));
+
+ m_painter = 0;
+ m_currentImage = 0;
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+}
+
+KisToolLine::~KisToolLine()
+{
+}
+
+void KisToolLine::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ m_currentImage = subject->currentImg();
+
+ super::update(m_subject);
+}
+
+
+void KisToolLine::paint(KisCanvasPainter& gc)
+{
+ if (m_dragging)
+ paintLine(gc, TQRect());
+}
+
+void KisToolLine::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ if (m_dragging)
+ paintLine(gc, rc);
+}
+
+void KisToolLine::buttonPress(KisButtonPressEvent *e)
+{
+ if (!m_subject || !m_currentImage) return;
+
+ if (!m_subject->currentBrush()) return;
+
+ if (e->button() == Qt::LeftButton) {
+ m_dragging = true;
+ //KisCanvasController *controller = m_subject->canvasController();
+ m_startPos = e->pos(); //controller->windowToView(e->pos());
+ m_endPos = e->pos(); //controller->windowToView(e->pos());
+ }
+}
+
+void KisToolLine::move(KisMoveEvent *e)
+{
+ if (m_dragging) {
+ if (m_startPos != m_endPos)
+ paintLine();
+ //KisCanvasController *controller = m_subject->canvasController();
+
+ if (e->state() & TQt::AltButton) {
+ KisPoint trans = e->pos() - m_endPos;
+ m_startPos += trans;
+ m_endPos += trans;
+ } else if (e->state() & TQt::ShiftButton)
+ m_endPos = straightLine(e->pos());
+ else
+ m_endPos = e->pos();//controller->windowToView(e->pos());
+ paintLine();
+ }
+}
+
+void KisToolLine::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_dragging && e->button() == Qt::LeftButton) {
+ m_dragging = false;
+ KisCanvasController *controller = m_subject->canvasController();
+ KisImageSP img = m_subject->currentImg();
+
+ if (m_startPos == m_endPos) {
+ controller->updateCanvas();
+ m_dragging = false;
+ return;
+ }
+
+ if ((e->state() & TQt::ShiftButton) == TQt::ShiftButton) {
+ m_endPos = straightLine(e->pos());
+ }
+ else {
+ m_endPos = e->pos();
+ }
+
+ KisPaintDeviceSP device;
+ if (m_currentImage &&
+ (device = m_currentImage->activeDevice()) &&
+ m_subject &&
+ m_subject->currentBrush())
+ {
+ delete m_painter;
+ m_painter = new KisPainter( device );
+ TQ_CHECK_PTR(m_painter);
+
+ if (m_currentImage->undo()) m_painter->beginTransaction(i18n("Line"));
+
+ m_painter->setPaintColor(m_subject->fgColor());
+ m_painter->setBrush(m_subject->currentBrush());
+ m_painter->setOpacity(m_opacity);
+ m_painter->setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), m_painter);
+ m_painter->setPaintOp(op); // Painter takes ownership
+ m_painter->paintLine(m_startPos, PRESSURE_DEFAULT, 0, 0, m_endPos, PRESSURE_DEFAULT, 0, 0);
+ device->setDirty( m_painter->dirtyRect() );
+ notifyModified();
+
+ /* remove remains of the line drawn while moving */
+ if (controller->kiscanvas()) {
+ controller->kiscanvas()->update();
+ }
+
+ if (m_currentImage->undo() && m_painter) {
+ m_currentImage->undoAdapter()->addCommand(m_painter->endTransaction());
+ }
+ delete m_painter;
+ m_painter = 0;
+ } else {
+ if (m_painter)
+ controller->updateCanvas(m_painter->dirtyRect()); // Removes the last remaining line.
+ }
+ }
+
+}
+
+KisPoint KisToolLine::straightLine(KisPoint point)
+{
+ KisPoint comparison = point - m_startPos;
+ KisPoint result;
+
+ if ( fabs(comparison.x()) > fabs(comparison.y())) {
+ result.setX(point.x());
+ result.setY(m_startPos.y());
+ } else {
+ result.setX( m_startPos.x() );
+ result.setY( point.y() );
+ }
+
+ return result;
+}
+
+void KisToolLine::paintLine()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintLine(gc, rc);
+ }
+}
+
+void KisToolLine::paintLine(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::SolidLine);
+ KisPoint start;
+ KisPoint end;
+
+// Q_ASSERT(controller);
+ start = controller->windowToView(m_startPos);
+ end = controller->windowToView(m_endPos);
+// start.setX(start.x() - controller->horzValue());
+// start.setY(start.y() - controller->vertValue());
+// end.setX(end.x() - controller->horzValue());
+// end.setY(end.y() - controller->vertValue());
+// end.setX((end.x() - start.x()));
+// end.setY((end.y() - start.y()));
+// start *= m_subject->zoomFactor();
+// end *= m_subject->zoomFactor();
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawLine(start.floorTQPoint(), end.floorTQPoint());
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolLine::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Line"),
+ "tool_line", TQt::Key_L, this,
+ TQT_SLOT(activate()), collection,
+ name());
+ m_action->setToolTip(i18n("Draw a line"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+TQString KisToolLine::quickHelp() const {
+ return i18n("Alt+Drag will move the origin of the currently displayed line around, Shift+Drag will force you to draw straight lines");
+}
+
+#include "kis_tool_line.moc"
+
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_move.cc b/chalk/plugins/tools/defaulttools/kis_tool_move.cpp
index be5065784..be5065784 100644
--- a/chalk/plugins/tools/defaulttools/kis_tool_move.cc
+++ b/chalk/plugins/tools/defaulttools/kis_tool_move.cpp
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_pan.cc b/chalk/plugins/tools/defaulttools/kis_tool_pan.cpp
index c95b10000..c95b10000 100644
--- a/chalk/plugins/tools/defaulttools/kis_tool_pan.cc
+++ b/chalk/plugins/tools/defaulttools/kis_tool_pan.cpp
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cc b/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cc
deleted file mode 100644
index 852d2c0e0..000000000
--- a/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cc
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * kis_tool_rectangle.cc - part of Chalk
- *
- * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2004 Clarence Dang <dang@k.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqpainter.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_canvas_controller.h"
-#include "kis_canvas_subject.h"
-#include "kis_move_event.h"
-#include "kis_painter.h"
-#include "kis_paintop_registry.h"
-#include "kis_tool_rectangle.h"
-#include "kis_undo_adapter.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_layer.h"
-
-KisToolRectangle::KisToolRectangle()
- : super(i18n ("Rectangle")),
- m_dragging (false),
- m_currentImage (0)
-{
- setName("tool_rectangle");
- setCursor(KisCursor::load("tool_rectangle_cursor.png", 6, 6));
-}
-
-KisToolRectangle::~KisToolRectangle()
-{
-}
-
-void KisToolRectangle::update (KisCanvasSubject *subject)
-{
- super::update (subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg ();
-}
-
-void KisToolRectangle::buttonPress(KisButtonPressEvent *event)
-{
- if (m_currentImage && event->button() == Qt::LeftButton) {
- m_dragging = true;
- m_dragStart = m_dragCenter = m_dragEnd = event->pos();
- draw(m_dragStart, m_dragEnd);
- }
-}
-
-void KisToolRectangle::move(KisMoveEvent *event)
-{
- if (m_dragging) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- // move (alt) or resize rectangle
- if (event->state() & TQt::AltButton) {
- KisPoint trans = event->pos() - m_dragEnd;
- m_dragStart += trans;
- m_dragEnd += trans;
- } else {
- KisPoint diag = event->pos() - (event->state() & TQt::ControlButton
- ? m_dragCenter : m_dragStart);
- // square?
- if (event->state() & TQt::ShiftButton) {
- double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
- double w = diag.x() < 0 ? -size : size;
- double h = diag.y() < 0 ? -size : size;
- diag = KisPoint(w, h);
- }
-
- // resize around center point?
- if (event->state() & TQt::ControlButton) {
- m_dragStart = m_dragCenter - diag;
- m_dragEnd = m_dragCenter + diag;
- } else {
- m_dragEnd = m_dragStart + diag;
- }
- }
- // draw new lines on canvas
- draw(m_dragStart, m_dragEnd);
- m_dragCenter = KisPoint((m_dragStart.x() + m_dragEnd.x()) / 2,
- (m_dragStart.y() + m_dragEnd.y()) / 2);
- }
-}
-
-void KisToolRectangle::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject)
- return;
-
- if (!m_currentImage)
- return;
-
- KisPaintDeviceSP device = m_currentImage->activeDevice ();
- if (!device) return;
-
- if (m_dragging && event->button() == Qt::LeftButton) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- m_dragging = false;
-
- if (m_dragStart == m_dragEnd)
- return;
-
- if (!m_currentImage)
- return;
-
-
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (i18n ("Rectangle"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBackgroundColor(m_subject->bgColor());
- painter.setFillStyle(fillStyle());
- painter.setBrush(m_subject->currentBrush());
- painter.setPattern(m_subject->currentPattern());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op);
-
- painter.paintRect(m_dragStart, m_dragEnd, PRESSURE_DEFAULT/*event->pressure()*/, event->xTilt(), event->yTilt());
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
- }
-}
-
-void KisToolRectangle::draw(const KisPoint& start, const KisPoint& end )
-{
- if (!m_subject)
- return;
-
- KisCanvasController *controller = m_subject->canvasController ();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter p (canvas);
-
- p.setRasterOp (TQt::NotROP);
- p.drawRect (TQRect (controller->windowToView (start).floorTQPoint(), controller->windowToView (end).floorTQPoint()));
- p.end ();
-}
-
-void KisToolRectangle::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Rectangle"),
- "tool_rectangle",
- TQt::Key_F6,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- m_action->setToolTip(i18n("Draw a rectangle"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_rectangle.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cpp b/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cpp
new file mode 100644
index 000000000..69e306ecf
--- /dev/null
+++ b/chalk/plugins/tools/defaulttools/kis_tool_rectangle.cpp
@@ -0,0 +1,187 @@
+/*
+ * kis_tool_rectangle.cpp - part of Chalk
+ *
+ * Copyright (c) 2000 John Califf <jcaliff@compuzone.net>
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2004 Clarence Dang <dang@k.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqpainter.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_canvas_controller.h"
+#include "kis_canvas_subject.h"
+#include "kis_move_event.h"
+#include "kis_painter.h"
+#include "kis_paintop_registry.h"
+#include "kis_tool_rectangle.h"
+#include "kis_undo_adapter.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_layer.h"
+
+KisToolRectangle::KisToolRectangle()
+ : super(i18n ("Rectangle")),
+ m_dragging (false),
+ m_currentImage (0)
+{
+ setName("tool_rectangle");
+ setCursor(KisCursor::load("tool_rectangle_cursor.png", 6, 6));
+}
+
+KisToolRectangle::~KisToolRectangle()
+{
+}
+
+void KisToolRectangle::update (KisCanvasSubject *subject)
+{
+ super::update (subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg ();
+}
+
+void KisToolRectangle::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_currentImage && event->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_dragStart = m_dragCenter = m_dragEnd = event->pos();
+ draw(m_dragStart, m_dragEnd);
+ }
+}
+
+void KisToolRectangle::move(KisMoveEvent *event)
+{
+ if (m_dragging) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ // move (alt) or resize rectangle
+ if (event->state() & TQt::AltButton) {
+ KisPoint trans = event->pos() - m_dragEnd;
+ m_dragStart += trans;
+ m_dragEnd += trans;
+ } else {
+ KisPoint diag = event->pos() - (event->state() & TQt::ControlButton
+ ? m_dragCenter : m_dragStart);
+ // square?
+ if (event->state() & TQt::ShiftButton) {
+ double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
+ double w = diag.x() < 0 ? -size : size;
+ double h = diag.y() < 0 ? -size : size;
+ diag = KisPoint(w, h);
+ }
+
+ // resize around center point?
+ if (event->state() & TQt::ControlButton) {
+ m_dragStart = m_dragCenter - diag;
+ m_dragEnd = m_dragCenter + diag;
+ } else {
+ m_dragEnd = m_dragStart + diag;
+ }
+ }
+ // draw new lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ m_dragCenter = KisPoint((m_dragStart.x() + m_dragEnd.x()) / 2,
+ (m_dragStart.y() + m_dragEnd.y()) / 2);
+ }
+}
+
+void KisToolRectangle::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject)
+ return;
+
+ if (!m_currentImage)
+ return;
+
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();
+ if (!device) return;
+
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ m_dragging = false;
+
+ if (m_dragStart == m_dragEnd)
+ return;
+
+ if (!m_currentImage)
+ return;
+
+
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (i18n ("Rectangle"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBackgroundColor(m_subject->bgColor());
+ painter.setFillStyle(fillStyle());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setPattern(m_subject->currentPattern());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op);
+
+ painter.paintRect(m_dragStart, m_dragEnd, PRESSURE_DEFAULT/*event->pressure()*/, event->xTilt(), event->yTilt());
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+ }
+}
+
+void KisToolRectangle::draw(const KisPoint& start, const KisPoint& end )
+{
+ if (!m_subject)
+ return;
+
+ KisCanvasController *controller = m_subject->canvasController ();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter p (canvas);
+
+ p.setRasterOp (TQt::NotROP);
+ p.drawRect (TQRect (controller->windowToView (start).floorTQPoint(), controller->windowToView (end).floorTQPoint()));
+ p.end ();
+}
+
+void KisToolRectangle::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Rectangle"),
+ "tool_rectangle",
+ TQt::Key_F6,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ m_action->setToolTip(i18n("Draw a rectangle"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_rectangle.moc"
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_text.cc b/chalk/plugins/tools/defaulttools/kis_tool_text.cpp
index 1a2687f13..1a2687f13 100644
--- a/chalk/plugins/tools/defaulttools/kis_tool_text.cc
+++ b/chalk/plugins/tools/defaulttools/kis_tool_text.cpp
diff --git a/chalk/plugins/tools/defaulttools/kis_tool_zoom.cc b/chalk/plugins/tools/defaulttools/kis_tool_zoom.cpp
index fe449ee4f..fe449ee4f 100644
--- a/chalk/plugins/tools/defaulttools/kis_tool_zoom.cc
+++ b/chalk/plugins/tools/defaulttools/kis_tool_zoom.cpp
diff --git a/chalk/plugins/tools/selectiontools/Makefile.am b/chalk/plugins/tools/selectiontools/Makefile.am
index febfd514c..0f1b8474d 100644
--- a/chalk/plugins/tools/selectiontools/Makefile.am
+++ b/chalk/plugins/tools/selectiontools/Makefile.am
@@ -9,10 +9,10 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkselectiontools_la_SOURCES = kis_tool_move_selection.cc \
- kis_tool_select_brush.cc kis_tool_select_contiguous.cc kis_tool_select_elliptical.cc \
- kis_tool_select_eraser.cc kis_tool_select_outline.cc kis_tool_select_polygonal.cc \
- kis_tool_select_rectangular.cc selection_tools.cc
+chalkselectiontools_la_SOURCES = kis_tool_move_selection.cpp \
+ kis_tool_select_brush.cpp kis_tool_select_contiguous.cpp kis_tool_select_elliptical.cpp \
+ kis_tool_select_eraser.cpp kis_tool_select_outline.cpp kis_tool_select_polygonal.cpp \
+ kis_tool_select_rectangular.cpp selection_tools.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalkselectiontools.la
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_move_selection.cc b/chalk/plugins/tools/selectiontools/kis_tool_move_selection.cpp
index a1f0902f4..a1f0902f4 100644
--- a/chalk/plugins/tools/selectiontools/kis_tool_move_selection.cc
+++ b/chalk/plugins/tools/selectiontools/kis_tool_move_selection.cpp
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cc
deleted file mode 100644
index acc903620..000000000
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cc
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * kis_tool_select_brush.cc - part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqevent.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqwidget.h>
-#include <tqrect.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_brush.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_cmb_composite.h"
-#include "kis_cursor.h"
-#include "kis_doc.h"
-#include "kis_paintop.h"
-#include "kis_paintop_registry.h"
-#include "kis_move_event.h"
-#include "kis_painter.h"
-#include "kis_selection.h"
-#include "kis_tool_select_brush.h"
-#include "kis_types.h"
-#include "kis_layer.h"
-#include "kis_view.h"
-#include "kis_selection_options.h"
-#include "kis_selected_transaction.h"
-
-KisToolSelectBrush::KisToolSelectBrush()
- : super(i18n("SelectBrush"))
-{
- setName("tool_select_brush");
- m_optWidget = 0;
- setCursor(KisCursor::load("tool_brush_selection_cursor.png", 5, 5));
- m_paintOnSelection = true;
-}
-
-KisToolSelectBrush::~KisToolSelectBrush()
-{
-}
-
-void KisToolSelectBrush::activate()
-{
- super::activate();
-
- if (!m_optWidget)
- return;
-
- m_optWidget->slotActivated();
-}
-
-void KisToolSelectBrush::initPaint(KisEvent* /*e*/)
-{
- if (!m_currentImage || !m_currentImage->activeDevice()) return;
-
- m_mode = PAINT;
- m_dragDist = 0;
-
- // Create painter
- KisPaintDeviceSP dev = m_currentImage->activeDevice();
- if (m_painter)
- delete m_painter;
- bool hasSelection = dev->hasSelection();
- if (m_currentImage->undo()) m_transaction = new KisSelectedTransaction(i18n("Selection Brush"), dev);
- if(! hasSelection)
- {
- dev->selection()->clear();
- dev->emitSelectionChanged();
- }
- KisSelectionSP selection = dev->selection();
-
- m_target = selection;
- m_painter = new KisPainter(selection.data());
- TQ_CHECK_PTR(m_painter);
- m_painter->setPaintColor(KisColor(TQt::black, selection->colorSpace()));
- m_painter->setBrush(m_subject->currentBrush());
- m_painter->setOpacity(OPACITY_OPAQUE);//m_subject->fgColor().colorSpace()->intensity8(m_subject->fgColor().data()));
- m_painter->setCompositeOp(COMPOSITE_OVER);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("paintbrush", 0, painter());
- painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
-
- // Set the cursor -- ideally. this should be a mask created from the brush,
- // now that X11 can handle colored cursors.
-#if 0
- // Setting cursors has no effect until the tool is selected again; this
- // should be fixed.
- setCursor(KisCursor::brushCursor());
-#endif
-}
-
-void KisToolSelectBrush::endPaint()
-{
- m_mode = HOVER;
- if (m_currentImage && m_currentImage->activeLayer()) {
- if (m_currentImage->undo() && m_painter) {
- // If painting in mouse release, make sure painter
- // is destructed or end()ed
- m_currentImage->undoAdapter()->addCommand(m_transaction);
- }
- delete m_painter;
- m_painter = 0;
- if (m_currentImage->activeDevice())
- m_currentImage->activeDevice()->emitSelectionChanged();
- notifyModified();
- }
-}
-
-
-void KisToolSelectBrush::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Selection Brush"),
- "tool_brush_selection", "Ctrl+Shift+B", this,
- TQT_SLOT(activate()), collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Paint a selection"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-TQWidget* KisToolSelectBrush::createOptionWidget(TQWidget* parent)
-{
- Q_UNUSED(parent);
- // Commented out due to the fact that this doesn't actually work if you change the action
-#if 0
- m_optWidget = new KisSelectionOptions(parent, m_subject);
- TQ_CHECK_PTR(m_optWidget);
- m_optWidget->setCaption(i18n("Selection Brush"));
-
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
-
- return m_optWidget;
-#endif
- return 0;
-}
-
-TQWidget* KisToolSelectBrush::optionWidget()
-{
- return m_optWidget;
-}
-
-#include "kis_tool_select_brush.moc"
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cpp b/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cpp
new file mode 100644
index 000000000..ba80434f3
--- /dev/null
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_brush.cpp
@@ -0,0 +1,168 @@
+/*
+ * kis_tool_select_brush.cpp - part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqevent.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqwidget.h>
+#include <tqrect.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_brush.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_cmb_composite.h"
+#include "kis_cursor.h"
+#include "kis_doc.h"
+#include "kis_paintop.h"
+#include "kis_paintop_registry.h"
+#include "kis_move_event.h"
+#include "kis_painter.h"
+#include "kis_selection.h"
+#include "kis_tool_select_brush.h"
+#include "kis_types.h"
+#include "kis_layer.h"
+#include "kis_view.h"
+#include "kis_selection_options.h"
+#include "kis_selected_transaction.h"
+
+KisToolSelectBrush::KisToolSelectBrush()
+ : super(i18n("SelectBrush"))
+{
+ setName("tool_select_brush");
+ m_optWidget = 0;
+ setCursor(KisCursor::load("tool_brush_selection_cursor.png", 5, 5));
+ m_paintOnSelection = true;
+}
+
+KisToolSelectBrush::~KisToolSelectBrush()
+{
+}
+
+void KisToolSelectBrush::activate()
+{
+ super::activate();
+
+ if (!m_optWidget)
+ return;
+
+ m_optWidget->slotActivated();
+}
+
+void KisToolSelectBrush::initPaint(KisEvent* /*e*/)
+{
+ if (!m_currentImage || !m_currentImage->activeDevice()) return;
+
+ m_mode = PAINT;
+ m_dragDist = 0;
+
+ // Create painter
+ KisPaintDeviceSP dev = m_currentImage->activeDevice();
+ if (m_painter)
+ delete m_painter;
+ bool hasSelection = dev->hasSelection();
+ if (m_currentImage->undo()) m_transaction = new KisSelectedTransaction(i18n("Selection Brush"), dev);
+ if(! hasSelection)
+ {
+ dev->selection()->clear();
+ dev->emitSelectionChanged();
+ }
+ KisSelectionSP selection = dev->selection();
+
+ m_target = selection;
+ m_painter = new KisPainter(selection.data());
+ TQ_CHECK_PTR(m_painter);
+ m_painter->setPaintColor(KisColor(TQt::black, selection->colorSpace()));
+ m_painter->setBrush(m_subject->currentBrush());
+ m_painter->setOpacity(OPACITY_OPAQUE);//m_subject->fgColor().colorSpace()->intensity8(m_subject->fgColor().data()));
+ m_painter->setCompositeOp(COMPOSITE_OVER);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("paintbrush", 0, painter());
+ painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
+
+ // Set the cursor -- ideally. this should be a mask created from the brush,
+ // now that X11 can handle colored cursors.
+#if 0
+ // Setting cursors has no effect until the tool is selected again; this
+ // should be fixed.
+ setCursor(KisCursor::brushCursor());
+#endif
+}
+
+void KisToolSelectBrush::endPaint()
+{
+ m_mode = HOVER;
+ if (m_currentImage && m_currentImage->activeLayer()) {
+ if (m_currentImage->undo() && m_painter) {
+ // If painting in mouse release, make sure painter
+ // is destructed or end()ed
+ m_currentImage->undoAdapter()->addCommand(m_transaction);
+ }
+ delete m_painter;
+ m_painter = 0;
+ if (m_currentImage->activeDevice())
+ m_currentImage->activeDevice()->emitSelectionChanged();
+ notifyModified();
+ }
+}
+
+
+void KisToolSelectBrush::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Selection Brush"),
+ "tool_brush_selection", "Ctrl+Shift+B", this,
+ TQT_SLOT(activate()), collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Paint a selection"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+TQWidget* KisToolSelectBrush::createOptionWidget(TQWidget* parent)
+{
+ Q_UNUSED(parent);
+ // Commented out due to the fact that this doesn't actually work if you change the action
+#if 0
+ m_optWidget = new KisSelectionOptions(parent, m_subject);
+ TQ_CHECK_PTR(m_optWidget);
+ m_optWidget->setCaption(i18n("Selection Brush"));
+
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
+
+ return m_optWidget;
+#endif
+ return 0;
+}
+
+TQWidget* KisToolSelectBrush::optionWidget()
+{
+ return m_optWidget;
+}
+
+#include "kis_tool_select_brush.moc"
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cpp
index 1a4932b75..1a4932b75 100644
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cc
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_contiguous.cpp
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cc
deleted file mode 100644
index def162ef4..000000000
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cc
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * kis_tool_select_elliptical.cc -- part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqapplication.h>
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqlayout.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_autobrush_resource.h"
-#include "kis_canvas_controller.h"
-#include "kis_canvas_subject.h"
-#include "kis_cursor.h"
-#include "kis_image.h"
-#include "kis_painter.h"
-#include "kis_tool_select_elliptical.h"
-#include "kis_layer.h"
-#include "kis_undo_adapter.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_selection.h"
-#include "kis_selection_options.h"
-#include "kis_selected_transaction.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-KisToolSelectElliptical::KisToolSelectElliptical()
- : super(i18n("Elliptical Select"))
-{
- setName("tool_select_elliptical");
- setCursor(KisCursor::load("tool_elliptical_selection_cursor.png", 6, 6));
-
- m_subject = 0;
- m_selecting = false;
- m_centerPos = KisPoint(0, 0);
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
- m_optWidget = 0;
- m_selectAction = SELECTION_ADD;
-}
-
-KisToolSelectElliptical::~KisToolSelectElliptical()
-{
-}
-
-void KisToolSelectElliptical::activate()
-{
- super::activate();
-
- if (!m_optWidget)
- return;
-
- m_optWidget->slotActivated();
-}
-
-void KisToolSelectElliptical::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- super::update(m_subject);
-}
-
-void KisToolSelectElliptical::paint(KisCanvasPainter& gc)
-{
- if (m_selecting)
- paintOutline(gc, TQRect());
-}
-
-void KisToolSelectElliptical::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- if (m_selecting)
- paintOutline(gc, rc);
-}
-
-void KisToolSelectElliptical::clearSelection()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisImageSP img = m_subject->currentImg();
-
- Q_ASSERT(controller);
-
-// if (img && img->floatingSelection().data() != 0) {
-// img->unsetFloatingSelection();
-// controller->canvas()->update();
-// }
-
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
- m_selecting = false;
- }
-}
-
-void KisToolSelectElliptical::buttonPress(KisButtonPressEvent *e)
-{
- if (m_subject) {
- KisImageSP img = m_subject->currentImg();
-
- if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
- clearSelection();
- m_startPos = m_endPos = m_centerPos = e->pos();
- m_selecting = true;
- paintOutline();
- }
- }
-}
-
-void KisToolSelectElliptical::move(KisMoveEvent *e)
-{
- if (m_subject && m_selecting) {
- paintOutline();
- // move (alt) or resize ellipse
- if (e->state() & TQt::AltButton) {
- KisPoint trans = e->pos() - m_endPos;
- m_startPos += trans;
- m_endPos += trans;
- } else {
- KisPoint diag = e->pos() - (e->state() & TQt::ControlButton
- ? m_centerPos : m_startPos);
- // circle?
- if (e->state() & TQt::ShiftButton) {
- double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
- double w = diag.x() < 0 ? -size : size;
- double h = diag.y() < 0 ? -size : size;
- diag = KisPoint(w, h);
- }
-
- // resize around center point?
- if (e->state() & TQt::ControlButton) {
- m_startPos = m_centerPos - diag;
- m_endPos = m_centerPos + diag;
- } else {
- m_endPos = m_startPos + diag;
- }
- }
- paintOutline();
- m_centerPos = KisPoint((m_startPos.x() + m_endPos.x()) / 2,
- (m_startPos.y() + m_endPos.y()) / 2);
- }
-}
-
-void KisToolSelectElliptical::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_subject && m_selecting && e->button() == Qt::LeftButton) {
-
- paintOutline();
-
- if (m_startPos == m_endPos) {
- clearSelection();
- } else {
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- KisImageSP img = m_subject->currentImg();
-
- if (!img)
- return;
-
- if (m_endPos.y() < 0)
- m_endPos.setY(0);
-
- if (m_endPos.y() > img->height())
- m_endPos.setY(img->height());
-
- if (m_endPos.x() < 0)
- m_endPos.setX(0);
-
- if (m_endPos.x() > img->width())
- m_endPos.setX(img->width());
-
- if (img && img->activeDevice()) {
- KisPaintDeviceSP dev = img->activeDevice();
- KisSelectedTransaction *t = 0;
- if (img->undo()) t = new KisSelectedTransaction(i18n("Elliptical Selection"), dev);
-
- bool hasSelection = dev->hasSelection();
- if(! hasSelection)
- {
- dev->selection()->clear();
- if(m_selectAction==SELECTION_SUBTRACT)
- dev->selection()->invert();
- }
- TQRect rc( m_startPos.floorTQPoint(), m_endPos.floorTQPoint());
- rc = rc.normalize();
-
- KisSelectionSP tmpSel = new KisSelection(dev);
- KisAutobrushCircleShape shape(rc.width(),rc.height(), 1, 1);
- TQ_UINT8 value;
- for (int y = 0; y <= rc.height(); y++)
- for (int x = 0; x <= rc.width(); x++)
- {
- value = MAX_SELECTED - shape.valueAt(x,y);
- tmpSel->setSelected( x+rc.x(), y+rc.y(), value);
- }
- switch(m_selectAction)
- {
- case SELECTION_ADD:
- dev->addSelection(tmpSel);
- break;
- case SELECTION_SUBTRACT:
- dev->subtractSelection(tmpSel);
- break;
- }
-
- if(hasSelection) {
- dev->setDirty(rc);
- dev->emitSelectionChanged(rc);
- } else {
- dev->setDirty();
- dev->emitSelectionChanged();
- }
-
- if (img->undo())
- img->undoAdapter()->addCommand(t);
-
- TQApplication::restoreOverrideCursor();
- }
- }
- m_selecting = false;
- }
-}
-
-void KisToolSelectElliptical::paintOutline()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintOutline(gc, rc);
- }
-}
-
-void KisToolSelectElliptical::paintOutline(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::DotLine);
- TQPoint start;
- TQPoint end;
-
- Q_ASSERT(controller);
- start = controller->windowToView(m_startPos).floorTQPoint();
- end = controller->windowToView(m_endPos).floorTQPoint();
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawEllipse(TQRect(start, end));
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolSelectElliptical::slotSetAction(int action) {
- if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
- m_selectAction =(enumSelectionMode)action;
-}
-
-void KisToolSelectElliptical::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Elliptical Selection"),
- "tool_elliptical_selection" ,
- TQt::Key_J,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Select an elliptical area"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-TQWidget* KisToolSelectElliptical::createOptionWidget(TQWidget* parent)
-{
- m_optWidget = new KisSelectionOptions(parent, m_subject);
- TQ_CHECK_PTR(m_optWidget);
- m_optWidget->setCaption(i18n("Elliptical Selection"));
-
- connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
-
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
-
- return m_optWidget;
-}
-
-TQWidget* KisToolSelectElliptical::optionWidget()
-{
- return m_optWidget;
-}
-
-
-
-#include "kis_tool_select_elliptical.moc"
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cpp b/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cpp
new file mode 100644
index 000000000..f85da3327
--- /dev/null
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_elliptical.cpp
@@ -0,0 +1,321 @@
+/*
+ * kis_tool_select_elliptical.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqapplication.h>
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqlayout.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_autobrush_resource.h"
+#include "kis_canvas_controller.h"
+#include "kis_canvas_subject.h"
+#include "kis_cursor.h"
+#include "kis_image.h"
+#include "kis_painter.h"
+#include "kis_tool_select_elliptical.h"
+#include "kis_layer.h"
+#include "kis_undo_adapter.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_selection.h"
+#include "kis_selection_options.h"
+#include "kis_selected_transaction.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+KisToolSelectElliptical::KisToolSelectElliptical()
+ : super(i18n("Elliptical Select"))
+{
+ setName("tool_select_elliptical");
+ setCursor(KisCursor::load("tool_elliptical_selection_cursor.png", 6, 6));
+
+ m_subject = 0;
+ m_selecting = false;
+ m_centerPos = KisPoint(0, 0);
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+ m_optWidget = 0;
+ m_selectAction = SELECTION_ADD;
+}
+
+KisToolSelectElliptical::~KisToolSelectElliptical()
+{
+}
+
+void KisToolSelectElliptical::activate()
+{
+ super::activate();
+
+ if (!m_optWidget)
+ return;
+
+ m_optWidget->slotActivated();
+}
+
+void KisToolSelectElliptical::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ super::update(m_subject);
+}
+
+void KisToolSelectElliptical::paint(KisCanvasPainter& gc)
+{
+ if (m_selecting)
+ paintOutline(gc, TQRect());
+}
+
+void KisToolSelectElliptical::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ if (m_selecting)
+ paintOutline(gc, rc);
+}
+
+void KisToolSelectElliptical::clearSelection()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisImageSP img = m_subject->currentImg();
+
+ Q_ASSERT(controller);
+
+// if (img && img->floatingSelection().data() != 0) {
+// img->unsetFloatingSelection();
+// controller->canvas()->update();
+// }
+
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+ m_selecting = false;
+ }
+}
+
+void KisToolSelectElliptical::buttonPress(KisButtonPressEvent *e)
+{
+ if (m_subject) {
+ KisImageSP img = m_subject->currentImg();
+
+ if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
+ clearSelection();
+ m_startPos = m_endPos = m_centerPos = e->pos();
+ m_selecting = true;
+ paintOutline();
+ }
+ }
+}
+
+void KisToolSelectElliptical::move(KisMoveEvent *e)
+{
+ if (m_subject && m_selecting) {
+ paintOutline();
+ // move (alt) or resize ellipse
+ if (e->state() & TQt::AltButton) {
+ KisPoint trans = e->pos() - m_endPos;
+ m_startPos += trans;
+ m_endPos += trans;
+ } else {
+ KisPoint diag = e->pos() - (e->state() & TQt::ControlButton
+ ? m_centerPos : m_startPos);
+ // circle?
+ if (e->state() & TQt::ShiftButton) {
+ double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
+ double w = diag.x() < 0 ? -size : size;
+ double h = diag.y() < 0 ? -size : size;
+ diag = KisPoint(w, h);
+ }
+
+ // resize around center point?
+ if (e->state() & TQt::ControlButton) {
+ m_startPos = m_centerPos - diag;
+ m_endPos = m_centerPos + diag;
+ } else {
+ m_endPos = m_startPos + diag;
+ }
+ }
+ paintOutline();
+ m_centerPos = KisPoint((m_startPos.x() + m_endPos.x()) / 2,
+ (m_startPos.y() + m_endPos.y()) / 2);
+ }
+}
+
+void KisToolSelectElliptical::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_subject && m_selecting && e->button() == Qt::LeftButton) {
+
+ paintOutline();
+
+ if (m_startPos == m_endPos) {
+ clearSelection();
+ } else {
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img)
+ return;
+
+ if (m_endPos.y() < 0)
+ m_endPos.setY(0);
+
+ if (m_endPos.y() > img->height())
+ m_endPos.setY(img->height());
+
+ if (m_endPos.x() < 0)
+ m_endPos.setX(0);
+
+ if (m_endPos.x() > img->width())
+ m_endPos.setX(img->width());
+
+ if (img && img->activeDevice()) {
+ KisPaintDeviceSP dev = img->activeDevice();
+ KisSelectedTransaction *t = 0;
+ if (img->undo()) t = new KisSelectedTransaction(i18n("Elliptical Selection"), dev);
+
+ bool hasSelection = dev->hasSelection();
+ if(! hasSelection)
+ {
+ dev->selection()->clear();
+ if(m_selectAction==SELECTION_SUBTRACT)
+ dev->selection()->invert();
+ }
+ TQRect rc( m_startPos.floorTQPoint(), m_endPos.floorTQPoint());
+ rc = rc.normalize();
+
+ KisSelectionSP tmpSel = new KisSelection(dev);
+ KisAutobrushCircleShape shape(rc.width(),rc.height(), 1, 1);
+ TQ_UINT8 value;
+ for (int y = 0; y <= rc.height(); y++)
+ for (int x = 0; x <= rc.width(); x++)
+ {
+ value = MAX_SELECTED - shape.valueAt(x,y);
+ tmpSel->setSelected( x+rc.x(), y+rc.y(), value);
+ }
+ switch(m_selectAction)
+ {
+ case SELECTION_ADD:
+ dev->addSelection(tmpSel);
+ break;
+ case SELECTION_SUBTRACT:
+ dev->subtractSelection(tmpSel);
+ break;
+ }
+
+ if(hasSelection) {
+ dev->setDirty(rc);
+ dev->emitSelectionChanged(rc);
+ } else {
+ dev->setDirty();
+ dev->emitSelectionChanged();
+ }
+
+ if (img->undo())
+ img->undoAdapter()->addCommand(t);
+
+ TQApplication::restoreOverrideCursor();
+ }
+ }
+ m_selecting = false;
+ }
+}
+
+void KisToolSelectElliptical::paintOutline()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintOutline(gc, rc);
+ }
+}
+
+void KisToolSelectElliptical::paintOutline(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::DotLine);
+ TQPoint start;
+ TQPoint end;
+
+ Q_ASSERT(controller);
+ start = controller->windowToView(m_startPos).floorTQPoint();
+ end = controller->windowToView(m_endPos).floorTQPoint();
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawEllipse(TQRect(start, end));
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolSelectElliptical::slotSetAction(int action) {
+ if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
+ m_selectAction =(enumSelectionMode)action;
+}
+
+void KisToolSelectElliptical::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Elliptical Selection"),
+ "tool_elliptical_selection" ,
+ TQt::Key_J,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Select an elliptical area"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+TQWidget* KisToolSelectElliptical::createOptionWidget(TQWidget* parent)
+{
+ m_optWidget = new KisSelectionOptions(parent, m_subject);
+ TQ_CHECK_PTR(m_optWidget);
+ m_optWidget->setCaption(i18n("Elliptical Selection"));
+
+ connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
+
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
+
+ return m_optWidget;
+}
+
+TQWidget* KisToolSelectElliptical::optionWidget()
+{
+ return m_optWidget;
+}
+
+
+
+#include "kis_tool_select_elliptical.moc"
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cc
deleted file mode 100644
index af7f8d84a..000000000
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * kis_tool_select_brush.cc - part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqevent.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqwidget.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_brush.h"
-#include "kis_layer.h"
-#include "kis_paintop.h"
-#include "kis_paintop_registry.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_cmb_composite.h"
-#include "kis_cursor.h"
-#include "kis_doc.h"
-#include "kis_move_event.h"
-#include "kis_painter.h"
-#include "kis_selection.h"
-#include "kis_tool_select_eraser.h"
-#include "kis_types.h"
-#include "kis_view.h"
-#include "kis_selection_options.h"
-
-KisToolSelectEraser::KisToolSelectEraser()
- : super(i18n("SelectEraser"))
-{
- setName("tool_select_eraser");
- setCursor(KisCursor::load("tool_eraser_selection_cursor.png", 5, 5));
- m_optWidget = 0;
- m_paintOnSelection = true;
-}
-
-KisToolSelectEraser::~KisToolSelectEraser()
-{
-}
-
-void KisToolSelectEraser::activate()
-{
- super::activate();
-
- if (!m_optWidget)
- return;
-
- m_optWidget->slotActivated();
-}
-
-void KisToolSelectEraser::initPaint(KisEvent */*e*/)
-{
- if (!m_currentImage || !m_currentImage->activeDevice()) return;
-
- m_mode = PAINT;
- m_dragDist = 0;
-
- // Create painter
- KisPaintDeviceSP dev = m_currentImage->activeDevice();
-
- if (dev == 0) return;
-
- if (m_painter)
- delete m_painter;
- if(! dev->hasSelection())
- {
- dev->selection()->clear();
- dev->emitSelectionChanged();
- }
- KisSelectionSP selection = dev->selection();
-
- m_target = selection;
- m_painter = new KisPainter(selection.data());
- TQ_CHECK_PTR(m_painter);
- m_painter->beginTransaction(i18n("Selection Eraser"));
- m_painter->setPaintColor(KisColor(TQt::white, selection->colorSpace()));
- m_painter->setBrush(m_subject->currentBrush());
- m_painter->setOpacity(OPACITY_OPAQUE);
- m_painter->setCompositeOp(COMPOSITE_ERASE);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("eraser", 0, painter());
- painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
-
- // Set the cursor -- ideally. this should be a mask created from the brush,
- // now that X11 can handle colored cursors.
-#if 0
- // Setting cursors has no effect until the tool is selected again; this
- // should be fixed.
- setCursor(KisCursor::eraserCursor());
-#endif
-}
-
-void KisToolSelectEraser::endPaint() {
- super::endPaint();
- if (m_currentImage && m_currentImage->activeDevice())
- m_currentImage->activeDevice()->emitSelectionChanged();
-}
-void KisToolSelectEraser::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("Selection &Eraser"),
- "tool_eraser_selection", "Ctrl+Shift+E", this,
- TQT_SLOT(activate()), collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Erase parts of a selection"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-TQWidget* KisToolSelectEraser::createOptionWidget(TQWidget* parent)
-{
- Q_UNUSED(parent);
- // Commented out due to the fact that this doesn't actually work if you change the action
-#if 0
- m_optWidget = new KisSelectionOptions(parent, m_subject);
- TQ_CHECK_PTR(m_optWidget);
- m_optWidget->setCaption(i18n("Selection Eraser"));
-
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
-
- return m_optWidget;
-#endif
- return 0;
-}
-
-TQWidget* KisToolSelectEraser::optionWidget()
-{
- return m_optWidget;
-}
-
-#include "kis_tool_select_eraser.moc"
-
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cpp b/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cpp
new file mode 100644
index 000000000..9cfef0a80
--- /dev/null
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_eraser.cpp
@@ -0,0 +1,156 @@
+/*
+ * kis_tool_select_brush.cpp - part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqevent.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqwidget.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_brush.h"
+#include "kis_layer.h"
+#include "kis_paintop.h"
+#include "kis_paintop_registry.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_cmb_composite.h"
+#include "kis_cursor.h"
+#include "kis_doc.h"
+#include "kis_move_event.h"
+#include "kis_painter.h"
+#include "kis_selection.h"
+#include "kis_tool_select_eraser.h"
+#include "kis_types.h"
+#include "kis_view.h"
+#include "kis_selection_options.h"
+
+KisToolSelectEraser::KisToolSelectEraser()
+ : super(i18n("SelectEraser"))
+{
+ setName("tool_select_eraser");
+ setCursor(KisCursor::load("tool_eraser_selection_cursor.png", 5, 5));
+ m_optWidget = 0;
+ m_paintOnSelection = true;
+}
+
+KisToolSelectEraser::~KisToolSelectEraser()
+{
+}
+
+void KisToolSelectEraser::activate()
+{
+ super::activate();
+
+ if (!m_optWidget)
+ return;
+
+ m_optWidget->slotActivated();
+}
+
+void KisToolSelectEraser::initPaint(KisEvent */*e*/)
+{
+ if (!m_currentImage || !m_currentImage->activeDevice()) return;
+
+ m_mode = PAINT;
+ m_dragDist = 0;
+
+ // Create painter
+ KisPaintDeviceSP dev = m_currentImage->activeDevice();
+
+ if (dev == 0) return;
+
+ if (m_painter)
+ delete m_painter;
+ if(! dev->hasSelection())
+ {
+ dev->selection()->clear();
+ dev->emitSelectionChanged();
+ }
+ KisSelectionSP selection = dev->selection();
+
+ m_target = selection;
+ m_painter = new KisPainter(selection.data());
+ TQ_CHECK_PTR(m_painter);
+ m_painter->beginTransaction(i18n("Selection Eraser"));
+ m_painter->setPaintColor(KisColor(TQt::white, selection->colorSpace()));
+ m_painter->setBrush(m_subject->currentBrush());
+ m_painter->setOpacity(OPACITY_OPAQUE);
+ m_painter->setCompositeOp(COMPOSITE_ERASE);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("eraser", 0, painter());
+ painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
+
+ // Set the cursor -- ideally. this should be a mask created from the brush,
+ // now that X11 can handle colored cursors.
+#if 0
+ // Setting cursors has no effect until the tool is selected again; this
+ // should be fixed.
+ setCursor(KisCursor::eraserCursor());
+#endif
+}
+
+void KisToolSelectEraser::endPaint() {
+ super::endPaint();
+ if (m_currentImage && m_currentImage->activeDevice())
+ m_currentImage->activeDevice()->emitSelectionChanged();
+}
+void KisToolSelectEraser::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("Selection &Eraser"),
+ "tool_eraser_selection", "Ctrl+Shift+E", this,
+ TQT_SLOT(activate()), collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Erase parts of a selection"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+TQWidget* KisToolSelectEraser::createOptionWidget(TQWidget* parent)
+{
+ Q_UNUSED(parent);
+ // Commented out due to the fact that this doesn't actually work if you change the action
+#if 0
+ m_optWidget = new KisSelectionOptions(parent, m_subject);
+ TQ_CHECK_PTR(m_optWidget);
+ m_optWidget->setCaption(i18n("Selection Eraser"));
+
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
+
+ return m_optWidget;
+#endif
+ return 0;
+}
+
+TQWidget* KisToolSelectEraser::optionWidget()
+{
+ return m_optWidget;
+}
+
+#include "kis_tool_select_eraser.moc"
+
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_outline.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_outline.cpp
index 7f5267366..7f5267366 100644
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_outline.cc
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_outline.cpp
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cpp
index 8d89eea2f..8d89eea2f 100644
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cc
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_polygonal.cpp
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cc b/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cc
deleted file mode 100644
index 09d338663..000000000
--- a/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cc
+++ /dev/null
@@ -1,323 +0,0 @@
-
-/*
- * kis_tool_select_rectangular.cc -- part of Chalk
- *
- * Copyright (c) 1999 Michael Koch <koch@kde.org>
- * 2001 John Califf <jcaliff@compuzone.net>
- * 2002 Patrick Julien <freak@codepimps.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqapplication.h>
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqlayout.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_canvas_controller.h"
-#include "kis_canvas_subject.h"
-#include "kis_cursor.h"
-#include "kis_image.h"
-#include "kis_painter.h"
-#include "kis_layer.h"
-#include "kis_tool_select_rectangular.h"
-#include "kis_undo_adapter.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_selection.h"
-#include "kis_selection_options.h"
-#include <kis_selected_transaction.h>
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-KisToolSelectRectangular::KisToolSelectRectangular()
- : super(i18n("Rectangular Select Tool"))
-{
- setName("tool_select_rectangular");
- setCursor(KisCursor::load("tool_rectangular_selection_cursor.png", 6, 6));
- m_subject = 0;
- m_selecting = false;
- m_centerPos = KisPoint(0, 0);
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
- m_optWidget = 0;
- m_selectAction = SELECTION_ADD;
-}
-
-KisToolSelectRectangular::~KisToolSelectRectangular()
-{
-}
-
-void KisToolSelectRectangular::activate()
-{
- super::activate();
-
- if (!m_optWidget)
- return;
-
- m_optWidget->slotActivated();
-}
-
-void KisToolSelectRectangular::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- super::update(m_subject);
-}
-
-void KisToolSelectRectangular::paint(KisCanvasPainter& gc)
-{
- if (m_selecting)
- paintOutline(gc, TQRect());
-}
-
-void KisToolSelectRectangular::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- if (m_selecting)
- paintOutline(gc, rc);
-}
-
-void KisToolSelectRectangular::clearSelection()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisImageSP img = m_subject->currentImg();
-
- Q_ASSERT(controller);
-
- m_centerPos = KisPoint(0, 0);
- m_startPos = KisPoint(0, 0);
- m_endPos = KisPoint(0, 0);
- m_selecting = false;
- }
-}
-
-void KisToolSelectRectangular::buttonPress(KisButtonPressEvent *e)
-{
- if (m_subject) {
- KisImageSP img = m_subject->currentImg();
-
- if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
- clearSelection();
- m_startPos = m_endPos = m_centerPos = e->pos();
- m_selecting = true;
- }
- }
-}
-
-void KisToolSelectRectangular::move(KisMoveEvent *e)
-{
- if (m_subject && m_selecting) {
- paintOutline();
- // move (alt) or resize rectangle
- if (e->state() & TQt::AltButton) {
- KisPoint trans = e->pos() - m_endPos;
- m_startPos += trans;
- m_endPos += trans;
- } else {
- KisPoint diag = e->pos() - (e->state() & TQt::ControlButton
- ? m_centerPos : m_startPos);
- // square?
- if (e->state() & TQt::ShiftButton) {
- double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
- double w = diag.x() < 0 ? -size : size;
- double h = diag.y() < 0 ? -size : size;
- diag = KisPoint(w, h);
- }
-
- // resize around center point?
- if (e->state() & TQt::ControlButton) {
- m_startPos = m_centerPos - diag;
- m_endPos = m_centerPos + diag;
- } else {
- m_endPos = m_startPos + diag;
- }
- }
- paintOutline();
- m_centerPos = KisPoint((m_startPos.x() + m_endPos.x()) / 2,
- (m_startPos.y() + m_endPos.y()) / 2);
- }
-}
-
-void KisToolSelectRectangular::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_subject && m_selecting && e->button() == Qt::LeftButton) {
-
- paintOutline();
-
- if (m_startPos == m_endPos) {
- clearSelection();
- } else {
- KisImageSP img = m_subject->currentImg();
-
- if (!img)
- return;
-
- if (m_endPos.y() < 0)
- m_endPos.setY(0);
-
- if (m_endPos.y() > img->height())
- m_endPos.setY(img->height());
-
- if (m_endPos.x() < 0)
- m_endPos.setX(0);
-
- if (m_endPos.x() > img->width())
- m_endPos.setX(img->width());
- if (img && img->activeDevice()) {
-
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- KisPaintDeviceSP dev = img->activeDevice();
- bool hasSelection = dev->hasSelection();
-
- KisSelectedTransaction *t = 0;
- if (img->undo()) t = new KisSelectedTransaction(i18n("Rectangular Selection"), dev);
- KisSelectionSP selection = dev->selection();
- TQRect rc(m_startPos.floorTQPoint(), m_endPos.floorTQPoint());
- rc = rc.normalize();
-
- // We don't want the border of the 'rectangle' to be included in our selection
- rc.setSize(rc.size() - TQSize(1,1));
-
- if(! hasSelection)
- {
- selection->clear();
- if(m_selectAction==SELECTION_SUBTRACT)
- selection->invert();
- }
-
- KisSelectionSP tmpSel = new KisSelection(dev);
- tmpSel->select(rc);
- switch(m_selectAction)
- {
- case SELECTION_ADD:
- dev->addSelection(tmpSel);
- break;
- case SELECTION_SUBTRACT:
- dev->subtractSelection(tmpSel);
- break;
- default:
- break;
- }
-
-
- if(hasSelection) {
- dev->setDirty(rc);
- dev->emitSelectionChanged(rc);
- } else {
- dev->setDirty();
- dev->emitSelectionChanged();
- }
-
- if (img->undo())
- img->undoAdapter()->addCommand(t);
-
- KisCanvasController *controller = m_subject -> canvasController();
- controller -> kiscanvas() -> update();
-
- TQApplication::restoreOverrideCursor();
- }
- }
-
- m_selecting = false;
- }
-}
-
-void KisToolSelectRectangular::paintOutline()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintOutline(gc, rc);
- }
-}
-
-void KisToolSelectRectangular::paintOutline(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::DotLine);
- TQPoint start;
- TQPoint end;
-
- Q_ASSERT(controller);
- start = controller->windowToView(m_startPos.floorTQPoint());
- end = controller->windowToView(m_endPos.floorTQPoint());
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawRect(TQRect(start, end));
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolSelectRectangular::slotSetAction(int action) {
- if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
- m_selectAction =(enumSelectionMode)action;
-}
-
-void KisToolSelectRectangular::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Rectangular Selection"),
- "tool_rect_selection",
- TQt::Key_R,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setExclusiveGroup("tools");
- m_action->setToolTip(i18n("Select a rectangular area"));
- m_ownAction = true;
- }
-}
-
-TQWidget* KisToolSelectRectangular::createOptionWidget(TQWidget* parent)
-{
- m_optWidget = new KisSelectionOptions(parent, m_subject);
- TQ_CHECK_PTR(m_optWidget);
- m_optWidget->setCaption(i18n("Rectangular Selection"));
-
- connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
-
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
-
- return m_optWidget;
-}
-
-TQWidget* KisToolSelectRectangular::optionWidget()
-{
- return m_optWidget;
-}
-
-
-
-
-#include "kis_tool_select_rectangular.moc"
diff --git a/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cpp b/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cpp
new file mode 100644
index 000000000..5a6772bac
--- /dev/null
+++ b/chalk/plugins/tools/selectiontools/kis_tool_select_rectangular.cpp
@@ -0,0 +1,323 @@
+
+/*
+ * kis_tool_select_rectangular.cpp -- part of Chalk
+ *
+ * Copyright (c) 1999 Michael Koch <koch@kde.org>
+ * 2001 John Califf <jcaliff@compuzone.net>
+ * 2002 Patrick Julien <freak@codepimps.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqapplication.h>
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqlayout.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_canvas_controller.h"
+#include "kis_canvas_subject.h"
+#include "kis_cursor.h"
+#include "kis_image.h"
+#include "kis_painter.h"
+#include "kis_layer.h"
+#include "kis_tool_select_rectangular.h"
+#include "kis_undo_adapter.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_selection.h"
+#include "kis_selection_options.h"
+#include <kis_selected_transaction.h>
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+KisToolSelectRectangular::KisToolSelectRectangular()
+ : super(i18n("Rectangular Select Tool"))
+{
+ setName("tool_select_rectangular");
+ setCursor(KisCursor::load("tool_rectangular_selection_cursor.png", 6, 6));
+ m_subject = 0;
+ m_selecting = false;
+ m_centerPos = KisPoint(0, 0);
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+ m_optWidget = 0;
+ m_selectAction = SELECTION_ADD;
+}
+
+KisToolSelectRectangular::~KisToolSelectRectangular()
+{
+}
+
+void KisToolSelectRectangular::activate()
+{
+ super::activate();
+
+ if (!m_optWidget)
+ return;
+
+ m_optWidget->slotActivated();
+}
+
+void KisToolSelectRectangular::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ super::update(m_subject);
+}
+
+void KisToolSelectRectangular::paint(KisCanvasPainter& gc)
+{
+ if (m_selecting)
+ paintOutline(gc, TQRect());
+}
+
+void KisToolSelectRectangular::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ if (m_selecting)
+ paintOutline(gc, rc);
+}
+
+void KisToolSelectRectangular::clearSelection()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisImageSP img = m_subject->currentImg();
+
+ Q_ASSERT(controller);
+
+ m_centerPos = KisPoint(0, 0);
+ m_startPos = KisPoint(0, 0);
+ m_endPos = KisPoint(0, 0);
+ m_selecting = false;
+ }
+}
+
+void KisToolSelectRectangular::buttonPress(KisButtonPressEvent *e)
+{
+ if (m_subject) {
+ KisImageSP img = m_subject->currentImg();
+
+ if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
+ clearSelection();
+ m_startPos = m_endPos = m_centerPos = e->pos();
+ m_selecting = true;
+ }
+ }
+}
+
+void KisToolSelectRectangular::move(KisMoveEvent *e)
+{
+ if (m_subject && m_selecting) {
+ paintOutline();
+ // move (alt) or resize rectangle
+ if (e->state() & TQt::AltButton) {
+ KisPoint trans = e->pos() - m_endPos;
+ m_startPos += trans;
+ m_endPos += trans;
+ } else {
+ KisPoint diag = e->pos() - (e->state() & TQt::ControlButton
+ ? m_centerPos : m_startPos);
+ // square?
+ if (e->state() & TQt::ShiftButton) {
+ double size = TQMAX(fabs(diag.x()), fabs(diag.y()));
+ double w = diag.x() < 0 ? -size : size;
+ double h = diag.y() < 0 ? -size : size;
+ diag = KisPoint(w, h);
+ }
+
+ // resize around center point?
+ if (e->state() & TQt::ControlButton) {
+ m_startPos = m_centerPos - diag;
+ m_endPos = m_centerPos + diag;
+ } else {
+ m_endPos = m_startPos + diag;
+ }
+ }
+ paintOutline();
+ m_centerPos = KisPoint((m_startPos.x() + m_endPos.x()) / 2,
+ (m_startPos.y() + m_endPos.y()) / 2);
+ }
+}
+
+void KisToolSelectRectangular::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_subject && m_selecting && e->button() == Qt::LeftButton) {
+
+ paintOutline();
+
+ if (m_startPos == m_endPos) {
+ clearSelection();
+ } else {
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img)
+ return;
+
+ if (m_endPos.y() < 0)
+ m_endPos.setY(0);
+
+ if (m_endPos.y() > img->height())
+ m_endPos.setY(img->height());
+
+ if (m_endPos.x() < 0)
+ m_endPos.setX(0);
+
+ if (m_endPos.x() > img->width())
+ m_endPos.setX(img->width());
+ if (img && img->activeDevice()) {
+
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ KisPaintDeviceSP dev = img->activeDevice();
+ bool hasSelection = dev->hasSelection();
+
+ KisSelectedTransaction *t = 0;
+ if (img->undo()) t = new KisSelectedTransaction(i18n("Rectangular Selection"), dev);
+ KisSelectionSP selection = dev->selection();
+ TQRect rc(m_startPos.floorTQPoint(), m_endPos.floorTQPoint());
+ rc = rc.normalize();
+
+ // We don't want the border of the 'rectangle' to be included in our selection
+ rc.setSize(rc.size() - TQSize(1,1));
+
+ if(! hasSelection)
+ {
+ selection->clear();
+ if(m_selectAction==SELECTION_SUBTRACT)
+ selection->invert();
+ }
+
+ KisSelectionSP tmpSel = new KisSelection(dev);
+ tmpSel->select(rc);
+ switch(m_selectAction)
+ {
+ case SELECTION_ADD:
+ dev->addSelection(tmpSel);
+ break;
+ case SELECTION_SUBTRACT:
+ dev->subtractSelection(tmpSel);
+ break;
+ default:
+ break;
+ }
+
+
+ if(hasSelection) {
+ dev->setDirty(rc);
+ dev->emitSelectionChanged(rc);
+ } else {
+ dev->setDirty();
+ dev->emitSelectionChanged();
+ }
+
+ if (img->undo())
+ img->undoAdapter()->addCommand(t);
+
+ KisCanvasController *controller = m_subject -> canvasController();
+ controller -> kiscanvas() -> update();
+
+ TQApplication::restoreOverrideCursor();
+ }
+ }
+
+ m_selecting = false;
+ }
+}
+
+void KisToolSelectRectangular::paintOutline()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintOutline(gc, rc);
+ }
+}
+
+void KisToolSelectRectangular::paintOutline(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::DotLine);
+ TQPoint start;
+ TQPoint end;
+
+ Q_ASSERT(controller);
+ start = controller->windowToView(m_startPos.floorTQPoint());
+ end = controller->windowToView(m_endPos.floorTQPoint());
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawRect(TQRect(start, end));
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolSelectRectangular::slotSetAction(int action) {
+ if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
+ m_selectAction =(enumSelectionMode)action;
+}
+
+void KisToolSelectRectangular::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Rectangular Selection"),
+ "tool_rect_selection",
+ TQt::Key_R,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setExclusiveGroup("tools");
+ m_action->setToolTip(i18n("Select a rectangular area"));
+ m_ownAction = true;
+ }
+}
+
+TQWidget* KisToolSelectRectangular::createOptionWidget(TQWidget* parent)
+{
+ m_optWidget = new KisSelectionOptions(parent, m_subject);
+ TQ_CHECK_PTR(m_optWidget);
+ m_optWidget->setCaption(i18n("Rectangular Selection"));
+
+ connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
+
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
+
+ return m_optWidget;
+}
+
+TQWidget* KisToolSelectRectangular::optionWidget()
+{
+ return m_optWidget;
+}
+
+
+
+
+#include "kis_tool_select_rectangular.moc"
diff --git a/chalk/plugins/tools/selectiontools/selection_tools.cc b/chalk/plugins/tools/selectiontools/selection_tools.cc
deleted file mode 100644
index 8407a076e..000000000
--- a/chalk/plugins/tools/selectiontools/selection_tools.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * selection_tools.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool.h>
-#include <kis_tool_registry.h>
-
-#include "selection_tools.h"
-
-#include "kis_tool_select_outline.h"
-#include "kis_tool_select_polygonal.h"
-#include "kis_tool_select_rectangular.h"
-#include "kis_tool_select_contiguous.h"
-#include "kis_tool_select_elliptical.h"
-#include "kis_tool_select_eraser.h"
-#include "kis_tool_select_brush.h"
-#include "kis_tool_move_selection.h"
-
-typedef KGenericFactory<SelectionTools> SelectionToolsFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkselectiontools, SelectionToolsFactory( "chalk" ) )
-
-
-SelectionTools::SelectionTools(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(SelectionToolsFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- r->add(new KisToolSelectOutlineFactory());
- r->add(new KisToolSelectPolygonalFactory());
- r->add(new KisToolSelectRectangularFactory());
- r->add(new KisToolSelectBrushFactory());
- r->add(new KisToolSelectContiguousFactory());
- r->add(new KisToolSelectEllipticalFactory());
- r->add(new KisToolSelectEraserFactory());
- r->add(new KisToolMoveSelectionFactory());
- }
-}
-
-SelectionTools::~SelectionTools()
-{
-}
-
-#include "selection_tools.moc"
diff --git a/chalk/plugins/tools/selectiontools/selection_tools.cpp b/chalk/plugins/tools/selectiontools/selection_tools.cpp
new file mode 100644
index 000000000..f34a3b34c
--- /dev/null
+++ b/chalk/plugins/tools/selectiontools/selection_tools.cpp
@@ -0,0 +1,77 @@
+/*
+ * selection_tools.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool.h>
+#include <kis_tool_registry.h>
+
+#include "selection_tools.h"
+
+#include "kis_tool_select_outline.h"
+#include "kis_tool_select_polygonal.h"
+#include "kis_tool_select_rectangular.h"
+#include "kis_tool_select_contiguous.h"
+#include "kis_tool_select_elliptical.h"
+#include "kis_tool_select_eraser.h"
+#include "kis_tool_select_brush.h"
+#include "kis_tool_move_selection.h"
+
+typedef KGenericFactory<SelectionTools> SelectionToolsFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkselectiontools, SelectionToolsFactory( "chalk" ) )
+
+
+SelectionTools::SelectionTools(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(SelectionToolsFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ r->add(new KisToolSelectOutlineFactory());
+ r->add(new KisToolSelectPolygonalFactory());
+ r->add(new KisToolSelectRectangularFactory());
+ r->add(new KisToolSelectBrushFactory());
+ r->add(new KisToolSelectContiguousFactory());
+ r->add(new KisToolSelectEllipticalFactory());
+ r->add(new KisToolSelectEraserFactory());
+ r->add(new KisToolMoveSelectionFactory());
+ }
+}
+
+SelectionTools::~SelectionTools()
+{
+}
+
+#include "selection_tools.moc"
diff --git a/chalk/plugins/tools/tool_crop/Makefile.am b/chalk/plugins/tools/tool_crop/Makefile.am
index fe320b849..5bf3c1f6d 100644
--- a/chalk/plugins/tools/tool_crop/Makefile.am
+++ b/chalk/plugins/tools/tool_crop/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalktoolcrop_la_SOURCES = \
wdg_tool_crop.ui \
- tool_crop.cc \
- kis_tool_crop.cc
+ tool_crop.cpp \
+ kis_tool_crop.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolcrop.la
diff --git a/chalk/plugins/tools/tool_crop/kis_tool_crop.cc b/chalk/plugins/tools/tool_crop/kis_tool_crop.cc
deleted file mode 100644
index 11a47590c..000000000
--- a/chalk/plugins/tools/tool_crop/kis_tool_crop.cc
+++ /dev/null
@@ -1,925 +0,0 @@
-/*
- * kis_tool_crop.cc -- part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <tqcheckbox.h>
-#include <tqcombobox.h>
-#include <tqobject.h>
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqpushbutton.h>
-#include <tqrect.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include <kis_global.h>
-#include <kis_painter.h>
-#include <kis_canvas_controller.h>
-#include <kis_canvas_subject.h>
-#include <kis_cursor.h>
-#include <kis_image.h>
-#include <kis_undo_adapter.h>
-#include <kis_button_press_event.h>
-#include <kis_button_release_event.h>
-#include <kis_move_event.h>
-#include <kis_selected_transaction.h>
-#include <kis_selection.h>
-#include <kis_layer.h>
-#include <kis_crop_visitor.h>
-
-#include "kis_tool_crop.h"
-#include "wdg_tool_crop.h"
-
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-
-
-KisToolCrop::KisToolCrop()
- : super(i18n("Crop"))
-{
- setName("tool_crop");
- m_cropCursor = KisCursor::load("tool_crop_cursor.png", 6, 6);
- setCursor(m_cropCursor);
- m_subject = 0;
- m_selecting = false;
- m_rectCrop = TQRect(0, 0, 0, 0);
- m_handleSize = 13;
- m_haveCropSelection = false;
- m_optWidget = 0;
-}
-
-KisToolCrop::~KisToolCrop()
-{
-}
-
-void KisToolCrop::update(KisCanvasSubject *subject)
-{
- m_subject = subject;
- super::update(m_subject);
-}
-
-void KisToolCrop::activate()
-{
- super::activate();
-
- // No current crop rectangle, try to use the selection of the device to make a rectangle
- if (m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice()) {
- KisPaintDeviceSP device = m_subject->currentImg()->activeDevice();
- if (!device->hasSelection()) {
- //m_rectCrop = m_subject->currentImg()->bounds();
- //validateSelection();
- m_haveCropSelection = false;
- m_selecting = false;
- }
- else {
-
- m_rectCrop = device->selection()->selectedRect();
- validateSelection();
- crop();
- }
- }
-}
-
-void KisToolCrop::deactivate()
-{
- clearRect();
-}
-
-
-void KisToolCrop::paint(KisCanvasPainter& gc)
-{
- paintOutlineWithHandles(gc, TQRect());
-}
-
-void KisToolCrop::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- paintOutlineWithHandles(gc, rc);
-}
-
-void KisToolCrop::clearRect()
-{
- kdDebug() << "Clearing\n";
- if (m_subject) {
-
- KisCanvasController *controller = m_subject->canvasController();
- KisImageSP img = m_subject->currentImg();
-
- Q_ASSERT(controller);
-
- controller->kiscanvas()->update();
-
- m_rectCrop = TQRect(0,0,0,0);
-
- updateWidgetValues();
- m_selecting = false;
- }
-}
-
-void KisToolCrop::buttonPress(KisButtonPressEvent *e)
-{
- if (m_subject) {
- KisImageSP img = m_subject->currentImg();
-
- if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
-
- TQPoint pos = e->pos().floorTQPoint();
- TQRect b = img->bounds();
-
- if (pos.x() < b.x())
- pos.setX(b.x());
- else if (pos.x() > b.x() + b.width())
- pos.setX(b.x() + b.width());
-
- if (pos.y() < b.y())
- pos.setY(b.y());
- else if (pos.y() > b.y() + b.height())
- pos.setY(b.y() + b.height());
-
- m_selecting = true;
-
- if( !m_haveCropSelection ) //if the selection is not set
- {
- m_rectCrop = TQRect( pos.x(), pos.y(), 0, 0);
- paintOutlineWithHandles();
- }
- else
- {
- KisCanvasController *controller = m_subject->canvasController();
- m_mouseOnHandleType = mouseOnHandle(controller ->windowToView(pos));
- m_dragStart = pos;
- }
-
- updateWidgetValues();
- }
- }
-}
-
-void KisToolCrop::move(KisMoveEvent *e)
-{
- if ( m_subject && m_subject->currentImg())
- {
- if( m_selecting ) //if the user selects
- {
- if( !m_haveCropSelection ) //if the cropSelection is not yet set
- {
- paintOutlineWithHandles();
-
- m_rectCrop.setBottomRight( e->pos().floorTQPoint());
-
- KisImageSP image = m_subject->currentImg();
-
- m_rectCrop.setRight( TQMIN(m_rectCrop.right(), image->width()));
- m_rectCrop.setBottom( TQMIN(m_rectCrop.bottom(), image->width()));
- m_rectCrop = m_rectCrop.normalize();
-
- paintOutlineWithHandles();
- }
- else //if the crop selection is set
- {
- m_dragStop = e->pos().floorTQPoint();
- if (m_mouseOnHandleType != None && m_dragStart != m_dragStop ) {
-
-
- TQ_INT32 imageWidth = m_subject->currentImg()->width();
- TQ_INT32 imageHeight = m_subject->currentImg()->height();
-
- paintOutlineWithHandles();
-
- TQPoint pos = e->pos().floorTQPoint();
- if( m_mouseOnHandleType == Inside )
- {
- m_rectCrop.moveBy( ( m_dragStop.x() - m_dragStart.x() ), ( m_dragStop.y() - m_dragStart.y() ) );
- if( m_rectCrop.left() < 0 )
- {
- m_rectCrop.moveLeft( 0 );
- }
- if( m_rectCrop.right() > imageWidth )
- {
- m_rectCrop.moveRight( imageWidth );
- }
- if( m_rectCrop.top() < 0 )
- {
- m_rectCrop.moveTop( 0 );
- }
- if( m_rectCrop.bottom() > imageHeight )
- {
- m_rectCrop.moveBottom( imageHeight );
- }
- } else if(m_optWidget->boolRatio->isChecked())
- {
- TQPoint drag = m_dragStop - m_dragStart;
- if( ! m_optWidget->boolWidth->isChecked() && !m_optWidget->boolHeight->isChecked() )
- {
- switch (m_mouseOnHandleType)
- {
- case (UpperLeft):
- {
- TQ_INT32 dep = (drag.x() + drag.y()) / 2;
- m_rectCrop.setTop( m_rectCrop.top() + dep );
- m_rectCrop.setLeft( (int) ( m_rectCrop.right() - m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
- }
- break;
- case (LowerRight):
- {
- TQ_INT32 dep = (drag.x() + drag.y()) / 2;
- m_rectCrop.setBottom( m_rectCrop.bottom() + dep );
- m_rectCrop.setWidth( (int) ( m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
- break;
- }
- case (UpperRight):
- {
- TQ_INT32 dep = (drag.x() - drag.y()) / 2;
- m_rectCrop.setTop( m_rectCrop.top() - dep );
- m_rectCrop.setWidth( (int) ( m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
- break;
- }
- case (LowerLeft):
- {
- TQ_INT32 dep = (drag.x() - drag.y()) / 2;
- m_rectCrop.setBottom( m_rectCrop.bottom() - dep );
- m_rectCrop.setLeft( (int) ( m_rectCrop.right() - m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
- break;
- }
- case (Upper):
- m_rectCrop.setTop( pos.y() + m_dy );
- m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
- break;
- case (Lower):
- m_rectCrop.setBottom( pos.y() + m_dy );
- m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
- break;
- case (Left):
- m_rectCrop.setLeft( pos.x() + m_dx );
- m_rectCrop.setHeight( (int) (m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
- break;
- case (Right):
- m_rectCrop.setRight( pos.x() + m_dx );
- m_rectCrop.setHeight( (int) (m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
- break;
- case (Inside): // never happen
- break;
- }
- }
- } else {
- if( m_optWidget->boolWidth->isChecked() )
- {
- m_rectCrop.setWidth( m_optWidget->intWidth->value() + 1 );
- } else {
- switch (m_mouseOnHandleType)
- {
- case (LowerLeft):
- case (Left):
- case (UpperLeft):
- m_rectCrop.setLeft( pos.x() + m_dx );
- break;
- case (Right):
- case (UpperRight):
- case (LowerRight):
- m_rectCrop.setRight( pos.x() + m_dx );
- break;
- default:
- break;
- }
- }
- if( m_optWidget->boolHeight->isChecked() )
- {
- m_rectCrop.setHeight( m_optWidget->intHeight->value() + 1 );
- } else {
- switch (m_mouseOnHandleType)
- {
- case (UpperLeft):
- case (Upper):
- case (UpperRight):
- m_rectCrop.setTop( pos.y() + m_dy );
- break;
- case (LowerRight):
- case (LowerLeft):
- case (Lower):
- m_rectCrop.setBottom( pos.y() + m_dy );
- break;
- default:
- break;
- }
- }
- }
- if( m_rectCrop.height() < 0)
- {
- if( m_mouseOnHandleType == Lower)
- m_mouseOnHandleType = Upper;
- else if( m_mouseOnHandleType == LowerLeft)
- m_mouseOnHandleType = UpperLeft;
- else if( m_mouseOnHandleType == LowerRight)
- m_mouseOnHandleType = UpperRight;
- else if( m_mouseOnHandleType == Upper)
- m_mouseOnHandleType = Lower;
- else if( m_mouseOnHandleType == UpperLeft)
- m_mouseOnHandleType = LowerLeft;
- else if( m_mouseOnHandleType == UpperRight)
- m_mouseOnHandleType = LowerRight;
- }
- if( m_rectCrop.width() < 0)
- {
- if( m_mouseOnHandleType == Right)
- m_mouseOnHandleType = Left;
- else if( m_mouseOnHandleType == UpperRight)
- m_mouseOnHandleType = UpperLeft;
- else if( m_mouseOnHandleType == LowerRight)
- m_mouseOnHandleType = LowerLeft;
- else if( m_mouseOnHandleType == Left)
- m_mouseOnHandleType = Right;
- else if( m_mouseOnHandleType == UpperLeft)
- m_mouseOnHandleType = UpperRight;
- else if( m_mouseOnHandleType == LowerLeft)
- m_mouseOnHandleType = LowerRight;
- }
-
- m_rectCrop = m_rectCrop.normalize();
- m_rectCrop = m_rectCrop.intersect( TQRect(0,0, imageWidth + 1, imageHeight + 1 ) );
- m_dragStart = e->pos().floorTQPoint();
- paintOutlineWithHandles();
- }
- }
- updateWidgetValues();
- }
- else //if we are not selecting
- {
- if ( m_haveCropSelection ) //if the crop selection is set
- {
- KisCanvasController *controller = m_subject->canvasController();
- TQ_INT32 type = mouseOnHandle(controller->windowToView(e->pos().floorTQPoint()));
- //set resize cursor if we are on one of the handles
- setMoveResizeCursor(type);
- }
- }
- }
-}
-
-void KisToolCrop::updateWidgetValues(bool updateratio)
-{
- TQRect r = realRectCrop();
- setOptionWidgetX(r.x());
- setOptionWidgetY(r.y());
- setOptionWidgetWidth(r.width() );
- setOptionWidgetHeight(r.height() );
- if(updateratio && !m_optWidget->boolRatio->isChecked() )
- setOptionWidgetRatio((double)r.width() / (double)r.height() );
-}
-
-void KisToolCrop::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_subject && m_subject->currentImg() && m_selecting && e->button() == Qt::LeftButton) {
-
- m_selecting = false;
- m_haveCropSelection = true;
-
- paintOutlineWithHandles();
- validateSelection();
- paintOutlineWithHandles();
- }
-}
-
-void KisToolCrop::doubleClick(KisDoubleClickEvent *)
-{
- if (m_haveCropSelection) crop();
-}
-
-void KisToolCrop::validateSelection(bool updateratio)
-{
- if (m_subject) {
- KisImageSP image = m_subject->currentImg();
-
- if (image) {
- TQ_INT32 imageWidth = image->width();
- TQ_INT32 imageHeight = image->height();
- m_rectCrop.setLeft(TQMAX(0, m_rectCrop.left()));
- m_rectCrop.setTop(TQMAX(0, m_rectCrop.top()));
- m_rectCrop.setRight(TQMIN(imageWidth, m_rectCrop.right()));
- m_rectCrop.setBottom(TQMIN(imageHeight, m_rectCrop.bottom()));
-
- updateWidgetValues(updateratio);
- }
- }
-}
-
-void KisToolCrop::paintOutlineWithHandles()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintOutlineWithHandles(gc, rc);
- }
-}
-
-void KisToolCrop::paintOutlineWithHandles(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject && (m_selecting || m_haveCropSelection)) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::SolidLine);
- pen.setWidth(1);
- TQPoint start;
- TQPoint end;
-
- Q_ASSERT(controller);
- start = controller->windowToView(m_rectCrop.topLeft());
- end = controller->windowToView(m_rectCrop.bottomRight());
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- //draw handles
- m_handlesRegion = handles(TQRect(start, end));
-
- TQ_INT32 startx;
- TQ_INT32 starty;
- TQ_INT32 endx;
- TQ_INT32 endy;
- if(start.x()<=end.x())
- {
- startx=start.x();
- endx=end.x();
- }
- else
- {
- startx=end.x();
- endx=start.x();
- }
- if(start.y()<=end.y())
- {
- starty=start.y();
- endy=end.y();
- }
- else
- {
- starty=end.y();
- endy=start.y();
- }
- //draw upper line of selection
- gc.drawLine(startx + m_handleSize / 2 + 1, starty, startx + (endx - startx - m_handleSize) / 2 + 1, starty);
- gc.drawLine(startx + (endx - startx + m_handleSize) / 2 + 1, starty, endx - m_handleSize / 2, starty);
- //draw lower line of selection
- gc.drawLine(startx + m_handleSize / 2 + 1, endy, startx + (endx - startx - m_handleSize) / 2 + 1, endy);
- gc.drawLine(startx + (endx - startx + m_handleSize) / 2 + 1, endy, endx - m_handleSize / 2 , endy);
- //draw right line of selection
- gc.drawLine(startx, starty + m_handleSize / 2 + 1, startx, starty + (endy - starty - m_handleSize) / 2 + 1);
- gc.drawLine(startx, starty + (endy - starty + m_handleSize) / 2 + 1, startx, endy - m_handleSize / 2);
- //draw left line of selection
- gc.drawLine(endx, starty + m_handleSize / 2 + 1, endx, starty + (endy - starty - m_handleSize) / 2 + 1);
- gc.drawLine(endx, starty + (endy - starty + m_handleSize) / 2 + 1, endx, endy - m_handleSize / 2);
-
- //draw guides
- gc.drawLine(0,endy,startx - m_handleSize / 2,endy);
- gc.drawLine(startx,endy + m_handleSize / 2 + 1, startx, controller->kiscanvas()->height());
- gc.drawLine(endx,0,endx,starty - m_handleSize / 2);
- gc.drawLine(endx + m_handleSize / 2 + 1,starty, controller->kiscanvas()->width(), starty);
- TQMemArray <TQRect> rects = m_handlesRegion.rects ();
- for (TQMemArray <TQRect>::ConstIterator it = rects.begin (); it != rects.end (); ++it)
- {
- gc.fillRect (*it, TQt::black);
- }
-
-
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolCrop::crop() {
- // XXX: Should cropping be part of KisImage/KisPaintDevice's API?
-
- m_haveCropSelection = false;
- setCursor(m_cropCursor);
-
- KisImageSP img = m_subject->currentImg();
-
- if (!img)
- return;
-
- TQRect rc = realRectCrop().normalize();
-
- // The visitor adds the undo steps to the macro
- if (m_optWidget->cmbType->currentItem() == 0) {
-
- TQRect dirty = img->bounds();
-
- // The layer(s) under the current layer will take care of adding
- // undo information to the Crop macro.
- if (img->undo())
- img->undoAdapter()->beginMacro(i18n("Crop"));
-
- KisCropVisitor v(rc, false);
- KisLayerSP layer = img->activeLayer();
- layer->accept(v);
- layer->setDirty( dirty );
- if (img->undo())
- img->undoAdapter()->endMacro();
-
- }
- else {
- // Resize creates the undo macro itself
- img->resize(rc, true);
- }
-
- m_rectCrop = TQRect(0,0,0,0);
-
- updateWidgetValues();
-}
-
-void KisToolCrop::setCropX(int x)
-{
- if (!m_haveCropSelection) {
- m_haveCropSelection = true;
- }
- else {
- paintOutlineWithHandles(); // remove outlines
- }
-
- m_rectCrop.setX(x);
-
- validateSelection();
- paintOutlineWithHandles();
-}
-
-void KisToolCrop::setCropY(int y)
-{
- if (!m_haveCropSelection) {
- m_haveCropSelection = true;
- }
- else {
- paintOutlineWithHandles(); // remove outlines
- }
-
- m_rectCrop.setY(y);
-
- validateSelection();
- paintOutlineWithHandles();
-
-}
-
-void KisToolCrop::setCropWidth(int w)
-{
- if (!m_haveCropSelection) {
- m_haveCropSelection = true;
- }
- else {
- paintOutlineWithHandles(); // remove outlines
- }
-
- m_rectCrop.setWidth(w + 1);
-
- if( m_optWidget->boolRatio->isChecked() )
- {
- m_rectCrop.setHeight( (int) ( w / m_optWidget->doubleRatio->value() ) );
- } else {
- setOptionWidgetRatio((double)m_rectCrop.width() / (double)m_rectCrop.height() );
- }
-
- validateSelection();
- paintOutlineWithHandles();
-
-}
-
-void KisToolCrop::setCropHeight(int h)
-{
- if (!m_haveCropSelection) {
- m_haveCropSelection = true;
- }
- else {
- paintOutlineWithHandles(); // remove outlines
- }
-
- m_rectCrop.setHeight(h + 1);
-
- if( m_optWidget->boolRatio->isChecked() )
- {
- m_rectCrop.setWidth( (int) ( h * m_optWidget->doubleRatio->value() ) );
- } else {
- setOptionWidgetRatio((double)m_rectCrop.width() / (double)m_rectCrop.height() );
- }
-
- validateSelection();
- paintOutlineWithHandles();
-
-}
-
-void KisToolCrop::setRatio(double )
-{
- if( ! (m_optWidget->boolWidth->isChecked() && m_optWidget->boolHeight->isChecked() ))
- {
- if (!m_haveCropSelection) {
- m_haveCropSelection = true;
- }
- else {
- paintOutlineWithHandles(); // remove outlines
- }
- if( m_optWidget->boolWidth->isChecked() )
- {
- m_rectCrop.setHeight( (int) ( m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
- setOptionWidgetHeight( m_rectCrop.height() );
- } else if(m_optWidget->boolHeight->isChecked()) {
- m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
- setOptionWidgetWidth( m_rectCrop.width() );
- } else {
- int newwidth = (int) (m_optWidget->doubleRatio->value() * m_rectCrop.height());
- newwidth = (newwidth + m_rectCrop.width()) / 2;
- m_rectCrop.setWidth( newwidth + 1);
- setOptionWidgetWidth( newwidth );
- m_rectCrop.setHeight( (int) (newwidth / m_optWidget->doubleRatio->value()) + 1 );
- setOptionWidgetHeight( m_rectCrop.height() - 1 );
- }
- validateSelection(false);
- paintOutlineWithHandles();
- }
-}
-
-void KisToolCrop::setOptionWidgetX(TQ_INT32 x)
-{
- // Disable signals otherwise we get the valueChanged signal, which we don't want
- // to go through the logic for setting values that way.
- m_optWidget->intX->blockSignals(true);
- m_optWidget->intX->setValue(x);
- m_optWidget->intX->blockSignals(false);
-}
-
-void KisToolCrop::setOptionWidgetY(TQ_INT32 y)
-{
- m_optWidget->intY->blockSignals(true);
- m_optWidget->intY->setValue(y);
- m_optWidget->intY->blockSignals(false);
-}
-
-void KisToolCrop::setOptionWidgetWidth(TQ_INT32 x)
-{
- m_optWidget->intWidth->blockSignals(true);
- m_optWidget->intWidth->setValue(x);
- m_optWidget->intWidth->blockSignals(false);
-}
-
-void KisToolCrop::setOptionWidgetHeight(TQ_INT32 y)
-{
- m_optWidget->intHeight->blockSignals(true);
- m_optWidget->intHeight->setValue(y);
- m_optWidget->intHeight->blockSignals(false);
-}
-
-void KisToolCrop::setOptionWidgetRatio(double ratio)
-{
- m_optWidget->doubleRatio->blockSignals(true);
- m_optWidget->doubleRatio->setValue(ratio);
- m_optWidget->doubleRatio->blockSignals(false);
-}
-
-
-TQWidget* KisToolCrop::createOptionWidget(TQWidget* parent)
-{
- m_optWidget = new WdgToolCrop(parent);
- TQ_CHECK_PTR(m_optWidget);
-
- connect(m_optWidget->bnCrop, TQT_SIGNAL(clicked()), this, TQT_SLOT(crop()));
-
- connect(m_optWidget->intX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropX(int)));
- connect(m_optWidget->intY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropY(int)));
- connect(m_optWidget->intWidth, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropWidth(int)));
- connect(m_optWidget->intHeight, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropHeight(int)));
- connect(m_optWidget->doubleRatio, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(setRatio( double )));
-
- return m_optWidget;
-}
-
-TQWidget* KisToolCrop::optionWidget()
-{
- return m_optWidget;
-}
-
-void KisToolCrop::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Crop"),
- "tool_crop",
- 0,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Crop an area"));
- m_action->setExclusiveGroup("tools");
-
- m_ownAction = true;
- }
-}
-
-TQRect toTQRect(double x, double y, int w, int h)
-{
- return TQRect(int(x), int(y), w, h);
-}
-
-TQRegion KisToolCrop::handles(TQRect rect)
-{
- TQRegion handlesRegion;
-
- //add handle at the lower right corner
- handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0, TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add handle at the upper right corner
- handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0 , 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add rectangle at the lower left corner
- handlesRegion += toTQRect( 0 - m_handleSize / 2.0 , TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add rectangle at the upper left corner
- handlesRegion += toTQRect( 0 - m_handleSize / 2.0, 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add handle at the lower edge of the rectangle
- handlesRegion += toTQRect( ( TQABS( rect.width() ) - m_handleSize ) / 2.0 , TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add handle at the right edge of the rectangle
- handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0 , ( TQABS( rect.height() ) - m_handleSize ) / 2.0, m_handleSize, m_handleSize );
- //add handle at the upper edge of the rectangle
- handlesRegion += toTQRect( ( TQABS( rect.width() ) - m_handleSize ) / 2.0 , 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
- //add handle at the left edge of the rectangle
- handlesRegion += toTQRect( 0 - m_handleSize / 2.0, ( TQABS( rect.height() ) - m_handleSize ) / 2.0, m_handleSize, m_handleSize );
-
- //move the handles to the correct position
- if( rect.width() >= 0 && rect.height() >= 0)
- {
- handlesRegion.translate ( rect.x(), rect.y() );
- }
- else if( rect.width() < 0 && rect.height() >= 0)
- {
- handlesRegion.translate ( rect.x() - TQABS( rect.width() ), rect.y() );
- }
- else if( rect.width() >= 0 && rect.height() < 0)
- {
- handlesRegion.translate ( rect.x(), rect.y() - TQABS( rect.height() ) );
- }
- else if( rect.width() < 0 && rect.height() < 0)
- {
- handlesRegion.translate ( rect.x() - TQABS( rect.width() ), rect.y() - TQABS( rect.height() ) );
- }
- return handlesRegion;
-}
-
-TQ_INT32 KisToolCrop::mouseOnHandle(TQPoint currentViewPoint)
-{
- KisCanvasController *controller = m_subject->canvasController();
- Q_ASSERT(controller);
- TQPoint start = controller->windowToView(m_rectCrop.topLeft());
- TQPoint end = controller->windowToView(m_rectCrop.bottomRight());
-
- TQ_INT32 startx;
- TQ_INT32 starty;
- TQ_INT32 endx;
- TQ_INT32 endy;
- if(start.x()<=end.x())
- {
- startx=start.x();
- endx=end.x();
- }
- else
- {
- startx=end.x();
- endx=start.x();
- }
- if(start.y()<=end.y())
- {
- starty=start.y();
- endy=end.y();
- }
- else
- {
- starty=end.y();
- endy=start.y();
- }
-
- if ( toTQRect ( startx - m_handleSize / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx= startx-currentViewPoint.x();
- m_dy = starty - currentViewPoint.y();
- }
- return UpperLeft;
- }
- else if ( toTQRect ( startx - m_handleSize / 2.0, endy - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx = startx-currentViewPoint.x();
- m_dy = endy-currentViewPoint.y();
- }
- return LowerLeft;
- }
- else if ( toTQRect ( endx - m_handleSize / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx = endx - currentViewPoint.x();
- m_dy = starty - currentViewPoint.y() ;
- }
- return UpperRight;
- }
- else if ( toTQRect ( endx - m_handleSize / 2.0, endy - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx = endx - currentViewPoint.x();
- m_dy= endy - currentViewPoint.y();
- }
- return LowerRight;
- }
- else if ( toTQRect ( startx + ( endx - startx - m_handleSize ) / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dy = starty - currentViewPoint.y() ;
- }
- return Upper;
- }
- else if ( toTQRect ( startx + ( endx - startx - m_handleSize ) / 2.0, endy - m_handleSize / 2, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dy = endy - currentViewPoint.y();
- }
- return Lower;
- }
- else if ( toTQRect ( startx - m_handleSize / 2.0, starty + ( endy - starty - m_handleSize ) / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx = startx - currentViewPoint.x() ;
- }
- return Left;
- }
- else if ( toTQRect ( endx - m_handleSize / 2.0 , starty + ( endy - starty - m_handleSize ) / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
- {
- if( !m_selecting )
- {
- m_dx = endx-currentViewPoint.x();
- }
- return Right;
- }
- else if ( toTQRect ( startx , starty, endx - startx , endy - starty ).contains( currentViewPoint ) )
- {
- return Inside;
- }
- else return None;
-}
-
-void KisToolCrop::setMoveResizeCursor (TQ_INT32 handle)
-{
- switch (handle)
- {
- case (UpperLeft):
- case (LowerRight):
- m_subject->canvasController()->setCanvasCursor(KisCursor::sizeFDiagCursor());
- return;
- case (LowerLeft):
- case (UpperRight):
- m_subject->canvasController()->setCanvasCursor(KisCursor::sizeBDiagCursor());
- return;
- case (Upper):
- case (Lower):
- m_subject->canvasController()->setCanvasCursor(KisCursor::sizeVerCursor());
- return;
- case (Left):
- case (Right):
- m_subject->canvasController()->setCanvasCursor(KisCursor::sizeHorCursor());
- return;
- case (Inside):
- m_subject->canvasController()->setCanvasCursor(KisCursor::sizeAllCursor());
- return;
- }
- m_subject->canvasController()->setCanvasCursor(KisCursor::arrowCursor());
- return;
-}
-
-
-#include "kis_tool_crop.moc"
diff --git a/chalk/plugins/tools/tool_crop/kis_tool_crop.cpp b/chalk/plugins/tools/tool_crop/kis_tool_crop.cpp
new file mode 100644
index 000000000..58454b4f5
--- /dev/null
+++ b/chalk/plugins/tools/tool_crop/kis_tool_crop.cpp
@@ -0,0 +1,925 @@
+/*
+ * kis_tool_crop.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <tqcheckbox.h>
+#include <tqcombobox.h>
+#include <tqobject.h>
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqpushbutton.h>
+#include <tqrect.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include <kis_global.h>
+#include <kis_painter.h>
+#include <kis_canvas_controller.h>
+#include <kis_canvas_subject.h>
+#include <kis_cursor.h>
+#include <kis_image.h>
+#include <kis_undo_adapter.h>
+#include <kis_button_press_event.h>
+#include <kis_button_release_event.h>
+#include <kis_move_event.h>
+#include <kis_selected_transaction.h>
+#include <kis_selection.h>
+#include <kis_layer.h>
+#include <kis_crop_visitor.h>
+
+#include "kis_tool_crop.h"
+#include "wdg_tool_crop.h"
+
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+
+
+KisToolCrop::KisToolCrop()
+ : super(i18n("Crop"))
+{
+ setName("tool_crop");
+ m_cropCursor = KisCursor::load("tool_crop_cursor.png", 6, 6);
+ setCursor(m_cropCursor);
+ m_subject = 0;
+ m_selecting = false;
+ m_rectCrop = TQRect(0, 0, 0, 0);
+ m_handleSize = 13;
+ m_haveCropSelection = false;
+ m_optWidget = 0;
+}
+
+KisToolCrop::~KisToolCrop()
+{
+}
+
+void KisToolCrop::update(KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ super::update(m_subject);
+}
+
+void KisToolCrop::activate()
+{
+ super::activate();
+
+ // No current crop rectangle, try to use the selection of the device to make a rectangle
+ if (m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice()) {
+ KisPaintDeviceSP device = m_subject->currentImg()->activeDevice();
+ if (!device->hasSelection()) {
+ //m_rectCrop = m_subject->currentImg()->bounds();
+ //validateSelection();
+ m_haveCropSelection = false;
+ m_selecting = false;
+ }
+ else {
+
+ m_rectCrop = device->selection()->selectedRect();
+ validateSelection();
+ crop();
+ }
+ }
+}
+
+void KisToolCrop::deactivate()
+{
+ clearRect();
+}
+
+
+void KisToolCrop::paint(KisCanvasPainter& gc)
+{
+ paintOutlineWithHandles(gc, TQRect());
+}
+
+void KisToolCrop::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ paintOutlineWithHandles(gc, rc);
+}
+
+void KisToolCrop::clearRect()
+{
+ kdDebug() << "Clearing\n";
+ if (m_subject) {
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisImageSP img = m_subject->currentImg();
+
+ Q_ASSERT(controller);
+
+ controller->kiscanvas()->update();
+
+ m_rectCrop = TQRect(0,0,0,0);
+
+ updateWidgetValues();
+ m_selecting = false;
+ }
+}
+
+void KisToolCrop::buttonPress(KisButtonPressEvent *e)
+{
+ if (m_subject) {
+ KisImageSP img = m_subject->currentImg();
+
+ if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
+
+ TQPoint pos = e->pos().floorTQPoint();
+ TQRect b = img->bounds();
+
+ if (pos.x() < b.x())
+ pos.setX(b.x());
+ else if (pos.x() > b.x() + b.width())
+ pos.setX(b.x() + b.width());
+
+ if (pos.y() < b.y())
+ pos.setY(b.y());
+ else if (pos.y() > b.y() + b.height())
+ pos.setY(b.y() + b.height());
+
+ m_selecting = true;
+
+ if( !m_haveCropSelection ) //if the selection is not set
+ {
+ m_rectCrop = TQRect( pos.x(), pos.y(), 0, 0);
+ paintOutlineWithHandles();
+ }
+ else
+ {
+ KisCanvasController *controller = m_subject->canvasController();
+ m_mouseOnHandleType = mouseOnHandle(controller ->windowToView(pos));
+ m_dragStart = pos;
+ }
+
+ updateWidgetValues();
+ }
+ }
+}
+
+void KisToolCrop::move(KisMoveEvent *e)
+{
+ if ( m_subject && m_subject->currentImg())
+ {
+ if( m_selecting ) //if the user selects
+ {
+ if( !m_haveCropSelection ) //if the cropSelection is not yet set
+ {
+ paintOutlineWithHandles();
+
+ m_rectCrop.setBottomRight( e->pos().floorTQPoint());
+
+ KisImageSP image = m_subject->currentImg();
+
+ m_rectCrop.setRight( TQMIN(m_rectCrop.right(), image->width()));
+ m_rectCrop.setBottom( TQMIN(m_rectCrop.bottom(), image->width()));
+ m_rectCrop = m_rectCrop.normalize();
+
+ paintOutlineWithHandles();
+ }
+ else //if the crop selection is set
+ {
+ m_dragStop = e->pos().floorTQPoint();
+ if (m_mouseOnHandleType != None && m_dragStart != m_dragStop ) {
+
+
+ TQ_INT32 imageWidth = m_subject->currentImg()->width();
+ TQ_INT32 imageHeight = m_subject->currentImg()->height();
+
+ paintOutlineWithHandles();
+
+ TQPoint pos = e->pos().floorTQPoint();
+ if( m_mouseOnHandleType == Inside )
+ {
+ m_rectCrop.moveBy( ( m_dragStop.x() - m_dragStart.x() ), ( m_dragStop.y() - m_dragStart.y() ) );
+ if( m_rectCrop.left() < 0 )
+ {
+ m_rectCrop.moveLeft( 0 );
+ }
+ if( m_rectCrop.right() > imageWidth )
+ {
+ m_rectCrop.moveRight( imageWidth );
+ }
+ if( m_rectCrop.top() < 0 )
+ {
+ m_rectCrop.moveTop( 0 );
+ }
+ if( m_rectCrop.bottom() > imageHeight )
+ {
+ m_rectCrop.moveBottom( imageHeight );
+ }
+ } else if(m_optWidget->boolRatio->isChecked())
+ {
+ TQPoint drag = m_dragStop - m_dragStart;
+ if( ! m_optWidget->boolWidth->isChecked() && !m_optWidget->boolHeight->isChecked() )
+ {
+ switch (m_mouseOnHandleType)
+ {
+ case (UpperLeft):
+ {
+ TQ_INT32 dep = (drag.x() + drag.y()) / 2;
+ m_rectCrop.setTop( m_rectCrop.top() + dep );
+ m_rectCrop.setLeft( (int) ( m_rectCrop.right() - m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
+ }
+ break;
+ case (LowerRight):
+ {
+ TQ_INT32 dep = (drag.x() + drag.y()) / 2;
+ m_rectCrop.setBottom( m_rectCrop.bottom() + dep );
+ m_rectCrop.setWidth( (int) ( m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
+ break;
+ }
+ case (UpperRight):
+ {
+ TQ_INT32 dep = (drag.x() - drag.y()) / 2;
+ m_rectCrop.setTop( m_rectCrop.top() - dep );
+ m_rectCrop.setWidth( (int) ( m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
+ break;
+ }
+ case (LowerLeft):
+ {
+ TQ_INT32 dep = (drag.x() - drag.y()) / 2;
+ m_rectCrop.setBottom( m_rectCrop.bottom() - dep );
+ m_rectCrop.setLeft( (int) ( m_rectCrop.right() - m_optWidget->doubleRatio->value() * m_rectCrop.height() ) );
+ break;
+ }
+ case (Upper):
+ m_rectCrop.setTop( pos.y() + m_dy );
+ m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
+ break;
+ case (Lower):
+ m_rectCrop.setBottom( pos.y() + m_dy );
+ m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
+ break;
+ case (Left):
+ m_rectCrop.setLeft( pos.x() + m_dx );
+ m_rectCrop.setHeight( (int) (m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
+ break;
+ case (Right):
+ m_rectCrop.setRight( pos.x() + m_dx );
+ m_rectCrop.setHeight( (int) (m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
+ break;
+ case (Inside): // never happen
+ break;
+ }
+ }
+ } else {
+ if( m_optWidget->boolWidth->isChecked() )
+ {
+ m_rectCrop.setWidth( m_optWidget->intWidth->value() + 1 );
+ } else {
+ switch (m_mouseOnHandleType)
+ {
+ case (LowerLeft):
+ case (Left):
+ case (UpperLeft):
+ m_rectCrop.setLeft( pos.x() + m_dx );
+ break;
+ case (Right):
+ case (UpperRight):
+ case (LowerRight):
+ m_rectCrop.setRight( pos.x() + m_dx );
+ break;
+ default:
+ break;
+ }
+ }
+ if( m_optWidget->boolHeight->isChecked() )
+ {
+ m_rectCrop.setHeight( m_optWidget->intHeight->value() + 1 );
+ } else {
+ switch (m_mouseOnHandleType)
+ {
+ case (UpperLeft):
+ case (Upper):
+ case (UpperRight):
+ m_rectCrop.setTop( pos.y() + m_dy );
+ break;
+ case (LowerRight):
+ case (LowerLeft):
+ case (Lower):
+ m_rectCrop.setBottom( pos.y() + m_dy );
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ if( m_rectCrop.height() < 0)
+ {
+ if( m_mouseOnHandleType == Lower)
+ m_mouseOnHandleType = Upper;
+ else if( m_mouseOnHandleType == LowerLeft)
+ m_mouseOnHandleType = UpperLeft;
+ else if( m_mouseOnHandleType == LowerRight)
+ m_mouseOnHandleType = UpperRight;
+ else if( m_mouseOnHandleType == Upper)
+ m_mouseOnHandleType = Lower;
+ else if( m_mouseOnHandleType == UpperLeft)
+ m_mouseOnHandleType = LowerLeft;
+ else if( m_mouseOnHandleType == UpperRight)
+ m_mouseOnHandleType = LowerRight;
+ }
+ if( m_rectCrop.width() < 0)
+ {
+ if( m_mouseOnHandleType == Right)
+ m_mouseOnHandleType = Left;
+ else if( m_mouseOnHandleType == UpperRight)
+ m_mouseOnHandleType = UpperLeft;
+ else if( m_mouseOnHandleType == LowerRight)
+ m_mouseOnHandleType = LowerLeft;
+ else if( m_mouseOnHandleType == Left)
+ m_mouseOnHandleType = Right;
+ else if( m_mouseOnHandleType == UpperLeft)
+ m_mouseOnHandleType = UpperRight;
+ else if( m_mouseOnHandleType == LowerLeft)
+ m_mouseOnHandleType = LowerRight;
+ }
+
+ m_rectCrop = m_rectCrop.normalize();
+ m_rectCrop = m_rectCrop.intersect( TQRect(0,0, imageWidth + 1, imageHeight + 1 ) );
+ m_dragStart = e->pos().floorTQPoint();
+ paintOutlineWithHandles();
+ }
+ }
+ updateWidgetValues();
+ }
+ else //if we are not selecting
+ {
+ if ( m_haveCropSelection ) //if the crop selection is set
+ {
+ KisCanvasController *controller = m_subject->canvasController();
+ TQ_INT32 type = mouseOnHandle(controller->windowToView(e->pos().floorTQPoint()));
+ //set resize cursor if we are on one of the handles
+ setMoveResizeCursor(type);
+ }
+ }
+ }
+}
+
+void KisToolCrop::updateWidgetValues(bool updateratio)
+{
+ TQRect r = realRectCrop();
+ setOptionWidgetX(r.x());
+ setOptionWidgetY(r.y());
+ setOptionWidgetWidth(r.width() );
+ setOptionWidgetHeight(r.height() );
+ if(updateratio && !m_optWidget->boolRatio->isChecked() )
+ setOptionWidgetRatio((double)r.width() / (double)r.height() );
+}
+
+void KisToolCrop::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_subject && m_subject->currentImg() && m_selecting && e->button() == Qt::LeftButton) {
+
+ m_selecting = false;
+ m_haveCropSelection = true;
+
+ paintOutlineWithHandles();
+ validateSelection();
+ paintOutlineWithHandles();
+ }
+}
+
+void KisToolCrop::doubleClick(KisDoubleClickEvent *)
+{
+ if (m_haveCropSelection) crop();
+}
+
+void KisToolCrop::validateSelection(bool updateratio)
+{
+ if (m_subject) {
+ KisImageSP image = m_subject->currentImg();
+
+ if (image) {
+ TQ_INT32 imageWidth = image->width();
+ TQ_INT32 imageHeight = image->height();
+ m_rectCrop.setLeft(TQMAX(0, m_rectCrop.left()));
+ m_rectCrop.setTop(TQMAX(0, m_rectCrop.top()));
+ m_rectCrop.setRight(TQMIN(imageWidth, m_rectCrop.right()));
+ m_rectCrop.setBottom(TQMIN(imageHeight, m_rectCrop.bottom()));
+
+ updateWidgetValues(updateratio);
+ }
+ }
+}
+
+void KisToolCrop::paintOutlineWithHandles()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintOutlineWithHandles(gc, rc);
+ }
+}
+
+void KisToolCrop::paintOutlineWithHandles(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject && (m_selecting || m_haveCropSelection)) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::SolidLine);
+ pen.setWidth(1);
+ TQPoint start;
+ TQPoint end;
+
+ Q_ASSERT(controller);
+ start = controller->windowToView(m_rectCrop.topLeft());
+ end = controller->windowToView(m_rectCrop.bottomRight());
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ //draw handles
+ m_handlesRegion = handles(TQRect(start, end));
+
+ TQ_INT32 startx;
+ TQ_INT32 starty;
+ TQ_INT32 endx;
+ TQ_INT32 endy;
+ if(start.x()<=end.x())
+ {
+ startx=start.x();
+ endx=end.x();
+ }
+ else
+ {
+ startx=end.x();
+ endx=start.x();
+ }
+ if(start.y()<=end.y())
+ {
+ starty=start.y();
+ endy=end.y();
+ }
+ else
+ {
+ starty=end.y();
+ endy=start.y();
+ }
+ //draw upper line of selection
+ gc.drawLine(startx + m_handleSize / 2 + 1, starty, startx + (endx - startx - m_handleSize) / 2 + 1, starty);
+ gc.drawLine(startx + (endx - startx + m_handleSize) / 2 + 1, starty, endx - m_handleSize / 2, starty);
+ //draw lower line of selection
+ gc.drawLine(startx + m_handleSize / 2 + 1, endy, startx + (endx - startx - m_handleSize) / 2 + 1, endy);
+ gc.drawLine(startx + (endx - startx + m_handleSize) / 2 + 1, endy, endx - m_handleSize / 2 , endy);
+ //draw right line of selection
+ gc.drawLine(startx, starty + m_handleSize / 2 + 1, startx, starty + (endy - starty - m_handleSize) / 2 + 1);
+ gc.drawLine(startx, starty + (endy - starty + m_handleSize) / 2 + 1, startx, endy - m_handleSize / 2);
+ //draw left line of selection
+ gc.drawLine(endx, starty + m_handleSize / 2 + 1, endx, starty + (endy - starty - m_handleSize) / 2 + 1);
+ gc.drawLine(endx, starty + (endy - starty + m_handleSize) / 2 + 1, endx, endy - m_handleSize / 2);
+
+ //draw guides
+ gc.drawLine(0,endy,startx - m_handleSize / 2,endy);
+ gc.drawLine(startx,endy + m_handleSize / 2 + 1, startx, controller->kiscanvas()->height());
+ gc.drawLine(endx,0,endx,starty - m_handleSize / 2);
+ gc.drawLine(endx + m_handleSize / 2 + 1,starty, controller->kiscanvas()->width(), starty);
+ TQMemArray <TQRect> rects = m_handlesRegion.rects ();
+ for (TQMemArray <TQRect>::ConstIterator it = rects.begin (); it != rects.end (); ++it)
+ {
+ gc.fillRect (*it, TQt::black);
+ }
+
+
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolCrop::crop() {
+ // XXX: Should cropping be part of KisImage/KisPaintDevice's API?
+
+ m_haveCropSelection = false;
+ setCursor(m_cropCursor);
+
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img)
+ return;
+
+ TQRect rc = realRectCrop().normalize();
+
+ // The visitor adds the undo steps to the macro
+ if (m_optWidget->cmbType->currentItem() == 0) {
+
+ TQRect dirty = img->bounds();
+
+ // The layer(s) under the current layer will take care of adding
+ // undo information to the Crop macro.
+ if (img->undo())
+ img->undoAdapter()->beginMacro(i18n("Crop"));
+
+ KisCropVisitor v(rc, false);
+ KisLayerSP layer = img->activeLayer();
+ layer->accept(v);
+ layer->setDirty( dirty );
+ if (img->undo())
+ img->undoAdapter()->endMacro();
+
+ }
+ else {
+ // Resize creates the undo macro itself
+ img->resize(rc, true);
+ }
+
+ m_rectCrop = TQRect(0,0,0,0);
+
+ updateWidgetValues();
+}
+
+void KisToolCrop::setCropX(int x)
+{
+ if (!m_haveCropSelection) {
+ m_haveCropSelection = true;
+ }
+ else {
+ paintOutlineWithHandles(); // remove outlines
+ }
+
+ m_rectCrop.setX(x);
+
+ validateSelection();
+ paintOutlineWithHandles();
+}
+
+void KisToolCrop::setCropY(int y)
+{
+ if (!m_haveCropSelection) {
+ m_haveCropSelection = true;
+ }
+ else {
+ paintOutlineWithHandles(); // remove outlines
+ }
+
+ m_rectCrop.setY(y);
+
+ validateSelection();
+ paintOutlineWithHandles();
+
+}
+
+void KisToolCrop::setCropWidth(int w)
+{
+ if (!m_haveCropSelection) {
+ m_haveCropSelection = true;
+ }
+ else {
+ paintOutlineWithHandles(); // remove outlines
+ }
+
+ m_rectCrop.setWidth(w + 1);
+
+ if( m_optWidget->boolRatio->isChecked() )
+ {
+ m_rectCrop.setHeight( (int) ( w / m_optWidget->doubleRatio->value() ) );
+ } else {
+ setOptionWidgetRatio((double)m_rectCrop.width() / (double)m_rectCrop.height() );
+ }
+
+ validateSelection();
+ paintOutlineWithHandles();
+
+}
+
+void KisToolCrop::setCropHeight(int h)
+{
+ if (!m_haveCropSelection) {
+ m_haveCropSelection = true;
+ }
+ else {
+ paintOutlineWithHandles(); // remove outlines
+ }
+
+ m_rectCrop.setHeight(h + 1);
+
+ if( m_optWidget->boolRatio->isChecked() )
+ {
+ m_rectCrop.setWidth( (int) ( h * m_optWidget->doubleRatio->value() ) );
+ } else {
+ setOptionWidgetRatio((double)m_rectCrop.width() / (double)m_rectCrop.height() );
+ }
+
+ validateSelection();
+ paintOutlineWithHandles();
+
+}
+
+void KisToolCrop::setRatio(double )
+{
+ if( ! (m_optWidget->boolWidth->isChecked() && m_optWidget->boolHeight->isChecked() ))
+ {
+ if (!m_haveCropSelection) {
+ m_haveCropSelection = true;
+ }
+ else {
+ paintOutlineWithHandles(); // remove outlines
+ }
+ if( m_optWidget->boolWidth->isChecked() )
+ {
+ m_rectCrop.setHeight( (int) ( m_rectCrop.width() / m_optWidget->doubleRatio->value()) );
+ setOptionWidgetHeight( m_rectCrop.height() );
+ } else if(m_optWidget->boolHeight->isChecked()) {
+ m_rectCrop.setWidth( (int) (m_rectCrop.height() * m_optWidget->doubleRatio->value()) );
+ setOptionWidgetWidth( m_rectCrop.width() );
+ } else {
+ int newwidth = (int) (m_optWidget->doubleRatio->value() * m_rectCrop.height());
+ newwidth = (newwidth + m_rectCrop.width()) / 2;
+ m_rectCrop.setWidth( newwidth + 1);
+ setOptionWidgetWidth( newwidth );
+ m_rectCrop.setHeight( (int) (newwidth / m_optWidget->doubleRatio->value()) + 1 );
+ setOptionWidgetHeight( m_rectCrop.height() - 1 );
+ }
+ validateSelection(false);
+ paintOutlineWithHandles();
+ }
+}
+
+void KisToolCrop::setOptionWidgetX(TQ_INT32 x)
+{
+ // Disable signals otherwise we get the valueChanged signal, which we don't want
+ // to go through the logic for setting values that way.
+ m_optWidget->intX->blockSignals(true);
+ m_optWidget->intX->setValue(x);
+ m_optWidget->intX->blockSignals(false);
+}
+
+void KisToolCrop::setOptionWidgetY(TQ_INT32 y)
+{
+ m_optWidget->intY->blockSignals(true);
+ m_optWidget->intY->setValue(y);
+ m_optWidget->intY->blockSignals(false);
+}
+
+void KisToolCrop::setOptionWidgetWidth(TQ_INT32 x)
+{
+ m_optWidget->intWidth->blockSignals(true);
+ m_optWidget->intWidth->setValue(x);
+ m_optWidget->intWidth->blockSignals(false);
+}
+
+void KisToolCrop::setOptionWidgetHeight(TQ_INT32 y)
+{
+ m_optWidget->intHeight->blockSignals(true);
+ m_optWidget->intHeight->setValue(y);
+ m_optWidget->intHeight->blockSignals(false);
+}
+
+void KisToolCrop::setOptionWidgetRatio(double ratio)
+{
+ m_optWidget->doubleRatio->blockSignals(true);
+ m_optWidget->doubleRatio->setValue(ratio);
+ m_optWidget->doubleRatio->blockSignals(false);
+}
+
+
+TQWidget* KisToolCrop::createOptionWidget(TQWidget* parent)
+{
+ m_optWidget = new WdgToolCrop(parent);
+ TQ_CHECK_PTR(m_optWidget);
+
+ connect(m_optWidget->bnCrop, TQT_SIGNAL(clicked()), this, TQT_SLOT(crop()));
+
+ connect(m_optWidget->intX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropX(int)));
+ connect(m_optWidget->intY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropY(int)));
+ connect(m_optWidget->intWidth, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropWidth(int)));
+ connect(m_optWidget->intHeight, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setCropHeight(int)));
+ connect(m_optWidget->doubleRatio, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(setRatio( double )));
+
+ return m_optWidget;
+}
+
+TQWidget* KisToolCrop::optionWidget()
+{
+ return m_optWidget;
+}
+
+void KisToolCrop::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Crop"),
+ "tool_crop",
+ 0,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Crop an area"));
+ m_action->setExclusiveGroup("tools");
+
+ m_ownAction = true;
+ }
+}
+
+TQRect toTQRect(double x, double y, int w, int h)
+{
+ return TQRect(int(x), int(y), w, h);
+}
+
+TQRegion KisToolCrop::handles(TQRect rect)
+{
+ TQRegion handlesRegion;
+
+ //add handle at the lower right corner
+ handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0, TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add handle at the upper right corner
+ handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0 , 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add rectangle at the lower left corner
+ handlesRegion += toTQRect( 0 - m_handleSize / 2.0 , TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add rectangle at the upper left corner
+ handlesRegion += toTQRect( 0 - m_handleSize / 2.0, 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add handle at the lower edge of the rectangle
+ handlesRegion += toTQRect( ( TQABS( rect.width() ) - m_handleSize ) / 2.0 , TQABS( rect.height() ) - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add handle at the right edge of the rectangle
+ handlesRegion += toTQRect( TQABS( rect.width() ) - m_handleSize / 2.0 , ( TQABS( rect.height() ) - m_handleSize ) / 2.0, m_handleSize, m_handleSize );
+ //add handle at the upper edge of the rectangle
+ handlesRegion += toTQRect( ( TQABS( rect.width() ) - m_handleSize ) / 2.0 , 0 - m_handleSize / 2.0, m_handleSize, m_handleSize );
+ //add handle at the left edge of the rectangle
+ handlesRegion += toTQRect( 0 - m_handleSize / 2.0, ( TQABS( rect.height() ) - m_handleSize ) / 2.0, m_handleSize, m_handleSize );
+
+ //move the handles to the correct position
+ if( rect.width() >= 0 && rect.height() >= 0)
+ {
+ handlesRegion.translate ( rect.x(), rect.y() );
+ }
+ else if( rect.width() < 0 && rect.height() >= 0)
+ {
+ handlesRegion.translate ( rect.x() - TQABS( rect.width() ), rect.y() );
+ }
+ else if( rect.width() >= 0 && rect.height() < 0)
+ {
+ handlesRegion.translate ( rect.x(), rect.y() - TQABS( rect.height() ) );
+ }
+ else if( rect.width() < 0 && rect.height() < 0)
+ {
+ handlesRegion.translate ( rect.x() - TQABS( rect.width() ), rect.y() - TQABS( rect.height() ) );
+ }
+ return handlesRegion;
+}
+
+TQ_INT32 KisToolCrop::mouseOnHandle(TQPoint currentViewPoint)
+{
+ KisCanvasController *controller = m_subject->canvasController();
+ Q_ASSERT(controller);
+ TQPoint start = controller->windowToView(m_rectCrop.topLeft());
+ TQPoint end = controller->windowToView(m_rectCrop.bottomRight());
+
+ TQ_INT32 startx;
+ TQ_INT32 starty;
+ TQ_INT32 endx;
+ TQ_INT32 endy;
+ if(start.x()<=end.x())
+ {
+ startx=start.x();
+ endx=end.x();
+ }
+ else
+ {
+ startx=end.x();
+ endx=start.x();
+ }
+ if(start.y()<=end.y())
+ {
+ starty=start.y();
+ endy=end.y();
+ }
+ else
+ {
+ starty=end.y();
+ endy=start.y();
+ }
+
+ if ( toTQRect ( startx - m_handleSize / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx= startx-currentViewPoint.x();
+ m_dy = starty - currentViewPoint.y();
+ }
+ return UpperLeft;
+ }
+ else if ( toTQRect ( startx - m_handleSize / 2.0, endy - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx = startx-currentViewPoint.x();
+ m_dy = endy-currentViewPoint.y();
+ }
+ return LowerLeft;
+ }
+ else if ( toTQRect ( endx - m_handleSize / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx = endx - currentViewPoint.x();
+ m_dy = starty - currentViewPoint.y() ;
+ }
+ return UpperRight;
+ }
+ else if ( toTQRect ( endx - m_handleSize / 2.0, endy - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx = endx - currentViewPoint.x();
+ m_dy= endy - currentViewPoint.y();
+ }
+ return LowerRight;
+ }
+ else if ( toTQRect ( startx + ( endx - startx - m_handleSize ) / 2.0, starty - m_handleSize / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dy = starty - currentViewPoint.y() ;
+ }
+ return Upper;
+ }
+ else if ( toTQRect ( startx + ( endx - startx - m_handleSize ) / 2.0, endy - m_handleSize / 2, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dy = endy - currentViewPoint.y();
+ }
+ return Lower;
+ }
+ else if ( toTQRect ( startx - m_handleSize / 2.0, starty + ( endy - starty - m_handleSize ) / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx = startx - currentViewPoint.x() ;
+ }
+ return Left;
+ }
+ else if ( toTQRect ( endx - m_handleSize / 2.0 , starty + ( endy - starty - m_handleSize ) / 2.0, m_handleSize, m_handleSize ).contains( currentViewPoint ) )
+ {
+ if( !m_selecting )
+ {
+ m_dx = endx-currentViewPoint.x();
+ }
+ return Right;
+ }
+ else if ( toTQRect ( startx , starty, endx - startx , endy - starty ).contains( currentViewPoint ) )
+ {
+ return Inside;
+ }
+ else return None;
+}
+
+void KisToolCrop::setMoveResizeCursor (TQ_INT32 handle)
+{
+ switch (handle)
+ {
+ case (UpperLeft):
+ case (LowerRight):
+ m_subject->canvasController()->setCanvasCursor(KisCursor::sizeFDiagCursor());
+ return;
+ case (LowerLeft):
+ case (UpperRight):
+ m_subject->canvasController()->setCanvasCursor(KisCursor::sizeBDiagCursor());
+ return;
+ case (Upper):
+ case (Lower):
+ m_subject->canvasController()->setCanvasCursor(KisCursor::sizeVerCursor());
+ return;
+ case (Left):
+ case (Right):
+ m_subject->canvasController()->setCanvasCursor(KisCursor::sizeHorCursor());
+ return;
+ case (Inside):
+ m_subject->canvasController()->setCanvasCursor(KisCursor::sizeAllCursor());
+ return;
+ }
+ m_subject->canvasController()->setCanvasCursor(KisCursor::arrowCursor());
+ return;
+}
+
+
+#include "kis_tool_crop.moc"
diff --git a/chalk/plugins/tools/tool_crop/tool_crop.cc b/chalk/plugins/tools/tool_crop/tool_crop.cc
deleted file mode 100644
index 97f6e0e85..000000000
--- a/chalk/plugins/tools/tool_crop/tool_crop.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * tool_crop.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_crop.h"
-#include "kis_tool_crop.h"
-
-
-typedef KGenericFactory<ToolCrop> ToolCropFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolcrop, ToolCropFactory( "chalk" ) )
-
-
-ToolCrop::ToolCrop(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolCropFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- r->add(new KisToolCropFactory());
- }
-
-}
-
-ToolCrop::~ToolCrop()
-{
-}
-
-#include "tool_crop.moc"
diff --git a/chalk/plugins/tools/tool_crop/tool_crop.cpp b/chalk/plugins/tools/tool_crop/tool_crop.cpp
new file mode 100644
index 000000000..30df11ec3
--- /dev/null
+++ b/chalk/plugins/tools/tool_crop/tool_crop.cpp
@@ -0,0 +1,62 @@
+/*
+ * tool_crop.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_crop.h"
+#include "kis_tool_crop.h"
+
+
+typedef KGenericFactory<ToolCrop> ToolCropFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolcrop, ToolCropFactory( "chalk" ) )
+
+
+ToolCrop::ToolCrop(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolCropFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ r->add(new KisToolCropFactory());
+ }
+
+}
+
+ToolCrop::~ToolCrop()
+{
+}
+
+#include "tool_crop.moc"
diff --git a/chalk/plugins/tools/tool_curves/Makefile.am b/chalk/plugins/tools/tool_curves/Makefile.am
index 92366e55c..75a515f29 100644
--- a/chalk/plugins/tools/tool_curves/Makefile.am
+++ b/chalk/plugins/tools/tool_curves/Makefile.am
@@ -10,15 +10,15 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolcurves_la_SOURCES = \
- kis_curve_framework.cc \
- kis_tool_curve.cc \
- tool_curves.cc \
+ kis_curve_framework.cpp \
+ kis_tool_curve.cpp \
+ tool_curves.cpp \
wdg_tool_example.ui \
- kis_tool_example.cc \
- kis_tool_bezier.cc \
- kis_tool_bezier_paint.cc \
- kis_tool_bezier_select.cc \
- kis_tool_moutline.cc
+ kis_tool_example.cpp \
+ kis_tool_bezier.cpp \
+ kis_tool_bezier_paint.cpp \
+ kis_tool_bezier_select.cpp \
+ kis_tool_moutline.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolcurves.la
diff --git a/chalk/plugins/tools/tool_curves/kis_curve_framework.cc b/chalk/plugins/tools/tool_curves/kis_curve_framework.cpp
index 8a9b4c886..8a9b4c886 100644
--- a/chalk/plugins/tools/tool_curves/kis_curve_framework.cc
+++ b/chalk/plugins/tools/tool_curves/kis_curve_framework.cpp
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier.cc b/chalk/plugins/tools/tool_curves/kis_tool_bezier.cc
deleted file mode 100644
index e4c1d05d0..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_bezier.cc
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * kis_tool_bezier.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <math.h>
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_global.h"
-#include "kis_doc.h"
-#include "kis_painter.h"
-#include "kis_point.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_vec.h"
-
-#include "kis_curve_framework.h"
-#include "kis_tool_bezier.h"
-
-KisCurve::iterator KisCurveBezier::groupEndpoint (KisCurve::iterator it) const
-{
- iterator temp = it;
- if ((*it).hint() == BEZIERNEXTCONTROLHINT)
- temp -= 1;
- if ((*it).hint() == BEZIERPREVCONTROLHINT)
- temp += 1;
- return temp;
-}
-
-KisCurve::iterator KisCurveBezier::groupPrevControl (KisCurve::iterator it) const
-{
- iterator temp = it;
- if ((*it).hint() == BEZIERENDHINT)
- temp -= 1;
- if ((*it).hint() == BEZIERNEXTCONTROLHINT)
- temp -= 2;
- return temp;
-}
-
-KisCurve::iterator KisCurveBezier::groupNextControl (KisCurve::iterator it) const
-{
- iterator temp = it;
- if ((*it).hint() == BEZIERENDHINT)
- temp += 1;
- if ((*it).hint() == BEZIERPREVCONTROLHINT)
- temp += 2;
- return temp;
-}
-
-bool KisCurveBezier::groupSelected (KisCurve::iterator it) const
-{
- if ((*groupPrevControl(it)).isSelected() || (*groupEndpoint(it)).isSelected() || (*groupNextControl(it)).isSelected())
- return true;
- return false;
-}
-
-KisCurve::iterator KisCurveBezier::nextGroupEndpoint (KisCurve::iterator it) const
-{
- iterator temp = it;
- if ((*it).hint() == BEZIERPREVCONTROLHINT) {
- temp += 2;
- temp = temp.nextPivot();
- }
- if ((*it).hint() == BEZIERENDHINT) {
- temp += 1;
- temp = temp.nextPivot();
- }
- if ((*it).hint() == BEZIERNEXTCONTROLHINT) {
- temp = temp.nextPivot();
- }
- temp = temp.nextPivot();
- return temp;
-}
-
-KisCurve::iterator KisCurveBezier::prevGroupEndpoint (KisCurve::iterator it) const
-{
- iterator temp = it;
- if ((*it).hint() == BEZIERNEXTCONTROLHINT) {
- temp -= 1;
- temp = temp.previousPivot().previousPivot();
- }
- if ((*it).hint() == BEZIERENDHINT) {
- temp = temp.previousPivot().previousPivot();
- }
- if ((*it).hint() == BEZIERPREVCONTROLHINT) {
- temp = temp.previousPivot();
- }
- temp = temp.previousPivot();
- return temp;
-}
-
-KisPoint KisCurveBezier::midpoint (const KisPoint& P1, const KisPoint& P2)
-{
- KisPoint temp;
- temp.setX((P1.x()+P2.x())/2);
- temp.setY((P1.y()+P2.y())/2);
- return temp;
-}
-
-void KisCurveBezier::recursiveCurve (const KisPoint& P1, const KisPoint& P2, const KisPoint& P3,
- const KisPoint& P4, int level, KisCurve::iterator it)
-{
- if (level > m_maxLevel) {
- addPoint(it,midpoint(P1,P4),false,false,LINEHINT);
- return;
- }
-
- KisPoint L1, L2, L3, L4;
- KisPoint H, R1, R2, R3, R4;
-
- L1 = P1;
- L2 = midpoint(P1, P2);
- H = midpoint(P2, P3);
- R3 = midpoint(P3, P4);
- R4 = P4;
- L3 = midpoint(L2, H);
- R2 = midpoint(R3, H);
- L4 = midpoint(L3, R2);
- R1 = L4;
- recursiveCurve(L1, L2, L3, L4, level + 1, it);
- recursiveCurve(R1, R2, R3, R4, level + 1, it);
-}
-
-void KisCurveBezier::calculateCurve(KisCurve::iterator tstart, KisCurve::iterator tend, KisCurve::iterator)
-{
- if (pivots().count() < 4)
- return;
-
- iterator origin, dest, control1, control2;
-
- if ((*tstart).hint() == BEZIERENDHINT) {
- origin = tstart;
- control1 = tstart.nextPivot();
- } else if ((*tstart).hint() == BEZIERNEXTCONTROLHINT) {
- origin = tstart.previousPivot();
- control1 = tstart;
- } else if ((*tstart).hint() == BEZIERPREVCONTROLHINT) {
- origin = tstart.nextPivot();
- control1 = origin.nextPivot();
- } else
- return;
-
- if ((*tend).hint() == BEZIERENDHINT) {
- dest = tend;
- control2 = tend.previousPivot();
- } else if ((*tend).hint() == BEZIERPREVCONTROLHINT) {
- dest = tend.nextPivot();
- control2 = tend;
- } else if ((*tend).hint() == BEZIERNEXTCONTROLHINT) {
- dest = tend.previousPivot();
- control2 = dest.previousPivot();
- } else
- return;
-
- deleteCurve(control1,control2);
- recursiveCurve((*origin).point(),(*control1).point(),(*control2).point(),(*dest).point(),1,control2);
-
-}
-
-KisCurve::iterator KisCurveBezier::pushPivot (const KisPoint& point)
-{
- iterator it;
-
- it = pushPoint(point,true,false,BEZIERENDHINT);
- if (count() > 1)
- addPoint(it,point,true,false,BEZIERPREVCONTROLHINT);
-
- it = pushPoint(point,true,false,BEZIERNEXTCONTROLHINT);
-
- return selectPivot(it);
-}
-
-KisCurve::iterator KisCurveBezier::movePivot(KisCurve::iterator it, const KisPoint& newPt)
-{
- if (!(*it).isPivot())
- return end();
-
- int hint = (*it).hint();
- iterator thisEnd, prevEnd, nextEnd;
-
- thisEnd = groupEndpoint(it);
- prevEnd = prevGroupEndpoint(it);
- nextEnd = nextGroupEndpoint(it);
-
- if (hint == BEZIERENDHINT) {
- KisPoint trans = newPt - (*it).point();
- (*thisEnd).setPoint((*thisEnd).point()+trans);
- (*thisEnd.previous()).setPoint((*thisEnd.previous()).point()+trans);
- (*thisEnd.next()).setPoint((*thisEnd.next()).point()+trans);
- } else if (!(m_actionOptions & KEEPSELECTEDOPTION))
- (*it).setPoint(newPt);
- if (!(m_actionOptions & KEEPSELECTEDOPTION) && hint != BEZIERENDHINT) {
- if (nextEnd == end() || (m_actionOptions & SYMMETRICALCONTROLSOPTION)) {
- KisPoint trans = (*it).point() - (*thisEnd).point();
- trans = KisPoint(-trans.x()*2,-trans.y()*2);
- if (hint == BEZIERNEXTCONTROLHINT)
- (*groupPrevControl(it)).setPoint(newPt+trans);
- else
- (*groupNextControl(it)).setPoint(newPt+trans);
- }
- }
-
- if (nextEnd != end() && count() > 4)
- calculateCurve (thisEnd,nextEnd,iterator());
- if (prevEnd != thisEnd && count() > 4)
- calculateCurve (prevEnd,thisEnd,iterator());
-
- return it;
-}
-
-void KisCurveBezier::deletePivot (KisCurve::iterator it)
-{
- if (!(*it).isPivot())
- return;
-
- iterator prevControl,thisEnd,nextControl;
-
- prevControl = prevGroupEndpoint(it).nextPivot();
- thisEnd = groupEndpoint(it);
- nextControl = nextGroupEndpoint(it).previousPivot();
-
- if ((*thisEnd) == first()) {
- deleteFirstPivot();
- deleteFirstPivot();
- deleteFirstPivot();
- } else if ((*thisEnd.next()) == last()) {
- deleteLastPivot();
- deleteLastPivot();
- deleteLastPivot();
- } else {
- deleteCurve(prevControl,nextControl);
- calculateCurve(prevControl,nextControl,iterator());
- }
-}
-
-KisToolBezier::KisToolBezier(const TQString& UIName)
- : super(UIName)
-{
- m_derivated = new KisCurveBezier;
- m_curve = m_derivated;
-
- m_supportMinimalDraw = false;
-
- m_transactionMessage = i18n("Bezier Curve");
-}
-
-KisToolBezier::~KisToolBezier()
-{
-
-}
-
-KisCurve::iterator KisToolBezier::handleUnderMouse(const TQPoint& pos)
-{
- TQPoint qpos;
- KisCurve pivs = m_curve->pivots(), inHandle;
- KisCurve::iterator it;
- int hint;
- for (it = pivs.begin(); it != pivs.end(); it++) {
- qpos = m_subject->canvasController()->windowToView((*it).point().toTQPoint());
- hint = (*it).hint();
- if (hint != BEZIERENDHINT && !m_derivated->groupSelected(it))
- continue;
- if (hint == BEZIERENDHINT && (m_actionOptions & SHIFTOPTION))
- continue;
- if (pivotRect(qpos).contains(pos)) {
- inHandle.pushPoint((*it));
- if (hint == BEZIERENDHINT && !(m_actionOptions & SHIFTOPTION))
- break;
- if (hint != BEZIERENDHINT && (m_actionOptions & SHIFTOPTION))
- break;
- }
- }
- if (inHandle.isEmpty())
- return m_curve->end();
-
- return m_curve->find(inHandle.last());
-}
-
-KisCurve::iterator KisToolBezier::drawPoint (KisCanvasPainter& gc, KisCurve::iterator point)
-{
- if ((*point).hint() != BEZIERENDHINT)
- return ++point;
-
- KisCanvasController *controller = m_subject->canvasController();
-
- // Now draw the bezier
-
- KisCurve::iterator origin,control1,control2,destination;
-
- origin = point;
- control1 = origin.next();
- control2 = control1.nextPivot();
- destination = control2.next();
-
- if (control2 != m_curve->end()) {
- point = control2;
- TQPointArray vec(4);
- vec[0] = controller->windowToView((*origin).point().toTQPoint());
- vec[1] = controller->windowToView((*control1).point().toTQPoint());
- vec[2] = controller->windowToView((*control2).point().toTQPoint());
- vec[3] = controller->windowToView((*destination).point().toTQPoint());
- gc.drawCubicBezier(vec);
- }
-
- point += 1;
-
- return point;
-}
-
-void KisToolBezier::drawPivotHandle (KisCanvasPainter& gc, KisCurve::iterator point)
-{
- if ((*point).hint() != BEZIERENDHINT)
- return;
-
- KisCanvasController *controller = m_subject->canvasController();
-
- TQPoint endpPos = controller->windowToView((*point).point().toTQPoint());
-
- if (!m_derivated->groupSelected(point)) {
- gc.setPen(m_pivotPen);
- gc.drawRoundRect(pivotRect(endpPos),m_pivotRounding,m_pivotRounding);
- } else {
- TQPoint nextControlPos = controller->windowToView((*point.next()).point().toTQPoint());
- TQPoint prevControlPos = controller->windowToView((*point.previousPivot()).point().toTQPoint());
-
- gc.setPen(m_selectedPivotPen);
- gc.drawRoundRect(selectedPivotRect(endpPos),m_selectedPivotRounding,m_selectedPivotRounding);
- if ((prevControlPos != endpPos || nextControlPos != endpPos) && !(m_actionOptions & CONTROLOPTION)) {
- gc.drawRoundRect(pivotRect(nextControlPos),m_pivotRounding,m_pivotRounding);
- gc.drawLine(endpPos,nextControlPos);
- gc.drawRoundRect(pivotRect(prevControlPos),m_pivotRounding,m_pivotRounding);
- gc.drawLine(prevControlPos,endpPos);
- }
- }
-
- gc.setPen(m_drawingPen);
-}
-
-#include "kis_tool_bezier.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier.cpp b/chalk/plugins/tools/tool_curves/kis_tool_bezier.cpp
new file mode 100644
index 000000000..9195dfbd7
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_bezier.cpp
@@ -0,0 +1,366 @@
+/*
+ * kis_tool_bezier.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <math.h>
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_global.h"
+#include "kis_doc.h"
+#include "kis_painter.h"
+#include "kis_point.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_vec.h"
+
+#include "kis_curve_framework.h"
+#include "kis_tool_bezier.h"
+
+KisCurve::iterator KisCurveBezier::groupEndpoint (KisCurve::iterator it) const
+{
+ iterator temp = it;
+ if ((*it).hint() == BEZIERNEXTCONTROLHINT)
+ temp -= 1;
+ if ((*it).hint() == BEZIERPREVCONTROLHINT)
+ temp += 1;
+ return temp;
+}
+
+KisCurve::iterator KisCurveBezier::groupPrevControl (KisCurve::iterator it) const
+{
+ iterator temp = it;
+ if ((*it).hint() == BEZIERENDHINT)
+ temp -= 1;
+ if ((*it).hint() == BEZIERNEXTCONTROLHINT)
+ temp -= 2;
+ return temp;
+}
+
+KisCurve::iterator KisCurveBezier::groupNextControl (KisCurve::iterator it) const
+{
+ iterator temp = it;
+ if ((*it).hint() == BEZIERENDHINT)
+ temp += 1;
+ if ((*it).hint() == BEZIERPREVCONTROLHINT)
+ temp += 2;
+ return temp;
+}
+
+bool KisCurveBezier::groupSelected (KisCurve::iterator it) const
+{
+ if ((*groupPrevControl(it)).isSelected() || (*groupEndpoint(it)).isSelected() || (*groupNextControl(it)).isSelected())
+ return true;
+ return false;
+}
+
+KisCurve::iterator KisCurveBezier::nextGroupEndpoint (KisCurve::iterator it) const
+{
+ iterator temp = it;
+ if ((*it).hint() == BEZIERPREVCONTROLHINT) {
+ temp += 2;
+ temp = temp.nextPivot();
+ }
+ if ((*it).hint() == BEZIERENDHINT) {
+ temp += 1;
+ temp = temp.nextPivot();
+ }
+ if ((*it).hint() == BEZIERNEXTCONTROLHINT) {
+ temp = temp.nextPivot();
+ }
+ temp = temp.nextPivot();
+ return temp;
+}
+
+KisCurve::iterator KisCurveBezier::prevGroupEndpoint (KisCurve::iterator it) const
+{
+ iterator temp = it;
+ if ((*it).hint() == BEZIERNEXTCONTROLHINT) {
+ temp -= 1;
+ temp = temp.previousPivot().previousPivot();
+ }
+ if ((*it).hint() == BEZIERENDHINT) {
+ temp = temp.previousPivot().previousPivot();
+ }
+ if ((*it).hint() == BEZIERPREVCONTROLHINT) {
+ temp = temp.previousPivot();
+ }
+ temp = temp.previousPivot();
+ return temp;
+}
+
+KisPoint KisCurveBezier::midpoint (const KisPoint& P1, const KisPoint& P2)
+{
+ KisPoint temp;
+ temp.setX((P1.x()+P2.x())/2);
+ temp.setY((P1.y()+P2.y())/2);
+ return temp;
+}
+
+void KisCurveBezier::recursiveCurve (const KisPoint& P1, const KisPoint& P2, const KisPoint& P3,
+ const KisPoint& P4, int level, KisCurve::iterator it)
+{
+ if (level > m_maxLevel) {
+ addPoint(it,midpoint(P1,P4),false,false,LINEHINT);
+ return;
+ }
+
+ KisPoint L1, L2, L3, L4;
+ KisPoint H, R1, R2, R3, R4;
+
+ L1 = P1;
+ L2 = midpoint(P1, P2);
+ H = midpoint(P2, P3);
+ R3 = midpoint(P3, P4);
+ R4 = P4;
+ L3 = midpoint(L2, H);
+ R2 = midpoint(R3, H);
+ L4 = midpoint(L3, R2);
+ R1 = L4;
+ recursiveCurve(L1, L2, L3, L4, level + 1, it);
+ recursiveCurve(R1, R2, R3, R4, level + 1, it);
+}
+
+void KisCurveBezier::calculateCurve(KisCurve::iterator tstart, KisCurve::iterator tend, KisCurve::iterator)
+{
+ if (pivots().count() < 4)
+ return;
+
+ iterator origin, dest, control1, control2;
+
+ if ((*tstart).hint() == BEZIERENDHINT) {
+ origin = tstart;
+ control1 = tstart.nextPivot();
+ } else if ((*tstart).hint() == BEZIERNEXTCONTROLHINT) {
+ origin = tstart.previousPivot();
+ control1 = tstart;
+ } else if ((*tstart).hint() == BEZIERPREVCONTROLHINT) {
+ origin = tstart.nextPivot();
+ control1 = origin.nextPivot();
+ } else
+ return;
+
+ if ((*tend).hint() == BEZIERENDHINT) {
+ dest = tend;
+ control2 = tend.previousPivot();
+ } else if ((*tend).hint() == BEZIERPREVCONTROLHINT) {
+ dest = tend.nextPivot();
+ control2 = tend;
+ } else if ((*tend).hint() == BEZIERNEXTCONTROLHINT) {
+ dest = tend.previousPivot();
+ control2 = dest.previousPivot();
+ } else
+ return;
+
+ deleteCurve(control1,control2);
+ recursiveCurve((*origin).point(),(*control1).point(),(*control2).point(),(*dest).point(),1,control2);
+
+}
+
+KisCurve::iterator KisCurveBezier::pushPivot (const KisPoint& point)
+{
+ iterator it;
+
+ it = pushPoint(point,true,false,BEZIERENDHINT);
+ if (count() > 1)
+ addPoint(it,point,true,false,BEZIERPREVCONTROLHINT);
+
+ it = pushPoint(point,true,false,BEZIERNEXTCONTROLHINT);
+
+ return selectPivot(it);
+}
+
+KisCurve::iterator KisCurveBezier::movePivot(KisCurve::iterator it, const KisPoint& newPt)
+{
+ if (!(*it).isPivot())
+ return end();
+
+ int hint = (*it).hint();
+ iterator thisEnd, prevEnd, nextEnd;
+
+ thisEnd = groupEndpoint(it);
+ prevEnd = prevGroupEndpoint(it);
+ nextEnd = nextGroupEndpoint(it);
+
+ if (hint == BEZIERENDHINT) {
+ KisPoint trans = newPt - (*it).point();
+ (*thisEnd).setPoint((*thisEnd).point()+trans);
+ (*thisEnd.previous()).setPoint((*thisEnd.previous()).point()+trans);
+ (*thisEnd.next()).setPoint((*thisEnd.next()).point()+trans);
+ } else if (!(m_actionOptions & KEEPSELECTEDOPTION))
+ (*it).setPoint(newPt);
+ if (!(m_actionOptions & KEEPSELECTEDOPTION) && hint != BEZIERENDHINT) {
+ if (nextEnd == end() || (m_actionOptions & SYMMETRICALCONTROLSOPTION)) {
+ KisPoint trans = (*it).point() - (*thisEnd).point();
+ trans = KisPoint(-trans.x()*2,-trans.y()*2);
+ if (hint == BEZIERNEXTCONTROLHINT)
+ (*groupPrevControl(it)).setPoint(newPt+trans);
+ else
+ (*groupNextControl(it)).setPoint(newPt+trans);
+ }
+ }
+
+ if (nextEnd != end() && count() > 4)
+ calculateCurve (thisEnd,nextEnd,iterator());
+ if (prevEnd != thisEnd && count() > 4)
+ calculateCurve (prevEnd,thisEnd,iterator());
+
+ return it;
+}
+
+void KisCurveBezier::deletePivot (KisCurve::iterator it)
+{
+ if (!(*it).isPivot())
+ return;
+
+ iterator prevControl,thisEnd,nextControl;
+
+ prevControl = prevGroupEndpoint(it).nextPivot();
+ thisEnd = groupEndpoint(it);
+ nextControl = nextGroupEndpoint(it).previousPivot();
+
+ if ((*thisEnd) == first()) {
+ deleteFirstPivot();
+ deleteFirstPivot();
+ deleteFirstPivot();
+ } else if ((*thisEnd.next()) == last()) {
+ deleteLastPivot();
+ deleteLastPivot();
+ deleteLastPivot();
+ } else {
+ deleteCurve(prevControl,nextControl);
+ calculateCurve(prevControl,nextControl,iterator());
+ }
+}
+
+KisToolBezier::KisToolBezier(const TQString& UIName)
+ : super(UIName)
+{
+ m_derivated = new KisCurveBezier;
+ m_curve = m_derivated;
+
+ m_supportMinimalDraw = false;
+
+ m_transactionMessage = i18n("Bezier Curve");
+}
+
+KisToolBezier::~KisToolBezier()
+{
+
+}
+
+KisCurve::iterator KisToolBezier::handleUnderMouse(const TQPoint& pos)
+{
+ TQPoint qpos;
+ KisCurve pivs = m_curve->pivots(), inHandle;
+ KisCurve::iterator it;
+ int hint;
+ for (it = pivs.begin(); it != pivs.end(); it++) {
+ qpos = m_subject->canvasController()->windowToView((*it).point().toTQPoint());
+ hint = (*it).hint();
+ if (hint != BEZIERENDHINT && !m_derivated->groupSelected(it))
+ continue;
+ if (hint == BEZIERENDHINT && (m_actionOptions & SHIFTOPTION))
+ continue;
+ if (pivotRect(qpos).contains(pos)) {
+ inHandle.pushPoint((*it));
+ if (hint == BEZIERENDHINT && !(m_actionOptions & SHIFTOPTION))
+ break;
+ if (hint != BEZIERENDHINT && (m_actionOptions & SHIFTOPTION))
+ break;
+ }
+ }
+ if (inHandle.isEmpty())
+ return m_curve->end();
+
+ return m_curve->find(inHandle.last());
+}
+
+KisCurve::iterator KisToolBezier::drawPoint (KisCanvasPainter& gc, KisCurve::iterator point)
+{
+ if ((*point).hint() != BEZIERENDHINT)
+ return ++point;
+
+ KisCanvasController *controller = m_subject->canvasController();
+
+ // Now draw the bezier
+
+ KisCurve::iterator origin,control1,control2,destination;
+
+ origin = point;
+ control1 = origin.next();
+ control2 = control1.nextPivot();
+ destination = control2.next();
+
+ if (control2 != m_curve->end()) {
+ point = control2;
+ TQPointArray vec(4);
+ vec[0] = controller->windowToView((*origin).point().toTQPoint());
+ vec[1] = controller->windowToView((*control1).point().toTQPoint());
+ vec[2] = controller->windowToView((*control2).point().toTQPoint());
+ vec[3] = controller->windowToView((*destination).point().toTQPoint());
+ gc.drawCubicBezier(vec);
+ }
+
+ point += 1;
+
+ return point;
+}
+
+void KisToolBezier::drawPivotHandle (KisCanvasPainter& gc, KisCurve::iterator point)
+{
+ if ((*point).hint() != BEZIERENDHINT)
+ return;
+
+ KisCanvasController *controller = m_subject->canvasController();
+
+ TQPoint endpPos = controller->windowToView((*point).point().toTQPoint());
+
+ if (!m_derivated->groupSelected(point)) {
+ gc.setPen(m_pivotPen);
+ gc.drawRoundRect(pivotRect(endpPos),m_pivotRounding,m_pivotRounding);
+ } else {
+ TQPoint nextControlPos = controller->windowToView((*point.next()).point().toTQPoint());
+ TQPoint prevControlPos = controller->windowToView((*point.previousPivot()).point().toTQPoint());
+
+ gc.setPen(m_selectedPivotPen);
+ gc.drawRoundRect(selectedPivotRect(endpPos),m_selectedPivotRounding,m_selectedPivotRounding);
+ if ((prevControlPos != endpPos || nextControlPos != endpPos) && !(m_actionOptions & CONTROLOPTION)) {
+ gc.drawRoundRect(pivotRect(nextControlPos),m_pivotRounding,m_pivotRounding);
+ gc.drawLine(endpPos,nextControlPos);
+ gc.drawRoundRect(pivotRect(prevControlPos),m_pivotRounding,m_pivotRounding);
+ gc.drawLine(prevControlPos,endpPos);
+ }
+ }
+
+ gc.setPen(m_drawingPen);
+}
+
+#include "kis_tool_bezier.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cc b/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cc
deleted file mode 100644
index 06f34f8cc..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cc
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * kis_tool_curve.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-#include <tqlabel.h>
-#include <tqpushbutton.h>
-#include <tqwhatsthis.h>
-#include <tqcheckbox.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kiconloader.h>
-
-#include "kis_cmb_composite.h"
-#include "kis_colorspace.h"
-#include "kis_config.h"
-#include "kis_cursor.h"
-#include "kis_doc.h"
-#include "kis_global.h"
-#include "kis_image.h"
-#include "kis_int_spinbox.h"
-#include "kis_paint_device.h"
-#include "kis_painter.h"
-#include "kis_paintop_registry.h"
-#include "kis_point.h"
-#include "kis_tool_controller.h"
-#include "kis_tool_paint.h"
-
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_canvas_subject.h"
-
-#include "kis_curve_framework.h"
-#include "kis_tool_bezier_paint.h"
-
-KisToolBezierPaint::KisToolBezierPaint()
- : super(i18n("Bezier Painting Tool"))
-{
- setName("tool_bezier_paint");
- m_cursor = "tool_bezier_cursor.png";
- setCursor(KisCursor::load(m_cursor, 6, 6));
-}
-
-KisToolBezierPaint::~KisToolBezierPaint()
-{
-
-}
-
-KisCurve::iterator KisToolBezierPaint::paintPoint (KisPainter& painter, KisCurve::iterator point)
-{
- KisCurve::iterator origin,destination,control1,control2;
- switch ((*point).hint()) {
- case BEZIERENDHINT:
- origin = point++;
- control1 = point;
- control2 = control1.nextPivot();
- destination = control2.next();
- if (m_curve->count() > 4 && (*point) != m_curve->last()) {
- point = point.nextPivot().next();
- painter.paintAt((*origin).point(),PRESSURE_DEFAULT,0,0);
- painter.paintBezierCurve((*origin).point(),PRESSURE_DEFAULT,0,0,(*control1).point(),
- (*control2).point(),(*destination).point(),PRESSURE_DEFAULT,0,0,0);
- }
- break;
- default:
- point = super::paintPoint(painter,point);
- }
-
- return point;
-}
-
-void KisToolBezierPaint::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Bezier"),
- "tool_bezier_paint",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Draw cubic beziers. Keep Alt, Control or Shift pressed for options. Return or double-click to finish."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_bezier_paint.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cpp b/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cpp
new file mode 100644
index 000000000..a8d1514be
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_bezier_paint.cpp
@@ -0,0 +1,115 @@
+/*
+ * kis_tool_curve.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+#include <tqlabel.h>
+#include <tqpushbutton.h>
+#include <tqwhatsthis.h>
+#include <tqcheckbox.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kiconloader.h>
+
+#include "kis_cmb_composite.h"
+#include "kis_colorspace.h"
+#include "kis_config.h"
+#include "kis_cursor.h"
+#include "kis_doc.h"
+#include "kis_global.h"
+#include "kis_image.h"
+#include "kis_int_spinbox.h"
+#include "kis_paint_device.h"
+#include "kis_painter.h"
+#include "kis_paintop_registry.h"
+#include "kis_point.h"
+#include "kis_tool_controller.h"
+#include "kis_tool_paint.h"
+
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_canvas_subject.h"
+
+#include "kis_curve_framework.h"
+#include "kis_tool_bezier_paint.h"
+
+KisToolBezierPaint::KisToolBezierPaint()
+ : super(i18n("Bezier Painting Tool"))
+{
+ setName("tool_bezier_paint");
+ m_cursor = "tool_bezier_cursor.png";
+ setCursor(KisCursor::load(m_cursor, 6, 6));
+}
+
+KisToolBezierPaint::~KisToolBezierPaint()
+{
+
+}
+
+KisCurve::iterator KisToolBezierPaint::paintPoint (KisPainter& painter, KisCurve::iterator point)
+{
+ KisCurve::iterator origin,destination,control1,control2;
+ switch ((*point).hint()) {
+ case BEZIERENDHINT:
+ origin = point++;
+ control1 = point;
+ control2 = control1.nextPivot();
+ destination = control2.next();
+ if (m_curve->count() > 4 && (*point) != m_curve->last()) {
+ point = point.nextPivot().next();
+ painter.paintAt((*origin).point(),PRESSURE_DEFAULT,0,0);
+ painter.paintBezierCurve((*origin).point(),PRESSURE_DEFAULT,0,0,(*control1).point(),
+ (*control2).point(),(*destination).point(),PRESSURE_DEFAULT,0,0,0);
+ }
+ break;
+ default:
+ point = super::paintPoint(painter,point);
+ }
+
+ return point;
+}
+
+void KisToolBezierPaint::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Bezier"),
+ "tool_bezier_paint",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Draw cubic beziers. Keep Alt, Control or Shift pressed for options. Return or double-click to finish."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_bezier_paint.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cc b/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cc
deleted file mode 100644
index 724189208..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cc
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * kis_tool_curve.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-#include <tqlabel.h>
-#include <tqpushbutton.h>
-#include <tqwhatsthis.h>
-#include <tqcheckbox.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kiconloader.h>
-
-#include "kis_cmb_composite.h"
-#include "kis_colorspace.h"
-#include "kis_config.h"
-#include "kis_cursor.h"
-#include "kis_doc.h"
-#include "kis_global.h"
-#include "kis_image.h"
-#include "kis_int_spinbox.h"
-#include "kis_paint_device.h"
-#include "kis_painter.h"
-#include "kis_paintop_registry.h"
-#include "kis_point.h"
-#include "kis_tool_controller.h"
-#include "kis_tool_paint.h"
-
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_canvas_subject.h"
-
-#include "kis_curve_framework.h"
-#include "kis_tool_bezier_select.h"
-
-KisToolBezierSelect::KisToolBezierSelect()
- : super(i18n("Bezier Selection Tool"))
-{
- setName("tool_bezier_select");
- m_cursor = "tool_bezier_cursor.png";
- setCursor(KisCursor::load(m_cursor, 6, 6));
-}
-
-KisToolBezierSelect::~KisToolBezierSelect()
-{
-
-}
-
-TQValueVector<KisPoint> KisToolBezierSelect::convertCurve()
-{
- TQValueVector<KisPoint> points;
-
- for (KisCurve::iterator i = m_curve->begin(); i != m_curve->end(); i++) {
- if (((*i).hint() != BEZIERPREVCONTROLHINT) && ((*i).hint() != BEZIERNEXTCONTROLHINT))
- points.append((*i).point());
- }
-
- return points;
-}
-
-void KisToolBezierSelect::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Bezier"),
- "tool_bezier_select",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Select areas of the image with bezier paths."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_bezier_select.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cpp b/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cpp
new file mode 100644
index 000000000..657358609
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_bezier_select.cpp
@@ -0,0 +1,104 @@
+/*
+ * kis_tool_curve.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+#include <tqlabel.h>
+#include <tqpushbutton.h>
+#include <tqwhatsthis.h>
+#include <tqcheckbox.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kiconloader.h>
+
+#include "kis_cmb_composite.h"
+#include "kis_colorspace.h"
+#include "kis_config.h"
+#include "kis_cursor.h"
+#include "kis_doc.h"
+#include "kis_global.h"
+#include "kis_image.h"
+#include "kis_int_spinbox.h"
+#include "kis_paint_device.h"
+#include "kis_painter.h"
+#include "kis_paintop_registry.h"
+#include "kis_point.h"
+#include "kis_tool_controller.h"
+#include "kis_tool_paint.h"
+
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_canvas_subject.h"
+
+#include "kis_curve_framework.h"
+#include "kis_tool_bezier_select.h"
+
+KisToolBezierSelect::KisToolBezierSelect()
+ : super(i18n("Bezier Selection Tool"))
+{
+ setName("tool_bezier_select");
+ m_cursor = "tool_bezier_cursor.png";
+ setCursor(KisCursor::load(m_cursor, 6, 6));
+}
+
+KisToolBezierSelect::~KisToolBezierSelect()
+{
+
+}
+
+TQValueVector<KisPoint> KisToolBezierSelect::convertCurve()
+{
+ TQValueVector<KisPoint> points;
+
+ for (KisCurve::iterator i = m_curve->begin(); i != m_curve->end(); i++) {
+ if (((*i).hint() != BEZIERPREVCONTROLHINT) && ((*i).hint() != BEZIERNEXTCONTROLHINT))
+ points.append((*i).point());
+ }
+
+ return points;
+}
+
+void KisToolBezierSelect::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Bezier"),
+ "tool_bezier_select",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Select areas of the image with bezier paths."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_bezier_select.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_curve.cc b/chalk/plugins/tools/tool_curves/kis_tool_curve.cc
deleted file mode 100644
index 7449e5817..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_curve.cc
+++ /dev/null
@@ -1,593 +0,0 @@
-/*
- * kis_tool_curve.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <math.h>
-#include <limits.h>
-
-#include <tqapplication.h>
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include "kis_global.h"
-#include "kis_doc.h"
-#include "kis_painter.h"
-#include "kis_point.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_tool_controller.h"
-#include "kis_vec.h"
-#include "kis_selection.h"
-#include "kis_selection_options.h"
-#include "kis_selected_transaction.h"
-#include "kis_paintop_registry.h"
-
-#include "kis_curve_framework.h"
-#include "kis_tool_curve.h"
-
-TQRect KisToolCurve::pivotRect (const TQPoint& pos)
-{
- return TQRect (pos-TQPoint(4,4),pos+TQPoint(4,4));
-}
-
-TQRect KisToolCurve::selectedPivotRect (const TQPoint& pos)
-{
- return TQRect (pos-TQPoint(5,5),pos+TQPoint(5,5));
-}
-
-KisToolCurve::KisToolCurve(const TQString& UIName)
- : super(UIName)
-{
- m_UIName = UIName;
- m_currentImage = 0;
- m_optWidget = 0;
-
- m_curve = 0;
-
- m_dragging = false;
- m_draggingCursor = false;
- m_drawPivots = true;
- m_drawingPen = TQPen(TQt::white, 0, TQt::SolidLine);
- m_pivotPen = TQPen(TQt::gray, 0, TQt::SolidLine);
- m_selectedPivotPen = TQPen(TQt::yellow, 0, TQt::SolidLine);
- m_pivotRounding = m_selectedPivotRounding = 55;
-
- m_actionOptions = NOOPTIONS;
- m_supportMinimalDraw = true;
- m_selectAction = SELECTION_ADD;
-}
-
-KisToolCurve::~KisToolCurve()
-{
-
-}
-
-void KisToolCurve::update (KisCanvasSubject *subject)
-{
- super::update(subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg();
-}
-
-void KisToolCurve::deactivate()
-{
- draw(false);
- if (m_curve) {
- m_curve->clear();
- m_curve->endActionOptions();
- }
-
- m_actionOptions = NOOPTIONS;
- m_dragging = false;
- m_drawPivots = true;
-}
-
-void KisToolCurve::buttonPress(KisButtonPressEvent *event)
-{
- updateOptions(event->state());
- if (!m_currentImage)
- return;
- if (event->button() == Qt::LeftButton) {
- m_dragging = true;
- m_currentPoint = event->pos();
- PointPair temp = pointUnderMouse (m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
- if (temp.first == m_curve->end() && !(m_actionOptions)) {
- draw(true, true);
- m_curve->selectAll(false);
- draw(true, true);
- draw(m_curve->end());
- m_previous = m_curve->find(m_curve->last());
- m_current = m_curve->pushPivot(event->pos());
- if (m_curve->pivots().count() > 1)
- m_curve->calculateCurve(m_previous,m_current,m_current);
- draw(m_current);
- } else {
- draw(true, true);
- if (temp.second)
- m_current = m_curve->selectPivot(temp.first);
- else
- m_current = selectByMouse(temp.first);
-
- if (!(*m_current).isSelected())
- m_dragging = false;
- draw(true, true);
- }
- }
-}
-
-void KisToolCurve::keyPress(TQKeyEvent *event)
-{
- if (event->key() == TQt::Key_Return) {
- m_dragging = false;
- commitCurve();
- } else
- if (event->key() == TQt::Key_Escape) {
- m_dragging = false;
- draw(false);
- m_curve->clear();
- } else
- if (event->key() == TQt::Key_Delete) {
- draw(false);
- m_dragging = false;
- m_curve->deleteSelected();
- m_current = m_curve->find(m_curve->last());
- m_previous = m_curve->selectPivot(m_current);
- draw(false);
- }
-}
-
-void KisToolCurve::keyRelease(TQKeyEvent *)
-{
-
-}
-
-void KisToolCurve::buttonRelease(KisButtonReleaseEvent *event)
-{
- updateOptions(event->state());
- m_dragging = false;
-}
-
-void KisToolCurve::doubleClick(KisDoubleClickEvent *)
-{
- commitCurve();
-}
-
-void KisToolCurve::move(KisMoveEvent *event)
-{
- updateOptions(event->state());
- PointPair temp = pointUnderMouse(m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
- if (temp.first == m_curve->end() && !m_dragging) {
- if (m_draggingCursor) {
- setCursor(KisCursor::load(m_cursor, 6, 6));
- m_draggingCursor = false;
- }
- } else {
- setCursor(KisCursor::load("tool_curve_dragging.png", 6, 6));
- m_draggingCursor = true;
- }
- if (m_dragging) {
- draw();
- KisPoint trans = event->pos() - m_currentPoint;
- m_curve->moveSelected(trans);
- m_currentPoint = event->pos();
- draw();
- }
-}
-
-double pointToSegmentDistance(const KisPoint& p, const KisPoint& l0, const KisPoint& l1)
-{
- double lineLength = sqrt((l1.x() - l0.x()) * (l1.x() - l0.x()) + (l1.y() - l0.y()) * (l1.y() - l0.y()));
- double distance = 0;
- KisVector2D v0(l0), v1(l1), v(p), seg(v0-v1), dist0(v0-p), dist1(v1-p);
-
- if (seg.length() < dist0.length() ||
- seg.length() < dist1.length()) // the point doesn't perpendicolarly intersecate the segment (or it's too far from the segment)
- return (double)INT_MAX;
-
- if (lineLength > DBL_EPSILON) {
- distance = ((l0.y() - l1.y()) * p.x() + (l1.x() - l0.x()) * p.y() + l0.x() * l1.y() - l1.x() * l0.y()) / lineLength;
- distance = fabs(distance);
- }
-
- return distance;
-}
-
-PointPair KisToolCurve::pointUnderMouse(const TQPoint& pos)
-{
- KisCurve::iterator it, next;
- TQPoint pos1, pos2;
- it = handleUnderMouse(pos);
- if (it != m_curve->end())
- return PointPair(it,true);
-
- for (it = m_curve->begin(); it != m_curve->end(); it++) {
- next = it.next();
- if (next == m_curve->end() || it == m_curve->end())
- return PointPair(m_curve->end(),false);
- if ((*it).hint() > LINEHINT || (*next).hint() > LINEHINT)
- continue;
- pos1 = m_subject->canvasController()->windowToView((*it).point().toTQPoint());
- pos2 = m_subject->canvasController()->windowToView((*next).point().toTQPoint());
- if (pos1 == pos2)
- continue;
- if (pointToSegmentDistance(pos,pos1,pos2) <= MAXDISTANCE)
- break;
- }
-
- return PointPair(it,false);
-}
-
-KisCurve::iterator KisToolCurve::handleUnderMouse(const TQPoint& pos)
-{
- KisCurve pivs = m_curve->pivots(), inHandle;
- KisCurve::iterator it;
- for (it = pivs.begin(); it != pivs.end(); it++) {
- if (pivotRect(m_subject->canvasController()->windowToView((*it).point().toTQPoint())).contains(pos))
- inHandle.pushPoint((*it));
- }
- if (inHandle.isEmpty())
- return m_curve->end();
- return m_curve->find(inHandle.last());
-}
-
-KisCurve::iterator KisToolCurve::selectByMouse(KisCurve::iterator it)
-{
- KisCurve::iterator prevPivot, nextPivot;
-
- if ((*it).isPivot())
- prevPivot = it;
- else
- prevPivot = it.previousPivot();
- nextPivot = it.nextPivot();
-
- m_curve->selectPivot(prevPivot);
- (*nextPivot).setSelected(true);
-
- return prevPivot;
-}
-
-int KisToolCurve::updateOptions(int key)
-{
- int options = 0x0000;
-
- if (key & TQt::ControlButton)
- options |= CONTROLOPTION;
-
- if (key & TQt::ShiftButton)
- options |= SHIFTOPTION;
-
- if (key & TQt::AltButton)
- options |= ALTOPTION;
-
- if (options != m_actionOptions) {
- draw(false);
- m_actionOptions = options;
- m_curve->setActionOptions(m_actionOptions);
- draw(false);
- }
-
- return m_actionOptions;
-}
-
-void KisToolCurve::draw(bool m, bool o)
-{
- draw(KisCurve::iterator(), o, m);
-}
-
-void KisToolCurve::draw(KisCurve::iterator inf, bool pivotonly, bool minimal)
-{
- if (m_curve->isEmpty())
- return;
- KisCanvasPainter *gc;
- KisCanvasController *controller;
- KisCanvas *canvas;
- if (m_subject && m_currentImage) {
- controller = m_subject->canvasController();
- canvas = controller->kiscanvas();
- gc = new KisCanvasPainter(canvas);
- } else
- return;
-
- gc->setPen(m_drawingPen);
- gc->setRasterOp(TQt::XorROP);
-
- KisCurve::iterator it, finish;
-
- if (minimal && m_supportMinimalDraw) {
- if (pivotonly) {
- KisCurve p = m_curve->pivots();
- for (KisCurve::iterator i = p.begin(); i != p.end(); i++)
- drawPivotHandle (*gc, i);
- delete gc;
- return;
- }
- if (inf.target() != 0) {
- if (inf != m_curve->end()) {
- it = inf.previousPivot();
- finish = inf.nextPivot();
- } else {
- it = --m_curve->end();
- finish = m_curve->end();
- }
- } else {
- KisCurve sel = m_curve->selectedPivots();
- if (sel.isEmpty()) {
- delete gc;
- return;
- }
- for (KisCurve::iterator i = sel.begin(); i != sel.end(); i++) {
- it = m_curve->find(*i).previousPivot();
- finish = m_curve->find(*i).nextPivot();
- if ((*finish).isSelected())
- finish = finish.previousPivot();
- while (it != finish) {
- if ((*it).isPivot())
- drawPivotHandle (*gc, it);
- it = drawPoint (*gc, it);
- }
- }
- delete gc;
- return;
- }
- } else {
- it = m_curve->begin();
- finish = m_curve->end();
- }
- while (it != finish) {
- if ((*it).isPivot())
- drawPivotHandle (*gc, it);
- it = drawPoint (*gc, it);
- }
-
- delete gc;
-}
-
-KisCurve::iterator KisToolCurve::drawPoint(KisCanvasPainter& gc, KisCurve::iterator point)
-{
- KisCanvasController *controller = m_subject->canvasController();
-
- TQPoint pos1, pos2;
- pos1 = controller->windowToView((*point).point().toTQPoint());
-
- switch ((*point).hint()) {
- case POINTHINT:
- gc.drawPoint(pos1);
- point += 1;
- break;
- case LINEHINT:
- gc.drawPoint(pos1);
- if (++point != m_curve->end() && (*point).hint() <= LINEHINT) {
- pos2 = controller->windowToView((*point).point().toTQPoint());
- gc.drawLine(pos1,pos2);
- }
- break;
- default:
- point += 1;
- }
-
- return point;
-}
-
-void KisToolCurve::drawPivotHandle(KisCanvasPainter& gc, KisCurve::iterator point)
-{
- KisCanvasController *controller = m_subject->canvasController();
-
- if (m_drawPivots) {
- TQPoint pos = controller->windowToView((*point).point().toTQPoint());
- if ((*point).isSelected()) {
- gc.setPen(m_selectedPivotPen);
- gc.drawRoundRect(selectedPivotRect(pos),m_selectedPivotRounding,m_selectedPivotRounding);
- } else {
- gc.setPen(m_pivotPen);
- gc.drawRoundRect(pivotRect(pos),m_pivotRounding,m_pivotRounding);
- }
- gc.setPen(m_drawingPen);
- }
-}
-
-void KisToolCurve::paint(KisCanvasPainter&)
-{
- draw(false);
-}
-
-void KisToolCurve::paint(KisCanvasPainter&, const TQRect&)
-{
- draw(false);
-}
-
-void KisToolCurve::commitCurve()
-{
- if (toolType() == TOOL_SHAPE || toolType() == TOOL_FREEHAND)
- paintCurve();
- else if (toolType() == TOOL_SELECT)
- selectCurve();
- else
- kdDebug(0) << "NO SUPPORT FOR THIS TYPE OF TOOL" << endl;
-
- m_curve->clear();
- m_curve->endActionOptions();
-}
-
-void KisToolCurve::paintCurve()
-{
- KisPaintDeviceSP device = m_currentImage->activeDevice ();
- if (!device) return;
-
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (m_transactionMessage);
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBrush(m_subject->currentBrush());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op); // Painter takes ownership
-
-// Call paintPoint
- KisCurve::iterator it = m_curve->begin();
- while (it != m_curve->end())
- it = paintPoint(painter,it);
-// Finish
-
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
-
- draw(false);
-}
-
-KisCurve::iterator KisToolCurve::paintPoint (KisPainter& painter, KisCurve::iterator point)
-{
- KisCurve::iterator next = point; next+=1;
- switch ((*point).hint()) {
- case POINTHINT:
- painter.paintAt((*point++).point(), PRESSURE_DEFAULT, 0, 0);
- break;
- case LINEHINT:
- if (next != m_curve->end() && (*next).hint() <= LINEHINT)
- painter.paintLine((*point++).point(), PRESSURE_DEFAULT, 0, 0, (*next).point(), PRESSURE_DEFAULT, 0, 0);
- else
- painter.paintAt((*point++).point(), PRESSURE_DEFAULT, 0, 0);
- break;
- default:
- point += 1;
- }
-
- return point;
-}
-
-TQValueVector<KisPoint> KisToolCurve::convertCurve()
-{
- TQValueVector<KisPoint> points;
-
- for (KisCurve::iterator i = m_curve->begin(); i != m_curve->end(); i++)
- if ((*i).hint() != NOHINTS)
- points.append((*i).point());
-
- return points;
-}
-
-void KisToolCurve::selectCurve()
-{
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- KisPaintDeviceSP dev = m_currentImage->activeDevice();
- bool hasSelection = dev->hasSelection();
- KisSelectedTransaction *t = 0;
- if (m_currentImage->undo()) t = new KisSelectedTransaction(m_transactionMessage, dev);
- KisSelectionSP selection = dev->selection();
-
- if (!hasSelection) {
- selection->clear();
- }
-
- KisPainter painter(selection.data());
-
- painter.setPaintColor(KisColor(TQt::black, selection->colorSpace()));
- painter.setFillStyle(KisPainter::FillStyleForegroundColor);
- painter.setStrokeStyle(KisPainter::StrokeStyleNone);
- painter.setBrush(m_subject->currentBrush());
- painter.setOpacity(OPACITY_OPAQUE);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("paintbrush", 0, &painter);
- painter.setPaintOp(op); // And now the painter owns the op and will destroy it.
-
- switch (m_selectAction) {
- case SELECTION_ADD:
- painter.setCompositeOp(COMPOSITE_OVER);
- break;
- case SELECTION_SUBTRACT:
- painter.setCompositeOp(COMPOSITE_SUBTRACT);
- break;
- default:
- break;
- }
-
- painter.paintPolygon(convertCurve());
-
-
- if(hasSelection) {
- TQRect dirty(painter.dirtyRect());
- dev->setDirty(dirty);
- dev->emitSelectionChanged(dirty);
- } else {
- dev->setDirty();
- dev->emitSelectionChanged();
- }
-
- if (m_currentImage->undo())
- m_currentImage->undoAdapter()->addCommand(t);
-
- TQApplication::restoreOverrideCursor();
-
- draw(false);
-}
-
-TQWidget* KisToolCurve::createOptionWidget(TQWidget* parent)
-{
- if (toolType() == TOOL_SHAPE || toolType() == TOOL_FREEHAND)
- return super::createOptionWidget(parent);
- else if (toolType() == TOOL_SELECT)
- return createSelectionOptionWidget(parent);
- else
- kdDebug(0) << "NO SUPPORT FOR THIS TOOL TYPE" << endl;
- return 0;
-}
-
-void KisToolCurve::slotSetAction(int action) {
- if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
- m_selectAction =(enumSelectionMode)action;
-}
-
-TQWidget* KisToolCurve::createSelectionOptionWidget(TQWidget* parent)
-{
- m_optWidget = new KisSelectionOptions(parent, m_subject);
- TQ_CHECK_PTR(m_optWidget);
- m_optWidget->setCaption(m_UIName);
-
- connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
-
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
-
- return m_optWidget;
-}
-
-TQWidget* KisToolCurve::optionWidget()
-{
- if (toolType() == TOOL_SELECT)
- return m_optWidget;
- else
- return super::optionWidget();
-}
-
-#include "kis_tool_curve.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_curve.cpp b/chalk/plugins/tools/tool_curves/kis_tool_curve.cpp
new file mode 100644
index 000000000..ea1f9a773
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_curve.cpp
@@ -0,0 +1,593 @@
+/*
+ * kis_tool_curve.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <math.h>
+#include <limits.h>
+
+#include <tqapplication.h>
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include "kis_global.h"
+#include "kis_doc.h"
+#include "kis_painter.h"
+#include "kis_point.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_tool_controller.h"
+#include "kis_vec.h"
+#include "kis_selection.h"
+#include "kis_selection_options.h"
+#include "kis_selected_transaction.h"
+#include "kis_paintop_registry.h"
+
+#include "kis_curve_framework.h"
+#include "kis_tool_curve.h"
+
+TQRect KisToolCurve::pivotRect (const TQPoint& pos)
+{
+ return TQRect (pos-TQPoint(4,4),pos+TQPoint(4,4));
+}
+
+TQRect KisToolCurve::selectedPivotRect (const TQPoint& pos)
+{
+ return TQRect (pos-TQPoint(5,5),pos+TQPoint(5,5));
+}
+
+KisToolCurve::KisToolCurve(const TQString& UIName)
+ : super(UIName)
+{
+ m_UIName = UIName;
+ m_currentImage = 0;
+ m_optWidget = 0;
+
+ m_curve = 0;
+
+ m_dragging = false;
+ m_draggingCursor = false;
+ m_drawPivots = true;
+ m_drawingPen = TQPen(TQt::white, 0, TQt::SolidLine);
+ m_pivotPen = TQPen(TQt::gray, 0, TQt::SolidLine);
+ m_selectedPivotPen = TQPen(TQt::yellow, 0, TQt::SolidLine);
+ m_pivotRounding = m_selectedPivotRounding = 55;
+
+ m_actionOptions = NOOPTIONS;
+ m_supportMinimalDraw = true;
+ m_selectAction = SELECTION_ADD;
+}
+
+KisToolCurve::~KisToolCurve()
+{
+
+}
+
+void KisToolCurve::update (KisCanvasSubject *subject)
+{
+ super::update(subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg();
+}
+
+void KisToolCurve::deactivate()
+{
+ draw(false);
+ if (m_curve) {
+ m_curve->clear();
+ m_curve->endActionOptions();
+ }
+
+ m_actionOptions = NOOPTIONS;
+ m_dragging = false;
+ m_drawPivots = true;
+}
+
+void KisToolCurve::buttonPress(KisButtonPressEvent *event)
+{
+ updateOptions(event->state());
+ if (!m_currentImage)
+ return;
+ if (event->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_currentPoint = event->pos();
+ PointPair temp = pointUnderMouse (m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
+ if (temp.first == m_curve->end() && !(m_actionOptions)) {
+ draw(true, true);
+ m_curve->selectAll(false);
+ draw(true, true);
+ draw(m_curve->end());
+ m_previous = m_curve->find(m_curve->last());
+ m_current = m_curve->pushPivot(event->pos());
+ if (m_curve->pivots().count() > 1)
+ m_curve->calculateCurve(m_previous,m_current,m_current);
+ draw(m_current);
+ } else {
+ draw(true, true);
+ if (temp.second)
+ m_current = m_curve->selectPivot(temp.first);
+ else
+ m_current = selectByMouse(temp.first);
+
+ if (!(*m_current).isSelected())
+ m_dragging = false;
+ draw(true, true);
+ }
+ }
+}
+
+void KisToolCurve::keyPress(TQKeyEvent *event)
+{
+ if (event->key() == TQt::Key_Return) {
+ m_dragging = false;
+ commitCurve();
+ } else
+ if (event->key() == TQt::Key_Escape) {
+ m_dragging = false;
+ draw(false);
+ m_curve->clear();
+ } else
+ if (event->key() == TQt::Key_Delete) {
+ draw(false);
+ m_dragging = false;
+ m_curve->deleteSelected();
+ m_current = m_curve->find(m_curve->last());
+ m_previous = m_curve->selectPivot(m_current);
+ draw(false);
+ }
+}
+
+void KisToolCurve::keyRelease(TQKeyEvent *)
+{
+
+}
+
+void KisToolCurve::buttonRelease(KisButtonReleaseEvent *event)
+{
+ updateOptions(event->state());
+ m_dragging = false;
+}
+
+void KisToolCurve::doubleClick(KisDoubleClickEvent *)
+{
+ commitCurve();
+}
+
+void KisToolCurve::move(KisMoveEvent *event)
+{
+ updateOptions(event->state());
+ PointPair temp = pointUnderMouse(m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
+ if (temp.first == m_curve->end() && !m_dragging) {
+ if (m_draggingCursor) {
+ setCursor(KisCursor::load(m_cursor, 6, 6));
+ m_draggingCursor = false;
+ }
+ } else {
+ setCursor(KisCursor::load("tool_curve_dragging.png", 6, 6));
+ m_draggingCursor = true;
+ }
+ if (m_dragging) {
+ draw();
+ KisPoint trans = event->pos() - m_currentPoint;
+ m_curve->moveSelected(trans);
+ m_currentPoint = event->pos();
+ draw();
+ }
+}
+
+double pointToSegmentDistance(const KisPoint& p, const KisPoint& l0, const KisPoint& l1)
+{
+ double lineLength = sqrt((l1.x() - l0.x()) * (l1.x() - l0.x()) + (l1.y() - l0.y()) * (l1.y() - l0.y()));
+ double distance = 0;
+ KisVector2D v0(l0), v1(l1), v(p), seg(v0-v1), dist0(v0-p), dist1(v1-p);
+
+ if (seg.length() < dist0.length() ||
+ seg.length() < dist1.length()) // the point doesn't perpendicolarly intersecate the segment (or it's too far from the segment)
+ return (double)INT_MAX;
+
+ if (lineLength > DBL_EPSILON) {
+ distance = ((l0.y() - l1.y()) * p.x() + (l1.x() - l0.x()) * p.y() + l0.x() * l1.y() - l1.x() * l0.y()) / lineLength;
+ distance = fabs(distance);
+ }
+
+ return distance;
+}
+
+PointPair KisToolCurve::pointUnderMouse(const TQPoint& pos)
+{
+ KisCurve::iterator it, next;
+ TQPoint pos1, pos2;
+ it = handleUnderMouse(pos);
+ if (it != m_curve->end())
+ return PointPair(it,true);
+
+ for (it = m_curve->begin(); it != m_curve->end(); it++) {
+ next = it.next();
+ if (next == m_curve->end() || it == m_curve->end())
+ return PointPair(m_curve->end(),false);
+ if ((*it).hint() > LINEHINT || (*next).hint() > LINEHINT)
+ continue;
+ pos1 = m_subject->canvasController()->windowToView((*it).point().toTQPoint());
+ pos2 = m_subject->canvasController()->windowToView((*next).point().toTQPoint());
+ if (pos1 == pos2)
+ continue;
+ if (pointToSegmentDistance(pos,pos1,pos2) <= MAXDISTANCE)
+ break;
+ }
+
+ return PointPair(it,false);
+}
+
+KisCurve::iterator KisToolCurve::handleUnderMouse(const TQPoint& pos)
+{
+ KisCurve pivs = m_curve->pivots(), inHandle;
+ KisCurve::iterator it;
+ for (it = pivs.begin(); it != pivs.end(); it++) {
+ if (pivotRect(m_subject->canvasController()->windowToView((*it).point().toTQPoint())).contains(pos))
+ inHandle.pushPoint((*it));
+ }
+ if (inHandle.isEmpty())
+ return m_curve->end();
+ return m_curve->find(inHandle.last());
+}
+
+KisCurve::iterator KisToolCurve::selectByMouse(KisCurve::iterator it)
+{
+ KisCurve::iterator prevPivot, nextPivot;
+
+ if ((*it).isPivot())
+ prevPivot = it;
+ else
+ prevPivot = it.previousPivot();
+ nextPivot = it.nextPivot();
+
+ m_curve->selectPivot(prevPivot);
+ (*nextPivot).setSelected(true);
+
+ return prevPivot;
+}
+
+int KisToolCurve::updateOptions(int key)
+{
+ int options = 0x0000;
+
+ if (key & TQt::ControlButton)
+ options |= CONTROLOPTION;
+
+ if (key & TQt::ShiftButton)
+ options |= SHIFTOPTION;
+
+ if (key & TQt::AltButton)
+ options |= ALTOPTION;
+
+ if (options != m_actionOptions) {
+ draw(false);
+ m_actionOptions = options;
+ m_curve->setActionOptions(m_actionOptions);
+ draw(false);
+ }
+
+ return m_actionOptions;
+}
+
+void KisToolCurve::draw(bool m, bool o)
+{
+ draw(KisCurve::iterator(), o, m);
+}
+
+void KisToolCurve::draw(KisCurve::iterator inf, bool pivotonly, bool minimal)
+{
+ if (m_curve->isEmpty())
+ return;
+ KisCanvasPainter *gc;
+ KisCanvasController *controller;
+ KisCanvas *canvas;
+ if (m_subject && m_currentImage) {
+ controller = m_subject->canvasController();
+ canvas = controller->kiscanvas();
+ gc = new KisCanvasPainter(canvas);
+ } else
+ return;
+
+ gc->setPen(m_drawingPen);
+ gc->setRasterOp(TQt::XorROP);
+
+ KisCurve::iterator it, finish;
+
+ if (minimal && m_supportMinimalDraw) {
+ if (pivotonly) {
+ KisCurve p = m_curve->pivots();
+ for (KisCurve::iterator i = p.begin(); i != p.end(); i++)
+ drawPivotHandle (*gc, i);
+ delete gc;
+ return;
+ }
+ if (inf.target() != 0) {
+ if (inf != m_curve->end()) {
+ it = inf.previousPivot();
+ finish = inf.nextPivot();
+ } else {
+ it = --m_curve->end();
+ finish = m_curve->end();
+ }
+ } else {
+ KisCurve sel = m_curve->selectedPivots();
+ if (sel.isEmpty()) {
+ delete gc;
+ return;
+ }
+ for (KisCurve::iterator i = sel.begin(); i != sel.end(); i++) {
+ it = m_curve->find(*i).previousPivot();
+ finish = m_curve->find(*i).nextPivot();
+ if ((*finish).isSelected())
+ finish = finish.previousPivot();
+ while (it != finish) {
+ if ((*it).isPivot())
+ drawPivotHandle (*gc, it);
+ it = drawPoint (*gc, it);
+ }
+ }
+ delete gc;
+ return;
+ }
+ } else {
+ it = m_curve->begin();
+ finish = m_curve->end();
+ }
+ while (it != finish) {
+ if ((*it).isPivot())
+ drawPivotHandle (*gc, it);
+ it = drawPoint (*gc, it);
+ }
+
+ delete gc;
+}
+
+KisCurve::iterator KisToolCurve::drawPoint(KisCanvasPainter& gc, KisCurve::iterator point)
+{
+ KisCanvasController *controller = m_subject->canvasController();
+
+ TQPoint pos1, pos2;
+ pos1 = controller->windowToView((*point).point().toTQPoint());
+
+ switch ((*point).hint()) {
+ case POINTHINT:
+ gc.drawPoint(pos1);
+ point += 1;
+ break;
+ case LINEHINT:
+ gc.drawPoint(pos1);
+ if (++point != m_curve->end() && (*point).hint() <= LINEHINT) {
+ pos2 = controller->windowToView((*point).point().toTQPoint());
+ gc.drawLine(pos1,pos2);
+ }
+ break;
+ default:
+ point += 1;
+ }
+
+ return point;
+}
+
+void KisToolCurve::drawPivotHandle(KisCanvasPainter& gc, KisCurve::iterator point)
+{
+ KisCanvasController *controller = m_subject->canvasController();
+
+ if (m_drawPivots) {
+ TQPoint pos = controller->windowToView((*point).point().toTQPoint());
+ if ((*point).isSelected()) {
+ gc.setPen(m_selectedPivotPen);
+ gc.drawRoundRect(selectedPivotRect(pos),m_selectedPivotRounding,m_selectedPivotRounding);
+ } else {
+ gc.setPen(m_pivotPen);
+ gc.drawRoundRect(pivotRect(pos),m_pivotRounding,m_pivotRounding);
+ }
+ gc.setPen(m_drawingPen);
+ }
+}
+
+void KisToolCurve::paint(KisCanvasPainter&)
+{
+ draw(false);
+}
+
+void KisToolCurve::paint(KisCanvasPainter&, const TQRect&)
+{
+ draw(false);
+}
+
+void KisToolCurve::commitCurve()
+{
+ if (toolType() == TOOL_SHAPE || toolType() == TOOL_FREEHAND)
+ paintCurve();
+ else if (toolType() == TOOL_SELECT)
+ selectCurve();
+ else
+ kdDebug(0) << "NO SUPPORT FOR THIS TYPE OF TOOL" << endl;
+
+ m_curve->clear();
+ m_curve->endActionOptions();
+}
+
+void KisToolCurve::paintCurve()
+{
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();
+ if (!device) return;
+
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (m_transactionMessage);
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op); // Painter takes ownership
+
+// Call paintPoint
+ KisCurve::iterator it = m_curve->begin();
+ while (it != m_curve->end())
+ it = paintPoint(painter,it);
+// Finish
+
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+
+ draw(false);
+}
+
+KisCurve::iterator KisToolCurve::paintPoint (KisPainter& painter, KisCurve::iterator point)
+{
+ KisCurve::iterator next = point; next+=1;
+ switch ((*point).hint()) {
+ case POINTHINT:
+ painter.paintAt((*point++).point(), PRESSURE_DEFAULT, 0, 0);
+ break;
+ case LINEHINT:
+ if (next != m_curve->end() && (*next).hint() <= LINEHINT)
+ painter.paintLine((*point++).point(), PRESSURE_DEFAULT, 0, 0, (*next).point(), PRESSURE_DEFAULT, 0, 0);
+ else
+ painter.paintAt((*point++).point(), PRESSURE_DEFAULT, 0, 0);
+ break;
+ default:
+ point += 1;
+ }
+
+ return point;
+}
+
+TQValueVector<KisPoint> KisToolCurve::convertCurve()
+{
+ TQValueVector<KisPoint> points;
+
+ for (KisCurve::iterator i = m_curve->begin(); i != m_curve->end(); i++)
+ if ((*i).hint() != NOHINTS)
+ points.append((*i).point());
+
+ return points;
+}
+
+void KisToolCurve::selectCurve()
+{
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ KisPaintDeviceSP dev = m_currentImage->activeDevice();
+ bool hasSelection = dev->hasSelection();
+ KisSelectedTransaction *t = 0;
+ if (m_currentImage->undo()) t = new KisSelectedTransaction(m_transactionMessage, dev);
+ KisSelectionSP selection = dev->selection();
+
+ if (!hasSelection) {
+ selection->clear();
+ }
+
+ KisPainter painter(selection.data());
+
+ painter.setPaintColor(KisColor(TQt::black, selection->colorSpace()));
+ painter.setFillStyle(KisPainter::FillStyleForegroundColor);
+ painter.setStrokeStyle(KisPainter::StrokeStyleNone);
+ painter.setBrush(m_subject->currentBrush());
+ painter.setOpacity(OPACITY_OPAQUE);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("paintbrush", 0, &painter);
+ painter.setPaintOp(op); // And now the painter owns the op and will destroy it.
+
+ switch (m_selectAction) {
+ case SELECTION_ADD:
+ painter.setCompositeOp(COMPOSITE_OVER);
+ break;
+ case SELECTION_SUBTRACT:
+ painter.setCompositeOp(COMPOSITE_SUBTRACT);
+ break;
+ default:
+ break;
+ }
+
+ painter.paintPolygon(convertCurve());
+
+
+ if(hasSelection) {
+ TQRect dirty(painter.dirtyRect());
+ dev->setDirty(dirty);
+ dev->emitSelectionChanged(dirty);
+ } else {
+ dev->setDirty();
+ dev->emitSelectionChanged();
+ }
+
+ if (m_currentImage->undo())
+ m_currentImage->undoAdapter()->addCommand(t);
+
+ TQApplication::restoreOverrideCursor();
+
+ draw(false);
+}
+
+TQWidget* KisToolCurve::createOptionWidget(TQWidget* parent)
+{
+ if (toolType() == TOOL_SHAPE || toolType() == TOOL_FREEHAND)
+ return super::createOptionWidget(parent);
+ else if (toolType() == TOOL_SELECT)
+ return createSelectionOptionWidget(parent);
+ else
+ kdDebug(0) << "NO SUPPORT FOR THIS TOOL TYPE" << endl;
+ return 0;
+}
+
+void KisToolCurve::slotSetAction(int action) {
+ if (action >= SELECTION_ADD && action <= SELECTION_SUBTRACT)
+ m_selectAction =(enumSelectionMode)action;
+}
+
+TQWidget* KisToolCurve::createSelectionOptionWidget(TQWidget* parent)
+{
+ m_optWidget = new KisSelectionOptions(parent, m_subject);
+ TQ_CHECK_PTR(m_optWidget);
+ m_optWidget->setCaption(m_UIName);
+
+ connect (m_optWidget, TQT_SIGNAL(actionChanged(int)), this, TQT_SLOT(slotSetAction(int)));
+
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ l->addItem(new TQSpacerItem(1, 1, TQSizePolicy::Fixed, TQSizePolicy::Expanding));
+
+ return m_optWidget;
+}
+
+TQWidget* KisToolCurve::optionWidget()
+{
+ if (toolType() == TOOL_SELECT)
+ return m_optWidget;
+ else
+ return super::optionWidget();
+}
+
+#include "kis_tool_curve.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_example.cc b/chalk/plugins/tools/tool_curves/kis_tool_example.cc
deleted file mode 100644
index 75e3da2be..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_example.cc
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * kis_tool_example.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_global.h"
-#include "kis_doc.h"
-#include "kis_painter.h"
-#include "kis_point.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_vec.h"
-
-#include "kis_curve_framework.h"
-
-#include "kis_tool_example.h"
-
-
-class KisCurveExample : public KisCurve {
-
- typedef KisCurve super;
-
-public:
-
- KisCurveExample() : super() {}
-
- ~KisCurveExample() {}
-
- virtual iterator pushPivot (const KisPoint&);
-
-};
-
-KisCurve::iterator KisCurveExample::pushPivot (const KisPoint& point)
-{
- return selectPivot(iterator(*this,m_curve.append(CurvePoint(point,true,false,LINEHINT))), true);
-}
-
-KisToolExample::KisToolExample()
- : super(i18n("Tool for Curves - Example"))
-{
- setName("tool_example");
- m_cursor = "tool_example_cursor.png";
- setCursor(KisCursor::load(m_cursor, 6, 6));
-
- m_curve = new KisCurveExample;
-}
-
-KisToolExample::~KisToolExample()
-{
-
-}
-
-void KisToolExample::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Example"),
- "tool_example",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("This is a test tool for the Curve Framework."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_example.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_example.cpp b/chalk/plugins/tools/tool_curves/kis_tool_example.cpp
new file mode 100644
index 000000000..a21bb8089
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_example.cpp
@@ -0,0 +1,108 @@
+/*
+ * kis_tool_example.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_global.h"
+#include "kis_doc.h"
+#include "kis_painter.h"
+#include "kis_point.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_vec.h"
+
+#include "kis_curve_framework.h"
+
+#include "kis_tool_example.h"
+
+
+class KisCurveExample : public KisCurve {
+
+ typedef KisCurve super;
+
+public:
+
+ KisCurveExample() : super() {}
+
+ ~KisCurveExample() {}
+
+ virtual iterator pushPivot (const KisPoint&);
+
+};
+
+KisCurve::iterator KisCurveExample::pushPivot (const KisPoint& point)
+{
+ return selectPivot(iterator(*this,m_curve.append(CurvePoint(point,true,false,LINEHINT))), true);
+}
+
+KisToolExample::KisToolExample()
+ : super(i18n("Tool for Curves - Example"))
+{
+ setName("tool_example");
+ m_cursor = "tool_example_cursor.png";
+ setCursor(KisCursor::load(m_cursor, 6, 6));
+
+ m_curve = new KisCurveExample;
+}
+
+KisToolExample::~KisToolExample()
+{
+
+}
+
+void KisToolExample::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Example"),
+ "tool_example",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("This is a test tool for the Curve Framework."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_example.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_moutline.cc b/chalk/plugins/tools/tool_curves/kis_tool_moutline.cc
deleted file mode 100644
index 178ff278f..000000000
--- a/chalk/plugins/tools/tool_curves/kis_tool_moutline.cc
+++ /dev/null
@@ -1,809 +0,0 @@
-/*
- * kis_tool_moutline.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <math.h>
-#include <set>
-
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqrect.h>
-#include <tqlabel.h>
-#include <tqpushbutton.h>
-#include <tqslider.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_global.h"
-#include "kis_iterators_pixel.h"
-#include "kis_colorspace.h"
-#include "kis_channelinfo.h"
-#include "kis_doc.h"
-#include "kis_painter.h"
-#include "kis_point.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_tool_controller.h"
-#include "kis_vec.h"
-#include "kis_selection.h"
-#include "kis_selection_options.h"
-#include "kis_selected_transaction.h"
-#include "kis_paintop_registry.h"
-#include "kis_convolution_painter.h"
-
-#include "kis_tool_moutline.h"
-
-using namespace std;
-
-#define RMS(a, b) (sqrt ((a) * (a) + (b) * (b)))
-#define ROUND(x) ((int) ((x) + 0.5))
-
-const int NOEDGE = 0x0000;
-
-const int ORTHOGONAL_COST = 10; // 1*10
-const int DIAGONAL_COST = 14; // sqrt(2)*10
-const int MALUS = 20; // This applies to NOEDGE nodes
-
-const int DEFAULTDIST = 40; // Default distance between two automatic pivots
-const int MAXDIST = 55; // Max distance
-const int MINDIST = 15;
-const int PAGESTEP = 5;
-
-class Node {
-
- TQPoint m_pos;
- int m_gCost;
- int m_hCost;
- int m_tCost;
- bool m_malus;
- TQPoint m_parent;
-
-public:
-
- Node()
- {
- m_pos = m_parent = TQPoint(-1,-1);
- m_gCost = m_hCost = m_tCost = 0;
- m_malus = false;
- }
-
- Node(const Node& node)
- {
- m_pos = node.pos();
- m_gCost = node.gCost();
- m_hCost = node.hCost();
- m_tCost = node.tCost();
- m_malus = node.malus();
- m_parent = node.parent();
- }
-
- Node(const TQPoint& parent, const TQPoint& pos, int g, int h, bool malus)
- : m_pos(pos), m_hCost(h), m_malus(malus)
- {
- setGCost(g);
- m_parent = parent;
- }
- ~Node ()
- {
- }
-
- int gCost () const {return m_gCost;}
- int hCost () const {return m_hCost;}
- int tCost () const {return m_tCost;}
- bool malus () const {return m_malus;}
- TQPoint pos () const {return m_pos;}
- int col () const {return m_pos.x();}
- int row () const {return m_pos.y();}
- TQPoint parent () const {return m_parent;}
-
- void setGCost (int g)
- {
- m_gCost = g+(m_malus?MALUS:0);
- m_tCost = m_gCost+m_hCost;
- }
- void setHCost (int h)
- {
- m_hCost = h;
- m_tCost = m_gCost+m_hCost;
- }
- void setPos (const TQPoint& pos)
- {
- m_pos = pos;
- }
- void setMalus (bool malus)
- {
- m_malus = malus;
- }
- void clear ()
- {
- m_pos = TQPoint(-1,-1);
- }
-
- bool operator== (const Node& n2) const
- {
- return m_pos == n2.pos();
- }
- bool operator!= (const Node& n2) const
- {
- return m_pos != n2.pos();
- }
- bool operator== (const TQPoint& n2) const
- {
- return m_pos == n2;
- }
- bool operator!= (const TQPoint& n2) const
- {
- return m_pos != n2;
- }
- bool operator< (const Node& n2) const
- {
- return m_tCost < n2.tCost();
- }
- bool operator> (const Node& n2) const
- {
- return m_tCost > n2.tCost();
- }
-
- TQValueList<Node> getNeighbor(const GrayMatrix& src, const Node& end)
- {
- TQPoint tmpdist;
- TQValueList<Node> temp;
- int dcol, drow;
- int g, h;
- bool malus;
- int x[8] = { 1, 1, 0,-1,-1,-1, 0, 1},
- y[8] = { 0,-1,-1,-1, 0, 1, 1, 1};
-
- for (int i = 0; i < 8; i++) {
- dcol = m_pos.x() + x[i];
- drow = m_pos.y() + y[i];
- tmpdist = TQPoint(dcol,drow) - end.pos();
- // I use src[0] here because all cols have same number of rows
- if (dcol == (int)src.count() || dcol < 0 ||
- drow == (int)src[0].count() || drow < 0)
- continue;
- if (src[dcol][drow])
- malus = false;
- else
- malus = true;
- if (i%2)
- g = m_gCost + DIAGONAL_COST;
- else
- g = m_gCost + ORTHOGONAL_COST;
- h = ORTHOGONAL_COST * (abs(tmpdist.x()) + abs(tmpdist.y()));
- temp.append(Node(m_pos,TQPoint(dcol,drow),g,h,malus));
- }
- return temp;
- }
-
-};
-
-KisKernelSP createKernel( TQ_INT32 i0, TQ_INT32 i1, TQ_INT32 i2,
- TQ_INT32 i3, TQ_INT32 i4, TQ_INT32 i5,
- TQ_INT32 i6, TQ_INT32 i7, TQ_INT32 i8,
- TQ_INT32 factor, TQ_INT32 offset )
-{
- KisKernelSP kernel = new KisKernel();
- kernel->width = 3;
- kernel->height = 3;
-
- kernel->factor = factor;
- kernel->offset = offset;
-
- kernel->data = new TQ_INT32[9];
- kernel->data[0] = i0;
- kernel->data[1] = i1;
- kernel->data[2] = i2;
- kernel->data[3] = i3;
- kernel->data[4] = i4;
- kernel->data[5] = i5;
- kernel->data[6] = i6;
- kernel->data[7] = i7;
- kernel->data[8] = i8;
-
- return kernel;
-}
-
-KisCurveMagnetic::KisCurveMagnetic (KisToolMagnetic *parent)
- : m_parent(parent)
-{
- m_standardkeepselected = false;
-}
-
-KisCurveMagnetic::~KisCurveMagnetic ()
-{
-
-}
-
-KisCurve::iterator KisCurveMagnetic::addPivot (KisCurve::iterator it, const KisPoint& point)
-{
- return iterator(*this,m_curve.insert(it.position(), CurvePoint(point,true,false,LINEHINT)));
-}
-
-KisCurve::iterator KisCurveMagnetic::pushPivot (const KisPoint& point)
-{
- iterator it;
-
- it = pushPoint(point,true,false,LINEHINT);
-// if (count() == 1 && !m_parent->editingMode())
-// addPoint(it,point,true,false,LINEHINT);
-
- return selectPivot(it);
-}
-
-void KisCurveMagnetic::calculateCurve (KisCurve::iterator p1, KisCurve::iterator p2, KisCurve::iterator it)
-{
- if (p1 == m_curve.end() || p2 == m_curve.end()) // It happens sometimes, for example on the first click
- return;
- if (m_parent->editingMode())
- return;
- TQPoint start = (*p1).point().roundTQPoint();
- TQPoint end = (*p2).point().roundTQPoint();
- TQRect rc = TQRect(start,end).normalize();
- rc.setTopLeft(rc.topLeft()+TQPoint(-8,-8)); // Enlarge the view, so problems with gaussian blur can be removed
- rc.setBottomRight(rc.bottomRight()+TQPoint(8,8)); // and we are able to find paths that go beyond the rect.
-
- KisPaintDeviceSP src = m_parent->m_currentImage->activeDevice();
- GrayMatrix dst = GrayMatrix(rc.width(),GrayCol(rc.height()));
-
- detectEdges (rc, src, dst);
- reduceMatrix (rc, dst, 3, 3, 3, 3);
-
- Node startNode, endNode;
- multiset<Node> openSet;
- NodeMatrix openMatrix = NodeMatrix(rc.width(),NodeCol(rc.height()));
- NodeMatrix closedMatrix = NodeMatrix(rc.width(),NodeCol(rc.height()));
-
- TQPoint tl(rc.topLeft().x(),rc.topLeft().y());
- start -= tl; // Relative to the matrix
- end -= tl; // Relative to the matrix
-
- findEdge (start.x(), start.y(), dst, startNode);
- openMatrix[startNode.col()][startNode.row()] = *openSet.insert(startNode);
- endNode.setPos(end);
-
- while (!openSet.empty()) {
- Node current = *openSet.begin();
-
- openSet.erase(openSet.begin());
- openMatrix[current.col()][current.row()].clear();
-
- TQValueList<Node> successors = current.getNeighbor(dst,endNode);
- for (TQValueList<Node>::iterator i = successors.begin(); i != successors.end(); i++) {
- int col = (*i).col();
- int row = (*i).row();
- if ((*i) == endNode) {
- while (current.parent() != TQPoint(-1,-1)) {
- it = addPoint(it,KisPoint(tl+current.pos()),false,false,LINEHINT);
- current = closedMatrix[current.parent().x()][current.parent().y()];
- }
- return;
- }
- Node *openNode = &openMatrix[col][row];
- if (*openNode != TQPoint(-1,-1)) {
- if (*i > *openNode)
- continue;
- else {
- openSet.erase(tqFind(openSet.begin(),openSet.end(),*openNode));
- openNode->clear(); // Clear the Node
- }
- }
- Node *closedNode = &closedMatrix[col][row];
- if (*closedNode != TQPoint(-1,-1)) {
- if ((*i) > (*closedNode))
- continue;
- else {
- openMatrix[col][row] = *openSet.insert(*closedNode);
- closedNode->clear(); // Clear the Node
- continue;
- }
- }
- openMatrix[col][row] = *openSet.insert(*i);
- }
- closedMatrix[current.col()][current.row()] = current;
- }
-}
-
-void KisCurveMagnetic::findEdge (int col, int row, const GrayMatrix& src, Node& node)
-{
- int x = -1;
- int y = -1;
-
- // tmpdist out of range
- KisVector2D mindist(5.0,5.0), tmpdist(1000.0,1000.0);
- for (int i = -5; i < 6; i++) {
- for (int j = -5; j < 6; j++) {
- if (src[col+i][row+j] != NOEDGE) {
- tmpdist = KisVector2D(i,j);
- if (tmpdist.length() < mindist.length())
- mindist = tmpdist;
- }
- }
- }
- if (tmpdist.x() == 1000.0)
- mindist = KisVector2D(0.0,0.0);
-
- x = (int)(col + mindist.x());
- y = (int)(row + mindist.y());
-
- node.setPos(TQPoint(x,y));
-}
-
-void KisCurveMagnetic::reduceMatrix (TQRect& rc, GrayMatrix& m, int top, int right, int bottom, int left)
-{
- TQPoint topleft(top, left);
- TQPoint bottomright(bottom, right);
-
- rc.setTopLeft(rc.topLeft()+topleft);
- rc.setBottomRight(rc.bottomRight()-bottomright);
-
- if (left)
- m.erase(m.begin(),m.begin()+left);
- if (right)
- m.erase(m.end()-right,m.end());
- if (top) {
- for (uint i = 0; i < m.count(); i++)
- m[i].erase(m[i].begin(),m[i].begin()+top);
- }
- if (bottom) {
- for (uint i = 0; i < m.count(); i++)
- m[i].erase(m[i].end()-bottom,m[i].end());
- }
-}
-
-void KisCurveMagnetic::detectEdges (const TQRect & rect, KisPaintDeviceSP src, GrayMatrix& dst)
-{
- GrayMatrix graysrc(rect.width(),GrayCol(rect.height()));
- GrayMatrix xdeltas(rect.width(),GrayCol(rect.height()));
- GrayMatrix ydeltas(rect.width(),GrayCol(rect.height()));
- GrayMatrix magnitude(rect.width(),GrayCol(rect.height()));
- KisPaintDeviceSP smooth = new KisPaintDevice(src->colorSpace());
-
- gaussianBlur(rect, src, smooth);
- toGrayScale(rect, smooth, graysrc);
- getDeltas(graysrc, xdeltas, ydeltas);
- getMagnitude(xdeltas, ydeltas, magnitude);
- nonMaxSupp(magnitude, xdeltas, ydeltas, dst);
-}
-
-void KisCurveMagnetic::gaussianBlur (const TQRect& rect, KisPaintDeviceSP src, KisPaintDeviceSP dst)
-{
- int grectx = rect.x();
- int grecty = rect.y();
- int grectw = rect.width();
- int grecth = rect.height();
- if (dst != src) {
- KisPainter gc(dst);
- gc.bitBlt(grectx, grecty, COMPOSITE_COPY, src, grectx, grecty, grectw, grecth);
- gc.end();
- }
-
- KisConvolutionPainter painter( dst );
- // FIXME createKernel could create dynamic gaussian kernels having sigma as argument
- KisKernelSP kernel = createKernel( 1, 1, 1, 1, 24, 1, 1, 1, 1, 32, 0);
- painter.applyMatrix(kernel, grectx, grecty, grectw, grecth, BORDER_AVOID);
-}
-
-void KisCurveMagnetic::toGrayScale (const TQRect& rect, KisPaintDeviceSP src, GrayMatrix& dst)
-{
- int grectx = rect.x();
- int grecty = rect.y();
- int grectw = rect.width();
- int grecth = rect.height();
- TQColor c;
- KisColorSpace *cs = src->colorSpace();
-
- for (int row = 0; row < grecth; row++) {
- KisHLineIteratorPixel srcIt = src->createHLineIterator(grectx, grecty+row, grectw, false);
- for (int col = 0; col < grectw; col++) {
- cs->toTQColor(srcIt.rawData(),&c);
- dst[col][row] = tqGray(c.rgb());
- ++srcIt;
- }
- }
-}
-
-void KisCurveMagnetic::getDeltas (const GrayMatrix& src, GrayMatrix& xdelta, GrayMatrix& ydelta)
-{
- uint start = 1, xend = src[0].count()-1, yend = src.count()-1;
- TQ_INT16 deri;
- for (uint col = 0; col < src.count(); col++) {
- for (uint row = 0; row < src[col].count(); row++) {
- if (row >= start && row < xend) {
- deri = src[col][row+1] - src[col][row-1];
- xdelta[col][row] = deri;
- } else
- xdelta[col][row] = 0;
- if (col >= start && col < yend) {
- deri = src[col+1][row] - src[col-1][row];
- ydelta[col][row] = deri;
- } else
- ydelta[col][row] = 0;
- }
- }
-}
-
-void KisCurveMagnetic::getMagnitude (const GrayMatrix& xdelta, const GrayMatrix& ydelta, GrayMatrix& gradient)
-{
- for (uint col = 0; col < xdelta.count(); col++) {
- for (uint row = 0; row < xdelta[col].count(); row++)
- gradient[col][row] = (TQ_INT16)(ROUND(RMS(xdelta[col][row],ydelta[col][row])));
- }
-}
-
-void KisCurveMagnetic::nonMaxSupp (const GrayMatrix& magnitude, const GrayMatrix& xdelta, const GrayMatrix& ydelta, GrayMatrix& nms)
-{
- // Directions:
- // 1: 0 - 22.5 degrees
- // 2: 22.5 - 67.5 degrees
- // 3: 67.5 - 90 degrees
- // Second direction is relative to a quadrant. The quadrant is known by looking at x and y derivatives
- // First quadrant: Gx < 0 & Gy >= 0
- // Second quadrant: Gx < 0 & Gy < 0
- // Third quadrant: Gx >= 0 & Gy < 0
- // Fourth quadrant: Gx >= 0 & Gy >= 0
- // For this reason: first direction is relative to Gy only and third direction to Gx only
-
- double theta; // theta = invtan (|Gy| / |Gx|) This give the direction relative to a quadrant
- TQ_INT16 mag; // Current magnitude
- TQ_INT16 lmag; // Magnitude at the left (So this pixel is "more internal" than the current
- TQ_INT16 rmag; // Magnitude at the right (So this pixel is "more external")
- double xdel; // Current xdelta
- double ydel; // Current ydelta
- TQ_INT16 result;
-
- for (uint col = 0; col < magnitude.count(); col++) {
- for (uint row = 0; row < magnitude[col].count(); row++) {
- mag = magnitude[col][row];
- if (!mag || row == 0 || row == (magnitude[col].count()-1) ||
- col == 0 || col == (magnitude.count()-1))
- {
- result = NOEDGE;
- } else {
- xdel = (double)xdelta[col][row];
- ydel = (double)ydelta[col][row];
- theta = atan(fabs(ydel)/fabs(xdel));
- if (theta < 0)
- theta = fabs(theta)+M_PI_2;
- theta = (theta * 360.0) / (2.0*M_PI); // Radians -> degrees
- if (theta >= 0 && theta < 22.5) { // .0 - .3926990816
- if (ydel >= 0) {
- lmag = magnitude[col][row-1];
- rmag = magnitude[col][row+1];
- } else {
- lmag = magnitude[col][row+1];
- rmag = magnitude[col][row-1];
- }
- }
- if (theta >= 22.5 && theta < 67.5) { // .3926990816 - 1.1780972449
- if (xdel >= 0) {
- if (ydel >= 0) {
- lmag = magnitude[col-1][row-1];
- rmag = magnitude[col+1][row+1];
- } else {
- lmag = magnitude[col+1][row-1];
- rmag = magnitude[col-1][row+1];
- }
- } else {
- if (ydel >= 0) {
- lmag = magnitude[col-1][row+1];
- rmag = magnitude[col+1][row-1];
- } else {
- lmag = magnitude[col+1][row+1];
- rmag = magnitude[col-1][row-1];
- }
- }
- }
- if (theta >= 67.5 && theta <= 90.0) { // 1.1780972449 - 1.5707963266
- if (xdel >= 0) {
- lmag = magnitude[col+1][row];
- rmag = magnitude[col-1][row];
- } else {
- lmag = magnitude[col-1][row];
- rmag = magnitude[col+1][row];
- }
- }
-
- if ((mag < lmag) || (mag < rmag)) {
- result = NOEDGE;
- } else {
- if (rmag == mag) // If the external magnitude is equal to the current, suppress current.
- result = NOEDGE;
- else
- result = (mag > 255) ? 255 : mag;
- }
- }
- nms[col][row] = result;
- }
- }
-}
-
-KisToolMagnetic::KisToolMagnetic ()
- : super("Magnetic Outline Tool")
-{
- setName("tool_moutline");
- setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
-
- m_editingMode = false;
- m_editingCursor = m_draggingCursor = false;
-
- m_mode = 0;
- m_curve = m_derived = 0;
- m_current = m_previous = 0;
-
- m_distance = DEFAULTDIST;
-
- m_transactionMessage = i18n("Magnetic Outline Selection");
-}
-
-KisToolMagnetic::~KisToolMagnetic ()
-{
- m_curve = 0;
- delete m_derived;
-}
-
-void KisToolMagnetic::update (KisCanvasSubject *subject)
-{
- super::update(subject);
-}
-
-void KisToolMagnetic::activate ()
-{
- super::activate();
- if (!m_derived) {
- m_derived = new KisCurveMagnetic(this);
- m_curve = m_derived;
- }
-}
-
-void KisToolMagnetic::deactivate ()
-{
- m_curve->endActionOptions();
- m_actionOptions = NOOPTIONS;
- m_dragging = false;
- m_drawPivots = true;
-}
-
-void KisToolMagnetic::keyPress(TQKeyEvent *event)
-{
- if (event->key() == TQt::Key_Control) {
- draw(false);
- if (m_editingMode) {
- m_editingMode = false;
- if (m_current != 0)
- m_curve->selectPivot(m_current,false);
- m_mode->setText(i18n("Automatic Mode"));
- } else {
- m_editingMode = true;
- m_mode->setText(i18n("Manual Mode"));
- }
- draw(false);
- } else if (event->key() == TQt::Key_Delete && m_curve->count()) {
- draw(false);
- m_dragging = false;
- if (m_curve->pivots().count() == 2)
- m_curve->clear();
- else {
- if ((*m_current) == m_curve->last() && !(m_editingMode)) {
- m_curve->deletePivot(m_current.previousPivot());
- m_previous = m_current.previousPivot();
- } else {
- m_editingMode = false;
- m_curve->deletePivot(m_current);
- m_previous = m_current = m_curve->selectPivot(m_curve->lastIterator());
- m_editingMode = true;
- }
- }
- draw(false);
- } else
- super::keyPress(event);
-}
-
-void KisToolMagnetic::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (m_editingMode) {
- draw(m_current);
- m_editingMode = false;
- if (!m_curve->isEmpty())
- m_curve->movePivot(m_current, m_currentPoint);
- m_editingMode = true;
- draw(m_current);
- }
- super::buttonRelease(event);
-}
-
-void KisToolMagnetic::buttonPress(KisButtonPressEvent *event)
-{
- updateOptions(event->state());
- if (!m_currentImage)
- return;
- if (event->button() == Qt::LeftButton) {
- m_dragging = true;
- m_currentPoint = event->pos();
- PointPair temp(m_curve->end(),false);
- if (m_editingMode)
- temp = pointUnderMouse (m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
- if (temp.first == m_curve->end() && !(m_actionOptions)) {
- if (m_editingMode) {
- draw(true, true);
- m_curve->selectAll(false);
- draw(true, true);
- }
- draw(m_curve->end());
- if (!m_curve->isEmpty()) {
- m_previous = m_current;
- m_current = m_curve->pushPivot(event->pos());
- } else {
- m_previous = m_current = m_curve->pushPivot(event->pos());
- }
- if (m_curve->pivots().count() > 1)
- m_curve->calculateCurve(m_previous,m_current,m_current);
- if (m_editingMode)
- draw();
- else {
- if ((*m_previous).point() == (*m_current).point())
- draw(m_curve->end());
- else
- draw();
- }
- } else if (temp.first != m_curve->end() && m_editingMode) {
- if (temp.second) {
- draw(true, true);
- m_current = m_curve->selectPivot(temp.first);
- draw(true, true);
- } else {
- draw(false);
- m_current = selectByMouse(temp.first);
- draw(false);
- }
- if (!(*m_current).isSelected())
- m_dragging = false;
- }
- }
-}
-
-void KisToolMagnetic::move(KisMoveEvent *event)
-{
- updateOptions(event->state());
- if (m_currentPoint == event->pos().floorTQPoint())
- return;
- if (m_editingMode) {
- PointPair temp = pointUnderMouse(m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
- if (temp.first == m_curve->end() && !m_dragging) {
- if (m_editingCursor || m_draggingCursor) {
- setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
- m_editingCursor = m_draggingCursor = false;
- }
- } else {
- if (!m_draggingCursor && temp.second) {
- setCursor(KisCursor::load("tool_moutline_dragging.png", 6, 6));
- m_editingCursor = false;
- m_draggingCursor = true;
- }
- if (!m_editingCursor && !temp.second) {
- setCursor(KisCursor::load("tool_moutline_editing.png", 6, 6));
- m_editingCursor = true;
- m_draggingCursor = false;
- }
- }
- if (!m_dragging)
- return;
- } else {
- if (m_editingCursor || m_draggingCursor) {
- setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
- m_editingCursor = m_draggingCursor = false;
- }
- }
- if (m_curve->selectedPivots().isEmpty())
- return;
-
- KisPoint trans = event->pos() - m_currentPoint;
- KisPoint dist;
- dist = (*m_current).point() - (*m_current.previousPivot()).point();
- if ((m_distance >= MINDIST && (fabs(dist.x()) + fabs(dist.y())) > m_distance && !(m_editingMode))
- || m_curve->pivots().count() == 1) {
- draw(m_curve->end());
- m_previous = m_current;
- m_current = m_curve->pushPivot(event->pos());
- } else if ((*m_previous).point() == (*m_current).point() && (*m_previous).point() == m_curve->last().point())
- draw(m_curve->end());
- else
- draw(m_current);
- m_curve->movePivot(m_current,event->pos());
- m_currentPoint = event->pos().floorTQPoint();
- draw(m_current);
-}
-
-KisCurve::iterator KisToolMagnetic::selectByMouse(KisCurve::iterator it)
-{
- KisCurve::iterator currPivot = m_curve->selectPivot(m_curve->addPivot(it, KisPoint(0,0)));
- m_curve->movePivot(currPivot,(*it).point());
-
- return currPivot;
-}
-
-void KisToolMagnetic::slotCommitCurve ()
-{
- if (!m_curve->isEmpty())
- commitCurve();
-}
-
-void KisToolMagnetic::slotSetDistance (int dist)
-{
- m_distance = dist;
-}
-
-TQWidget* KisToolMagnetic::createOptionWidget(TQWidget* parent)
-{
- m_optWidget = super::createOptionWidget(parent);
- TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
- TQGridLayout *box = new TQGridLayout(l, 2, 2, 3);
- box->setColStretch(0, 1);
- box->setColStretch(1, 1);
- TQ_CHECK_PTR(box);
-
- m_mode = new TQLabel(i18n("Automatic mode"), m_optWidget);
- m_lbDistance = new TQLabel(i18n("Distance: "), m_optWidget);
- TQPushButton *finish = new TQPushButton(i18n("To Selection"), m_optWidget);
- m_slDistance = new TQSlider(MINDIST, MAXDIST, PAGESTEP, m_distance, Qt::Horizontal, m_optWidget);
-
- connect(m_slDistance, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotSetDistance(int)));
- connect(finish, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotCommitCurve()));
-
- box->addWidget(m_lbDistance, 0, 0);
- box->addWidget(m_slDistance, 0, 1);
- box->addWidget(m_mode, 1, 0);
- box->addWidget(finish, 1, 1);
-
- return m_optWidget;
-}
-
-void KisToolMagnetic::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("Magnetic Outline"),
- "tool_moutline",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Magnetic Selection: move around an edge to select it. Hit Ctrl to enter/quit manual mode, and double click to finish."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_moutline.moc"
diff --git a/chalk/plugins/tools/tool_curves/kis_tool_moutline.cpp b/chalk/plugins/tools/tool_curves/kis_tool_moutline.cpp
new file mode 100644
index 000000000..ebf82634f
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/kis_tool_moutline.cpp
@@ -0,0 +1,809 @@
+/*
+ * kis_tool_moutline.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <math.h>
+#include <set>
+
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqrect.h>
+#include <tqlabel.h>
+#include <tqpushbutton.h>
+#include <tqslider.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_global.h"
+#include "kis_iterators_pixel.h"
+#include "kis_colorspace.h"
+#include "kis_channelinfo.h"
+#include "kis_doc.h"
+#include "kis_painter.h"
+#include "kis_point.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_tool_controller.h"
+#include "kis_vec.h"
+#include "kis_selection.h"
+#include "kis_selection_options.h"
+#include "kis_selected_transaction.h"
+#include "kis_paintop_registry.h"
+#include "kis_convolution_painter.h"
+
+#include "kis_tool_moutline.h"
+
+using namespace std;
+
+#define RMS(a, b) (sqrt ((a) * (a) + (b) * (b)))
+#define ROUND(x) ((int) ((x) + 0.5))
+
+const int NOEDGE = 0x0000;
+
+const int ORTHOGONAL_COST = 10; // 1*10
+const int DIAGONAL_COST = 14; // sqrt(2)*10
+const int MALUS = 20; // This applies to NOEDGE nodes
+
+const int DEFAULTDIST = 40; // Default distance between two automatic pivots
+const int MAXDIST = 55; // Max distance
+const int MINDIST = 15;
+const int PAGESTEP = 5;
+
+class Node {
+
+ TQPoint m_pos;
+ int m_gCost;
+ int m_hCost;
+ int m_tCost;
+ bool m_malus;
+ TQPoint m_parent;
+
+public:
+
+ Node()
+ {
+ m_pos = m_parent = TQPoint(-1,-1);
+ m_gCost = m_hCost = m_tCost = 0;
+ m_malus = false;
+ }
+
+ Node(const Node& node)
+ {
+ m_pos = node.pos();
+ m_gCost = node.gCost();
+ m_hCost = node.hCost();
+ m_tCost = node.tCost();
+ m_malus = node.malus();
+ m_parent = node.parent();
+ }
+
+ Node(const TQPoint& parent, const TQPoint& pos, int g, int h, bool malus)
+ : m_pos(pos), m_hCost(h), m_malus(malus)
+ {
+ setGCost(g);
+ m_parent = parent;
+ }
+ ~Node ()
+ {
+ }
+
+ int gCost () const {return m_gCost;}
+ int hCost () const {return m_hCost;}
+ int tCost () const {return m_tCost;}
+ bool malus () const {return m_malus;}
+ TQPoint pos () const {return m_pos;}
+ int col () const {return m_pos.x();}
+ int row () const {return m_pos.y();}
+ TQPoint parent () const {return m_parent;}
+
+ void setGCost (int g)
+ {
+ m_gCost = g+(m_malus?MALUS:0);
+ m_tCost = m_gCost+m_hCost;
+ }
+ void setHCost (int h)
+ {
+ m_hCost = h;
+ m_tCost = m_gCost+m_hCost;
+ }
+ void setPos (const TQPoint& pos)
+ {
+ m_pos = pos;
+ }
+ void setMalus (bool malus)
+ {
+ m_malus = malus;
+ }
+ void clear ()
+ {
+ m_pos = TQPoint(-1,-1);
+ }
+
+ bool operator== (const Node& n2) const
+ {
+ return m_pos == n2.pos();
+ }
+ bool operator!= (const Node& n2) const
+ {
+ return m_pos != n2.pos();
+ }
+ bool operator== (const TQPoint& n2) const
+ {
+ return m_pos == n2;
+ }
+ bool operator!= (const TQPoint& n2) const
+ {
+ return m_pos != n2;
+ }
+ bool operator< (const Node& n2) const
+ {
+ return m_tCost < n2.tCost();
+ }
+ bool operator> (const Node& n2) const
+ {
+ return m_tCost > n2.tCost();
+ }
+
+ TQValueList<Node> getNeighbor(const GrayMatrix& src, const Node& end)
+ {
+ TQPoint tmpdist;
+ TQValueList<Node> temp;
+ int dcol, drow;
+ int g, h;
+ bool malus;
+ int x[8] = { 1, 1, 0,-1,-1,-1, 0, 1},
+ y[8] = { 0,-1,-1,-1, 0, 1, 1, 1};
+
+ for (int i = 0; i < 8; i++) {
+ dcol = m_pos.x() + x[i];
+ drow = m_pos.y() + y[i];
+ tmpdist = TQPoint(dcol,drow) - end.pos();
+ // I use src[0] here because all cols have same number of rows
+ if (dcol == (int)src.count() || dcol < 0 ||
+ drow == (int)src[0].count() || drow < 0)
+ continue;
+ if (src[dcol][drow])
+ malus = false;
+ else
+ malus = true;
+ if (i%2)
+ g = m_gCost + DIAGONAL_COST;
+ else
+ g = m_gCost + ORTHOGONAL_COST;
+ h = ORTHOGONAL_COST * (abs(tmpdist.x()) + abs(tmpdist.y()));
+ temp.append(Node(m_pos,TQPoint(dcol,drow),g,h,malus));
+ }
+ return temp;
+ }
+
+};
+
+KisKernelSP createKernel( TQ_INT32 i0, TQ_INT32 i1, TQ_INT32 i2,
+ TQ_INT32 i3, TQ_INT32 i4, TQ_INT32 i5,
+ TQ_INT32 i6, TQ_INT32 i7, TQ_INT32 i8,
+ TQ_INT32 factor, TQ_INT32 offset )
+{
+ KisKernelSP kernel = new KisKernel();
+ kernel->width = 3;
+ kernel->height = 3;
+
+ kernel->factor = factor;
+ kernel->offset = offset;
+
+ kernel->data = new TQ_INT32[9];
+ kernel->data[0] = i0;
+ kernel->data[1] = i1;
+ kernel->data[2] = i2;
+ kernel->data[3] = i3;
+ kernel->data[4] = i4;
+ kernel->data[5] = i5;
+ kernel->data[6] = i6;
+ kernel->data[7] = i7;
+ kernel->data[8] = i8;
+
+ return kernel;
+}
+
+KisCurveMagnetic::KisCurveMagnetic (KisToolMagnetic *parent)
+ : m_parent(parent)
+{
+ m_standardkeepselected = false;
+}
+
+KisCurveMagnetic::~KisCurveMagnetic ()
+{
+
+}
+
+KisCurve::iterator KisCurveMagnetic::addPivot (KisCurve::iterator it, const KisPoint& point)
+{
+ return iterator(*this,m_curve.insert(it.position(), CurvePoint(point,true,false,LINEHINT)));
+}
+
+KisCurve::iterator KisCurveMagnetic::pushPivot (const KisPoint& point)
+{
+ iterator it;
+
+ it = pushPoint(point,true,false,LINEHINT);
+// if (count() == 1 && !m_parent->editingMode())
+// addPoint(it,point,true,false,LINEHINT);
+
+ return selectPivot(it);
+}
+
+void KisCurveMagnetic::calculateCurve (KisCurve::iterator p1, KisCurve::iterator p2, KisCurve::iterator it)
+{
+ if (p1 == m_curve.end() || p2 == m_curve.end()) // It happens sometimes, for example on the first click
+ return;
+ if (m_parent->editingMode())
+ return;
+ TQPoint start = (*p1).point().roundTQPoint();
+ TQPoint end = (*p2).point().roundTQPoint();
+ TQRect rc = TQRect(start,end).normalize();
+ rc.setTopLeft(rc.topLeft()+TQPoint(-8,-8)); // Enlarge the view, so problems with gaussian blur can be removed
+ rc.setBottomRight(rc.bottomRight()+TQPoint(8,8)); // and we are able to find paths that go beyond the rect.
+
+ KisPaintDeviceSP src = m_parent->m_currentImage->activeDevice();
+ GrayMatrix dst = GrayMatrix(rc.width(),GrayCol(rc.height()));
+
+ detectEdges (rc, src, dst);
+ reduceMatrix (rc, dst, 3, 3, 3, 3);
+
+ Node startNode, endNode;
+ multiset<Node> openSet;
+ NodeMatrix openMatrix = NodeMatrix(rc.width(),NodeCol(rc.height()));
+ NodeMatrix closedMatrix = NodeMatrix(rc.width(),NodeCol(rc.height()));
+
+ TQPoint tl(rc.topLeft().x(),rc.topLeft().y());
+ start -= tl; // Relative to the matrix
+ end -= tl; // Relative to the matrix
+
+ findEdge (start.x(), start.y(), dst, startNode);
+ openMatrix[startNode.col()][startNode.row()] = *openSet.insert(startNode);
+ endNode.setPos(end);
+
+ while (!openSet.empty()) {
+ Node current = *openSet.begin();
+
+ openSet.erase(openSet.begin());
+ openMatrix[current.col()][current.row()].clear();
+
+ TQValueList<Node> successors = current.getNeighbor(dst,endNode);
+ for (TQValueList<Node>::iterator i = successors.begin(); i != successors.end(); i++) {
+ int col = (*i).col();
+ int row = (*i).row();
+ if ((*i) == endNode) {
+ while (current.parent() != TQPoint(-1,-1)) {
+ it = addPoint(it,KisPoint(tl+current.pos()),false,false,LINEHINT);
+ current = closedMatrix[current.parent().x()][current.parent().y()];
+ }
+ return;
+ }
+ Node *openNode = &openMatrix[col][row];
+ if (*openNode != TQPoint(-1,-1)) {
+ if (*i > *openNode)
+ continue;
+ else {
+ openSet.erase(tqFind(openSet.begin(),openSet.end(),*openNode));
+ openNode->clear(); // Clear the Node
+ }
+ }
+ Node *closedNode = &closedMatrix[col][row];
+ if (*closedNode != TQPoint(-1,-1)) {
+ if ((*i) > (*closedNode))
+ continue;
+ else {
+ openMatrix[col][row] = *openSet.insert(*closedNode);
+ closedNode->clear(); // Clear the Node
+ continue;
+ }
+ }
+ openMatrix[col][row] = *openSet.insert(*i);
+ }
+ closedMatrix[current.col()][current.row()] = current;
+ }
+}
+
+void KisCurveMagnetic::findEdge (int col, int row, const GrayMatrix& src, Node& node)
+{
+ int x = -1;
+ int y = -1;
+
+ // tmpdist out of range
+ KisVector2D mindist(5.0,5.0), tmpdist(1000.0,1000.0);
+ for (int i = -5; i < 6; i++) {
+ for (int j = -5; j < 6; j++) {
+ if (src[col+i][row+j] != NOEDGE) {
+ tmpdist = KisVector2D(i,j);
+ if (tmpdist.length() < mindist.length())
+ mindist = tmpdist;
+ }
+ }
+ }
+ if (tmpdist.x() == 1000.0)
+ mindist = KisVector2D(0.0,0.0);
+
+ x = (int)(col + mindist.x());
+ y = (int)(row + mindist.y());
+
+ node.setPos(TQPoint(x,y));
+}
+
+void KisCurveMagnetic::reduceMatrix (TQRect& rc, GrayMatrix& m, int top, int right, int bottom, int left)
+{
+ TQPoint topleft(top, left);
+ TQPoint bottomright(bottom, right);
+
+ rc.setTopLeft(rc.topLeft()+topleft);
+ rc.setBottomRight(rc.bottomRight()-bottomright);
+
+ if (left)
+ m.erase(m.begin(),m.begin()+left);
+ if (right)
+ m.erase(m.end()-right,m.end());
+ if (top) {
+ for (uint i = 0; i < m.count(); i++)
+ m[i].erase(m[i].begin(),m[i].begin()+top);
+ }
+ if (bottom) {
+ for (uint i = 0; i < m.count(); i++)
+ m[i].erase(m[i].end()-bottom,m[i].end());
+ }
+}
+
+void KisCurveMagnetic::detectEdges (const TQRect & rect, KisPaintDeviceSP src, GrayMatrix& dst)
+{
+ GrayMatrix graysrc(rect.width(),GrayCol(rect.height()));
+ GrayMatrix xdeltas(rect.width(),GrayCol(rect.height()));
+ GrayMatrix ydeltas(rect.width(),GrayCol(rect.height()));
+ GrayMatrix magnitude(rect.width(),GrayCol(rect.height()));
+ KisPaintDeviceSP smooth = new KisPaintDevice(src->colorSpace());
+
+ gaussianBlur(rect, src, smooth);
+ toGrayScale(rect, smooth, graysrc);
+ getDeltas(graysrc, xdeltas, ydeltas);
+ getMagnitude(xdeltas, ydeltas, magnitude);
+ nonMaxSupp(magnitude, xdeltas, ydeltas, dst);
+}
+
+void KisCurveMagnetic::gaussianBlur (const TQRect& rect, KisPaintDeviceSP src, KisPaintDeviceSP dst)
+{
+ int grectx = rect.x();
+ int grecty = rect.y();
+ int grectw = rect.width();
+ int grecth = rect.height();
+ if (dst != src) {
+ KisPainter gc(dst);
+ gc.bitBlt(grectx, grecty, COMPOSITE_COPY, src, grectx, grecty, grectw, grecth);
+ gc.end();
+ }
+
+ KisConvolutionPainter painter( dst );
+ // FIXME createKernel could create dynamic gaussian kernels having sigma as argument
+ KisKernelSP kernel = createKernel( 1, 1, 1, 1, 24, 1, 1, 1, 1, 32, 0);
+ painter.applyMatrix(kernel, grectx, grecty, grectw, grecth, BORDER_AVOID);
+}
+
+void KisCurveMagnetic::toGrayScale (const TQRect& rect, KisPaintDeviceSP src, GrayMatrix& dst)
+{
+ int grectx = rect.x();
+ int grecty = rect.y();
+ int grectw = rect.width();
+ int grecth = rect.height();
+ TQColor c;
+ KisColorSpace *cs = src->colorSpace();
+
+ for (int row = 0; row < grecth; row++) {
+ KisHLineIteratorPixel srcIt = src->createHLineIterator(grectx, grecty+row, grectw, false);
+ for (int col = 0; col < grectw; col++) {
+ cs->toTQColor(srcIt.rawData(),&c);
+ dst[col][row] = tqGray(c.rgb());
+ ++srcIt;
+ }
+ }
+}
+
+void KisCurveMagnetic::getDeltas (const GrayMatrix& src, GrayMatrix& xdelta, GrayMatrix& ydelta)
+{
+ uint start = 1, xend = src[0].count()-1, yend = src.count()-1;
+ TQ_INT16 deri;
+ for (uint col = 0; col < src.count(); col++) {
+ for (uint row = 0; row < src[col].count(); row++) {
+ if (row >= start && row < xend) {
+ deri = src[col][row+1] - src[col][row-1];
+ xdelta[col][row] = deri;
+ } else
+ xdelta[col][row] = 0;
+ if (col >= start && col < yend) {
+ deri = src[col+1][row] - src[col-1][row];
+ ydelta[col][row] = deri;
+ } else
+ ydelta[col][row] = 0;
+ }
+ }
+}
+
+void KisCurveMagnetic::getMagnitude (const GrayMatrix& xdelta, const GrayMatrix& ydelta, GrayMatrix& gradient)
+{
+ for (uint col = 0; col < xdelta.count(); col++) {
+ for (uint row = 0; row < xdelta[col].count(); row++)
+ gradient[col][row] = (TQ_INT16)(ROUND(RMS(xdelta[col][row],ydelta[col][row])));
+ }
+}
+
+void KisCurveMagnetic::nonMaxSupp (const GrayMatrix& magnitude, const GrayMatrix& xdelta, const GrayMatrix& ydelta, GrayMatrix& nms)
+{
+ // Directions:
+ // 1: 0 - 22.5 degrees
+ // 2: 22.5 - 67.5 degrees
+ // 3: 67.5 - 90 degrees
+ // Second direction is relative to a quadrant. The quadrant is known by looking at x and y derivatives
+ // First quadrant: Gx < 0 & Gy >= 0
+ // Second quadrant: Gx < 0 & Gy < 0
+ // Third quadrant: Gx >= 0 & Gy < 0
+ // Fourth quadrant: Gx >= 0 & Gy >= 0
+ // For this reason: first direction is relative to Gy only and third direction to Gx only
+
+ double theta; // theta = invtan (|Gy| / |Gx|) This give the direction relative to a quadrant
+ TQ_INT16 mag; // Current magnitude
+ TQ_INT16 lmag; // Magnitude at the left (So this pixel is "more internal" than the current
+ TQ_INT16 rmag; // Magnitude at the right (So this pixel is "more external")
+ double xdel; // Current xdelta
+ double ydel; // Current ydelta
+ TQ_INT16 result;
+
+ for (uint col = 0; col < magnitude.count(); col++) {
+ for (uint row = 0; row < magnitude[col].count(); row++) {
+ mag = magnitude[col][row];
+ if (!mag || row == 0 || row == (magnitude[col].count()-1) ||
+ col == 0 || col == (magnitude.count()-1))
+ {
+ result = NOEDGE;
+ } else {
+ xdel = (double)xdelta[col][row];
+ ydel = (double)ydelta[col][row];
+ theta = atan(fabs(ydel)/fabs(xdel));
+ if (theta < 0)
+ theta = fabs(theta)+M_PI_2;
+ theta = (theta * 360.0) / (2.0*M_PI); // Radians -> degrees
+ if (theta >= 0 && theta < 22.5) { // .0 - .3926990816
+ if (ydel >= 0) {
+ lmag = magnitude[col][row-1];
+ rmag = magnitude[col][row+1];
+ } else {
+ lmag = magnitude[col][row+1];
+ rmag = magnitude[col][row-1];
+ }
+ }
+ if (theta >= 22.5 && theta < 67.5) { // .3926990816 - 1.1780972449
+ if (xdel >= 0) {
+ if (ydel >= 0) {
+ lmag = magnitude[col-1][row-1];
+ rmag = magnitude[col+1][row+1];
+ } else {
+ lmag = magnitude[col+1][row-1];
+ rmag = magnitude[col-1][row+1];
+ }
+ } else {
+ if (ydel >= 0) {
+ lmag = magnitude[col-1][row+1];
+ rmag = magnitude[col+1][row-1];
+ } else {
+ lmag = magnitude[col+1][row+1];
+ rmag = magnitude[col-1][row-1];
+ }
+ }
+ }
+ if (theta >= 67.5 && theta <= 90.0) { // 1.1780972449 - 1.5707963266
+ if (xdel >= 0) {
+ lmag = magnitude[col+1][row];
+ rmag = magnitude[col-1][row];
+ } else {
+ lmag = magnitude[col-1][row];
+ rmag = magnitude[col+1][row];
+ }
+ }
+
+ if ((mag < lmag) || (mag < rmag)) {
+ result = NOEDGE;
+ } else {
+ if (rmag == mag) // If the external magnitude is equal to the current, suppress current.
+ result = NOEDGE;
+ else
+ result = (mag > 255) ? 255 : mag;
+ }
+ }
+ nms[col][row] = result;
+ }
+ }
+}
+
+KisToolMagnetic::KisToolMagnetic ()
+ : super("Magnetic Outline Tool")
+{
+ setName("tool_moutline");
+ setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
+
+ m_editingMode = false;
+ m_editingCursor = m_draggingCursor = false;
+
+ m_mode = 0;
+ m_curve = m_derived = 0;
+ m_current = m_previous = 0;
+
+ m_distance = DEFAULTDIST;
+
+ m_transactionMessage = i18n("Magnetic Outline Selection");
+}
+
+KisToolMagnetic::~KisToolMagnetic ()
+{
+ m_curve = 0;
+ delete m_derived;
+}
+
+void KisToolMagnetic::update (KisCanvasSubject *subject)
+{
+ super::update(subject);
+}
+
+void KisToolMagnetic::activate ()
+{
+ super::activate();
+ if (!m_derived) {
+ m_derived = new KisCurveMagnetic(this);
+ m_curve = m_derived;
+ }
+}
+
+void KisToolMagnetic::deactivate ()
+{
+ m_curve->endActionOptions();
+ m_actionOptions = NOOPTIONS;
+ m_dragging = false;
+ m_drawPivots = true;
+}
+
+void KisToolMagnetic::keyPress(TQKeyEvent *event)
+{
+ if (event->key() == TQt::Key_Control) {
+ draw(false);
+ if (m_editingMode) {
+ m_editingMode = false;
+ if (m_current != 0)
+ m_curve->selectPivot(m_current,false);
+ m_mode->setText(i18n("Automatic Mode"));
+ } else {
+ m_editingMode = true;
+ m_mode->setText(i18n("Manual Mode"));
+ }
+ draw(false);
+ } else if (event->key() == TQt::Key_Delete && m_curve->count()) {
+ draw(false);
+ m_dragging = false;
+ if (m_curve->pivots().count() == 2)
+ m_curve->clear();
+ else {
+ if ((*m_current) == m_curve->last() && !(m_editingMode)) {
+ m_curve->deletePivot(m_current.previousPivot());
+ m_previous = m_current.previousPivot();
+ } else {
+ m_editingMode = false;
+ m_curve->deletePivot(m_current);
+ m_previous = m_current = m_curve->selectPivot(m_curve->lastIterator());
+ m_editingMode = true;
+ }
+ }
+ draw(false);
+ } else
+ super::keyPress(event);
+}
+
+void KisToolMagnetic::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (m_editingMode) {
+ draw(m_current);
+ m_editingMode = false;
+ if (!m_curve->isEmpty())
+ m_curve->movePivot(m_current, m_currentPoint);
+ m_editingMode = true;
+ draw(m_current);
+ }
+ super::buttonRelease(event);
+}
+
+void KisToolMagnetic::buttonPress(KisButtonPressEvent *event)
+{
+ updateOptions(event->state());
+ if (!m_currentImage)
+ return;
+ if (event->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_currentPoint = event->pos();
+ PointPair temp(m_curve->end(),false);
+ if (m_editingMode)
+ temp = pointUnderMouse (m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
+ if (temp.first == m_curve->end() && !(m_actionOptions)) {
+ if (m_editingMode) {
+ draw(true, true);
+ m_curve->selectAll(false);
+ draw(true, true);
+ }
+ draw(m_curve->end());
+ if (!m_curve->isEmpty()) {
+ m_previous = m_current;
+ m_current = m_curve->pushPivot(event->pos());
+ } else {
+ m_previous = m_current = m_curve->pushPivot(event->pos());
+ }
+ if (m_curve->pivots().count() > 1)
+ m_curve->calculateCurve(m_previous,m_current,m_current);
+ if (m_editingMode)
+ draw();
+ else {
+ if ((*m_previous).point() == (*m_current).point())
+ draw(m_curve->end());
+ else
+ draw();
+ }
+ } else if (temp.first != m_curve->end() && m_editingMode) {
+ if (temp.second) {
+ draw(true, true);
+ m_current = m_curve->selectPivot(temp.first);
+ draw(true, true);
+ } else {
+ draw(false);
+ m_current = selectByMouse(temp.first);
+ draw(false);
+ }
+ if (!(*m_current).isSelected())
+ m_dragging = false;
+ }
+ }
+}
+
+void KisToolMagnetic::move(KisMoveEvent *event)
+{
+ updateOptions(event->state());
+ if (m_currentPoint == event->pos().floorTQPoint())
+ return;
+ if (m_editingMode) {
+ PointPair temp = pointUnderMouse(m_subject->canvasController()->windowToView(event->pos().toTQPoint()));
+ if (temp.first == m_curve->end() && !m_dragging) {
+ if (m_editingCursor || m_draggingCursor) {
+ setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
+ m_editingCursor = m_draggingCursor = false;
+ }
+ } else {
+ if (!m_draggingCursor && temp.second) {
+ setCursor(KisCursor::load("tool_moutline_dragging.png", 6, 6));
+ m_editingCursor = false;
+ m_draggingCursor = true;
+ }
+ if (!m_editingCursor && !temp.second) {
+ setCursor(KisCursor::load("tool_moutline_editing.png", 6, 6));
+ m_editingCursor = true;
+ m_draggingCursor = false;
+ }
+ }
+ if (!m_dragging)
+ return;
+ } else {
+ if (m_editingCursor || m_draggingCursor) {
+ setCursor(KisCursor::load("tool_moutline_cursor.png", 6, 6));
+ m_editingCursor = m_draggingCursor = false;
+ }
+ }
+ if (m_curve->selectedPivots().isEmpty())
+ return;
+
+ KisPoint trans = event->pos() - m_currentPoint;
+ KisPoint dist;
+ dist = (*m_current).point() - (*m_current.previousPivot()).point();
+ if ((m_distance >= MINDIST && (fabs(dist.x()) + fabs(dist.y())) > m_distance && !(m_editingMode))
+ || m_curve->pivots().count() == 1) {
+ draw(m_curve->end());
+ m_previous = m_current;
+ m_current = m_curve->pushPivot(event->pos());
+ } else if ((*m_previous).point() == (*m_current).point() && (*m_previous).point() == m_curve->last().point())
+ draw(m_curve->end());
+ else
+ draw(m_current);
+ m_curve->movePivot(m_current,event->pos());
+ m_currentPoint = event->pos().floorTQPoint();
+ draw(m_current);
+}
+
+KisCurve::iterator KisToolMagnetic::selectByMouse(KisCurve::iterator it)
+{
+ KisCurve::iterator currPivot = m_curve->selectPivot(m_curve->addPivot(it, KisPoint(0,0)));
+ m_curve->movePivot(currPivot,(*it).point());
+
+ return currPivot;
+}
+
+void KisToolMagnetic::slotCommitCurve ()
+{
+ if (!m_curve->isEmpty())
+ commitCurve();
+}
+
+void KisToolMagnetic::slotSetDistance (int dist)
+{
+ m_distance = dist;
+}
+
+TQWidget* KisToolMagnetic::createOptionWidget(TQWidget* parent)
+{
+ m_optWidget = super::createOptionWidget(parent);
+ TQVBoxLayout * l = dynamic_cast<TQVBoxLayout*>(m_optWidget->layout());
+ TQGridLayout *box = new TQGridLayout(l, 2, 2, 3);
+ box->setColStretch(0, 1);
+ box->setColStretch(1, 1);
+ TQ_CHECK_PTR(box);
+
+ m_mode = new TQLabel(i18n("Automatic mode"), m_optWidget);
+ m_lbDistance = new TQLabel(i18n("Distance: "), m_optWidget);
+ TQPushButton *finish = new TQPushButton(i18n("To Selection"), m_optWidget);
+ m_slDistance = new TQSlider(MINDIST, MAXDIST, PAGESTEP, m_distance, Qt::Horizontal, m_optWidget);
+
+ connect(m_slDistance, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotSetDistance(int)));
+ connect(finish, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotCommitCurve()));
+
+ box->addWidget(m_lbDistance, 0, 0);
+ box->addWidget(m_slDistance, 0, 1);
+ box->addWidget(m_mode, 1, 0);
+ box->addWidget(finish, 1, 1);
+
+ return m_optWidget;
+}
+
+void KisToolMagnetic::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("Magnetic Outline"),
+ "tool_moutline",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Magnetic Selection: move around an edge to select it. Hit Ctrl to enter/quit manual mode, and double click to finish."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_moutline.moc"
diff --git a/chalk/plugins/tools/tool_curves/tool_curves.cc b/chalk/plugins/tools/tool_curves/tool_curves.cc
deleted file mode 100644
index b21f5aae3..000000000
--- a/chalk/plugins/tools/tool_curves/tool_curves.cc
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * tool_bezier.cc -- part of Chalk
- *
- * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_curves.h"
-#include "kis_tool_bezier_paint.h"
-#include "kis_tool_bezier_select.h"
-#include "kis_tool_moutline.h"
-
-
-typedef KGenericFactory<ToolCurves> ToolCurvesFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolcurves, ToolCurvesFactory( "chalk" ) )
-
-
-ToolCurves::ToolCurves(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolCurvesFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
- r->add(new KisToolBezierPaintFactory());
- r->add(new KisToolBezierSelectFactory());
- r->add(new KisToolMagneticFactory());
- }
-
-}
-
-ToolCurves::~ToolCurves()
-{
-}
-
-#include "tool_curves.moc"
diff --git a/chalk/plugins/tools/tool_curves/tool_curves.cpp b/chalk/plugins/tools/tool_curves/tool_curves.cpp
new file mode 100644
index 000000000..28f65604a
--- /dev/null
+++ b/chalk/plugins/tools/tool_curves/tool_curves.cpp
@@ -0,0 +1,67 @@
+/*
+ * tool_bezier.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Emanuele Tamponi <emanuele@valinor.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_curves.h"
+#include "kis_tool_bezier_paint.h"
+#include "kis_tool_bezier_select.h"
+#include "kis_tool_moutline.h"
+
+
+typedef KGenericFactory<ToolCurves> ToolCurvesFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolcurves, ToolCurvesFactory( "chalk" ) )
+
+
+ToolCurves::ToolCurves(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolCurvesFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
+ r->add(new KisToolBezierPaintFactory());
+ r->add(new KisToolBezierSelectFactory());
+ r->add(new KisToolMagneticFactory());
+ }
+
+}
+
+ToolCurves::~ToolCurves()
+{
+}
+
+#include "tool_curves.moc"
diff --git a/chalk/plugins/tools/tool_filter/Makefile.am b/chalk/plugins/tools/tool_filter/Makefile.am
index d99a39249..b12ab69b5 100644
--- a/chalk/plugins/tools/tool_filter/Makefile.am
+++ b/chalk/plugins/tools/tool_filter/Makefile.am
@@ -10,9 +10,9 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolfilter_la_SOURCES = \
- kis_filterop.cc \
- kis_tool_filter.cc \
- tool_filter.cc
+ kis_filterop.cpp \
+ kis_tool_filter.cpp \
+ tool_filter.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolfilter.la
diff --git a/chalk/plugins/tools/tool_filter/kis_filterop.cc b/chalk/plugins/tools/tool_filter/kis_filterop.cpp
index d3378730f..d3378730f 100644
--- a/chalk/plugins/tools/tool_filter/kis_filterop.cc
+++ b/chalk/plugins/tools/tool_filter/kis_filterop.cpp
diff --git a/chalk/plugins/tools/tool_filter/kis_tool_filter.cc b/chalk/plugins/tools/tool_filter/kis_tool_filter.cc
deleted file mode 100644
index 07133d3bb..000000000
--- a/chalk/plugins/tools/tool_filter/kis_tool_filter.cc
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * kis_tool_filter.cc - part of Chalk
- *
- * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqbitmap.h>
-#include <tqpainter.h>
-#include <tqcombobox.h>
-#include <tqlayout.h>
-#include <tqlabel.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-
-#include "kis_filter_config_widget.h"
-#include "kis_tool_filter.h"
-#include <kis_brush.h>
-#include <kis_button_press_event.h>
-#include <kis_button_release_event.h>
-#include <kis_canvas_subject.h>
-#include <kis_cmb_idlist.h>
-#include <kis_cursor.h>
-#include <kis_doc.h>
-#include <kis_filter.h>
-#include <kis_filterop.h>
-#include <kis_id.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_move_event.h>
-#include <kis_painter.h>
-#include <kis_paintop.h>
-#include <kis_paintop_registry.h>
-#include <kis_vec.h>
-
-KisToolFilter::KisToolFilter()
- : super(i18n("Filter Brush")), m_filterConfigurationWidget(0)
-{
- setName("tool_filter");
- m_subject = 0;
- setCursor(KisCursor::load("tool_filter_cursor.png", 5, 5));
-}
-
-KisToolFilter::~KisToolFilter()
-{
-}
-
-void KisToolFilter::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Filter Brush"),
- "tool_filter", 0, this,
- TQT_SLOT(activate()), collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Paint with filters"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-void KisToolFilter::initPaint(KisEvent *e)
-{
- // Some filters want to paint directly on the current state of
- // the canvas, others cannot handle that and need a temporary layer
- // so they can work on the old data before painting started.
- m_paintIncremental = m_filter->supportsIncrementalPainting();
-
- super::initPaint(e);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("filter", 0, painter());
- op->setSource ( m_source );
- painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
- painter()->setFilter( m_filter );
-
- // XXX: Isn't there a better way to set the config? The filter config widget needs to
- // to go into the tool options widget, and just the data carried over to the filter.
- // I've got a bit of a problem with core classes having too much GUI about them.
- // BSAR.
- dynamic_cast<KisFilterOp *>(op)->setFilterConfiguration( m_filter->configuration( m_filterConfigurationWidget) );
-}
-
-TQWidget* KisToolFilter::createOptionWidget(TQWidget* parent)
-{
- TQWidget *widget = super::createOptionWidget(parent);
-
- m_cbFilter = new KisCmbIDList(widget);
- TQ_CHECK_PTR(m_cbFilter);
-
- TQLabel* lbFilter = new TQLabel(i18n("Filter:"), widget);
- TQ_CHECK_PTR(lbFilter);
-
- // Check which filters support painting
- KisIDList l = KisFilterRegistry::instance()->listKeys();
- KisIDList l2;
- KisIDList::iterator it;
- for (it = l.begin(); it != l.end(); ++it) {
- KisFilterSP f = KisFilterRegistry::instance()->get(*it);
- if (f->supportsPainting()) {
- l2.push_back(*it);
- }
- }
- m_cbFilter ->setIDList( l2 );
-
- addOptionWidgetOption(m_cbFilter, lbFilter);
-
- m_optionLayout = new TQGridLayout(widget, 1, 1, 0, 6);
- TQ_CHECK_PTR(m_optionLayout);
- super::addOptionWidgetLayout(m_optionLayout);
-
- connect(m_cbFilter, TQT_SIGNAL(activated ( const KisID& )), this, TQT_SLOT( changeFilter( const KisID& ) ) );
- changeFilter( m_cbFilter->currentItem () );
-
- return widget;
-}
-
-void KisToolFilter::changeFilter( const KisID & id)
-{
- m_filter = KisFilterRegistry::instance()->get( id );
- Q_ASSERT(m_filter != 0);
- if( m_filterConfigurationWidget != 0 )
- {
- m_optionLayout->remove ( m_filterConfigurationWidget );
- delete m_filterConfigurationWidget;
- }
-
- m_source = m_currentImage->activeDevice();
- if (!m_source) return;
-
- m_filterConfigurationWidget = m_filter->createConfigurationWidget( optionWidget(), m_source );
- if( m_filterConfigurationWidget != 0 )
- {
- m_optionLayout->addMultiCellWidget ( m_filterConfigurationWidget, 2, 2, 0, 1 );
- m_filterConfigurationWidget->show();
- }
-}
-
-#include "kis_tool_filter.moc"
diff --git a/chalk/plugins/tools/tool_filter/kis_tool_filter.cpp b/chalk/plugins/tools/tool_filter/kis_tool_filter.cpp
new file mode 100644
index 000000000..14e2d6168
--- /dev/null
+++ b/chalk/plugins/tools/tool_filter/kis_tool_filter.cpp
@@ -0,0 +1,154 @@
+/*
+ * kis_tool_filter.cpp - part of Chalk
+ *
+ * Copyright (c) 2004 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqbitmap.h>
+#include <tqpainter.h>
+#include <tqcombobox.h>
+#include <tqlayout.h>
+#include <tqlabel.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+
+#include "kis_filter_config_widget.h"
+#include "kis_tool_filter.h"
+#include <kis_brush.h>
+#include <kis_button_press_event.h>
+#include <kis_button_release_event.h>
+#include <kis_canvas_subject.h>
+#include <kis_cmb_idlist.h>
+#include <kis_cursor.h>
+#include <kis_doc.h>
+#include <kis_filter.h>
+#include <kis_filterop.h>
+#include <kis_id.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_move_event.h>
+#include <kis_painter.h>
+#include <kis_paintop.h>
+#include <kis_paintop_registry.h>
+#include <kis_vec.h>
+
+KisToolFilter::KisToolFilter()
+ : super(i18n("Filter Brush")), m_filterConfigurationWidget(0)
+{
+ setName("tool_filter");
+ m_subject = 0;
+ setCursor(KisCursor::load("tool_filter_cursor.png", 5, 5));
+}
+
+KisToolFilter::~KisToolFilter()
+{
+}
+
+void KisToolFilter::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Filter Brush"),
+ "tool_filter", 0, this,
+ TQT_SLOT(activate()), collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Paint with filters"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+void KisToolFilter::initPaint(KisEvent *e)
+{
+ // Some filters want to paint directly on the current state of
+ // the canvas, others cannot handle that and need a temporary layer
+ // so they can work on the old data before painting started.
+ m_paintIncremental = m_filter->supportsIncrementalPainting();
+
+ super::initPaint(e);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp("filter", 0, painter());
+ op->setSource ( m_source );
+ painter()->setPaintOp(op); // And now the painter owns the op and will destroy it.
+ painter()->setFilter( m_filter );
+
+ // XXX: Isn't there a better way to set the config? The filter config widget needs to
+ // to go into the tool options widget, and just the data carried over to the filter.
+ // I've got a bit of a problem with core classes having too much GUI about them.
+ // BSAR.
+ dynamic_cast<KisFilterOp *>(op)->setFilterConfiguration( m_filter->configuration( m_filterConfigurationWidget) );
+}
+
+TQWidget* KisToolFilter::createOptionWidget(TQWidget* parent)
+{
+ TQWidget *widget = super::createOptionWidget(parent);
+
+ m_cbFilter = new KisCmbIDList(widget);
+ TQ_CHECK_PTR(m_cbFilter);
+
+ TQLabel* lbFilter = new TQLabel(i18n("Filter:"), widget);
+ TQ_CHECK_PTR(lbFilter);
+
+ // Check which filters support painting
+ KisIDList l = KisFilterRegistry::instance()->listKeys();
+ KisIDList l2;
+ KisIDList::iterator it;
+ for (it = l.begin(); it != l.end(); ++it) {
+ KisFilterSP f = KisFilterRegistry::instance()->get(*it);
+ if (f->supportsPainting()) {
+ l2.push_back(*it);
+ }
+ }
+ m_cbFilter ->setIDList( l2 );
+
+ addOptionWidgetOption(m_cbFilter, lbFilter);
+
+ m_optionLayout = new TQGridLayout(widget, 1, 1, 0, 6);
+ TQ_CHECK_PTR(m_optionLayout);
+ super::addOptionWidgetLayout(m_optionLayout);
+
+ connect(m_cbFilter, TQT_SIGNAL(activated ( const KisID& )), this, TQT_SLOT( changeFilter( const KisID& ) ) );
+ changeFilter( m_cbFilter->currentItem () );
+
+ return widget;
+}
+
+void KisToolFilter::changeFilter( const KisID & id)
+{
+ m_filter = KisFilterRegistry::instance()->get( id );
+ Q_ASSERT(m_filter != 0);
+ if( m_filterConfigurationWidget != 0 )
+ {
+ m_optionLayout->remove ( m_filterConfigurationWidget );
+ delete m_filterConfigurationWidget;
+ }
+
+ m_source = m_currentImage->activeDevice();
+ if (!m_source) return;
+
+ m_filterConfigurationWidget = m_filter->createConfigurationWidget( optionWidget(), m_source );
+ if( m_filterConfigurationWidget != 0 )
+ {
+ m_optionLayout->addMultiCellWidget ( m_filterConfigurationWidget, 2, 2, 0, 1 );
+ m_filterConfigurationWidget->show();
+ }
+}
+
+#include "kis_tool_filter.moc"
diff --git a/chalk/plugins/tools/tool_filter/tool_filter.cc b/chalk/plugins/tools/tool_filter/tool_filter.cc
deleted file mode 100644
index bda2357e3..000000000
--- a/chalk/plugins/tools/tool_filter/tool_filter.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * tool_filter.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_debug_areas.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-#include <kis_paintop_registry.h>
-
-#include "tool_filter.h"
-#include "kis_filterop.h"
-#include "kis_tool_filter.h"
-
-
-typedef KGenericFactory<ToolFilter> ToolFilterFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolfilter, ToolFilterFactory( "chalk" ) )
-
-
-ToolFilter::ToolFilter(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolFilterFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- r->add( new KisToolFilterFactory());
-
- // XXX: Put this in a separate plugin?
- KisPaintOpRegistry * pr = KisPaintOpRegistry::instance();
- pr->add( new KisFilterOpFactory );
-
- }
-}
-
-ToolFilter::~ToolFilter()
-{
-}
-
-#include "tool_filter.moc"
diff --git a/chalk/plugins/tools/tool_filter/tool_filter.cpp b/chalk/plugins/tools/tool_filter/tool_filter.cpp
new file mode 100644
index 000000000..484a7d9f3
--- /dev/null
+++ b/chalk/plugins/tools/tool_filter/tool_filter.cpp
@@ -0,0 +1,68 @@
+/*
+ * tool_filter.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_debug_areas.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+#include <kis_paintop_registry.h>
+
+#include "tool_filter.h"
+#include "kis_filterop.h"
+#include "kis_tool_filter.h"
+
+
+typedef KGenericFactory<ToolFilter> ToolFilterFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolfilter, ToolFilterFactory( "chalk" ) )
+
+
+ToolFilter::ToolFilter(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolFilterFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ r->add( new KisToolFilterFactory());
+
+ // XXX: Put this in a separate plugin?
+ KisPaintOpRegistry * pr = KisPaintOpRegistry::instance();
+ pr->add( new KisFilterOpFactory );
+
+ }
+}
+
+ToolFilter::~ToolFilter()
+{
+}
+
+#include "tool_filter.moc"
diff --git a/chalk/plugins/tools/tool_perspectivegrid/Makefile.am b/chalk/plugins/tools/tool_perspectivegrid/Makefile.am
index 8544c078a..c15df2687 100644
--- a/chalk/plugins/tools/tool_perspectivegrid/Makefile.am
+++ b/chalk/plugins/tools/tool_perspectivegrid/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolperspectivegrid_la_SOURCES = \
- tool_perspectivegrid.cc \
- kis_tool_perspectivegrid.cc
+ tool_perspectivegrid.cpp \
+ kis_tool_perspectivegrid.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolperspectivegrid.la
diff --git a/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cc b/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cc
deleted file mode 100644
index 2dbe56d3d..000000000
--- a/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cc
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- * kis_tool_perspectivegrid.cc - part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <kis_tool_perspectivegrid.h>
-
-#include <tqapplication.h>
-#include <tqpainter.h>
-#include <tqregion.h>
-#include <tqwidget.h>
-#include <tqlayout.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include <kis_button_press_event.h>
-#include <kis_button_release_event.h>
-#include <kis_canvas_controller.h>
-#include <kis_canvas_painter.h>
-#include <kis_canvas_subject.h>
-#include <kis_cursor.h>
-#include <kis_image.h>
-#include <kis_move_event.h>
-#include <kis_perspective_grid_manager.h>
-#include <kis_selected_transaction.h>
-#include <kis_painter.h>
-#include <kis_paintop_registry.h>
-#include <kis_vec.h>
-
-#include <kis_canvas.h>
-
-KisToolPerspectiveGrid::KisToolPerspectiveGrid()
- : super(i18n("Perspective Grid")), m_handleSize(13), m_handleHalfSize(6)
-
-{
- setName("tool_perspectivegrid");
-
- m_subject = 0;
- m_dragging = false;
-}
-
-KisToolPerspectiveGrid::~KisToolPerspectiveGrid()
-{
-}
-
-void KisToolPerspectiveGrid::activate()
-{
- m_subject->perspectiveGridManager()->startEdition();
- if( ! m_subject->currentImg()->perspectiveGrid()->hasSubGrids() )
- {
- m_mode = MODE_CREATION;
- m_points.clear();
- } else {
- m_mode = MODE_EDITING;
- drawGrid();
- }
- super::activate();
-}
-
-void KisToolPerspectiveGrid::deactivate()
-{
- m_subject->perspectiveGridManager()->stopEdition();
- m_subject->perspectiveGridManager()->setGridVisible( true);
- if( m_mode == MODE_CREATION )
- {
- drawGridCreation();
- m_points.clear();
- m_dragging = false;
- } else {
- drawGrid();
- }
-}
-
-
-void KisToolPerspectiveGrid::update (KisCanvasSubject *subject)
-{
- m_subject = subject;
- super::update(m_subject);
-}
-
-bool KisToolPerspectiveGrid::mouseNear(const TQPoint& mousep, const TQPoint point)
-{
- return (TQRect( (point.x() - m_handleHalfSize), (point.y() - m_handleHalfSize), m_handleSize, m_handleSize).contains(mousep) );
-}
-
-void KisToolPerspectiveGrid::buttonPress(KisButtonPressEvent *event)
-{
- KisPerspectiveGrid* pGrid = m_subject->currentImg()->perspectiveGrid();
- if(!pGrid->hasSubGrids() && m_mode != MODE_CREATION)
- { // it's possible that the perspectiv grid was cleared
- m_mode = MODE_CREATION;
- m_points.clear();
- }
- if( m_mode == MODE_CREATION && event->button() == Qt::LeftButton)
- {
- m_dragging = true;
-
- if (m_points.isEmpty())
- {
- m_dragStart = event->pos();
- m_dragEnd = event->pos();
- m_points.append(m_dragStart);
- } else {
- m_dragStart = m_dragEnd;
- m_dragEnd = event->pos();
- drawGridCreation();
- }
- } else if(m_mode == MODE_EDITING && event->button() == Qt::LeftButton){
- // Look for the handle which was pressed
- if (!m_subject)
- return;
- KisCanvasController *controller = m_subject->canvasController();
- Q_ASSERT(controller);
- TQPoint mousep = controller->windowToView( event->pos().roundTQPoint() );
-
- for( TQValueList<KisSubPerspectiveGrid*>::const_iterator it = pGrid->begin(); it != pGrid->end(); ++it)
- {
- KisSubPerspectiveGrid* grid = *it;
- if( mouseNear( mousep, controller->windowToView(grid->topLeft()->roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS TOPLEFT HANDLE " << endl;
- m_mode = MODE_DRAGING_NODE;
- m_selectedNode1 = grid->topLeft();
- break;
- }
- else if( mouseNear( mousep, controller->windowToView(grid->topRight()->roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS TOPRIGHT HANDLE " << endl;
- m_mode = MODE_DRAGING_NODE;
- m_selectedNode1 = grid->topRight();
- break;
- }
- else if( mouseNear( mousep, controller->windowToView(grid->bottomLeft()->roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS BOTTOMLEFT HANDLE " << endl;
- m_mode = MODE_DRAGING_NODE;
- m_selectedNode1 = grid->bottomLeft();
- break;
- }
- else if( mouseNear( mousep, controller->windowToView(grid->bottomRight()->roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS BOTTOMRIGHT HANDLE " << endl;
- m_mode = MODE_DRAGING_NODE;
- m_selectedNode1 = grid->bottomRight();
- break;
- }
- else if( !grid->leftGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topLeft() + *grid->bottomLeft() )*0.5) ).roundTQPoint() ) )
- {
- kdDebug() << " PRESS LEFT HANDLE " << endl;
- m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
- drawGrid();
- m_selectedNode1 = new KisPerspectiveGridNode( *grid->topLeft() );
- m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomLeft() );
- KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( m_selectedNode1, grid->topLeft() , grid->bottomLeft(), m_selectedNode2);
- m_dragEnd = event->pos();
- newsubgrid->setRightGrid( grid);
- grid->setLeftGrid( newsubgrid);
- pGrid->addNewSubGrid( newsubgrid);
- drawGrid();
- break;
- }
- else if( !grid->rightGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topRight() + *grid->bottomRight() )*0.5) ).roundTQPoint() ) )
- {
- kdDebug() << " PRESS RIGHT HANDLE " << endl;
- m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
- drawGrid();
- m_selectedNode1 = new KisPerspectiveGridNode( *grid->topRight() );
- m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomRight() );
- KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( grid->topRight(), m_selectedNode1, m_selectedNode2, grid->bottomRight());
- m_dragEnd = event->pos();
- newsubgrid->setLeftGrid( grid);
- grid->setRightGrid( newsubgrid);
- pGrid->addNewSubGrid( newsubgrid);
- drawGrid();
- break;
- }
- else if( !grid->topGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topLeft() + *grid->topRight() )*0.5) ).roundTQPoint() ) )
- {
- kdDebug() << " PRESS TOP HANDLE " << endl;
- m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
- drawGrid();
- m_selectedNode1 = new KisPerspectiveGridNode( *grid->topLeft() );
- m_selectedNode2 = new KisPerspectiveGridNode( *grid->topRight() );
- KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( m_selectedNode1, m_selectedNode2, grid->topRight(), grid->topLeft() );
- m_dragEnd = event->pos();
- newsubgrid->setBottomGrid( grid);
- grid->setTopGrid( newsubgrid);
- pGrid->addNewSubGrid( newsubgrid);
- drawGrid();
- break;
- }
- else if( !grid->bottomGrid() && mouseNear( mousep, controller->windowToView( ((*grid->bottomLeft() + *grid->bottomRight() )*0.5) ).roundTQPoint() ) )
- {
- kdDebug() << " PRESS BOTTOM HANDLE " << endl;
- m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
- drawGrid();
- m_selectedNode1 = new KisPerspectiveGridNode( *grid->bottomLeft() );
- m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomRight() );
- KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( grid->bottomLeft(), grid->bottomRight(), m_selectedNode2, m_selectedNode1);
- m_dragEnd = event->pos();
- newsubgrid->setTopGrid( grid);
- grid->setBottomGrid( newsubgrid);
- pGrid->addNewSubGrid( newsubgrid);
- drawGrid();
- break;
- }
- }
- }
-}
-
-
-void KisToolPerspectiveGrid::move(KisMoveEvent *event)
-{
- if( m_mode == MODE_CREATION )
- {
- if (m_dragging) {
- // erase old lines on canvas
- drawGridCreation();
- // get current mouse position
- m_dragEnd = event->pos();
- // draw new lines on canvas
- drawGridCreation();
- }
- } else {
- if( m_mode == MODE_DRAGING_NODE)
- {
- drawGrid();
- m_selectedNode1->setX( event->pos().x() );
- m_selectedNode1->setY( event->pos().y() );
- drawGrid();
- }
- if( m_mode == MODE_DRAGING_TRANSLATING_TWONODES)
- {
- drawGrid();
- KisPoint translate = event->pos() - m_dragEnd;
- m_dragEnd = event->pos();
- *m_selectedNode1 += translate;;
- *m_selectedNode2 += translate;;
- drawGrid();
- }
- }
-}
-
-void KisToolPerspectiveGrid::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject)
- return;
-
- if( m_mode == MODE_CREATION )
- {
- if (m_dragging && event->button() == Qt::LeftButton) {
- m_dragging = false;
- m_points.append (m_dragEnd);
- if( m_points.size() == 4)
- { // wow we have a grid, isn't that cool ?
- drawGridCreation(); // Clean
- m_subject->currentImg()->perspectiveGrid()->addNewSubGrid( new KisSubPerspectiveGrid( new KisPerspectiveGridNode(m_points[0]), new KisPerspectiveGridNode(m_points[1]), new KisPerspectiveGridNode(m_points[2]), new KisPerspectiveGridNode(m_points[3]) ) );
- drawGrid();
- m_mode = MODE_EDITING;
- }
- }
- } else {
- m_mode = MODE_EDITING;
- m_selectedNode1 = 0;
- m_selectedNode2 = 0;
- }
-
-/* if (m_dragging && event->button() == RightButton) {
-
- }*/
-}
-
-void KisToolPerspectiveGrid::paint(KisCanvasPainter& gc)
-{
- if( m_mode == MODE_CREATION )
- {
- drawGridCreation(gc);
- } else {
- drawGrid(gc);
- }
-}
-
-void KisToolPerspectiveGrid::paint(KisCanvasPainter& gc, const TQRect&)
-{
- if( m_mode == MODE_CREATION )
- {
- drawGridCreation(gc);
- } else {
- drawGrid(gc);
- }
-}
-
-void KisToolPerspectiveGrid::drawGridCreation()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
-
- drawGridCreation(gc);
- }
-}
-
-
-void KisToolPerspectiveGrid::drawGridCreation(KisCanvasPainter& gc)
-{
- if (!m_subject)
- return;
-
- TQPen pen(TQt::white);
-
- gc.setPen(pen);
- gc.setRasterOp(TQt::XorROP);
-
- KisCanvasController *controller = m_subject->canvasController();
- KisPoint start, end;
- TQPoint startPos;
- TQPoint endPos;
-
- if (m_dragging) {
- startPos = controller->windowToView(m_dragStart.floorTQPoint());
- endPos = controller->windowToView(m_dragEnd.floorTQPoint());
- gc.drawLine(startPos, endPos);
- } else {
- for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
-
- if (it == m_points.begin())
- {
- start = (*it);
- } else {
- end = (*it);
-
- startPos = controller->windowToView(start.floorTQPoint());
- endPos = controller->windowToView(end.floorTQPoint());
-
- gc.drawLine(startPos, endPos);
-
- start = end;
- }
- }
- }
-}
-
-void KisToolPerspectiveGrid::drawSmallRectangle(KisCanvasPainter& gc, TQPoint p)
-{
- gc.drawRect( p.x() - m_handleHalfSize - 1, p.y() - m_handleHalfSize - 1, m_handleSize, m_handleSize);
-}
-
-void KisToolPerspectiveGrid::drawGrid(KisCanvasPainter& gc)
-{
-
- if (!m_subject)
- return;
-
- KisCanvasController *controller = m_subject->canvasController();
-
- TQPen pen(TQt::white);
- TQPoint startPos;
- TQPoint endPos;
-
- gc.setPen(pen);
- gc.setRasterOp(TQt::XorROP);
- KisPerspectiveGrid* pGrid = m_subject->currentImg()->perspectiveGrid();
-
- for( TQValueList<KisSubPerspectiveGrid*>::const_iterator it = pGrid->begin(); it != pGrid->end(); ++it)
- {
- KisSubPerspectiveGrid* grid = *it;
- int index = grid->index();
- bool drawLeft = !(grid->leftGrid() && (index > grid->leftGrid()->index() ) );
- bool drawRight = !(grid->rightGrid() && (index > grid->rightGrid()->index() ) );
- bool drawTop = !(grid->topGrid() && (index > grid->topGrid()->index() ) );
- bool drawBottom = !(grid->bottomGrid() && (index > grid->bottomGrid()->index() ) );
- if(drawTop) {
- startPos = controller->windowToView(grid->topLeft()->roundTQPoint());
- endPos = controller->windowToView(grid->topRight()->roundTQPoint());
- gc.drawLine( startPos, endPos );
- if( !grid->topGrid() )
- {
- drawSmallRectangle(gc, (endPos + startPos) / 2);
- }
- if(drawLeft) {
- drawSmallRectangle(gc, startPos);
- }
- if(drawRight) {
- drawSmallRectangle(gc, endPos);
- }
- }
- if(drawRight) {
- startPos = controller->windowToView(grid->topRight()->roundTQPoint());
- endPos = controller->windowToView(grid->bottomRight()->roundTQPoint());
- gc.drawLine( startPos, endPos );
- if( !grid->rightGrid() )
- {
- drawSmallRectangle(gc, (endPos + startPos) / 2);
- }
- }
- if(drawBottom) {
- startPos = controller->windowToView(grid->bottomRight()->roundTQPoint());
- endPos = controller->windowToView(grid->bottomLeft()->roundTQPoint());
- gc.drawLine( startPos, endPos );
- if( !grid->bottomGrid() )
- {
- drawSmallRectangle(gc, (endPos + startPos) / 2);
- }
- if(drawLeft) {
- drawSmallRectangle(gc, endPos);
- }
- if(drawRight) {
- drawSmallRectangle(gc, startPos);
- }
- }
- if(drawLeft) {
- startPos = controller->windowToView(grid->bottomLeft()->roundTQPoint());
- endPos = controller->windowToView(grid->topLeft()->roundTQPoint());
- gc.drawLine( startPos, endPos );
- if( !grid->leftGrid() )
- {
- drawSmallRectangle(gc, (endPos + startPos) / 2);
- }
- }
- KisPoint tbVpf = grid->topBottomVanishingPoint();
- if( fabs(tbVpf.x()) < 30000000. && fabs(tbVpf.y()) < 30000000.)
- {
- TQPoint tbVp = controller->windowToView(tbVpf.roundTQPoint());
- gc.drawLine( tbVp.x() - m_handleHalfSize, tbVp.y() - m_handleHalfSize, tbVp.x() + m_handleHalfSize, tbVp.y() + m_handleHalfSize);
- gc.drawLine( tbVp.x() - m_handleHalfSize, tbVp.y() + m_handleHalfSize, tbVp.x() + m_handleHalfSize, tbVp.y() - m_handleHalfSize);
- }
- KisPoint lrVpf = grid->leftRightVanishingPoint();
- if( fabs(lrVpf.x()) < 30000000. && fabs(lrVpf.y()) < 30000000.)
- { // Don't display it, if it is too far, or you get funny results
- TQPoint lrVp = controller->windowToView(lrVpf.roundTQPoint());
- gc.drawLine( lrVp.x() - m_handleHalfSize, lrVp.y() - m_handleHalfSize, lrVp.x() + m_handleHalfSize, lrVp.y() + m_handleHalfSize);
- gc.drawLine( lrVp.x() - m_handleHalfSize, lrVp.y() + m_handleHalfSize, lrVp.x() + m_handleHalfSize, lrVp.y() - m_handleHalfSize);
- }
- }
-}
-
-void KisToolPerspectiveGrid::drawGrid()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
-
- drawGrid(gc);
- }
-
-}
-
-
-void KisToolPerspectiveGrid::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Perspective Grid"),
- "tool_perspectivegrid" ,
- 0,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setExclusiveGroup("tools");
- m_action->setToolTip(i18n("Edit the perspective grid"));
- m_ownAction = true;
- }
-}
-
-
-// TQWidget* KisToolPerspectiveGrid::createOptionWidget(TQWidget* parent)
-// {
-// return 0;
-// }
-//
-// TQWidget* KisToolPerspectiveGrid::optionWidget()
-// {
-// return 0;
-// }
-
-
-#include "kis_tool_perspectivegrid.moc"
diff --git a/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cpp b/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cpp
new file mode 100644
index 000000000..7d5df0f2b
--- /dev/null
+++ b/chalk/plugins/tools/tool_perspectivegrid/kis_tool_perspectivegrid.cpp
@@ -0,0 +1,499 @@
+/*
+ * kis_tool_perspectivegrid.cpp - part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <kis_tool_perspectivegrid.h>
+
+#include <tqapplication.h>
+#include <tqpainter.h>
+#include <tqregion.h>
+#include <tqwidget.h>
+#include <tqlayout.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include <kis_button_press_event.h>
+#include <kis_button_release_event.h>
+#include <kis_canvas_controller.h>
+#include <kis_canvas_painter.h>
+#include <kis_canvas_subject.h>
+#include <kis_cursor.h>
+#include <kis_image.h>
+#include <kis_move_event.h>
+#include <kis_perspective_grid_manager.h>
+#include <kis_selected_transaction.h>
+#include <kis_painter.h>
+#include <kis_paintop_registry.h>
+#include <kis_vec.h>
+
+#include <kis_canvas.h>
+
+KisToolPerspectiveGrid::KisToolPerspectiveGrid()
+ : super(i18n("Perspective Grid")), m_handleSize(13), m_handleHalfSize(6)
+
+{
+ setName("tool_perspectivegrid");
+
+ m_subject = 0;
+ m_dragging = false;
+}
+
+KisToolPerspectiveGrid::~KisToolPerspectiveGrid()
+{
+}
+
+void KisToolPerspectiveGrid::activate()
+{
+ m_subject->perspectiveGridManager()->startEdition();
+ if( ! m_subject->currentImg()->perspectiveGrid()->hasSubGrids() )
+ {
+ m_mode = MODE_CREATION;
+ m_points.clear();
+ } else {
+ m_mode = MODE_EDITING;
+ drawGrid();
+ }
+ super::activate();
+}
+
+void KisToolPerspectiveGrid::deactivate()
+{
+ m_subject->perspectiveGridManager()->stopEdition();
+ m_subject->perspectiveGridManager()->setGridVisible( true);
+ if( m_mode == MODE_CREATION )
+ {
+ drawGridCreation();
+ m_points.clear();
+ m_dragging = false;
+ } else {
+ drawGrid();
+ }
+}
+
+
+void KisToolPerspectiveGrid::update (KisCanvasSubject *subject)
+{
+ m_subject = subject;
+ super::update(m_subject);
+}
+
+bool KisToolPerspectiveGrid::mouseNear(const TQPoint& mousep, const TQPoint point)
+{
+ return (TQRect( (point.x() - m_handleHalfSize), (point.y() - m_handleHalfSize), m_handleSize, m_handleSize).contains(mousep) );
+}
+
+void KisToolPerspectiveGrid::buttonPress(KisButtonPressEvent *event)
+{
+ KisPerspectiveGrid* pGrid = m_subject->currentImg()->perspectiveGrid();
+ if(!pGrid->hasSubGrids() && m_mode != MODE_CREATION)
+ { // it's possible that the perspectiv grid was cleared
+ m_mode = MODE_CREATION;
+ m_points.clear();
+ }
+ if( m_mode == MODE_CREATION && event->button() == Qt::LeftButton)
+ {
+ m_dragging = true;
+
+ if (m_points.isEmpty())
+ {
+ m_dragStart = event->pos();
+ m_dragEnd = event->pos();
+ m_points.append(m_dragStart);
+ } else {
+ m_dragStart = m_dragEnd;
+ m_dragEnd = event->pos();
+ drawGridCreation();
+ }
+ } else if(m_mode == MODE_EDITING && event->button() == Qt::LeftButton){
+ // Look for the handle which was pressed
+ if (!m_subject)
+ return;
+ KisCanvasController *controller = m_subject->canvasController();
+ Q_ASSERT(controller);
+ TQPoint mousep = controller->windowToView( event->pos().roundTQPoint() );
+
+ for( TQValueList<KisSubPerspectiveGrid*>::const_iterator it = pGrid->begin(); it != pGrid->end(); ++it)
+ {
+ KisSubPerspectiveGrid* grid = *it;
+ if( mouseNear( mousep, controller->windowToView(grid->topLeft()->roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS TOPLEFT HANDLE " << endl;
+ m_mode = MODE_DRAGING_NODE;
+ m_selectedNode1 = grid->topLeft();
+ break;
+ }
+ else if( mouseNear( mousep, controller->windowToView(grid->topRight()->roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS TOPRIGHT HANDLE " << endl;
+ m_mode = MODE_DRAGING_NODE;
+ m_selectedNode1 = grid->topRight();
+ break;
+ }
+ else if( mouseNear( mousep, controller->windowToView(grid->bottomLeft()->roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS BOTTOMLEFT HANDLE " << endl;
+ m_mode = MODE_DRAGING_NODE;
+ m_selectedNode1 = grid->bottomLeft();
+ break;
+ }
+ else if( mouseNear( mousep, controller->windowToView(grid->bottomRight()->roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS BOTTOMRIGHT HANDLE " << endl;
+ m_mode = MODE_DRAGING_NODE;
+ m_selectedNode1 = grid->bottomRight();
+ break;
+ }
+ else if( !grid->leftGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topLeft() + *grid->bottomLeft() )*0.5) ).roundTQPoint() ) )
+ {
+ kdDebug() << " PRESS LEFT HANDLE " << endl;
+ m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
+ drawGrid();
+ m_selectedNode1 = new KisPerspectiveGridNode( *grid->topLeft() );
+ m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomLeft() );
+ KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( m_selectedNode1, grid->topLeft() , grid->bottomLeft(), m_selectedNode2);
+ m_dragEnd = event->pos();
+ newsubgrid->setRightGrid( grid);
+ grid->setLeftGrid( newsubgrid);
+ pGrid->addNewSubGrid( newsubgrid);
+ drawGrid();
+ break;
+ }
+ else if( !grid->rightGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topRight() + *grid->bottomRight() )*0.5) ).roundTQPoint() ) )
+ {
+ kdDebug() << " PRESS RIGHT HANDLE " << endl;
+ m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
+ drawGrid();
+ m_selectedNode1 = new KisPerspectiveGridNode( *grid->topRight() );
+ m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomRight() );
+ KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( grid->topRight(), m_selectedNode1, m_selectedNode2, grid->bottomRight());
+ m_dragEnd = event->pos();
+ newsubgrid->setLeftGrid( grid);
+ grid->setRightGrid( newsubgrid);
+ pGrid->addNewSubGrid( newsubgrid);
+ drawGrid();
+ break;
+ }
+ else if( !grid->topGrid() && mouseNear( mousep, controller->windowToView( ((*grid->topLeft() + *grid->topRight() )*0.5) ).roundTQPoint() ) )
+ {
+ kdDebug() << " PRESS TOP HANDLE " << endl;
+ m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
+ drawGrid();
+ m_selectedNode1 = new KisPerspectiveGridNode( *grid->topLeft() );
+ m_selectedNode2 = new KisPerspectiveGridNode( *grid->topRight() );
+ KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( m_selectedNode1, m_selectedNode2, grid->topRight(), grid->topLeft() );
+ m_dragEnd = event->pos();
+ newsubgrid->setBottomGrid( grid);
+ grid->setTopGrid( newsubgrid);
+ pGrid->addNewSubGrid( newsubgrid);
+ drawGrid();
+ break;
+ }
+ else if( !grid->bottomGrid() && mouseNear( mousep, controller->windowToView( ((*grid->bottomLeft() + *grid->bottomRight() )*0.5) ).roundTQPoint() ) )
+ {
+ kdDebug() << " PRESS BOTTOM HANDLE " << endl;
+ m_mode = MODE_DRAGING_TRANSLATING_TWONODES;
+ drawGrid();
+ m_selectedNode1 = new KisPerspectiveGridNode( *grid->bottomLeft() );
+ m_selectedNode2 = new KisPerspectiveGridNode( *grid->bottomRight() );
+ KisSubPerspectiveGrid* newsubgrid = new KisSubPerspectiveGrid( grid->bottomLeft(), grid->bottomRight(), m_selectedNode2, m_selectedNode1);
+ m_dragEnd = event->pos();
+ newsubgrid->setTopGrid( grid);
+ grid->setBottomGrid( newsubgrid);
+ pGrid->addNewSubGrid( newsubgrid);
+ drawGrid();
+ break;
+ }
+ }
+ }
+}
+
+
+void KisToolPerspectiveGrid::move(KisMoveEvent *event)
+{
+ if( m_mode == MODE_CREATION )
+ {
+ if (m_dragging) {
+ // erase old lines on canvas
+ drawGridCreation();
+ // get current mouse position
+ m_dragEnd = event->pos();
+ // draw new lines on canvas
+ drawGridCreation();
+ }
+ } else {
+ if( m_mode == MODE_DRAGING_NODE)
+ {
+ drawGrid();
+ m_selectedNode1->setX( event->pos().x() );
+ m_selectedNode1->setY( event->pos().y() );
+ drawGrid();
+ }
+ if( m_mode == MODE_DRAGING_TRANSLATING_TWONODES)
+ {
+ drawGrid();
+ KisPoint translate = event->pos() - m_dragEnd;
+ m_dragEnd = event->pos();
+ *m_selectedNode1 += translate;;
+ *m_selectedNode2 += translate;;
+ drawGrid();
+ }
+ }
+}
+
+void KisToolPerspectiveGrid::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject)
+ return;
+
+ if( m_mode == MODE_CREATION )
+ {
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ m_dragging = false;
+ m_points.append (m_dragEnd);
+ if( m_points.size() == 4)
+ { // wow we have a grid, isn't that cool ?
+ drawGridCreation(); // Clean
+ m_subject->currentImg()->perspectiveGrid()->addNewSubGrid( new KisSubPerspectiveGrid( new KisPerspectiveGridNode(m_points[0]), new KisPerspectiveGridNode(m_points[1]), new KisPerspectiveGridNode(m_points[2]), new KisPerspectiveGridNode(m_points[3]) ) );
+ drawGrid();
+ m_mode = MODE_EDITING;
+ }
+ }
+ } else {
+ m_mode = MODE_EDITING;
+ m_selectedNode1 = 0;
+ m_selectedNode2 = 0;
+ }
+
+/* if (m_dragging && event->button() == RightButton) {
+
+ }*/
+}
+
+void KisToolPerspectiveGrid::paint(KisCanvasPainter& gc)
+{
+ if( m_mode == MODE_CREATION )
+ {
+ drawGridCreation(gc);
+ } else {
+ drawGrid(gc);
+ }
+}
+
+void KisToolPerspectiveGrid::paint(KisCanvasPainter& gc, const TQRect&)
+{
+ if( m_mode == MODE_CREATION )
+ {
+ drawGridCreation(gc);
+ } else {
+ drawGrid(gc);
+ }
+}
+
+void KisToolPerspectiveGrid::drawGridCreation()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+
+ drawGridCreation(gc);
+ }
+}
+
+
+void KisToolPerspectiveGrid::drawGridCreation(KisCanvasPainter& gc)
+{
+ if (!m_subject)
+ return;
+
+ TQPen pen(TQt::white);
+
+ gc.setPen(pen);
+ gc.setRasterOp(TQt::XorROP);
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisPoint start, end;
+ TQPoint startPos;
+ TQPoint endPos;
+
+ if (m_dragging) {
+ startPos = controller->windowToView(m_dragStart.floorTQPoint());
+ endPos = controller->windowToView(m_dragEnd.floorTQPoint());
+ gc.drawLine(startPos, endPos);
+ } else {
+ for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
+
+ if (it == m_points.begin())
+ {
+ start = (*it);
+ } else {
+ end = (*it);
+
+ startPos = controller->windowToView(start.floorTQPoint());
+ endPos = controller->windowToView(end.floorTQPoint());
+
+ gc.drawLine(startPos, endPos);
+
+ start = end;
+ }
+ }
+ }
+}
+
+void KisToolPerspectiveGrid::drawSmallRectangle(KisCanvasPainter& gc, TQPoint p)
+{
+ gc.drawRect( p.x() - m_handleHalfSize - 1, p.y() - m_handleHalfSize - 1, m_handleSize, m_handleSize);
+}
+
+void KisToolPerspectiveGrid::drawGrid(KisCanvasPainter& gc)
+{
+
+ if (!m_subject)
+ return;
+
+ KisCanvasController *controller = m_subject->canvasController();
+
+ TQPen pen(TQt::white);
+ TQPoint startPos;
+ TQPoint endPos;
+
+ gc.setPen(pen);
+ gc.setRasterOp(TQt::XorROP);
+ KisPerspectiveGrid* pGrid = m_subject->currentImg()->perspectiveGrid();
+
+ for( TQValueList<KisSubPerspectiveGrid*>::const_iterator it = pGrid->begin(); it != pGrid->end(); ++it)
+ {
+ KisSubPerspectiveGrid* grid = *it;
+ int index = grid->index();
+ bool drawLeft = !(grid->leftGrid() && (index > grid->leftGrid()->index() ) );
+ bool drawRight = !(grid->rightGrid() && (index > grid->rightGrid()->index() ) );
+ bool drawTop = !(grid->topGrid() && (index > grid->topGrid()->index() ) );
+ bool drawBottom = !(grid->bottomGrid() && (index > grid->bottomGrid()->index() ) );
+ if(drawTop) {
+ startPos = controller->windowToView(grid->topLeft()->roundTQPoint());
+ endPos = controller->windowToView(grid->topRight()->roundTQPoint());
+ gc.drawLine( startPos, endPos );
+ if( !grid->topGrid() )
+ {
+ drawSmallRectangle(gc, (endPos + startPos) / 2);
+ }
+ if(drawLeft) {
+ drawSmallRectangle(gc, startPos);
+ }
+ if(drawRight) {
+ drawSmallRectangle(gc, endPos);
+ }
+ }
+ if(drawRight) {
+ startPos = controller->windowToView(grid->topRight()->roundTQPoint());
+ endPos = controller->windowToView(grid->bottomRight()->roundTQPoint());
+ gc.drawLine( startPos, endPos );
+ if( !grid->rightGrid() )
+ {
+ drawSmallRectangle(gc, (endPos + startPos) / 2);
+ }
+ }
+ if(drawBottom) {
+ startPos = controller->windowToView(grid->bottomRight()->roundTQPoint());
+ endPos = controller->windowToView(grid->bottomLeft()->roundTQPoint());
+ gc.drawLine( startPos, endPos );
+ if( !grid->bottomGrid() )
+ {
+ drawSmallRectangle(gc, (endPos + startPos) / 2);
+ }
+ if(drawLeft) {
+ drawSmallRectangle(gc, endPos);
+ }
+ if(drawRight) {
+ drawSmallRectangle(gc, startPos);
+ }
+ }
+ if(drawLeft) {
+ startPos = controller->windowToView(grid->bottomLeft()->roundTQPoint());
+ endPos = controller->windowToView(grid->topLeft()->roundTQPoint());
+ gc.drawLine( startPos, endPos );
+ if( !grid->leftGrid() )
+ {
+ drawSmallRectangle(gc, (endPos + startPos) / 2);
+ }
+ }
+ KisPoint tbVpf = grid->topBottomVanishingPoint();
+ if( fabs(tbVpf.x()) < 30000000. && fabs(tbVpf.y()) < 30000000.)
+ {
+ TQPoint tbVp = controller->windowToView(tbVpf.roundTQPoint());
+ gc.drawLine( tbVp.x() - m_handleHalfSize, tbVp.y() - m_handleHalfSize, tbVp.x() + m_handleHalfSize, tbVp.y() + m_handleHalfSize);
+ gc.drawLine( tbVp.x() - m_handleHalfSize, tbVp.y() + m_handleHalfSize, tbVp.x() + m_handleHalfSize, tbVp.y() - m_handleHalfSize);
+ }
+ KisPoint lrVpf = grid->leftRightVanishingPoint();
+ if( fabs(lrVpf.x()) < 30000000. && fabs(lrVpf.y()) < 30000000.)
+ { // Don't display it, if it is too far, or you get funny results
+ TQPoint lrVp = controller->windowToView(lrVpf.roundTQPoint());
+ gc.drawLine( lrVp.x() - m_handleHalfSize, lrVp.y() - m_handleHalfSize, lrVp.x() + m_handleHalfSize, lrVp.y() + m_handleHalfSize);
+ gc.drawLine( lrVp.x() - m_handleHalfSize, lrVp.y() + m_handleHalfSize, lrVp.x() + m_handleHalfSize, lrVp.y() - m_handleHalfSize);
+ }
+ }
+}
+
+void KisToolPerspectiveGrid::drawGrid()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+
+ drawGrid(gc);
+ }
+
+}
+
+
+void KisToolPerspectiveGrid::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Perspective Grid"),
+ "tool_perspectivegrid" ,
+ 0,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setExclusiveGroup("tools");
+ m_action->setToolTip(i18n("Edit the perspective grid"));
+ m_ownAction = true;
+ }
+}
+
+
+// TQWidget* KisToolPerspectiveGrid::createOptionWidget(TQWidget* parent)
+// {
+// return 0;
+// }
+//
+// TQWidget* KisToolPerspectiveGrid::optionWidget()
+// {
+// return 0;
+// }
+
+
+#include "kis_tool_perspectivegrid.moc"
diff --git a/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cc b/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cc
deleted file mode 100644
index f2800a594..000000000
--- a/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * tool_perspectivegrid.cc -- Part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_perspectivegrid.h"
-#include "kis_tool_perspectivegrid.h"
-
-
-typedef KGenericFactory<ToolPerspectiveGrid> ToolPerspectiveGridFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolperspectivegrid, ToolPerspectiveGridFactory( "chalk" ) )
-
-
-ToolPerspectiveGrid::ToolPerspectiveGrid(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolPerspectiveGridFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- r->add(new KisToolPerspectiveGridFactory());
- }
-
-}
-
-ToolPerspectiveGrid::~ToolPerspectiveGrid()
-{
-}
-
-#include "tool_perspectivegrid.moc"
diff --git a/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cpp b/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cpp
new file mode 100644
index 000000000..2f326965b
--- /dev/null
+++ b/chalk/plugins/tools/tool_perspectivegrid/tool_perspectivegrid.cpp
@@ -0,0 +1,62 @@
+/*
+ * tool_perspectivegrid.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_perspectivegrid.h"
+#include "kis_tool_perspectivegrid.h"
+
+
+typedef KGenericFactory<ToolPerspectiveGrid> ToolPerspectiveGridFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolperspectivegrid, ToolPerspectiveGridFactory( "chalk" ) )
+
+
+ToolPerspectiveGrid::ToolPerspectiveGrid(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolPerspectiveGridFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ r->add(new KisToolPerspectiveGridFactory());
+ }
+
+}
+
+ToolPerspectiveGrid::~ToolPerspectiveGrid()
+{
+}
+
+#include "tool_perspectivegrid.moc"
diff --git a/chalk/plugins/tools/tool_perspectivetransform/Makefile.am b/chalk/plugins/tools/tool_perspectivetransform/Makefile.am
index 08c8d7079..275f6413d 100644
--- a/chalk/plugins/tools/tool_perspectivetransform/Makefile.am
+++ b/chalk/plugins/tools/tool_perspectivetransform/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolperspectivetransform_la_SOURCES = \
- tool_perspectivetransform.cc \
- kis_tool_perspectivetransform.cc
+ tool_perspectivetransform.cpp \
+ kis_tool_perspectivetransform.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolperspectivetransform.la
diff --git a/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cc b/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cc
deleted file mode 100644
index ae334e627..000000000
--- a/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cc
+++ /dev/null
@@ -1,742 +0,0 @@
-/*
- * kis_tool_transform.cc -- part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * Based on the transform tool from :
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2005 Casper Boemann <cbr@boemann.dk>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; version 2 of the License.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "kis_tool_perspectivetransform.h"
-
-
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqpushbutton.h>
-#include <tqobject.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqapplication.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-
-#include <kis_global.h>
-#include <kis_painter.h>
-#include <kis_canvas_controller.h>
-#include <kis_canvas_subject.h>
-#include <kis_cursor.h>
-#include <kis_image.h>
-#include <kis_undo_adapter.h>
-#include <kis_selected_transaction.h>
-#include <kis_button_press_event.h>
-#include <kis_button_release_event.h>
-#include <kis_move_event.h>
-#include <kis_selection.h>
-#include <kis_filter_strategy.h>
-#include <kis_cmb_idlist.h>
-#include <kis_id.h>
-#include <kis_tool_controller.h>
-#include <kis_perspectivetransform_worker.h>
-
-//#include "wdg_tool_transform.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-namespace {
- class PerspectiveTransformCmd : public KisSelectedTransaction {
- typedef KisSelectedTransaction super;
-
- public:
- PerspectiveTransformCmd(KisToolPerspectiveTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, KisPoint topleft, KisPoint topright, KisPoint bottomleft, KisPoint bottomright, KisSelectionSP origSel, TQRect initialRect);
- virtual ~PerspectiveTransformCmd();
-
- public:
- virtual void execute();
- virtual void unexecute();
- void transformArgs(KisPoint &topleft, KisPoint &topright, KisPoint &bottomleft, KisPoint& bottomright) const;
- KisSelectionSP origSelection(TQRect& initialRect) const;
- KisPaintDeviceSP theDevice();
- KisPaintDeviceSP origDevice();
-
- private:
- TQRect m_initialRect;
- KisPoint m_topleft, m_topright, m_bottomleft, m_bottomright;
- KisToolPerspectiveTransform *m_tool;
- KisSelectionSP m_origSelection;
- KisPaintDeviceSP m_device;
- KisPaintDeviceSP m_origDevice;
- };
-
- PerspectiveTransformCmd::PerspectiveTransformCmd(KisToolPerspectiveTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, KisPoint topleft, KisPoint topright, KisPoint bottomleft, KisPoint bottomright, KisSelectionSP origSel, TQRect initialRect) :
- super(i18n("Perspective Transform"), device), m_initialRect(initialRect)
- , m_topleft(topleft), m_topright(topright), m_bottomleft(bottomleft), m_bottomright(bottomright)
- , m_tool(tool), m_origSelection(origSel), m_device(device), m_origDevice(origDevice)
- {
- }
-
- PerspectiveTransformCmd::~PerspectiveTransformCmd()
- {
- }
-
- void PerspectiveTransformCmd::transformArgs(KisPoint &topleft, KisPoint &topright, KisPoint &bottomleft, KisPoint& bottomright) const
- {
- topleft = m_topleft;
- topright = m_topright;
- bottomleft = m_bottomleft;
- bottomright = m_bottomright;
- }
-
- KisSelectionSP PerspectiveTransformCmd::origSelection(TQRect& initialRect) const
- {
- initialRect = m_initialRect;
- return m_origSelection;
- }
-
- void PerspectiveTransformCmd::execute()
- {
- super::execute();
- }
-
- void PerspectiveTransformCmd::unexecute()
- {
- super::unexecute();
- }
-
- KisPaintDeviceSP PerspectiveTransformCmd::theDevice()
- {
- return m_device;
- }
-
- KisPaintDeviceSP PerspectiveTransformCmd::origDevice()
- {
- return m_origDevice;
- }
-}
-
-KisToolPerspectiveTransform::KisToolPerspectiveTransform()
- : super(i18n("Perspective Transform"))
-{
- setName("tool_perspectivetransform");
- setCursor(KisCursor::selectCursor());
- m_subject = 0;
- m_origDevice = 0;
- m_origSelection = 0;
- m_handleHalfSize = 8;
- m_handleSize = 2 * m_handleHalfSize;
- m_handleSelected = NOHANDLE;
-}
-
-KisToolPerspectiveTransform::~KisToolPerspectiveTransform()
-{
-}
-
-void KisToolPerspectiveTransform::deactivate()
-{
- if (m_subject && m_subject->undoAdapter()) m_subject->undoAdapter()->removeCommandHistoryListener( this );
-
- KisImageSP img = m_subject->currentImg();
- if (!img) return;
-
- paintOutline();
-
- disconnect(m_subject->currentImg().data(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
-}
-
-void KisToolPerspectiveTransform::activate()
-{
- super::activate();
- m_currentSelectedPoint = 0;
- if(m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice())
- {
- //connect(m_subject, commandExecuted(KCommand *c), this, notifyCommandAdded( KCommand * c));
- m_subject->undoAdapter()->setCommandHistoryListener( this );
-
-// KisToolControllerInterface *controller = m_subject->toolController();
-// if (controller)
-// controller->setCurrentTool(this);
-
- PerspectiveTransformCmd * cmd=0;
-
- if(m_subject->currentImg()->undoAdapter()->presentCommand())
- cmd = dynamic_cast<PerspectiveTransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
-
- // One of our commands is on top
- if(cmd &&cmd->theDevice() == m_subject->currentImg()->activeDevice())
- {
- m_interractionMode = EDITRECTINTERRACTION;
- // and it even has the same device
- // We should ask for tool args and orig selection
- m_origDevice = cmd->origDevice();
- cmd->transformArgs(m_topleft, m_topright, m_bottomleft, m_bottomright);
- m_origSelection = cmd->origSelection(m_initialRect);
- paintOutline();
- }
- else
- {
- m_interractionMode = DRAWRECTINTERRACTION;
- m_points.clear();
- initHandles();
- }
- }
- connect(m_subject->currentImg(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
-}
-
-void KisToolPerspectiveTransform::initHandles()
-{
-// TQ_INT32 x,y,w,h;
- KisImageSP img = m_subject->currentImg();
-
- KisPaintDeviceSP dev = img->activeDevice();
- if (!dev ) return;
-
- // Create a lazy copy of the current state
- m_origDevice = new KisPaintDevice(*dev.data());
- Q_ASSERT(m_origDevice);
-
- if(dev->hasSelection())
- {
- KisSelectionSP sel = dev->selection();
- m_origSelection = new KisSelection(*sel.data());
- m_initialRect = sel->selectedExactRect();
- }
- else {
- m_initialRect = dev->exactBounds();
- }
- m_topleft = KisPoint(m_initialRect.topLeft());
- m_topright = KisPoint(m_initialRect.topRight());
- m_bottomleft = KisPoint(m_initialRect.bottomLeft());
- m_bottomright = KisPoint(m_initialRect.bottomRight());
-
- m_subject->canvasController() ->updateCanvas();
-}
-
-void KisToolPerspectiveTransform::paint(KisCanvasPainter& gc)
-{
- paintOutline(gc, TQRect());
-}
-
-void KisToolPerspectiveTransform::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- paintOutline(gc, rc);
-}
-
-bool KisToolPerspectiveTransform::mouseNear(const TQPoint& mousep, const TQPoint point)
-{
- return (TQRect( (point.x() - m_handleHalfSize), (point.y() - m_handleHalfSize), m_handleSize, m_handleSize).contains(mousep) );
-}
-
-void KisToolPerspectiveTransform::buttonPress(KisButtonPressEvent *event)
-{
- if (m_subject) {
- switch(m_interractionMode)
- {
- case DRAWRECTINTERRACTION:
- {
- if (m_points.isEmpty())
- {
- m_dragging = false;
- m_dragStart = event->pos();
- m_dragEnd = event->pos();
- m_points.append(m_dragStart);
- paintOutline();
- } else {
- m_dragging = true;
- m_dragStart = m_dragEnd;
- m_dragEnd = event->pos();
- paintOutline();
- }
- }
- case EDITRECTINTERRACTION:
- {
- KisImageSP img = m_subject->currentImg();
-
- if (img && img->activeDevice() && event->button() == Qt::LeftButton) {
- m_actualyMoveWhileSelected = false;
- m_dragEnd = event->pos();
- KisCanvasController *controller = m_subject->canvasController();
- TQPoint mousep = controller->windowToView( event->pos().roundTQPoint() );
- if( mouseNear( mousep, controller->windowToView(m_topleft.roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS TOPLEFT HANDLE " << endl;
- m_currentSelectedPoint = &m_topleft;
- }
- else if( mouseNear( mousep, controller->windowToView(m_topright.roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS TOPRIGHT HANDLE " << endl;
- m_currentSelectedPoint = &m_topright;
- }
- else if( mouseNear( mousep, controller->windowToView(m_bottomleft.roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS BOTTOMLEFT HANDLE " << endl;
- m_currentSelectedPoint = &m_bottomleft;
- }
- else if( mouseNear( mousep, controller->windowToView(m_bottomright.roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS BOTTOMRIGHT HANDLE " << endl;
- m_currentSelectedPoint = &m_bottomright;
- } else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_topright)*0.5).roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS TOP HANDLE " << endl;
- m_handleSelected = TOPHANDLE;
- }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_bottomleft)*0.5).roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS LEFT HANDLE " << endl;
- m_handleSelected = LEFTHANDLE;
- }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_bottomleft+m_bottomright)*0.5).roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS BOTTOM HANDLE " << endl;
- m_handleSelected = BOTTOMHANDLE;
- }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_bottomright+m_topright)*0.5).roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS RIGHT HANDLE " << endl;
- m_handleSelected = RIGHTHANDLE;
- }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_bottomleft + m_bottomright+m_topright)*0.25).roundTQPoint() ) ) )
- {
- kdDebug() << " PRESS MIDDLE HANDLE " << endl;
- m_handleSelected = MIDDLEHANDLE;
- }
- }
- }
- }
- }
-}
-
-void KisToolPerspectiveTransform::move(KisMoveEvent *event)
-{
- switch(m_interractionMode)
- {
- case DRAWRECTINTERRACTION:
- {
- if (m_dragging) {
- // erase old lines on canvas
- paintOutline();
- // get current mouse position
- m_dragEnd = event->pos();
- // draw new lines on canvas
- paintOutline();
- }
- }
-
- case EDITRECTINTERRACTION:
- {
- if(m_currentSelectedPoint)
- {
- paintOutline();
- KisPoint translate = event->pos() - m_dragEnd;
- m_dragEnd = event->pos();
- *m_currentSelectedPoint += translate;;
- paintOutline();
- m_actualyMoveWhileSelected = true;
- }
- else if(m_handleSelected == TOPHANDLE || m_handleSelected == LEFTHANDLE || m_handleSelected == BOTTOMHANDLE || m_handleSelected == RIGHTHANDLE)
- {
- paintOutline();
-
- KisPoint translate = event->pos() - m_dragEnd;
- m_dragEnd = event->pos();
-
- double matrixFrom[3][3];
- double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(m_topleft, m_topright, m_bottomleft, m_bottomright, m_initialRect);
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- matrixFrom[i][j] = b[3*i+j];
- }
- }
- delete b;
-
- KisPoint topLeft = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.topLeft()) );
- KisPoint topRight = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.topRight()) );
- KisPoint bottomLeft = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.bottomLeft()) );
- KisPoint bottomRight = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.bottomRight()) );
- TQRect dstRect = m_initialRect;
- switch(m_handleSelected)
- {
- case TOPHANDLE:
- dstRect.setTop( static_cast<int>( dstRect.top() + translate.y() ) ) ;
- break;
- case LEFTHANDLE:
- dstRect.setLeft( static_cast<int>( dstRect.left() + translate.x() ) );
- break;
- case BOTTOMHANDLE:
- dstRect.setBottom( static_cast<int>( dstRect.bottom() + translate.y() ) );
- break;
- case RIGHTHANDLE:
- dstRect.setRight( static_cast<int>( dstRect.right() + translate.x() ) );
- break;
- case MIDDLEHANDLE:
- case NOHANDLE:
- kdDebug() << "Should NOT happen" << endl;
- }
- double matrixTo[3][3];
- b = KisPerspectiveMath::computeMatrixTransfoToPerspective(topLeft, topRight, bottomLeft, bottomRight, dstRect );
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- matrixTo[i][j] = b[3*i+j];
- }
- }
- delete b;
- m_topleft = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.topLeft()));
- m_topright = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.topRight()));
- m_bottomleft = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.bottomLeft()));
- m_bottomright = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.bottomRight()));
-
- paintOutline();
- m_actualyMoveWhileSelected = true;
- } else if (m_handleSelected == MIDDLEHANDLE) {
- paintOutline();
- KisPoint translate = event->pos() - m_dragEnd;
- m_dragEnd = event->pos();
- m_topleft += translate;
- m_topright += translate;
- m_bottomleft += translate;
- m_bottomright += translate;
- paintOutline();
- m_actualyMoveWhileSelected = true;
- }
- }
- };
-}
-
-void KisToolPerspectiveTransform::buttonRelease(KisButtonReleaseEvent * event)
-{
- KisImageSP img = m_subject->currentImg();
-
- if (!img)
- return;
- if( event->button() == Qt::LeftButton)
- {
- switch(m_interractionMode)
- {
- case DRAWRECTINTERRACTION:
- {
- if (m_dragging && event->button() == Qt::LeftButton) {
- paintOutline();
- m_dragging = false;
- m_points.append (m_dragEnd);
- if( m_points.size() == 4)
- {
- // from the points, select which is topleft ? topright ? bottomright ? and bottomleft ?
- m_topleft = m_points[0];
- m_topright = m_points[1];
- m_bottomleft = m_points[3];
- m_bottomright = m_points[2];
- double matrix[3][3];
- double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(m_topleft, m_topright, m_bottomleft, m_bottomright, m_initialRect );
- for(int i = 0; i < 3; i++)
- {
- for(int j = 0; j < 3; j++)
- {
- kdDebug() << "sol[" << 3*i+j << "]=" << b[3*i+j] << endl;
- matrix[i][j] = b[3*i+j];
- }
- }
- m_topleft = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.topLeft()));
- m_topright = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.topRight()));
- m_bottomleft = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.bottomLeft()));
- m_bottomright = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.bottomRight()));
- m_interractionMode = EDITRECTINTERRACTION;
- paintOutline();
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- transform();
- TQApplication::restoreOverrideCursor();
- } else {
- paintOutline();
- }
- }
- }
- break;
- case EDITRECTINTERRACTION:
- {
- if(m_currentSelectedPoint )
- {
- m_currentSelectedPoint = 0;
- if(m_actualyMoveWhileSelected)
- {
- paintOutline();
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- transform();
- TQApplication::restoreOverrideCursor();
- }
- }
- if(m_handleSelected != NOHANDLE)
- {
- m_handleSelected = NOHANDLE;
- if(m_actualyMoveWhileSelected)
- {
-// paintOutline();
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- transform();
- TQApplication::restoreOverrideCursor();
- }
- }
- }
- break;
- }
- }
-}
-
-void KisToolPerspectiveTransform::paintOutline()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintOutline(gc, rc);
- }
-}
-
-void KisToolPerspectiveTransform::paintOutline(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::SolidLine);
- pen.setWidth(1);
- Q_ASSERT(controller);
-
- switch(m_interractionMode)
- {
- case DRAWRECTINTERRACTION:
- {
- kdDebug() << "DRAWRECTINTERRACTION paintOutline " << m_points.size() << endl;
- KisPoint start, end;
- TQPoint startPos;
- TQPoint endPos;
- for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
-
- if (it == m_points.begin())
- {
- start = (*it);
- } else {
- end = (*it);
-
- startPos = controller->windowToView(start.floorTQPoint());
- endPos = controller->windowToView(end.floorTQPoint());
-
- gc.drawLine(startPos, endPos);
-
- start = end;
- }
- }
- }
- break;
- case EDITRECTINTERRACTION:
- {
- TQPoint topleft = controller->windowToView(m_topleft ).roundTQPoint();
- TQPoint topright = controller->windowToView(m_topright).roundTQPoint();
- TQPoint bottomleft = controller->windowToView(m_bottomleft).roundTQPoint();
- TQPoint bottomright = controller->windowToView(m_bottomright).roundTQPoint();
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawRect(topleft.x()-4, topleft.y()-4, 8, 8);
- gc.drawLine(topleft.x(), topleft.y(), (topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2);
- gc.drawRect((topleft.x()+topright.x())/2-4, (topleft.y()+topright.y())/2-4, 8, 8);
- gc.drawLine((topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2, topright.x(), topright.y());
- gc.drawRect(topright.x()-4, topright.y()-4, 8, 8);
- gc.drawLine(topright.x(), topright.y(), (topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2);
- gc.drawRect((topright.x()+bottomright.x())/2-4, (topright.y()+bottomright.y())/2-4, 8, 8);
- gc.drawLine((topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2,bottomright.x(), bottomright.y());
- gc.drawRect(bottomright.x()-4, bottomright.y()-4, 8, 8);
- gc.drawLine(bottomright.x(), bottomright.y(), (bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2);
- gc.drawRect((bottomleft.x()+bottomright.x())/2-4, (bottomleft.y()+bottomright.y())/2-4, 8, 8);
- gc.drawLine((bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2, bottomleft.x(), bottomleft.y());
- gc.drawRect(bottomleft.x()-4, bottomleft.y()-4, 8, 8);
- gc.drawLine(bottomleft.x(), bottomleft.y(), (topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2);
- gc.drawRect((topleft.x()+bottomleft.x())/2-4, (topleft.y()+bottomleft.y())/2-4, 8, 8);
- gc.drawLine((topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2, topleft.x(), topleft.y());
- gc.drawRect((bottomleft.x()+bottomright.x()+topleft.x()+topright.x())/4-4, (bottomleft.y()+bottomright.y()+topleft.y()+topright.y())/4-4, 8, 8);
- }
- break;
- }
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolPerspectiveTransform::transform()
-{
- KisImageSP img = m_subject->currentImg();
-
- if (!img || !img->activeDevice())
- return;
-
- KisProgressDisplayInterface *progress = m_subject->progressDisplay();
-
- // This mementoes the current state of the active device.
- PerspectiveTransformCmd * transaction = new PerspectiveTransformCmd(this, img->activeDevice(), m_origDevice,
- m_topleft, m_topright, m_bottomleft, m_bottomright, m_origSelection, m_initialRect);
-
- // Copy the original state back.
- TQRect rc = m_origDevice->extent();
- rc = rc.normalize();
- img->activeDevice()->clear();
- KisPainter gc(img->activeDevice());
- gc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origDevice, rc.x(), rc.y(), rc.width(), rc.height());
- gc.end();
-
- // Also restore the original selection.
- if(m_origSelection)
- {
- TQRect rc = m_origSelection->selectedRect();
- rc = rc.normalize();
- img->activeDevice()->selection()->clear();
- KisPainter sgc(img->activeDevice()->selection().data());
- sgc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origSelection.data(), rc.x(), rc.y(), rc.width(), rc.height());
- sgc.end();
- }
- else
- if(img->activeDevice()->hasSelection())
- img->activeDevice()->selection()->clear();
-
- // Perform the transform. Since we copied the original state back, this doesn't degrade
- // after many tweaks. Since we started the transaction before the copy back, the memento
- // has the previous state.
- KisPerspectiveTransformWorker t(img->activeDevice(),m_topleft, m_topright, m_bottomleft, m_bottomright, progress);
- t.run();
-
- // If canceled, go back to the memento
- if(t.isCanceled())
- {
- transaction->unexecute();
- delete transaction;
- return;
- }
-
- img->activeDevice()->setDirty(rc); // XXX: This is not enough - should union with new extent
-
- // Else add the command -- this will have the memento from the previous state,
- // and the transformed state from the original device we cached in our activated()
- // method.
- if (transaction) {
- if (img->undo())
- img->undoAdapter()->addCommand(transaction);
- else
- delete transaction;
- }
-}
-
-void KisToolPerspectiveTransform::notifyCommandAdded( KCommand * command)
-{
- PerspectiveTransformCmd * cmd = dynamic_cast<PerspectiveTransformCmd*>(command);
- if (cmd == 0) {
- // The last added command wasn't one of ours;
- // we should reset to the new state of the canvas.
- // In effect we should treat this as if the tool has been just activated
- initHandles();
- }
-}
-
-void KisToolPerspectiveTransform::notifyCommandExecuted( KCommand * command)
-{
- Q_UNUSED(command);
- PerspectiveTransformCmd * cmd=0;
- if(m_subject->currentImg()->undoAdapter()->presentCommand())
- cmd = dynamic_cast<PerspectiveTransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
-
- if (cmd == 0) {
- // The command now on the top of the stack isn't one of ours
- // We should treat this as if the tool has been just activated
- initHandles();
- }
- else
- {
- // One of our commands is now on top
- // We should ask for tool args and orig selection
- m_origDevice = cmd->origDevice();
- cmd->transformArgs(m_topleft, m_topright, m_bottomleft, m_bottomright);
- m_origSelection = cmd->origSelection(m_initialRect);
- m_subject->canvasController() ->updateCanvas();
- }
-}
-
-void KisToolPerspectiveTransform::slotLayerActivated(KisLayerSP)
-{
- activate();
-}
-
-
-TQWidget* KisToolPerspectiveTransform::createOptionWidget(TQWidget* /*parent*/)
-{
-#if 0
- m_optWidget = new WdgToolPerspectiveTransform(parent);
- TQ_CHECK_PTR(m_optWidget);
-
- m_optWidget->cmbFilter->clear();
- m_optWidget->cmbFilter->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
-
- m_optWidget->cmbFilter->setCurrentText("Mitchell");
- connect(m_optWidget->cmbFilter, TQT_SIGNAL(activated(const KisID &)),
- this, TQT_SLOT(slotSetFilter(const KisID &)));
-
- KisID filterID = m_optWidget->cmbFilter->currentItem();
- m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
-
-/*
- connect(m_optWidget->intStartX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartX(int)));
- connect(m_optWidget->intStartY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartY(int)));
- connect(m_optWidget->intEndX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndX(int)));
- connect(m_optWidget->intEndY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndY(int)));
-*/
- m_optWidget->intStartX->hide();
- m_optWidget->intStartY->hide();
- m_optWidget->intEndX->hide();
- m_optWidget->intEndY->hide();
- m_optWidget->textLabel1->hide();
- m_optWidget->textLabel2->hide();
- m_optWidget->textLabel3->hide();
- m_optWidget->textLabel4->hide();
-#endif
- return 0;
-}
-
-TQWidget* KisToolPerspectiveTransform::optionWidget()
-{
- return 0;
-}
-
-void KisToolPerspectiveTransform::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Perspective Transform"),
- "tool_perspectivetransform",
- 0,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Perspective transform a layer or a selection"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_perspectivetransform.moc"
diff --git a/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cpp b/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cpp
new file mode 100644
index 000000000..e73f5da3c
--- /dev/null
+++ b/chalk/plugins/tools/tool_perspectivetransform/kis_tool_perspectivetransform.cpp
@@ -0,0 +1,742 @@
+/*
+ * kis_tool_transform.cpp -- part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * Based on the transform tool from :
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2005 Casper Boemann <cbr@boemann.dk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "kis_tool_perspectivetransform.h"
+
+
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqpushbutton.h>
+#include <tqobject.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqapplication.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+
+#include <kis_global.h>
+#include <kis_painter.h>
+#include <kis_canvas_controller.h>
+#include <kis_canvas_subject.h>
+#include <kis_cursor.h>
+#include <kis_image.h>
+#include <kis_undo_adapter.h>
+#include <kis_selected_transaction.h>
+#include <kis_button_press_event.h>
+#include <kis_button_release_event.h>
+#include <kis_move_event.h>
+#include <kis_selection.h>
+#include <kis_filter_strategy.h>
+#include <kis_cmb_idlist.h>
+#include <kis_id.h>
+#include <kis_tool_controller.h>
+#include <kis_perspectivetransform_worker.h>
+
+//#include "wdg_tool_transform.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+namespace {
+ class PerspectiveTransformCmd : public KisSelectedTransaction {
+ typedef KisSelectedTransaction super;
+
+ public:
+ PerspectiveTransformCmd(KisToolPerspectiveTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, KisPoint topleft, KisPoint topright, KisPoint bottomleft, KisPoint bottomright, KisSelectionSP origSel, TQRect initialRect);
+ virtual ~PerspectiveTransformCmd();
+
+ public:
+ virtual void execute();
+ virtual void unexecute();
+ void transformArgs(KisPoint &topleft, KisPoint &topright, KisPoint &bottomleft, KisPoint& bottomright) const;
+ KisSelectionSP origSelection(TQRect& initialRect) const;
+ KisPaintDeviceSP theDevice();
+ KisPaintDeviceSP origDevice();
+
+ private:
+ TQRect m_initialRect;
+ KisPoint m_topleft, m_topright, m_bottomleft, m_bottomright;
+ KisToolPerspectiveTransform *m_tool;
+ KisSelectionSP m_origSelection;
+ KisPaintDeviceSP m_device;
+ KisPaintDeviceSP m_origDevice;
+ };
+
+ PerspectiveTransformCmd::PerspectiveTransformCmd(KisToolPerspectiveTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, KisPoint topleft, KisPoint topright, KisPoint bottomleft, KisPoint bottomright, KisSelectionSP origSel, TQRect initialRect) :
+ super(i18n("Perspective Transform"), device), m_initialRect(initialRect)
+ , m_topleft(topleft), m_topright(topright), m_bottomleft(bottomleft), m_bottomright(bottomright)
+ , m_tool(tool), m_origSelection(origSel), m_device(device), m_origDevice(origDevice)
+ {
+ }
+
+ PerspectiveTransformCmd::~PerspectiveTransformCmd()
+ {
+ }
+
+ void PerspectiveTransformCmd::transformArgs(KisPoint &topleft, KisPoint &topright, KisPoint &bottomleft, KisPoint& bottomright) const
+ {
+ topleft = m_topleft;
+ topright = m_topright;
+ bottomleft = m_bottomleft;
+ bottomright = m_bottomright;
+ }
+
+ KisSelectionSP PerspectiveTransformCmd::origSelection(TQRect& initialRect) const
+ {
+ initialRect = m_initialRect;
+ return m_origSelection;
+ }
+
+ void PerspectiveTransformCmd::execute()
+ {
+ super::execute();
+ }
+
+ void PerspectiveTransformCmd::unexecute()
+ {
+ super::unexecute();
+ }
+
+ KisPaintDeviceSP PerspectiveTransformCmd::theDevice()
+ {
+ return m_device;
+ }
+
+ KisPaintDeviceSP PerspectiveTransformCmd::origDevice()
+ {
+ return m_origDevice;
+ }
+}
+
+KisToolPerspectiveTransform::KisToolPerspectiveTransform()
+ : super(i18n("Perspective Transform"))
+{
+ setName("tool_perspectivetransform");
+ setCursor(KisCursor::selectCursor());
+ m_subject = 0;
+ m_origDevice = 0;
+ m_origSelection = 0;
+ m_handleHalfSize = 8;
+ m_handleSize = 2 * m_handleHalfSize;
+ m_handleSelected = NOHANDLE;
+}
+
+KisToolPerspectiveTransform::~KisToolPerspectiveTransform()
+{
+}
+
+void KisToolPerspectiveTransform::deactivate()
+{
+ if (m_subject && m_subject->undoAdapter()) m_subject->undoAdapter()->removeCommandHistoryListener( this );
+
+ KisImageSP img = m_subject->currentImg();
+ if (!img) return;
+
+ paintOutline();
+
+ disconnect(m_subject->currentImg().data(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
+}
+
+void KisToolPerspectiveTransform::activate()
+{
+ super::activate();
+ m_currentSelectedPoint = 0;
+ if(m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice())
+ {
+ //connect(m_subject, commandExecuted(KCommand *c), this, notifyCommandAdded( KCommand * c));
+ m_subject->undoAdapter()->setCommandHistoryListener( this );
+
+// KisToolControllerInterface *controller = m_subject->toolController();
+// if (controller)
+// controller->setCurrentTool(this);
+
+ PerspectiveTransformCmd * cmd=0;
+
+ if(m_subject->currentImg()->undoAdapter()->presentCommand())
+ cmd = dynamic_cast<PerspectiveTransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
+
+ // One of our commands is on top
+ if(cmd &&cmd->theDevice() == m_subject->currentImg()->activeDevice())
+ {
+ m_interractionMode = EDITRECTINTERRACTION;
+ // and it even has the same device
+ // We should ask for tool args and orig selection
+ m_origDevice = cmd->origDevice();
+ cmd->transformArgs(m_topleft, m_topright, m_bottomleft, m_bottomright);
+ m_origSelection = cmd->origSelection(m_initialRect);
+ paintOutline();
+ }
+ else
+ {
+ m_interractionMode = DRAWRECTINTERRACTION;
+ m_points.clear();
+ initHandles();
+ }
+ }
+ connect(m_subject->currentImg(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
+}
+
+void KisToolPerspectiveTransform::initHandles()
+{
+// TQ_INT32 x,y,w,h;
+ KisImageSP img = m_subject->currentImg();
+
+ KisPaintDeviceSP dev = img->activeDevice();
+ if (!dev ) return;
+
+ // Create a lazy copy of the current state
+ m_origDevice = new KisPaintDevice(*dev.data());
+ Q_ASSERT(m_origDevice);
+
+ if(dev->hasSelection())
+ {
+ KisSelectionSP sel = dev->selection();
+ m_origSelection = new KisSelection(*sel.data());
+ m_initialRect = sel->selectedExactRect();
+ }
+ else {
+ m_initialRect = dev->exactBounds();
+ }
+ m_topleft = KisPoint(m_initialRect.topLeft());
+ m_topright = KisPoint(m_initialRect.topRight());
+ m_bottomleft = KisPoint(m_initialRect.bottomLeft());
+ m_bottomright = KisPoint(m_initialRect.bottomRight());
+
+ m_subject->canvasController() ->updateCanvas();
+}
+
+void KisToolPerspectiveTransform::paint(KisCanvasPainter& gc)
+{
+ paintOutline(gc, TQRect());
+}
+
+void KisToolPerspectiveTransform::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ paintOutline(gc, rc);
+}
+
+bool KisToolPerspectiveTransform::mouseNear(const TQPoint& mousep, const TQPoint point)
+{
+ return (TQRect( (point.x() - m_handleHalfSize), (point.y() - m_handleHalfSize), m_handleSize, m_handleSize).contains(mousep) );
+}
+
+void KisToolPerspectiveTransform::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_subject) {
+ switch(m_interractionMode)
+ {
+ case DRAWRECTINTERRACTION:
+ {
+ if (m_points.isEmpty())
+ {
+ m_dragging = false;
+ m_dragStart = event->pos();
+ m_dragEnd = event->pos();
+ m_points.append(m_dragStart);
+ paintOutline();
+ } else {
+ m_dragging = true;
+ m_dragStart = m_dragEnd;
+ m_dragEnd = event->pos();
+ paintOutline();
+ }
+ }
+ case EDITRECTINTERRACTION:
+ {
+ KisImageSP img = m_subject->currentImg();
+
+ if (img && img->activeDevice() && event->button() == Qt::LeftButton) {
+ m_actualyMoveWhileSelected = false;
+ m_dragEnd = event->pos();
+ KisCanvasController *controller = m_subject->canvasController();
+ TQPoint mousep = controller->windowToView( event->pos().roundTQPoint() );
+ if( mouseNear( mousep, controller->windowToView(m_topleft.roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS TOPLEFT HANDLE " << endl;
+ m_currentSelectedPoint = &m_topleft;
+ }
+ else if( mouseNear( mousep, controller->windowToView(m_topright.roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS TOPRIGHT HANDLE " << endl;
+ m_currentSelectedPoint = &m_topright;
+ }
+ else if( mouseNear( mousep, controller->windowToView(m_bottomleft.roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS BOTTOMLEFT HANDLE " << endl;
+ m_currentSelectedPoint = &m_bottomleft;
+ }
+ else if( mouseNear( mousep, controller->windowToView(m_bottomright.roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS BOTTOMRIGHT HANDLE " << endl;
+ m_currentSelectedPoint = &m_bottomright;
+ } else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_topright)*0.5).roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS TOP HANDLE " << endl;
+ m_handleSelected = TOPHANDLE;
+ }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_bottomleft)*0.5).roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS LEFT HANDLE " << endl;
+ m_handleSelected = LEFTHANDLE;
+ }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_bottomleft+m_bottomright)*0.5).roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS BOTTOM HANDLE " << endl;
+ m_handleSelected = BOTTOMHANDLE;
+ }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_bottomright+m_topright)*0.5).roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS RIGHT HANDLE " << endl;
+ m_handleSelected = RIGHTHANDLE;
+ }else if( mouseNear( mousep, controller->windowToView(KisPoint((m_topleft+m_bottomleft + m_bottomright+m_topright)*0.25).roundTQPoint() ) ) )
+ {
+ kdDebug() << " PRESS MIDDLE HANDLE " << endl;
+ m_handleSelected = MIDDLEHANDLE;
+ }
+ }
+ }
+ }
+ }
+}
+
+void KisToolPerspectiveTransform::move(KisMoveEvent *event)
+{
+ switch(m_interractionMode)
+ {
+ case DRAWRECTINTERRACTION:
+ {
+ if (m_dragging) {
+ // erase old lines on canvas
+ paintOutline();
+ // get current mouse position
+ m_dragEnd = event->pos();
+ // draw new lines on canvas
+ paintOutline();
+ }
+ }
+
+ case EDITRECTINTERRACTION:
+ {
+ if(m_currentSelectedPoint)
+ {
+ paintOutline();
+ KisPoint translate = event->pos() - m_dragEnd;
+ m_dragEnd = event->pos();
+ *m_currentSelectedPoint += translate;;
+ paintOutline();
+ m_actualyMoveWhileSelected = true;
+ }
+ else if(m_handleSelected == TOPHANDLE || m_handleSelected == LEFTHANDLE || m_handleSelected == BOTTOMHANDLE || m_handleSelected == RIGHTHANDLE)
+ {
+ paintOutline();
+
+ KisPoint translate = event->pos() - m_dragEnd;
+ m_dragEnd = event->pos();
+
+ double matrixFrom[3][3];
+ double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(m_topleft, m_topright, m_bottomleft, m_bottomright, m_initialRect);
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ matrixFrom[i][j] = b[3*i+j];
+ }
+ }
+ delete b;
+
+ KisPoint topLeft = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.topLeft()) );
+ KisPoint topRight = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.topRight()) );
+ KisPoint bottomLeft = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.bottomLeft()) );
+ KisPoint bottomRight = KisPerspectiveMath::matProd(matrixFrom, KisPoint(m_initialRect.bottomRight()) );
+ TQRect dstRect = m_initialRect;
+ switch(m_handleSelected)
+ {
+ case TOPHANDLE:
+ dstRect.setTop( static_cast<int>( dstRect.top() + translate.y() ) ) ;
+ break;
+ case LEFTHANDLE:
+ dstRect.setLeft( static_cast<int>( dstRect.left() + translate.x() ) );
+ break;
+ case BOTTOMHANDLE:
+ dstRect.setBottom( static_cast<int>( dstRect.bottom() + translate.y() ) );
+ break;
+ case RIGHTHANDLE:
+ dstRect.setRight( static_cast<int>( dstRect.right() + translate.x() ) );
+ break;
+ case MIDDLEHANDLE:
+ case NOHANDLE:
+ kdDebug() << "Should NOT happen" << endl;
+ }
+ double matrixTo[3][3];
+ b = KisPerspectiveMath::computeMatrixTransfoToPerspective(topLeft, topRight, bottomLeft, bottomRight, dstRect );
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ matrixTo[i][j] = b[3*i+j];
+ }
+ }
+ delete b;
+ m_topleft = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.topLeft()));
+ m_topright = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.topRight()));
+ m_bottomleft = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.bottomLeft()));
+ m_bottomright = KisPerspectiveMath::matProd(matrixTo, KisPoint(m_initialRect.bottomRight()));
+
+ paintOutline();
+ m_actualyMoveWhileSelected = true;
+ } else if (m_handleSelected == MIDDLEHANDLE) {
+ paintOutline();
+ KisPoint translate = event->pos() - m_dragEnd;
+ m_dragEnd = event->pos();
+ m_topleft += translate;
+ m_topright += translate;
+ m_bottomleft += translate;
+ m_bottomright += translate;
+ paintOutline();
+ m_actualyMoveWhileSelected = true;
+ }
+ }
+ };
+}
+
+void KisToolPerspectiveTransform::buttonRelease(KisButtonReleaseEvent * event)
+{
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img)
+ return;
+ if( event->button() == Qt::LeftButton)
+ {
+ switch(m_interractionMode)
+ {
+ case DRAWRECTINTERRACTION:
+ {
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ paintOutline();
+ m_dragging = false;
+ m_points.append (m_dragEnd);
+ if( m_points.size() == 4)
+ {
+ // from the points, select which is topleft ? topright ? bottomright ? and bottomleft ?
+ m_topleft = m_points[0];
+ m_topright = m_points[1];
+ m_bottomleft = m_points[3];
+ m_bottomright = m_points[2];
+ double matrix[3][3];
+ double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(m_topleft, m_topright, m_bottomleft, m_bottomright, m_initialRect );
+ for(int i = 0; i < 3; i++)
+ {
+ for(int j = 0; j < 3; j++)
+ {
+ kdDebug() << "sol[" << 3*i+j << "]=" << b[3*i+j] << endl;
+ matrix[i][j] = b[3*i+j];
+ }
+ }
+ m_topleft = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.topLeft()));
+ m_topright = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.topRight()));
+ m_bottomleft = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.bottomLeft()));
+ m_bottomright = KisPerspectiveMath::matProd(matrix, KisPoint(m_initialRect.bottomRight()));
+ m_interractionMode = EDITRECTINTERRACTION;
+ paintOutline();
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ transform();
+ TQApplication::restoreOverrideCursor();
+ } else {
+ paintOutline();
+ }
+ }
+ }
+ break;
+ case EDITRECTINTERRACTION:
+ {
+ if(m_currentSelectedPoint )
+ {
+ m_currentSelectedPoint = 0;
+ if(m_actualyMoveWhileSelected)
+ {
+ paintOutline();
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ transform();
+ TQApplication::restoreOverrideCursor();
+ }
+ }
+ if(m_handleSelected != NOHANDLE)
+ {
+ m_handleSelected = NOHANDLE;
+ if(m_actualyMoveWhileSelected)
+ {
+// paintOutline();
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ transform();
+ TQApplication::restoreOverrideCursor();
+ }
+ }
+ }
+ break;
+ }
+ }
+}
+
+void KisToolPerspectiveTransform::paintOutline()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintOutline(gc, rc);
+ }
+}
+
+void KisToolPerspectiveTransform::paintOutline(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::SolidLine);
+ pen.setWidth(1);
+ Q_ASSERT(controller);
+
+ switch(m_interractionMode)
+ {
+ case DRAWRECTINTERRACTION:
+ {
+ kdDebug() << "DRAWRECTINTERRACTION paintOutline " << m_points.size() << endl;
+ KisPoint start, end;
+ TQPoint startPos;
+ TQPoint endPos;
+ for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
+
+ if (it == m_points.begin())
+ {
+ start = (*it);
+ } else {
+ end = (*it);
+
+ startPos = controller->windowToView(start.floorTQPoint());
+ endPos = controller->windowToView(end.floorTQPoint());
+
+ gc.drawLine(startPos, endPos);
+
+ start = end;
+ }
+ }
+ }
+ break;
+ case EDITRECTINTERRACTION:
+ {
+ TQPoint topleft = controller->windowToView(m_topleft ).roundTQPoint();
+ TQPoint topright = controller->windowToView(m_topright).roundTQPoint();
+ TQPoint bottomleft = controller->windowToView(m_bottomleft).roundTQPoint();
+ TQPoint bottomright = controller->windowToView(m_bottomright).roundTQPoint();
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawRect(topleft.x()-4, topleft.y()-4, 8, 8);
+ gc.drawLine(topleft.x(), topleft.y(), (topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2);
+ gc.drawRect((topleft.x()+topright.x())/2-4, (topleft.y()+topright.y())/2-4, 8, 8);
+ gc.drawLine((topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2, topright.x(), topright.y());
+ gc.drawRect(topright.x()-4, topright.y()-4, 8, 8);
+ gc.drawLine(topright.x(), topright.y(), (topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2);
+ gc.drawRect((topright.x()+bottomright.x())/2-4, (topright.y()+bottomright.y())/2-4, 8, 8);
+ gc.drawLine((topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2,bottomright.x(), bottomright.y());
+ gc.drawRect(bottomright.x()-4, bottomright.y()-4, 8, 8);
+ gc.drawLine(bottomright.x(), bottomright.y(), (bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2);
+ gc.drawRect((bottomleft.x()+bottomright.x())/2-4, (bottomleft.y()+bottomright.y())/2-4, 8, 8);
+ gc.drawLine((bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2, bottomleft.x(), bottomleft.y());
+ gc.drawRect(bottomleft.x()-4, bottomleft.y()-4, 8, 8);
+ gc.drawLine(bottomleft.x(), bottomleft.y(), (topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2);
+ gc.drawRect((topleft.x()+bottomleft.x())/2-4, (topleft.y()+bottomleft.y())/2-4, 8, 8);
+ gc.drawLine((topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2, topleft.x(), topleft.y());
+ gc.drawRect((bottomleft.x()+bottomright.x()+topleft.x()+topright.x())/4-4, (bottomleft.y()+bottomright.y()+topleft.y()+topright.y())/4-4, 8, 8);
+ }
+ break;
+ }
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolPerspectiveTransform::transform()
+{
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img || !img->activeDevice())
+ return;
+
+ KisProgressDisplayInterface *progress = m_subject->progressDisplay();
+
+ // This mementoes the current state of the active device.
+ PerspectiveTransformCmd * transaction = new PerspectiveTransformCmd(this, img->activeDevice(), m_origDevice,
+ m_topleft, m_topright, m_bottomleft, m_bottomright, m_origSelection, m_initialRect);
+
+ // Copy the original state back.
+ TQRect rc = m_origDevice->extent();
+ rc = rc.normalize();
+ img->activeDevice()->clear();
+ KisPainter gc(img->activeDevice());
+ gc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origDevice, rc.x(), rc.y(), rc.width(), rc.height());
+ gc.end();
+
+ // Also restore the original selection.
+ if(m_origSelection)
+ {
+ TQRect rc = m_origSelection->selectedRect();
+ rc = rc.normalize();
+ img->activeDevice()->selection()->clear();
+ KisPainter sgc(img->activeDevice()->selection().data());
+ sgc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origSelection.data(), rc.x(), rc.y(), rc.width(), rc.height());
+ sgc.end();
+ }
+ else
+ if(img->activeDevice()->hasSelection())
+ img->activeDevice()->selection()->clear();
+
+ // Perform the transform. Since we copied the original state back, this doesn't degrade
+ // after many tweaks. Since we started the transaction before the copy back, the memento
+ // has the previous state.
+ KisPerspectiveTransformWorker t(img->activeDevice(),m_topleft, m_topright, m_bottomleft, m_bottomright, progress);
+ t.run();
+
+ // If canceled, go back to the memento
+ if(t.isCanceled())
+ {
+ transaction->unexecute();
+ delete transaction;
+ return;
+ }
+
+ img->activeDevice()->setDirty(rc); // XXX: This is not enough - should union with new extent
+
+ // Else add the command -- this will have the memento from the previous state,
+ // and the transformed state from the original device we cached in our activated()
+ // method.
+ if (transaction) {
+ if (img->undo())
+ img->undoAdapter()->addCommand(transaction);
+ else
+ delete transaction;
+ }
+}
+
+void KisToolPerspectiveTransform::notifyCommandAdded( KCommand * command)
+{
+ PerspectiveTransformCmd * cmd = dynamic_cast<PerspectiveTransformCmd*>(command);
+ if (cmd == 0) {
+ // The last added command wasn't one of ours;
+ // we should reset to the new state of the canvas.
+ // In effect we should treat this as if the tool has been just activated
+ initHandles();
+ }
+}
+
+void KisToolPerspectiveTransform::notifyCommandExecuted( KCommand * command)
+{
+ Q_UNUSED(command);
+ PerspectiveTransformCmd * cmd=0;
+ if(m_subject->currentImg()->undoAdapter()->presentCommand())
+ cmd = dynamic_cast<PerspectiveTransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
+
+ if (cmd == 0) {
+ // The command now on the top of the stack isn't one of ours
+ // We should treat this as if the tool has been just activated
+ initHandles();
+ }
+ else
+ {
+ // One of our commands is now on top
+ // We should ask for tool args and orig selection
+ m_origDevice = cmd->origDevice();
+ cmd->transformArgs(m_topleft, m_topright, m_bottomleft, m_bottomright);
+ m_origSelection = cmd->origSelection(m_initialRect);
+ m_subject->canvasController() ->updateCanvas();
+ }
+}
+
+void KisToolPerspectiveTransform::slotLayerActivated(KisLayerSP)
+{
+ activate();
+}
+
+
+TQWidget* KisToolPerspectiveTransform::createOptionWidget(TQWidget* /*parent*/)
+{
+#if 0
+ m_optWidget = new WdgToolPerspectiveTransform(parent);
+ TQ_CHECK_PTR(m_optWidget);
+
+ m_optWidget->cmbFilter->clear();
+ m_optWidget->cmbFilter->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
+
+ m_optWidget->cmbFilter->setCurrentText("Mitchell");
+ connect(m_optWidget->cmbFilter, TQT_SIGNAL(activated(const KisID &)),
+ this, TQT_SLOT(slotSetFilter(const KisID &)));
+
+ KisID filterID = m_optWidget->cmbFilter->currentItem();
+ m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
+
+/*
+ connect(m_optWidget->intStartX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartX(int)));
+ connect(m_optWidget->intStartY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartY(int)));
+ connect(m_optWidget->intEndX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndX(int)));
+ connect(m_optWidget->intEndY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndY(int)));
+*/
+ m_optWidget->intStartX->hide();
+ m_optWidget->intStartY->hide();
+ m_optWidget->intEndX->hide();
+ m_optWidget->intEndY->hide();
+ m_optWidget->textLabel1->hide();
+ m_optWidget->textLabel2->hide();
+ m_optWidget->textLabel3->hide();
+ m_optWidget->textLabel4->hide();
+#endif
+ return 0;
+}
+
+TQWidget* KisToolPerspectiveTransform::optionWidget()
+{
+ return 0;
+}
+
+void KisToolPerspectiveTransform::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Perspective Transform"),
+ "tool_perspectivetransform",
+ 0,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Perspective transform a layer or a selection"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_perspectivetransform.moc"
diff --git a/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cc b/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cc
deleted file mode 100644
index 0c4023cce..000000000
--- a/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * tool_perspectivetransform.cc -- Part of Chalk
- *
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_perspectivetransform.h"
-#include "kis_tool_perspectivetransform.h"
-
-
-typedef KGenericFactory<ToolPerspectiveTransform> ToolPerspectiveTransformFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolperspectivetransform, ToolPerspectiveTransformFactory( "chalk" ) )
-
-
-ToolPerspectiveTransform::ToolPerspectiveTransform(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolPerspectiveTransformFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- kdDebug() << " add perspective transform tool to the registry" << endl;
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- r->add(new KisToolPerspectiveTransformFactory());
- }
-
-}
-
-ToolPerspectiveTransform::~ToolPerspectiveTransform()
-{
-}
-
-#include "tool_perspectivetransform.moc"
diff --git a/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cpp b/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cpp
new file mode 100644
index 000000000..73705264b
--- /dev/null
+++ b/chalk/plugins/tools/tool_perspectivetransform/tool_perspectivetransform.cpp
@@ -0,0 +1,63 @@
+/*
+ * tool_perspectivetransform.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_perspectivetransform.h"
+#include "kis_tool_perspectivetransform.h"
+
+
+typedef KGenericFactory<ToolPerspectiveTransform> ToolPerspectiveTransformFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolperspectivetransform, ToolPerspectiveTransformFactory( "chalk" ) )
+
+
+ToolPerspectiveTransform::ToolPerspectiveTransform(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolPerspectiveTransformFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ kdDebug() << " add perspective transform tool to the registry" << endl;
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ r->add(new KisToolPerspectiveTransformFactory());
+ }
+
+}
+
+ToolPerspectiveTransform::~ToolPerspectiveTransform()
+{
+}
+
+#include "tool_perspectivetransform.moc"
diff --git a/chalk/plugins/tools/tool_polygon/Makefile.am b/chalk/plugins/tools/tool_polygon/Makefile.am
index 555f59a0e..4ad417da0 100644
--- a/chalk/plugins/tools/tool_polygon/Makefile.am
+++ b/chalk/plugins/tools/tool_polygon/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolpolygon_la_SOURCES = \
- tool_polygon.cc \
- kis_tool_polygon.cc
+ tool_polygon.cpp \
+ kis_tool_polygon.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolpolygon.la
diff --git a/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cc b/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cc
deleted file mode 100644
index a7371e49f..000000000
--- a/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cc
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * kis_tool_polygon.cc -- part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <tqpainter.h>
-#include <tqspinbox.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_doc.h"
-#include "kis_view.h"
-#include "kis_painter.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-
-#include "kis_tool_polygon.h"
-
-KisToolPolygon::KisToolPolygon()
- : super(i18n ("Polygon")),
- m_dragging (false),
- m_currentImage (0)
-{
- setName("tool_polygon");
- setCursor(KisCursor::load("tool_polygon_cursor.png", 6, 6));
-}
-
-KisToolPolygon::~KisToolPolygon()
-{
-}
-
-void KisToolPolygon::update (KisCanvasSubject *subject)
-{
- super::update (subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg ();
-}
-
-void KisToolPolygon::buttonPress(KisButtonPressEvent *event)
-{
- if (m_currentImage) {
- if (event->button() == Qt::LeftButton && event->state() != ShiftButton) {
-
- m_dragging = true;
-
- if (m_points.isEmpty())
- {
- m_dragStart = event->pos();
- m_dragEnd = event->pos();
- m_points.append(m_dragStart);
- } else {
- m_dragStart = m_dragEnd;
- m_dragEnd = event->pos();
- draw();
- }
- } else if (event->button() == Qt::LeftButton && event->state() == ShiftButton) {
- finish();
- }
- }
-}
-
-void KisToolPolygon::finish()
-{
- // erase old lines on canvas
- draw();
- m_dragging = false;
-
- KisPaintDeviceSP device = m_currentImage->activeDevice ();
- if (!device) return;
-
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (i18n ("Polygon"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBackgroundColor(m_subject->bgColor());
- painter.setFillStyle(fillStyle());
- painter.setBrush(m_subject->currentBrush());
- painter.setPattern(m_subject->currentPattern());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op); // Painter takes ownership
-
- painter.paintPolygon(m_points);
-
- m_points.clear();
-
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
-}
-
-void KisToolPolygon::doubleClick( KisDoubleClickEvent * )
-{
- finish();
-}
-
-void KisToolPolygon::move(KisMoveEvent *event)
-{
- if (m_dragging) {
- // erase old lines on canvas
- draw();
- // get current mouse position
- m_dragEnd = event->pos();
- // draw new lines on canvas
- draw();
- }
-}
-
-void KisToolPolygon::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- if (m_dragging && event->button() == Qt::LeftButton) {
- m_dragging = false;
- m_points.append (m_dragEnd);
- }
-
- if (m_dragging && event->button() == Qt::RightButton) {
-
- }
-}
-
-void KisToolPolygon::paint(KisCanvasPainter& gc)
-{
- draw(gc);
-}
-
-void KisToolPolygon::paint(KisCanvasPainter& gc, const TQRect&)
-{
- draw(gc);
-}
-
-void KisToolPolygon::draw()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
-
- draw(gc);
- }
-}
-
-void KisToolPolygon::draw(KisCanvasPainter& gc)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- TQPen pen(TQt::white, 0, TQt::SolidLine);
-
- gc.setPen(pen);
- gc.setRasterOp(TQt::XorROP);
-
- KisCanvasController *controller = m_subject->canvasController();
- KisPoint start, end;
- TQPoint startPos;
- TQPoint endPos;
-
- if (m_dragging) {
- startPos = controller->windowToView(m_dragStart.floorTQPoint());
- endPos = controller->windowToView(m_dragEnd.floorTQPoint());
- gc.drawLine(startPos, endPos);
- } else {
- for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
-
- if (it == m_points.begin())
- {
- start = (*it);
- } else {
- end = (*it);
-
- startPos = controller->windowToView(start.floorTQPoint());
- endPos = controller->windowToView(end.floorTQPoint());
-
- gc.drawLine(startPos, endPos);
-
- start = end;
- }
- }
- }
-}
-
-
-
-void KisToolPolygon::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Polygon"),
- "tool_polygon",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Draw a polygon. Shift-mouseclick ends the polygon."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-void KisToolPolygon::keyPress(TQKeyEvent *e)
-{
- if (e->key()==TQt::Key_Escape) {
- // erase old lines on canvas
- draw();
- m_dragging = false;
- m_points.clear();
- }
-}
-
-
-#include "kis_tool_polygon.moc"
diff --git a/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cpp b/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cpp
new file mode 100644
index 000000000..601fc6907
--- /dev/null
+++ b/chalk/plugins/tools/tool_polygon/kis_tool_polygon.cpp
@@ -0,0 +1,252 @@
+/*
+ * kis_tool_polygon.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <tqpainter.h>
+#include <tqspinbox.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_doc.h"
+#include "kis_view.h"
+#include "kis_painter.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+
+#include "kis_tool_polygon.h"
+
+KisToolPolygon::KisToolPolygon()
+ : super(i18n ("Polygon")),
+ m_dragging (false),
+ m_currentImage (0)
+{
+ setName("tool_polygon");
+ setCursor(KisCursor::load("tool_polygon_cursor.png", 6, 6));
+}
+
+KisToolPolygon::~KisToolPolygon()
+{
+}
+
+void KisToolPolygon::update (KisCanvasSubject *subject)
+{
+ super::update (subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg ();
+}
+
+void KisToolPolygon::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_currentImage) {
+ if (event->button() == Qt::LeftButton && event->state() != ShiftButton) {
+
+ m_dragging = true;
+
+ if (m_points.isEmpty())
+ {
+ m_dragStart = event->pos();
+ m_dragEnd = event->pos();
+ m_points.append(m_dragStart);
+ } else {
+ m_dragStart = m_dragEnd;
+ m_dragEnd = event->pos();
+ draw();
+ }
+ } else if (event->button() == Qt::LeftButton && event->state() == ShiftButton) {
+ finish();
+ }
+ }
+}
+
+void KisToolPolygon::finish()
+{
+ // erase old lines on canvas
+ draw();
+ m_dragging = false;
+
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();
+ if (!device) return;
+
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (i18n ("Polygon"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBackgroundColor(m_subject->bgColor());
+ painter.setFillStyle(fillStyle());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setPattern(m_subject->currentPattern());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op); // Painter takes ownership
+
+ painter.paintPolygon(m_points);
+
+ m_points.clear();
+
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+}
+
+void KisToolPolygon::doubleClick( KisDoubleClickEvent * )
+{
+ finish();
+}
+
+void KisToolPolygon::move(KisMoveEvent *event)
+{
+ if (m_dragging) {
+ // erase old lines on canvas
+ draw();
+ // get current mouse position
+ m_dragEnd = event->pos();
+ // draw new lines on canvas
+ draw();
+ }
+}
+
+void KisToolPolygon::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ m_dragging = false;
+ m_points.append (m_dragEnd);
+ }
+
+ if (m_dragging && event->button() == Qt::RightButton) {
+
+ }
+}
+
+void KisToolPolygon::paint(KisCanvasPainter& gc)
+{
+ draw(gc);
+}
+
+void KisToolPolygon::paint(KisCanvasPainter& gc, const TQRect&)
+{
+ draw(gc);
+}
+
+void KisToolPolygon::draw()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+
+ draw(gc);
+ }
+}
+
+void KisToolPolygon::draw(KisCanvasPainter& gc)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ TQPen pen(TQt::white, 0, TQt::SolidLine);
+
+ gc.setPen(pen);
+ gc.setRasterOp(TQt::XorROP);
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisPoint start, end;
+ TQPoint startPos;
+ TQPoint endPos;
+
+ if (m_dragging) {
+ startPos = controller->windowToView(m_dragStart.floorTQPoint());
+ endPos = controller->windowToView(m_dragEnd.floorTQPoint());
+ gc.drawLine(startPos, endPos);
+ } else {
+ for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
+
+ if (it == m_points.begin())
+ {
+ start = (*it);
+ } else {
+ end = (*it);
+
+ startPos = controller->windowToView(start.floorTQPoint());
+ endPos = controller->windowToView(end.floorTQPoint());
+
+ gc.drawLine(startPos, endPos);
+
+ start = end;
+ }
+ }
+ }
+}
+
+
+
+void KisToolPolygon::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Polygon"),
+ "tool_polygon",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Draw a polygon. Shift-mouseclick ends the polygon."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+void KisToolPolygon::keyPress(TQKeyEvent *e)
+{
+ if (e->key()==TQt::Key_Escape) {
+ // erase old lines on canvas
+ draw();
+ m_dragging = false;
+ m_points.clear();
+ }
+}
+
+
+#include "kis_tool_polygon.moc"
diff --git a/chalk/plugins/tools/tool_polygon/tool_polygon.cc b/chalk/plugins/tools/tool_polygon/tool_polygon.cc
deleted file mode 100644
index 626a773d3..000000000
--- a/chalk/plugins/tools/tool_polygon/tool_polygon.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * tool_polygon.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-#include "tool_polygon.h"
-#include "tool_polygon.moc"
-#include "kis_tool_polygon.h"
-
-
-typedef KGenericFactory<ToolPolygon> ToolPolygonFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolpolygon, ToolPolygonFactory( "chalk" ) )
-
-
-ToolPolygon::ToolPolygon(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolPolygonFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
- r->add(new KisToolPolygonFactory());
- }
-
-}
-
-ToolPolygon::~ToolPolygon()
-{
-}
-
-//#include "tool_polygon.moc"
diff --git a/chalk/plugins/tools/tool_polygon/tool_polygon.cpp b/chalk/plugins/tools/tool_polygon/tool_polygon.cpp
new file mode 100644
index 000000000..f903551fb
--- /dev/null
+++ b/chalk/plugins/tools/tool_polygon/tool_polygon.cpp
@@ -0,0 +1,62 @@
+/*
+ * tool_polygon.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+#include "tool_polygon.h"
+#include "tool_polygon.moc"
+#include "kis_tool_polygon.h"
+
+
+typedef KGenericFactory<ToolPolygon> ToolPolygonFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolpolygon, ToolPolygonFactory( "chalk" ) )
+
+
+ToolPolygon::ToolPolygon(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolPolygonFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
+ r->add(new KisToolPolygonFactory());
+ }
+
+}
+
+ToolPolygon::~ToolPolygon()
+{
+}
+
+//#include "tool_polygon.moc"
diff --git a/chalk/plugins/tools/tool_polyline/Makefile.am b/chalk/plugins/tools/tool_polyline/Makefile.am
index 1812b13bc..87fa1ce27 100644
--- a/chalk/plugins/tools/tool_polyline/Makefile.am
+++ b/chalk/plugins/tools/tool_polyline/Makefile.am
@@ -10,8 +10,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalktoolpolyline_la_SOURCES = \
- tool_polyline.cc \
- kis_tool_polyline.cc
+ tool_polyline.cpp \
+ kis_tool_polyline.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolpolyline.la
diff --git a/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cc b/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cc
deleted file mode 100644
index c99513f47..000000000
--- a/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cc
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * kis_tool_polyline.cc -- part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <tqpainter.h>
-#include <tqspinbox.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_doc.h"
-#include "kis_view.h"
-#include "kis_painter.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-
-#include "kis_tool_polyline.h"
-
-KisToolPolyline::KisToolPolyline()
- : super(i18n ("Polyline")),
- m_dragging (false),
- m_currentImage (0)
-{
- setName("tool_polyline");
- setCursor(KisCursor::load("tool_polyline_cursor.png", 6, 6));
-}
-
-KisToolPolyline::~KisToolPolyline()
-{
-}
-
-void KisToolPolyline::update (KisCanvasSubject *subject)
-{
- super::update (subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg ();
-}
-
-void KisToolPolyline::buttonPress(KisButtonPressEvent *event)
-{
- if (m_currentImage) {
- if (event->button() == Qt::LeftButton && event->state() != TQt::ShiftButton ) {
-
- m_dragging = true;
-
- if (m_points.isEmpty())
- {
- m_dragStart = event->pos();
- m_dragEnd = event->pos();
- m_points.append(m_dragStart);
- } else {
- m_dragStart = m_dragEnd;
- m_dragEnd = event->pos();
- draw();
- }
- } else if (event->button() == Qt::LeftButton && event->state() == TQt::ShiftButton ) {
- finish();
- }
- }
-}
-
-void KisToolPolyline::deactivate()
-{
- draw();
- m_points.clear();
- m_dragging = false;
-}
-
-void KisToolPolyline::finish()
-{
- // erase old lines on canvas
- draw();
- m_dragging = false;
-
- KisPaintDeviceSP device = m_currentImage->activeDevice ();
- if (!device) return;
-
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (i18n ("Polyline"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBrush(m_subject->currentBrush());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op); // Painter takes ownership
-
- KisPoint start,end;
- KisPointVector::iterator it;
- for( it = m_points.begin(); it != m_points.end(); ++it )
- {
- if( it == m_points.begin() )
- {
- start = (*it);
- } else {
- end = (*it);
- painter.paintLine(start, PRESSURE_DEFAULT, 0, 0, end, PRESSURE_DEFAULT, 0, 0);
- start = end;
- }
- }
- m_points.clear();
-
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
-
-}
-void KisToolPolyline::move(KisMoveEvent *event)
-{
- if (m_dragging) {
- // erase old lines on canvas
- draw();
- // get current mouse position
- m_dragEnd = event->pos();
- // draw new lines on canvas
- draw();
- }
-}
-
-void KisToolPolyline::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- if (m_dragging && event->button() == Qt::LeftButton) {
- m_dragging = false;
- m_points.append (m_dragEnd);
- }
-
- if (m_dragging && event->button() == Qt::RightButton) {
-
- }
-}
-
-
-void KisToolPolyline::doubleClick(KisDoubleClickEvent *)
-{
- finish();
-}
-
-
-void KisToolPolyline::paint(KisCanvasPainter& gc)
-{
- draw(gc);
-}
-
-void KisToolPolyline::paint(KisCanvasPainter& gc, const TQRect&)
-{
- draw(gc);
-}
-
-void KisToolPolyline::draw()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
-
- draw(gc);
- }
-}
-
-void KisToolPolyline::draw(KisCanvasPainter& gc)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- TQPen pen(TQt::white, 0, TQt::SolidLine);
-
- gc.setPen(pen);
- gc.setRasterOp(TQt::XorROP);
-
- KisCanvasController *controller = m_subject->canvasController();
- KisPoint start, end;
- TQPoint startPos;
- TQPoint endPos;
-
- if (m_dragging) {
- startPos = controller->windowToView(m_dragStart.floorTQPoint());
- endPos = controller->windowToView(m_dragEnd.floorTQPoint());
- gc.drawLine(startPos, endPos);
- } else {
- for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
-
- if (it == m_points.begin())
- {
- start = (*it);
- } else {
- end = (*it);
-
- startPos = controller->windowToView(start.floorTQPoint());
- endPos = controller->windowToView(end.floorTQPoint());
-
- gc.drawLine(startPos, endPos);
-
- start = end;
- }
- }
- }
-}
-
-void KisToolPolyline::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Polyline"),
- "polyline",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Draw a polyline. Shift-mouseclick ends the polyline."));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-TQString KisToolPolyline::quickHelp() const
-{
- return i18n("Press shift-mouseclick to end the polyline.");
-}
-
-void KisToolPolyline::keyPress(TQKeyEvent *e)
-{
- if (e->key()==TQt::Key_Escape) {
- // erase old lines on canvas
- draw();
- m_dragging = false;
- m_points.clear();
- }
-}
-
-#include "kis_tool_polyline.moc"
diff --git a/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cpp b/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cpp
new file mode 100644
index 000000000..ab89cf3f4
--- /dev/null
+++ b/chalk/plugins/tools/tool_polyline/kis_tool_polyline.cpp
@@ -0,0 +1,271 @@
+/*
+ * kis_tool_polyline.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <tqpainter.h>
+#include <tqspinbox.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_doc.h"
+#include "kis_view.h"
+#include "kis_painter.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+
+#include "kis_tool_polyline.h"
+
+KisToolPolyline::KisToolPolyline()
+ : super(i18n ("Polyline")),
+ m_dragging (false),
+ m_currentImage (0)
+{
+ setName("tool_polyline");
+ setCursor(KisCursor::load("tool_polyline_cursor.png", 6, 6));
+}
+
+KisToolPolyline::~KisToolPolyline()
+{
+}
+
+void KisToolPolyline::update (KisCanvasSubject *subject)
+{
+ super::update (subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg ();
+}
+
+void KisToolPolyline::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_currentImage) {
+ if (event->button() == Qt::LeftButton && event->state() != TQt::ShiftButton ) {
+
+ m_dragging = true;
+
+ if (m_points.isEmpty())
+ {
+ m_dragStart = event->pos();
+ m_dragEnd = event->pos();
+ m_points.append(m_dragStart);
+ } else {
+ m_dragStart = m_dragEnd;
+ m_dragEnd = event->pos();
+ draw();
+ }
+ } else if (event->button() == Qt::LeftButton && event->state() == TQt::ShiftButton ) {
+ finish();
+ }
+ }
+}
+
+void KisToolPolyline::deactivate()
+{
+ draw();
+ m_points.clear();
+ m_dragging = false;
+}
+
+void KisToolPolyline::finish()
+{
+ // erase old lines on canvas
+ draw();
+ m_dragging = false;
+
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();
+ if (!device) return;
+
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (i18n ("Polyline"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op); // Painter takes ownership
+
+ KisPoint start,end;
+ KisPointVector::iterator it;
+ for( it = m_points.begin(); it != m_points.end(); ++it )
+ {
+ if( it == m_points.begin() )
+ {
+ start = (*it);
+ } else {
+ end = (*it);
+ painter.paintLine(start, PRESSURE_DEFAULT, 0, 0, end, PRESSURE_DEFAULT, 0, 0);
+ start = end;
+ }
+ }
+ m_points.clear();
+
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+
+}
+void KisToolPolyline::move(KisMoveEvent *event)
+{
+ if (m_dragging) {
+ // erase old lines on canvas
+ draw();
+ // get current mouse position
+ m_dragEnd = event->pos();
+ // draw new lines on canvas
+ draw();
+ }
+}
+
+void KisToolPolyline::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ m_dragging = false;
+ m_points.append (m_dragEnd);
+ }
+
+ if (m_dragging && event->button() == Qt::RightButton) {
+
+ }
+}
+
+
+void KisToolPolyline::doubleClick(KisDoubleClickEvent *)
+{
+ finish();
+}
+
+
+void KisToolPolyline::paint(KisCanvasPainter& gc)
+{
+ draw(gc);
+}
+
+void KisToolPolyline::paint(KisCanvasPainter& gc, const TQRect&)
+{
+ draw(gc);
+}
+
+void KisToolPolyline::draw()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+
+ draw(gc);
+ }
+}
+
+void KisToolPolyline::draw(KisCanvasPainter& gc)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ TQPen pen(TQt::white, 0, TQt::SolidLine);
+
+ gc.setPen(pen);
+ gc.setRasterOp(TQt::XorROP);
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisPoint start, end;
+ TQPoint startPos;
+ TQPoint endPos;
+
+ if (m_dragging) {
+ startPos = controller->windowToView(m_dragStart.floorTQPoint());
+ endPos = controller->windowToView(m_dragEnd.floorTQPoint());
+ gc.drawLine(startPos, endPos);
+ } else {
+ for (KisPointVector::iterator it = m_points.begin(); it != m_points.end(); ++it) {
+
+ if (it == m_points.begin())
+ {
+ start = (*it);
+ } else {
+ end = (*it);
+
+ startPos = controller->windowToView(start.floorTQPoint());
+ endPos = controller->windowToView(end.floorTQPoint());
+
+ gc.drawLine(startPos, endPos);
+
+ start = end;
+ }
+ }
+ }
+}
+
+void KisToolPolyline::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Polyline"),
+ "polyline",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Draw a polyline. Shift-mouseclick ends the polyline."));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+TQString KisToolPolyline::quickHelp() const
+{
+ return i18n("Press shift-mouseclick to end the polyline.");
+}
+
+void KisToolPolyline::keyPress(TQKeyEvent *e)
+{
+ if (e->key()==TQt::Key_Escape) {
+ // erase old lines on canvas
+ draw();
+ m_dragging = false;
+ m_points.clear();
+ }
+}
+
+#include "kis_tool_polyline.moc"
diff --git a/chalk/plugins/tools/tool_polyline/tool_polyline.cc b/chalk/plugins/tools/tool_polyline/tool_polyline.cc
deleted file mode 100644
index a5bfa27f2..000000000
--- a/chalk/plugins/tools/tool_polyline/tool_polyline.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * tool_polyline.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-#include <kis_view.h>
-
-#include "tool_polyline.h"
-#include "kis_tool_polyline.h"
-
-
-typedef KGenericFactory<ToolPolyline> ToolPolylineFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolpolyline, ToolPolylineFactory( "chalk" ) )
-
-
-ToolPolyline::ToolPolyline(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolPolylineFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
-
- r->add(new KisToolPolylineFactory());
- }
-
-}
-
-ToolPolyline::~ToolPolyline()
-{
-}
-
-#include "tool_polyline.moc"
diff --git a/chalk/plugins/tools/tool_polyline/tool_polyline.cpp b/chalk/plugins/tools/tool_polyline/tool_polyline.cpp
new file mode 100644
index 000000000..d6abff71a
--- /dev/null
+++ b/chalk/plugins/tools/tool_polyline/tool_polyline.cpp
@@ -0,0 +1,64 @@
+/*
+ * tool_polyline.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+#include <kis_view.h>
+
+#include "tool_polyline.h"
+#include "kis_tool_polyline.h"
+
+
+typedef KGenericFactory<ToolPolyline> ToolPolylineFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolpolyline, ToolPolylineFactory( "chalk" ) )
+
+
+ToolPolyline::ToolPolyline(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolPolylineFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+
+ r->add(new KisToolPolylineFactory());
+ }
+
+}
+
+ToolPolyline::~ToolPolyline()
+{
+}
+
+#include "tool_polyline.moc"
diff --git a/chalk/plugins/tools/tool_selectsimilar/Makefile.am b/chalk/plugins/tools/tool_selectsimilar/Makefile.am
index 5c1897f40..224f67ba4 100644
--- a/chalk/plugins/tools/tool_selectsimilar/Makefile.am
+++ b/chalk/plugins/tools/tool_selectsimilar/Makefile.am
@@ -9,7 +9,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
-chalktoolselectsimilar_la_SOURCES = selectsimilar.cc kis_tool_selectsimilar.cc
+chalktoolselectsimilar_la_SOURCES = selectsimilar.cpp kis_tool_selectsimilar.cpp
noinst_HEADERS = selectsimilar.h kis_tool_selectsimilar.h
kde_module_LTLIBRARIES = chalktoolselectsimilar.la
diff --git a/chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cc b/chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cpp
index 65b05957a..65b05957a 100644
--- a/chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cc
+++ b/chalk/plugins/tools/tool_selectsimilar/kis_tool_selectsimilar.cpp
diff --git a/chalk/plugins/tools/tool_selectsimilar/selectsimilar.cc b/chalk/plugins/tools/tool_selectsimilar/selectsimilar.cpp
index af8070171..af8070171 100644
--- a/chalk/plugins/tools/tool_selectsimilar/selectsimilar.cc
+++ b/chalk/plugins/tools/tool_selectsimilar/selectsimilar.cpp
diff --git a/chalk/plugins/tools/tool_star/Makefile.am b/chalk/plugins/tools/tool_star/Makefile.am
index ed88d27ed..1f4627dd6 100644
--- a/chalk/plugins/tools/tool_star/Makefile.am
+++ b/chalk/plugins/tools/tool_star/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalktoolstar_la_SOURCES = \
wdg_tool_star.ui \
- tool_star.cc \
- kis_tool_star.cc
+ tool_star.cpp \
+ kis_tool_star.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktoolstar.la
diff --git a/chalk/plugins/tools/tool_star/kis_tool_star.cc b/chalk/plugins/tools/tool_star/kis_tool_star.cc
deleted file mode 100644
index cd4bb0b2e..000000000
--- a/chalk/plugins/tools/tool_star/kis_tool_star.cc
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * kis_tool_star.cc -- part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <tqpainter.h>
-#include <tqspinbox.h>
-#include <tqlayout.h>
-
-#include <tdeaction.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <knuminput.h>
-
-#include "kis_doc.h"
-#include "kis_view.h"
-#include "kis_painter.h"
-#include "kis_int_spinbox.h"
-#include "kis_canvas_subject.h"
-#include "kis_canvas_controller.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_paintop_registry.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_cursor.h"
-#include "kis_int_spinbox.h"
-
-#include "kis_tool_star.h"
-#include "wdg_tool_star.h"
-
-KisToolStar::KisToolStar()
- : super(i18n("Star")),
- m_dragging (false),
- m_currentImage (0)
-{
- setName("tool_star");
- setCursor(KisCursor::load("tool_star_cursor.png", 6, 6));
- m_innerOuterRatio=40;
- m_vertices=5;
-}
-
-KisToolStar::~KisToolStar()
-{
-}
-
-void KisToolStar::update (KisCanvasSubject *subject)
-{
- super::update (subject);
- if (m_subject)
- m_currentImage = m_subject->currentImg ();
-}
-
-void KisToolStar::buttonPress(KisButtonPressEvent *event)
-{
- if (m_currentImage && event->button() == Qt::LeftButton) {
- m_dragging = true;
- m_dragStart = event->pos();
- m_dragEnd = event->pos();
- m_vertices = m_optWidget->verticesSpinBox->value();
- m_innerOuterRatio = m_optWidget->ratioSpinBox->value();
- }
-}
-
-void KisToolStar::move(KisMoveEvent *event)
-{
- if (m_dragging) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- // move (alt) or resize star
- if (event->state() & TQt::AltButton) {
- KisPoint trans = event->pos() - m_dragEnd;
- m_dragStart += trans;
- m_dragEnd += trans;
- } else {
- m_dragEnd = event->pos();
- }
- // draw new lines on canvas
- draw(m_dragStart, m_dragEnd);
- }
-}
-
-void KisToolStar::buttonRelease(KisButtonReleaseEvent *event)
-{
- if (!m_subject || !m_currentImage)
- return;
-
- if (m_dragging && event->button() == Qt::LeftButton) {
- // erase old lines on canvas
- draw(m_dragStart, m_dragEnd);
- m_dragging = false;
-
- if (m_dragStart == m_dragEnd)
- return;
-
- if (!m_currentImage)
- return;
-
- if (!m_currentImage->activeDevice())
- return;
-
- KisPaintDeviceSP device = m_currentImage->activeDevice ();;
- KisPainter painter (device);
- if (m_currentImage->undo()) painter.beginTransaction (i18n("Star"));
-
- painter.setPaintColor(m_subject->fgColor());
- painter.setBackgroundColor(m_subject->bgColor());
- painter.setFillStyle(fillStyle());
- painter.setBrush(m_subject->currentBrush());
- painter.setPattern(m_subject->currentPattern());
- painter.setOpacity(m_opacity);
- painter.setCompositeOp(m_compositeOp);
- KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
- painter.setPaintOp(op); // Painter takes ownership
-
- vKisPoint coord = starCoordinates(m_vertices, m_dragStart.x(), m_dragStart.y(), m_dragEnd.x(), m_dragEnd.y());
-
- painter.paintPolygon(coord);
-
- device->setDirty( painter.dirtyRect() );
- notifyModified();
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- }
- }
-}
-
-void KisToolStar::draw(const KisPoint& start, const KisPoint& end )
-{
- if (!m_subject || !m_currentImage)
- return;
-
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter p (canvas);
- TQPen pen(TQt::SolidLine);
-
- KisPoint startPos;
- KisPoint endPos;
- startPos = controller->windowToView(start);
- endPos = controller->windowToView(end);
-
- p.setRasterOp(TQt::NotROP);
-
- vKisPoint points = starCoordinates(m_vertices, startPos.x(), startPos.y(), endPos.x(), endPos.y());
-
- for (uint i = 0; i < points.count() - 1; i++) {
- p.drawLine(points[i].floorTQPoint(), points[i + 1].floorTQPoint());
- }
- p.drawLine(points[points.count() - 1].floorTQPoint(), points[0].floorTQPoint());
-
- p.end ();
-}
-
-void KisToolStar::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- TDEShortcut shortcut(TQt::Key_Plus);
- shortcut.append(TDEShortcut(TQt::Key_F9));
- m_action = new TDERadioAction(i18n("&Star"),
- "tool_star",
- shortcut,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
-
- m_action->setToolTip(i18n("Draw a star"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-vKisPoint KisToolStar::starCoordinates(int N, double mx, double my, double x, double y)
-{
- double R=0, r=0;
- TQ_INT32 n=0;
- double angle;
-
- vKisPoint starCoordinatesArray(2*N);
-
- // the radius of the outer edges
- R=sqrt((x-mx)*(x-mx)+(y-my)*(y-my));
-
- // the radius of the inner edges
- r=R*m_innerOuterRatio/100.0;
-
- // the angle
- angle=-atan2((x-mx),(y-my));
-
- //set outer edges
- for(n=0;n<N;n++){
- starCoordinatesArray[2*n] = KisPoint(mx+R*cos(n * 2.0 * M_PI / N + angle),my+R*sin(n *2.0 * M_PI / N+angle));
- }
-
- //set inner edges
- for(n=0;n<N;n++){
- starCoordinatesArray[2*n+1] = KisPoint(mx+r*cos((n + 0.5) * 2.0 * M_PI / N + angle),my+r*sin((n +0.5) * 2.0 * M_PI / N + angle));
- }
-
- return starCoordinatesArray;
-}
-
-TQWidget* KisToolStar::createOptionWidget(TQWidget* parent)
-{
- TQWidget *widget = super::createOptionWidget(parent);
-
- m_optWidget = new WdgToolStar(widget);
- TQ_CHECK_PTR(m_optWidget);
-
- m_optWidget->ratioSpinBox->setValue(m_innerOuterRatio);
-
- TQGridLayout *optionLayout = new TQGridLayout(widget, 1, 1);
- super::addOptionWidgetLayout(optionLayout);
-
- optionLayout->addWidget(m_optWidget, 0, 0);
-
- return widget;
-}
-
-#include "kis_tool_star.moc"
diff --git a/chalk/plugins/tools/tool_star/kis_tool_star.cpp b/chalk/plugins/tools/tool_star/kis_tool_star.cpp
new file mode 100644
index 000000000..3a260545b
--- /dev/null
+++ b/chalk/plugins/tools/tool_star/kis_tool_star.cpp
@@ -0,0 +1,245 @@
+/*
+ * kis_tool_star.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <tqpainter.h>
+#include <tqspinbox.h>
+#include <tqlayout.h>
+
+#include <tdeaction.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <knuminput.h>
+
+#include "kis_doc.h"
+#include "kis_view.h"
+#include "kis_painter.h"
+#include "kis_int_spinbox.h"
+#include "kis_canvas_subject.h"
+#include "kis_canvas_controller.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_paintop_registry.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_cursor.h"
+#include "kis_int_spinbox.h"
+
+#include "kis_tool_star.h"
+#include "wdg_tool_star.h"
+
+KisToolStar::KisToolStar()
+ : super(i18n("Star")),
+ m_dragging (false),
+ m_currentImage (0)
+{
+ setName("tool_star");
+ setCursor(KisCursor::load("tool_star_cursor.png", 6, 6));
+ m_innerOuterRatio=40;
+ m_vertices=5;
+}
+
+KisToolStar::~KisToolStar()
+{
+}
+
+void KisToolStar::update (KisCanvasSubject *subject)
+{
+ super::update (subject);
+ if (m_subject)
+ m_currentImage = m_subject->currentImg ();
+}
+
+void KisToolStar::buttonPress(KisButtonPressEvent *event)
+{
+ if (m_currentImage && event->button() == Qt::LeftButton) {
+ m_dragging = true;
+ m_dragStart = event->pos();
+ m_dragEnd = event->pos();
+ m_vertices = m_optWidget->verticesSpinBox->value();
+ m_innerOuterRatio = m_optWidget->ratioSpinBox->value();
+ }
+}
+
+void KisToolStar::move(KisMoveEvent *event)
+{
+ if (m_dragging) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ // move (alt) or resize star
+ if (event->state() & TQt::AltButton) {
+ KisPoint trans = event->pos() - m_dragEnd;
+ m_dragStart += trans;
+ m_dragEnd += trans;
+ } else {
+ m_dragEnd = event->pos();
+ }
+ // draw new lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ }
+}
+
+void KisToolStar::buttonRelease(KisButtonReleaseEvent *event)
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ if (m_dragging && event->button() == Qt::LeftButton) {
+ // erase old lines on canvas
+ draw(m_dragStart, m_dragEnd);
+ m_dragging = false;
+
+ if (m_dragStart == m_dragEnd)
+ return;
+
+ if (!m_currentImage)
+ return;
+
+ if (!m_currentImage->activeDevice())
+ return;
+
+ KisPaintDeviceSP device = m_currentImage->activeDevice ();;
+ KisPainter painter (device);
+ if (m_currentImage->undo()) painter.beginTransaction (i18n("Star"));
+
+ painter.setPaintColor(m_subject->fgColor());
+ painter.setBackgroundColor(m_subject->bgColor());
+ painter.setFillStyle(fillStyle());
+ painter.setBrush(m_subject->currentBrush());
+ painter.setPattern(m_subject->currentPattern());
+ painter.setOpacity(m_opacity);
+ painter.setCompositeOp(m_compositeOp);
+ KisPaintOp * op = KisPaintOpRegistry::instance()->paintOp(m_subject->currentPaintop(), m_subject->currentPaintopSettings(), &painter);
+ painter.setPaintOp(op); // Painter takes ownership
+
+ vKisPoint coord = starCoordinates(m_vertices, m_dragStart.x(), m_dragStart.y(), m_dragEnd.x(), m_dragEnd.y());
+
+ painter.paintPolygon(coord);
+
+ device->setDirty( painter.dirtyRect() );
+ notifyModified();
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ }
+ }
+}
+
+void KisToolStar::draw(const KisPoint& start, const KisPoint& end )
+{
+ if (!m_subject || !m_currentImage)
+ return;
+
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter p (canvas);
+ TQPen pen(TQt::SolidLine);
+
+ KisPoint startPos;
+ KisPoint endPos;
+ startPos = controller->windowToView(start);
+ endPos = controller->windowToView(end);
+
+ p.setRasterOp(TQt::NotROP);
+
+ vKisPoint points = starCoordinates(m_vertices, startPos.x(), startPos.y(), endPos.x(), endPos.y());
+
+ for (uint i = 0; i < points.count() - 1; i++) {
+ p.drawLine(points[i].floorTQPoint(), points[i + 1].floorTQPoint());
+ }
+ p.drawLine(points[points.count() - 1].floorTQPoint(), points[0].floorTQPoint());
+
+ p.end ();
+}
+
+void KisToolStar::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ TDEShortcut shortcut(TQt::Key_Plus);
+ shortcut.append(TDEShortcut(TQt::Key_F9));
+ m_action = new TDERadioAction(i18n("&Star"),
+ "tool_star",
+ shortcut,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+
+ m_action->setToolTip(i18n("Draw a star"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+vKisPoint KisToolStar::starCoordinates(int N, double mx, double my, double x, double y)
+{
+ double R=0, r=0;
+ TQ_INT32 n=0;
+ double angle;
+
+ vKisPoint starCoordinatesArray(2*N);
+
+ // the radius of the outer edges
+ R=sqrt((x-mx)*(x-mx)+(y-my)*(y-my));
+
+ // the radius of the inner edges
+ r=R*m_innerOuterRatio/100.0;
+
+ // the angle
+ angle=-atan2((x-mx),(y-my));
+
+ //set outer edges
+ for(n=0;n<N;n++){
+ starCoordinatesArray[2*n] = KisPoint(mx+R*cos(n * 2.0 * M_PI / N + angle),my+R*sin(n *2.0 * M_PI / N+angle));
+ }
+
+ //set inner edges
+ for(n=0;n<N;n++){
+ starCoordinatesArray[2*n+1] = KisPoint(mx+r*cos((n + 0.5) * 2.0 * M_PI / N + angle),my+r*sin((n +0.5) * 2.0 * M_PI / N + angle));
+ }
+
+ return starCoordinatesArray;
+}
+
+TQWidget* KisToolStar::createOptionWidget(TQWidget* parent)
+{
+ TQWidget *widget = super::createOptionWidget(parent);
+
+ m_optWidget = new WdgToolStar(widget);
+ TQ_CHECK_PTR(m_optWidget);
+
+ m_optWidget->ratioSpinBox->setValue(m_innerOuterRatio);
+
+ TQGridLayout *optionLayout = new TQGridLayout(widget, 1, 1);
+ super::addOptionWidgetLayout(optionLayout);
+
+ optionLayout->addWidget(m_optWidget, 0, 0);
+
+ return widget;
+}
+
+#include "kis_tool_star.moc"
diff --git a/chalk/plugins/tools/tool_star/tool_star.cc b/chalk/plugins/tools/tool_star/tool_star.cc
deleted file mode 100644
index 9ac1b62f8..000000000
--- a/chalk/plugins/tools/tool_star/tool_star.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * tool_star.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_star.h"
-#include "kis_tool_star.h"
-
-
-typedef KGenericFactory<ToolStar> ToolStarFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktoolstar, ToolStarFactory( "chalk" ) )
-
-
-ToolStar::ToolStar(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolStarFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
- r->add(new KisToolStarFactory());
- }
-
-}
-
-ToolStar::~ToolStar()
-{
-}
-
-#include "tool_star.moc"
diff --git a/chalk/plugins/tools/tool_star/tool_star.cpp b/chalk/plugins/tools/tool_star/tool_star.cpp
new file mode 100644
index 000000000..7309e8a1a
--- /dev/null
+++ b/chalk/plugins/tools/tool_star/tool_star.cpp
@@ -0,0 +1,62 @@
+/*
+ * tool_star.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_star.h"
+#include "kis_tool_star.h"
+
+
+typedef KGenericFactory<ToolStar> ToolStarFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktoolstar, ToolStarFactory( "chalk" ) )
+
+
+ToolStar::ToolStar(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolStarFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>( parent );
+ r->add(new KisToolStarFactory());
+ }
+
+}
+
+ToolStar::~ToolStar()
+{
+}
+
+#include "tool_star.moc"
diff --git a/chalk/plugins/tools/tool_transform/Makefile.am b/chalk/plugins/tools/tool_transform/Makefile.am
index 12a32774c..a5adea177 100644
--- a/chalk/plugins/tools/tool_transform/Makefile.am
+++ b/chalk/plugins/tools/tool_transform/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
chalktooltransform_la_SOURCES = \
wdg_tool_transform.ui \
- tool_transform.cc \
- kis_tool_transform.cc
+ tool_transform.cpp \
+ kis_tool_transform.cpp
# Install this plugin in the KDE modules directory
kde_module_LTLIBRARIES = chalktooltransform.la
diff --git a/chalk/plugins/tools/tool_transform/kis_tool_transform.cc b/chalk/plugins/tools/tool_transform/kis_tool_transform.cc
deleted file mode 100644
index de20ce7f6..000000000
--- a/chalk/plugins/tools/tool_transform/kis_tool_transform.cc
+++ /dev/null
@@ -1,916 +0,0 @@
-/*
- * kis_tool_transform.cc -- part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2005 Casper Boemann <cbr@boemann.dk>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqpushbutton.h>
-#include <tqobject.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqapplication.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-
-#include <kis_global.h>
-#include <kis_painter.h>
-#include <kis_canvas_controller.h>
-#include <kis_canvas_subject.h>
-#include <kis_cursor.h>
-#include <kis_image.h>
-#include <kis_undo_adapter.h>
-#include <kis_selected_transaction.h>
-#include <kis_button_press_event.h>
-#include <kis_button_release_event.h>
-#include <kis_move_event.h>
-#include <kis_selection.h>
-#include <kis_filter_strategy.h>
-#include <kis_cmb_idlist.h>
-#include <kis_id.h>
-#include <kis_tool_controller.h>
-#include <kis_transform_worker.h>
-
-#include "kis_tool_transform.h"
-#include "wdg_tool_transform.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-
-namespace {
- class TransformCmd : public KisSelectedTransaction {
- typedef KisSelectedTransaction super;
-
- public:
- TransformCmd(KisToolTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, double scaleX, double scaleY, double tX, double tY, double a, KisSelectionSP origSel, TQPoint startPos, TQPoint endPos);
- virtual ~TransformCmd();
-
- public:
- virtual void execute();
- virtual void unexecute();
- void transformArgs(double &sx, double &sy, double &tx, double &ty, double &a);
- KisSelectionSP origSelection(TQPoint &startPos, TQPoint &endPos);
- KisPaintDeviceSP theDevice();
- KisPaintDeviceSP origDevice();
-
- private:
- double m_scaleX;
- double m_scaleY;
- double m_translateX;
- double m_translateY;
- double m_a;
- KisToolTransform *m_tool;
- KisSelectionSP m_origSelection;
- TQPoint m_startPos;
- TQPoint m_endPos;
- KisPaintDeviceSP m_device;
- KisPaintDeviceSP m_origDevice;
- };
-
- TransformCmd::TransformCmd(KisToolTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, double scaleX, double scaleY, double tX, double tY, double a, KisSelectionSP origSel, TQPoint startPos, TQPoint endPos) :
- super(i18n("Transform"), device)
- , m_scaleX(scaleX)
- , m_scaleY(scaleY)
- , m_translateX(tX)
- , m_translateY(tY)
- , m_a(a)
- , m_tool(tool)
- , m_origSelection(origSel)
- , m_startPos(startPos)
- , m_endPos(endPos)
- , m_device(device)
- , m_origDevice(origDevice)
- {
- }
-
- TransformCmd::~TransformCmd()
- {
- }
-
- void TransformCmd::transformArgs(double &sx, double &sy, double &tx, double &ty, double &a)
- {
- sx = m_scaleX;
- sy = m_scaleY;
- tx= m_translateX;
- ty = m_translateY;
- a = m_a;
- }
-
- KisSelectionSP TransformCmd::origSelection(TQPoint &startPos, TQPoint &endPos)
- {
- startPos = m_startPos;
- endPos = m_endPos;
- return m_origSelection;
- }
-
- void TransformCmd::execute()
- {
- super::execute();
- }
-
- void TransformCmd::unexecute()
- {
- super::unexecute();
- }
-
- KisPaintDeviceSP TransformCmd::theDevice()
- {
- return m_device;
- }
-
- KisPaintDeviceSP TransformCmd::origDevice()
- {
- return m_origDevice;
- }
-}
-
-KisToolTransform::KisToolTransform()
- : super(i18n("Transform"))
- , m_wasPressed( false )
-{
- setName("tool_transform");
- setCursor(KisCursor::selectCursor());
- m_subject = 0;
- m_selecting = false;
- m_startPos = TQPoint(0, 0);
- m_endPos = TQPoint(0, 0);
- m_optWidget = 0;
- m_sizeCursors[0] = KisCursor::sizeVerCursor();
- m_sizeCursors[1] = KisCursor::sizeBDiagCursor();
- m_sizeCursors[2] = KisCursor::sizeHorCursor();
- m_sizeCursors[3] = KisCursor::sizeFDiagCursor();
- m_sizeCursors[4] = KisCursor::sizeVerCursor();
- m_sizeCursors[5] = KisCursor::sizeBDiagCursor();
- m_sizeCursors[6] = KisCursor::sizeHorCursor();
- m_sizeCursors[7] = KisCursor::sizeFDiagCursor();
- m_origDevice = 0;
- m_origSelection = 0;
-
-}
-
-KisToolTransform::~KisToolTransform()
-{
-}
-
-void KisToolTransform::deactivate()
-{
- if (m_subject && m_subject->undoAdapter()) m_subject->undoAdapter()->removeCommandHistoryListener( this );
-
- KisImageSP img = m_subject->currentImg();
- if (!img) return;
-
- paintOutline();
-
- disconnect(m_subject->currentImg().data(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
-}
-
-void KisToolTransform::activate()
-{
- if(m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice())
- {
- //connect(m_subject, commandExecuted(KCommand *c), this, notifyCommandAdded( KCommand * c));
- m_subject->undoAdapter()->setCommandHistoryListener( this );
-
- KisToolControllerInterface *controller = m_subject->toolController();
-
- if (controller)
- controller->setCurrentTool(this);
-
- TransformCmd * cmd=0;
-
- if(m_subject->currentImg()->undoAdapter()->presentCommand())
- cmd = dynamic_cast<TransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
-
- if (cmd == 0) {
- initHandles();
- }
- else
- {
- // One of our commands is on top
- if(cmd->theDevice() == m_subject->currentImg()->activeDevice())
- {
- // and it even has the same device
- // We should ask for tool args and orig selection
- m_origDevice = cmd->origDevice();
- cmd->transformArgs(m_scaleX, m_scaleY, m_translateX, m_translateY, m_a);
- m_origSelection = cmd->origSelection(m_startPos, m_endPos);
- m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
- m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
- paintOutline();
- }
- else
- initHandles();
- }
- }
- connect(m_subject->currentImg(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
-}
-
-void KisToolTransform::initHandles()
-{
- TQ_INT32 x,y,w,h;
- KisImageSP img = m_subject->currentImg();
-
- KisPaintDeviceSP dev = img->activeDevice();
- if (!dev ) return;
-
- // Create a lazy copy of the current state
- m_origDevice = new KisPaintDevice(*dev.data());
- Q_ASSERT(m_origDevice);
-
- if(dev->hasSelection())
- {
- KisSelectionSP sel = dev->selection();
- m_origSelection = new KisSelection(*sel.data());
- TQRect r = sel->selectedExactRect();
- r.rect(&x, &y, &w, &h);
- }
- else {
- dev->exactBounds(x,y,w,h);
- m_origSelection = 0;
- }
- m_startPos = TQPoint(x, y);
- m_endPos = TQPoint(x+w-1, y+h-1);
- m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
- m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
-
- m_a = 0.0;
- m_scaleX = 1.0;
- m_scaleY = 1.0;
- m_translateX = m_org_cenX;
- m_translateY = m_org_cenY;
-
- m_subject->canvasController() ->updateCanvas();
-}
-
-void KisToolTransform::paint(KisCanvasPainter& gc)
-{
- paintOutline(gc, TQRect());
-}
-
-void KisToolTransform::paint(KisCanvasPainter& gc, const TQRect& rc)
-{
- paintOutline(gc, rc);
-}
-
-
-void KisToolTransform::buttonPress(KisButtonPressEvent *e)
-{
- if (m_subject && e->button() == Qt::LeftButton) {
- m_wasPressed = true;
- }
-
- if (m_subject) {
- KisImageSP img = m_subject->currentImg();
-
- if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
- switch(m_function)
- {
- case ROTATE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint(static_cast<int>(m_translateX),static_cast<int>(m_translateY));
- m_clickangle = -m_a - atan2(m_clickoffset.x(),m_clickoffset.y());
- m_clickoffset = TQPoint(0, 0);
- break;
- case MOVE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint(static_cast<int>(m_translateX),static_cast<int>(m_translateY));
- break;
- case TOPSCALE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint((m_topleft + m_topright)/2);
- break;
- case TOPRIGHTSCALE:
- m_clickoffset = e->pos().floorTQPoint() - m_topright;
- break;
- case RIGHTSCALE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint((m_topright + m_bottomright)/2);
- break;
- case BOTTOMRIGHTSCALE:
- m_clickoffset = e->pos().floorTQPoint() - m_bottomright;
- break;
- case BOTTOMSCALE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint((m_bottomleft + m_bottomright)/2);
- break;
- case BOTTOMLEFTSCALE:
- m_clickoffset = e->pos().floorTQPoint() - m_bottomleft;
- break;
- case LEFTSCALE:
- m_clickoffset = e->pos().floorTQPoint()
- - TQPoint((m_topleft + m_bottomleft)/2);
- break;
- case TOPLEFTSCALE:
- m_clickoffset = e->pos().floorTQPoint() - m_topleft;
- break;
- }
- m_selecting = true;
- m_actualyMoveWhileSelected = false;
- }
- }
-}
-
-int KisToolTransform::det(TQPoint v,TQPoint w)
-{
- return v.x()*w.y()-v.y()*w.x();
-}
-int KisToolTransform::distsq(TQPoint v,TQPoint w)
-{
- v -= w;
- return v.x()*v.x() + v.y()*v.y();
-}
-
-void KisToolTransform::setFunctionalCursor()
-{
- int rotOctant = 8 + int(8.5 + m_a* 4 / M_PI);
-
- int s;
- if(m_scaleX*m_scaleY<0)
- s = -1;
- else
- s=1;
-
- switch(m_function)
- {
- case MOVE:
- setCursor(KisCursor::moveCursor());
- break;
- case ROTATE:
- setCursor(KisCursor::rotateCursor());
- break;
- case TOPSCALE:
- setCursor(m_sizeCursors[(0*s +rotOctant)%8]);
- break;
- case TOPRIGHTSCALE:
- setCursor(m_sizeCursors[(1*s +rotOctant)%8]);
- break;
- case RIGHTSCALE:
- setCursor(m_sizeCursors[(2*s +rotOctant)%8]);
- break;
- case BOTTOMRIGHTSCALE:
- setCursor(m_sizeCursors[(3*s +rotOctant)%8]);
- break;
- case BOTTOMSCALE:
- setCursor(m_sizeCursors[(4*s +rotOctant)%8]);
- break;
- case BOTTOMLEFTSCALE:
- setCursor(m_sizeCursors[(5*s +rotOctant)%8]);
- break;
- case LEFTSCALE:
- setCursor(m_sizeCursors[(6*s +rotOctant)%8]);
- break;
- case TOPLEFTSCALE:
- setCursor(m_sizeCursors[(7*s +rotOctant)%8]);
- break;
- }
-}
-
-void KisToolTransform::move(KisMoveEvent *e)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
-
- Q_ASSERT(controller);
- TQPoint topleft = m_topleft;
- TQPoint topright = m_topright;
- TQPoint bottomleft = m_bottomleft;
- TQPoint bottomright = m_bottomright;
-
- TQPoint mousePos = e->pos().floorTQPoint();
-
- if (m_subject && m_selecting) {
- paintOutline();
- m_actualyMoveWhileSelected = true;
- mousePos -= m_clickoffset;
-
- // transform mousePos coords, so it seems like it isn't rotated and centered at 0,0
- double newX = invrotX(mousePos.x() - m_translateX, mousePos.y() - m_translateY);
- double newY = invrotY(mousePos.x() - m_translateX, mousePos.y() - m_translateY);
- double dx=0, dy=0;
- double oldScaleX = m_scaleX;
- double oldScaleY = m_scaleY;
-
- if(m_function == MOVE)
- {
- m_translateX += mousePos.x() - m_translateX;
- m_translateY += mousePos.y() - m_translateY;
- }
-
- if(m_function == ROTATE)
- {
- m_a = -atan2(mousePos.x() - m_translateX, mousePos.y() - m_translateY)
- - m_clickangle;
- }
-
- if(m_function == TOPSCALE)
- {
- dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- }
- }
-
- if(m_function == TOPRIGHTSCALE)
- {
- dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
-
- dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
-
- // enforce same aspect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX < m_scaleY)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- dx = (m_scaleX - oldScaleX) * (m_endPos.x() - m_org_cenX);
- }
- else
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- dy = (m_scaleY - oldScaleY) * (m_startPos.y() - m_org_cenY);
- }
- }
- }
-
- if(m_function == RIGHTSCALE)
- {
- dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- }
- }
-
- if(m_function == BOTTOMRIGHTSCALE)
- {
- dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
-
- dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX < m_scaleY)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- dx = (m_scaleX - oldScaleX) * (m_endPos.x() - m_org_cenX);
- }
- else
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- dy = (m_scaleY - oldScaleY) * (m_endPos.y() - m_org_cenY);
- }
- }
- }
-
- if(m_function == BOTTOMSCALE)
- {
- dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- }
- }
-
- if(m_function == BOTTOMLEFTSCALE)
- {
- dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
-
- dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX < m_scaleY)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- dx = (m_scaleX - oldScaleX) * (m_startPos.x() - m_org_cenX);
- }
- else
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- dy = (m_scaleY - oldScaleY) * (m_endPos.y() - m_org_cenY);
- }
- }
- }
-
- if(m_function == LEFTSCALE)
- {
- dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- }
- }
-
- if(m_function == TOPLEFTSCALE)
- {
- dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
- m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
-
- dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
- m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
-
- // enforce same acpect if shift button is pressed
- if(e->state() & TQt::ShiftButton)
- {
- if(m_scaleX < m_scaleY)
- {
- if(m_scaleX>0) // handle the mirrored cases
- m_scaleX = fabs(m_scaleY);
- else
- m_scaleX = -fabs(m_scaleY);
- dx = (m_scaleX - oldScaleX) * (m_startPos.x() - m_org_cenX);
- }
- else
- {
- if(m_scaleY>0) // handle the mirrored cases
- m_scaleY = fabs(m_scaleX);
- else
- m_scaleY = -fabs(m_scaleX);
- dy = (m_scaleY - oldScaleY) * (m_startPos.y() - m_org_cenY);
- }
- }
- }
-
- m_translateX += rotX(dx, dy);
- m_translateY += rotY(dx, dy);
-
- paintOutline();
- }
- else
- {
- if(det(mousePos - topleft, topright - topleft)>0)
- m_function = ROTATE;
- else if(det(mousePos - topright, bottomright - topright)>0)
- m_function = ROTATE;
- else if(det(mousePos - bottomright, bottomleft - bottomright)>0)
- m_function = ROTATE;
- else if(det(mousePos - bottomleft, topleft - bottomleft)>0)
- m_function = ROTATE;
- else
- m_function = MOVE;
-
- int handleradius = int( 25 / (m_subject->zoomFactor() * m_subject->zoomFactor()) );
-
- if(distsq(mousePos, (m_topleft + m_topright)/2)<=handleradius)
- m_function = TOPSCALE;
- if(distsq(mousePos, m_topright)<=handleradius)
- m_function = TOPRIGHTSCALE;
- if(distsq(mousePos, (m_topright + m_bottomright)/2)<=handleradius)
- m_function = RIGHTSCALE;
- if(distsq(mousePos, m_bottomright)<=handleradius)
- m_function = BOTTOMRIGHTSCALE;
- if(distsq(mousePos, (m_bottomleft + m_bottomright)/2)<=handleradius)
- m_function = BOTTOMSCALE;
- if(distsq(mousePos, m_bottomleft)<=handleradius)
- m_function = BOTTOMLEFTSCALE;
- if(distsq(mousePos, (m_topleft + m_bottomleft)/2)<=handleradius)
- m_function = LEFTSCALE;
- if(distsq(mousePos, m_topleft)<=handleradius)
- m_function = TOPLEFTSCALE;
-
- setFunctionalCursor();
- }
- }
-}
-
-void KisToolTransform::buttonRelease(KisButtonReleaseEvent *e)
-{
- if (m_subject && e->button() == Qt::LeftButton) {
- if(!m_wasPressed) return;
- m_wasPressed = false;
-
- KisImageSP img = m_subject->currentImg();
-
- if (!img)
- return;
-
- m_selecting = false;
-
- if(m_actualyMoveWhileSelected)
- {
- paintOutline();
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- transform();
- TQApplication::restoreOverrideCursor();
- }
- }
-}
-
-void KisToolTransform::paintOutline()
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- KisCanvas *canvas = controller->kiscanvas();
- KisCanvasPainter gc(canvas);
- TQRect rc;
-
- paintOutline(gc, rc);
- }
-}
-
-void KisToolTransform::recalcOutline()
-{
- double x,y;
-
- m_sina = sin(m_a);
- m_cosa = cos(m_a);
-
- x = (m_startPos.x() - m_org_cenX) * m_scaleX;
- y = (m_startPos.y() - m_org_cenY) * m_scaleY;
- m_topleft = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
-
- x = (m_endPos.x() - m_org_cenX) * m_scaleX;
- y = (m_startPos.y() - m_org_cenY) * m_scaleY;
- m_topright = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
-
- x = (m_startPos.x() - m_org_cenX) * m_scaleX;
- y = (m_endPos.y() - m_org_cenY) * m_scaleY;
- m_bottomleft = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
-
- x = (m_endPos.x() - m_org_cenX) * m_scaleX;
- y = (m_endPos.y() - m_org_cenY) * m_scaleY;
- m_bottomright = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
-}
-
-void KisToolTransform::paintOutline(KisCanvasPainter& gc, const TQRect&)
-{
- if (m_subject) {
- KisCanvasController *controller = m_subject->canvasController();
- RasterOp op = gc.rasterOp();
- TQPen old = gc.pen();
- TQPen pen(TQt::SolidLine);
- pen.setWidth(1);
- Q_ASSERT(controller);
-
- recalcOutline();
- TQPoint topleft = controller->windowToView(m_topleft);
- TQPoint topright = controller->windowToView(m_topright);
- TQPoint bottomleft = controller->windowToView(m_bottomleft);
- TQPoint bottomright = controller->windowToView(m_bottomright);
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.drawRect(topleft.x()-4, topleft.y()-4, 8, 8);
- gc.drawLine(topleft.x(), topleft.y(), (topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2);
- gc.drawRect((topleft.x()+topright.x())/2-4, (topleft.y()+topright.y())/2-4, 8, 8);
- gc.drawLine((topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2, topright.x(), topright.y());
- gc.drawRect(topright.x()-4, topright.y()-4, 8, 8);
- gc.drawLine(topright.x(), topright.y(), (topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2);
- gc.drawRect((topright.x()+bottomright.x())/2-4, (topright.y()+bottomright.y())/2-4, 8, 8);
- gc.drawLine((topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2,bottomright.x(), bottomright.y());
- gc.drawRect(bottomright.x()-4, bottomright.y()-4, 8, 8);
- gc.drawLine(bottomright.x(), bottomright.y(), (bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2);
- gc.drawRect((bottomleft.x()+bottomright.x())/2-4, (bottomleft.y()+bottomright.y())/2-4, 8, 8);
- gc.drawLine((bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2, bottomleft.x(), bottomleft.y());
- gc.drawRect(bottomleft.x()-4, bottomleft.y()-4, 8, 8);
- gc.drawLine(bottomleft.x(), bottomleft.y(), (topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2);
- gc.drawRect((topleft.x()+bottomleft.x())/2-4, (topleft.y()+bottomleft.y())/2-4, 8, 8);
- gc.drawLine((topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2, topleft.x(), topleft.y());
- gc.setRasterOp(op);
- gc.setPen(old);
- }
-}
-
-void KisToolTransform::transform()
-{
-
- KisImageSP img = m_subject->currentImg();
-
- if (!img || !img->activeDevice())
- return;
-
- double tx = m_translateX - rotX(m_org_cenX * m_scaleX, m_org_cenY * m_scaleY);
- double ty = m_translateY - rotY(m_org_cenX * m_scaleX, m_org_cenY * m_scaleY);
- KisProgressDisplayInterface *progress = m_subject->progressDisplay();
-
- // This mementoes the current state of the active device.
- TransformCmd * transaction = new TransformCmd(this, img->activeDevice(), m_origDevice,
- m_scaleX, m_scaleY, m_translateX, m_translateY, m_a, m_origSelection, m_startPos, m_endPos);
-
- // Copy the original state back.
- TQRect rc = m_origDevice->extent();
- rc = rc.normalize();
- img->activeDevice()->clear();
- KisPainter gc(img->activeDevice());
- gc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origDevice, rc.x(), rc.y(), rc.width(), rc.height());
- gc.end();
-
- // Also restore the original selection.
- if(m_origSelection)
- {
- //TQRect rc = m_origSelection->extent();
- TQRect rc = m_origSelection->selectedRect();
- rc = rc.normalize();
- img->activeDevice()->selection()->clear();
- KisPainter sgc(img->activeDevice()->selection().data());
- sgc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origSelection.data(), rc.x(), rc.y(), rc.width(), rc.height());
- sgc.end();
- }
- else
- if(img->activeDevice()->hasSelection())
- img->activeDevice()->selection()->clear();
-
- // Perform the transform. Since we copied the original state back, this doesn't degrade
- // after many tweaks. Since we started the transaction before the copy back, the memento
- // has the previous state.
- KisTransformWorker t(img->activeDevice(), m_scaleX, m_scaleY, 0, 0, m_a, int(tx), int(ty), progress, m_filter);
- t.run();
-
- // If canceled, go back to the memento
- if(t.isCanceled())
- {
- transaction->unexecute();
- delete transaction;
- return;
- }
-
- img->activeDevice()->setDirty(rc); // XXX: This is not enough - should union with new extent
-
- // Else add the command -- this will have the memento from the previous state,
- // and the transformed state from the original device we cached in our activated()
- // method.
- if (transaction) {
- if (img->undo())
- img->undoAdapter()->addCommand(transaction);
- else
- delete transaction;
- }
-}
-
-void KisToolTransform::notifyCommandAdded( KCommand * command)
-{
- TransformCmd * cmd = dynamic_cast<TransformCmd*>(command);
- if (cmd == 0) {
- // The last added command wasn't one of ours;
- // we should reset to the new state of the canvas.
- // In effect we should treat this as if the tool has been just activated
- initHandles();
- }
-}
-
-void KisToolTransform::notifyCommandExecuted( KCommand * command)
-{
- Q_UNUSED(command);
- TransformCmd * cmd=0;
-
- if(m_subject->currentImg()->undoAdapter()->presentCommand())
- cmd = dynamic_cast<TransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
-
- if (cmd == 0) {
- // The command now on the top of the stack isn't one of ours
- // We should treat this as if the tool has been just activated
- initHandles();
- }
- else
- {
- // One of our commands is now on top
- // We should ask for tool args and orig selection
- cmd->transformArgs(m_scaleX, m_scaleY, m_translateX, m_translateY, m_a);
- m_origSelection = cmd->origSelection(m_startPos, m_endPos);
- m_origDevice = cmd->origDevice();
- m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
- m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
- m_subject->canvasController() ->updateCanvas();
- }
-}
-
-void KisToolTransform::slotSetFilter(const KisID &filterID)
-{
- m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
-}
-
-void KisToolTransform::slotLayerActivated(KisLayerSP)
-{
- activate();
-}
-
-
-TQWidget* KisToolTransform::createOptionWidget(TQWidget* parent)
-{
-
- m_optWidget = new WdgToolTransform(parent);
- TQ_CHECK_PTR(m_optWidget);
-
- m_optWidget->cmbFilter->clear();
- m_optWidget->cmbFilter->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
-
- m_optWidget->cmbFilter->setCurrentText("Mitchell");
- connect(m_optWidget->cmbFilter, TQT_SIGNAL(activated(const KisID &)),
- this, TQT_SLOT(slotSetFilter(const KisID &)));
-
- KisID filterID = m_optWidget->cmbFilter->currentItem();
- m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
-
-/*
- connect(m_optWidget->intStartX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartX(int)));
- connect(m_optWidget->intStartY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartY(int)));
- connect(m_optWidget->intEndX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndX(int)));
- connect(m_optWidget->intEndY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndY(int)));
-*/
- m_optWidget->intStartX->hide();
- m_optWidget->intStartY->hide();
- m_optWidget->intEndX->hide();
- m_optWidget->intEndY->hide();
- m_optWidget->textLabel1->hide();
- m_optWidget->textLabel2->hide();
- m_optWidget->textLabel3->hide();
- m_optWidget->textLabel4->hide();
- return m_optWidget;
-}
-
-TQWidget* KisToolTransform::optionWidget()
-{
- return m_optWidget;
-}
-
-void KisToolTransform::setup(TDEActionCollection *collection)
-{
- m_action = static_cast<TDERadioAction *>(collection->action(name()));
-
- if (m_action == 0) {
- m_action = new TDERadioAction(i18n("&Transform"),
- "tool_transform",
- 0,
- this,
- TQT_SLOT(activate()),
- collection,
- name());
- TQ_CHECK_PTR(m_action);
- m_action->setToolTip(i18n("Transform a layer or a selection"));
- m_action->setExclusiveGroup("tools");
- m_ownAction = true;
- }
-}
-
-#include "kis_tool_transform.moc"
diff --git a/chalk/plugins/tools/tool_transform/kis_tool_transform.cpp b/chalk/plugins/tools/tool_transform/kis_tool_transform.cpp
new file mode 100644
index 000000000..88a675663
--- /dev/null
+++ b/chalk/plugins/tools/tool_transform/kis_tool_transform.cpp
@@ -0,0 +1,916 @@
+/*
+ * kis_tool_transform.cpp -- part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2005 Casper Boemann <cbr@boemann.dk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqpushbutton.h>
+#include <tqobject.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqapplication.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+
+#include <kis_global.h>
+#include <kis_painter.h>
+#include <kis_canvas_controller.h>
+#include <kis_canvas_subject.h>
+#include <kis_cursor.h>
+#include <kis_image.h>
+#include <kis_undo_adapter.h>
+#include <kis_selected_transaction.h>
+#include <kis_button_press_event.h>
+#include <kis_button_release_event.h>
+#include <kis_move_event.h>
+#include <kis_selection.h>
+#include <kis_filter_strategy.h>
+#include <kis_cmb_idlist.h>
+#include <kis_id.h>
+#include <kis_tool_controller.h>
+#include <kis_transform_worker.h>
+
+#include "kis_tool_transform.h"
+#include "wdg_tool_transform.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+
+namespace {
+ class TransformCmd : public KisSelectedTransaction {
+ typedef KisSelectedTransaction super;
+
+ public:
+ TransformCmd(KisToolTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, double scaleX, double scaleY, double tX, double tY, double a, KisSelectionSP origSel, TQPoint startPos, TQPoint endPos);
+ virtual ~TransformCmd();
+
+ public:
+ virtual void execute();
+ virtual void unexecute();
+ void transformArgs(double &sx, double &sy, double &tx, double &ty, double &a);
+ KisSelectionSP origSelection(TQPoint &startPos, TQPoint &endPos);
+ KisPaintDeviceSP theDevice();
+ KisPaintDeviceSP origDevice();
+
+ private:
+ double m_scaleX;
+ double m_scaleY;
+ double m_translateX;
+ double m_translateY;
+ double m_a;
+ KisToolTransform *m_tool;
+ KisSelectionSP m_origSelection;
+ TQPoint m_startPos;
+ TQPoint m_endPos;
+ KisPaintDeviceSP m_device;
+ KisPaintDeviceSP m_origDevice;
+ };
+
+ TransformCmd::TransformCmd(KisToolTransform *tool, KisPaintDeviceSP device, KisPaintDeviceSP origDevice, double scaleX, double scaleY, double tX, double tY, double a, KisSelectionSP origSel, TQPoint startPos, TQPoint endPos) :
+ super(i18n("Transform"), device)
+ , m_scaleX(scaleX)
+ , m_scaleY(scaleY)
+ , m_translateX(tX)
+ , m_translateY(tY)
+ , m_a(a)
+ , m_tool(tool)
+ , m_origSelection(origSel)
+ , m_startPos(startPos)
+ , m_endPos(endPos)
+ , m_device(device)
+ , m_origDevice(origDevice)
+ {
+ }
+
+ TransformCmd::~TransformCmd()
+ {
+ }
+
+ void TransformCmd::transformArgs(double &sx, double &sy, double &tx, double &ty, double &a)
+ {
+ sx = m_scaleX;
+ sy = m_scaleY;
+ tx= m_translateX;
+ ty = m_translateY;
+ a = m_a;
+ }
+
+ KisSelectionSP TransformCmd::origSelection(TQPoint &startPos, TQPoint &endPos)
+ {
+ startPos = m_startPos;
+ endPos = m_endPos;
+ return m_origSelection;
+ }
+
+ void TransformCmd::execute()
+ {
+ super::execute();
+ }
+
+ void TransformCmd::unexecute()
+ {
+ super::unexecute();
+ }
+
+ KisPaintDeviceSP TransformCmd::theDevice()
+ {
+ return m_device;
+ }
+
+ KisPaintDeviceSP TransformCmd::origDevice()
+ {
+ return m_origDevice;
+ }
+}
+
+KisToolTransform::KisToolTransform()
+ : super(i18n("Transform"))
+ , m_wasPressed( false )
+{
+ setName("tool_transform");
+ setCursor(KisCursor::selectCursor());
+ m_subject = 0;
+ m_selecting = false;
+ m_startPos = TQPoint(0, 0);
+ m_endPos = TQPoint(0, 0);
+ m_optWidget = 0;
+ m_sizeCursors[0] = KisCursor::sizeVerCursor();
+ m_sizeCursors[1] = KisCursor::sizeBDiagCursor();
+ m_sizeCursors[2] = KisCursor::sizeHorCursor();
+ m_sizeCursors[3] = KisCursor::sizeFDiagCursor();
+ m_sizeCursors[4] = KisCursor::sizeVerCursor();
+ m_sizeCursors[5] = KisCursor::sizeBDiagCursor();
+ m_sizeCursors[6] = KisCursor::sizeHorCursor();
+ m_sizeCursors[7] = KisCursor::sizeFDiagCursor();
+ m_origDevice = 0;
+ m_origSelection = 0;
+
+}
+
+KisToolTransform::~KisToolTransform()
+{
+}
+
+void KisToolTransform::deactivate()
+{
+ if (m_subject && m_subject->undoAdapter()) m_subject->undoAdapter()->removeCommandHistoryListener( this );
+
+ KisImageSP img = m_subject->currentImg();
+ if (!img) return;
+
+ paintOutline();
+
+ disconnect(m_subject->currentImg().data(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
+}
+
+void KisToolTransform::activate()
+{
+ if(m_subject && m_subject->currentImg() && m_subject->currentImg()->activeDevice())
+ {
+ //connect(m_subject, commandExecuted(KCommand *c), this, notifyCommandAdded( KCommand * c));
+ m_subject->undoAdapter()->setCommandHistoryListener( this );
+
+ KisToolControllerInterface *controller = m_subject->toolController();
+
+ if (controller)
+ controller->setCurrentTool(this);
+
+ TransformCmd * cmd=0;
+
+ if(m_subject->currentImg()->undoAdapter()->presentCommand())
+ cmd = dynamic_cast<TransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
+
+ if (cmd == 0) {
+ initHandles();
+ }
+ else
+ {
+ // One of our commands is on top
+ if(cmd->theDevice() == m_subject->currentImg()->activeDevice())
+ {
+ // and it even has the same device
+ // We should ask for tool args and orig selection
+ m_origDevice = cmd->origDevice();
+ cmd->transformArgs(m_scaleX, m_scaleY, m_translateX, m_translateY, m_a);
+ m_origSelection = cmd->origSelection(m_startPos, m_endPos);
+ m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
+ m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
+ paintOutline();
+ }
+ else
+ initHandles();
+ }
+ }
+ connect(m_subject->currentImg(), TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
+}
+
+void KisToolTransform::initHandles()
+{
+ TQ_INT32 x,y,w,h;
+ KisImageSP img = m_subject->currentImg();
+
+ KisPaintDeviceSP dev = img->activeDevice();
+ if (!dev ) return;
+
+ // Create a lazy copy of the current state
+ m_origDevice = new KisPaintDevice(*dev.data());
+ Q_ASSERT(m_origDevice);
+
+ if(dev->hasSelection())
+ {
+ KisSelectionSP sel = dev->selection();
+ m_origSelection = new KisSelection(*sel.data());
+ TQRect r = sel->selectedExactRect();
+ r.rect(&x, &y, &w, &h);
+ }
+ else {
+ dev->exactBounds(x,y,w,h);
+ m_origSelection = 0;
+ }
+ m_startPos = TQPoint(x, y);
+ m_endPos = TQPoint(x+w-1, y+h-1);
+ m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
+ m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
+
+ m_a = 0.0;
+ m_scaleX = 1.0;
+ m_scaleY = 1.0;
+ m_translateX = m_org_cenX;
+ m_translateY = m_org_cenY;
+
+ m_subject->canvasController() ->updateCanvas();
+}
+
+void KisToolTransform::paint(KisCanvasPainter& gc)
+{
+ paintOutline(gc, TQRect());
+}
+
+void KisToolTransform::paint(KisCanvasPainter& gc, const TQRect& rc)
+{
+ paintOutline(gc, rc);
+}
+
+
+void KisToolTransform::buttonPress(KisButtonPressEvent *e)
+{
+ if (m_subject && e->button() == Qt::LeftButton) {
+ m_wasPressed = true;
+ }
+
+ if (m_subject) {
+ KisImageSP img = m_subject->currentImg();
+
+ if (img && img->activeDevice() && e->button() == Qt::LeftButton) {
+ switch(m_function)
+ {
+ case ROTATE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint(static_cast<int>(m_translateX),static_cast<int>(m_translateY));
+ m_clickangle = -m_a - atan2(m_clickoffset.x(),m_clickoffset.y());
+ m_clickoffset = TQPoint(0, 0);
+ break;
+ case MOVE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint(static_cast<int>(m_translateX),static_cast<int>(m_translateY));
+ break;
+ case TOPSCALE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint((m_topleft + m_topright)/2);
+ break;
+ case TOPRIGHTSCALE:
+ m_clickoffset = e->pos().floorTQPoint() - m_topright;
+ break;
+ case RIGHTSCALE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint((m_topright + m_bottomright)/2);
+ break;
+ case BOTTOMRIGHTSCALE:
+ m_clickoffset = e->pos().floorTQPoint() - m_bottomright;
+ break;
+ case BOTTOMSCALE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint((m_bottomleft + m_bottomright)/2);
+ break;
+ case BOTTOMLEFTSCALE:
+ m_clickoffset = e->pos().floorTQPoint() - m_bottomleft;
+ break;
+ case LEFTSCALE:
+ m_clickoffset = e->pos().floorTQPoint()
+ - TQPoint((m_topleft + m_bottomleft)/2);
+ break;
+ case TOPLEFTSCALE:
+ m_clickoffset = e->pos().floorTQPoint() - m_topleft;
+ break;
+ }
+ m_selecting = true;
+ m_actualyMoveWhileSelected = false;
+ }
+ }
+}
+
+int KisToolTransform::det(TQPoint v,TQPoint w)
+{
+ return v.x()*w.y()-v.y()*w.x();
+}
+int KisToolTransform::distsq(TQPoint v,TQPoint w)
+{
+ v -= w;
+ return v.x()*v.x() + v.y()*v.y();
+}
+
+void KisToolTransform::setFunctionalCursor()
+{
+ int rotOctant = 8 + int(8.5 + m_a* 4 / M_PI);
+
+ int s;
+ if(m_scaleX*m_scaleY<0)
+ s = -1;
+ else
+ s=1;
+
+ switch(m_function)
+ {
+ case MOVE:
+ setCursor(KisCursor::moveCursor());
+ break;
+ case ROTATE:
+ setCursor(KisCursor::rotateCursor());
+ break;
+ case TOPSCALE:
+ setCursor(m_sizeCursors[(0*s +rotOctant)%8]);
+ break;
+ case TOPRIGHTSCALE:
+ setCursor(m_sizeCursors[(1*s +rotOctant)%8]);
+ break;
+ case RIGHTSCALE:
+ setCursor(m_sizeCursors[(2*s +rotOctant)%8]);
+ break;
+ case BOTTOMRIGHTSCALE:
+ setCursor(m_sizeCursors[(3*s +rotOctant)%8]);
+ break;
+ case BOTTOMSCALE:
+ setCursor(m_sizeCursors[(4*s +rotOctant)%8]);
+ break;
+ case BOTTOMLEFTSCALE:
+ setCursor(m_sizeCursors[(5*s +rotOctant)%8]);
+ break;
+ case LEFTSCALE:
+ setCursor(m_sizeCursors[(6*s +rotOctant)%8]);
+ break;
+ case TOPLEFTSCALE:
+ setCursor(m_sizeCursors[(7*s +rotOctant)%8]);
+ break;
+ }
+}
+
+void KisToolTransform::move(KisMoveEvent *e)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+
+ Q_ASSERT(controller);
+ TQPoint topleft = m_topleft;
+ TQPoint topright = m_topright;
+ TQPoint bottomleft = m_bottomleft;
+ TQPoint bottomright = m_bottomright;
+
+ TQPoint mousePos = e->pos().floorTQPoint();
+
+ if (m_subject && m_selecting) {
+ paintOutline();
+ m_actualyMoveWhileSelected = true;
+ mousePos -= m_clickoffset;
+
+ // transform mousePos coords, so it seems like it isn't rotated and centered at 0,0
+ double newX = invrotX(mousePos.x() - m_translateX, mousePos.y() - m_translateY);
+ double newY = invrotY(mousePos.x() - m_translateX, mousePos.y() - m_translateY);
+ double dx=0, dy=0;
+ double oldScaleX = m_scaleX;
+ double oldScaleY = m_scaleY;
+
+ if(m_function == MOVE)
+ {
+ m_translateX += mousePos.x() - m_translateX;
+ m_translateY += mousePos.y() - m_translateY;
+ }
+
+ if(m_function == ROTATE)
+ {
+ m_a = -atan2(mousePos.x() - m_translateX, mousePos.y() - m_translateY)
+ - m_clickangle;
+ }
+
+ if(m_function == TOPSCALE)
+ {
+ dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ }
+ }
+
+ if(m_function == TOPRIGHTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
+
+ dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
+
+ // enforce same aspect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX < m_scaleY)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ dx = (m_scaleX - oldScaleX) * (m_endPos.x() - m_org_cenX);
+ }
+ else
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ dy = (m_scaleY - oldScaleY) * (m_startPos.y() - m_org_cenY);
+ }
+ }
+ }
+
+ if(m_function == RIGHTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ }
+ }
+
+ if(m_function == BOTTOMRIGHTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_endPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_endPos.x() - m_org_cenX);
+
+ dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX < m_scaleY)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ dx = (m_scaleX - oldScaleX) * (m_endPos.x() - m_org_cenX);
+ }
+ else
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ dy = (m_scaleY - oldScaleY) * (m_endPos.y() - m_org_cenY);
+ }
+ }
+ }
+
+ if(m_function == BOTTOMSCALE)
+ {
+ dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ }
+ }
+
+ if(m_function == BOTTOMLEFTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
+
+ dy = (newY - m_scaleY * (m_endPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_endPos.y() - m_org_cenY);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX < m_scaleY)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ dx = (m_scaleX - oldScaleX) * (m_startPos.x() - m_org_cenX);
+ }
+ else
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ dy = (m_scaleY - oldScaleY) * (m_endPos.y() - m_org_cenY);
+ }
+ }
+ }
+
+ if(m_function == LEFTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ }
+ }
+
+ if(m_function == TOPLEFTSCALE)
+ {
+ dx = (newX - m_scaleX * (m_startPos.x() - m_org_cenX)) / 2;
+ m_scaleX = (newX - dx) / (m_startPos.x() - m_org_cenX);
+
+ dy = (newY - m_scaleY * (m_startPos.y() - m_org_cenY)) / 2;
+ m_scaleY = (newY - dy) / (m_startPos.y() - m_org_cenY);
+
+ // enforce same acpect if shift button is pressed
+ if(e->state() & TQt::ShiftButton)
+ {
+ if(m_scaleX < m_scaleY)
+ {
+ if(m_scaleX>0) // handle the mirrored cases
+ m_scaleX = fabs(m_scaleY);
+ else
+ m_scaleX = -fabs(m_scaleY);
+ dx = (m_scaleX - oldScaleX) * (m_startPos.x() - m_org_cenX);
+ }
+ else
+ {
+ if(m_scaleY>0) // handle the mirrored cases
+ m_scaleY = fabs(m_scaleX);
+ else
+ m_scaleY = -fabs(m_scaleX);
+ dy = (m_scaleY - oldScaleY) * (m_startPos.y() - m_org_cenY);
+ }
+ }
+ }
+
+ m_translateX += rotX(dx, dy);
+ m_translateY += rotY(dx, dy);
+
+ paintOutline();
+ }
+ else
+ {
+ if(det(mousePos - topleft, topright - topleft)>0)
+ m_function = ROTATE;
+ else if(det(mousePos - topright, bottomright - topright)>0)
+ m_function = ROTATE;
+ else if(det(mousePos - bottomright, bottomleft - bottomright)>0)
+ m_function = ROTATE;
+ else if(det(mousePos - bottomleft, topleft - bottomleft)>0)
+ m_function = ROTATE;
+ else
+ m_function = MOVE;
+
+ int handleradius = int( 25 / (m_subject->zoomFactor() * m_subject->zoomFactor()) );
+
+ if(distsq(mousePos, (m_topleft + m_topright)/2)<=handleradius)
+ m_function = TOPSCALE;
+ if(distsq(mousePos, m_topright)<=handleradius)
+ m_function = TOPRIGHTSCALE;
+ if(distsq(mousePos, (m_topright + m_bottomright)/2)<=handleradius)
+ m_function = RIGHTSCALE;
+ if(distsq(mousePos, m_bottomright)<=handleradius)
+ m_function = BOTTOMRIGHTSCALE;
+ if(distsq(mousePos, (m_bottomleft + m_bottomright)/2)<=handleradius)
+ m_function = BOTTOMSCALE;
+ if(distsq(mousePos, m_bottomleft)<=handleradius)
+ m_function = BOTTOMLEFTSCALE;
+ if(distsq(mousePos, (m_topleft + m_bottomleft)/2)<=handleradius)
+ m_function = LEFTSCALE;
+ if(distsq(mousePos, m_topleft)<=handleradius)
+ m_function = TOPLEFTSCALE;
+
+ setFunctionalCursor();
+ }
+ }
+}
+
+void KisToolTransform::buttonRelease(KisButtonReleaseEvent *e)
+{
+ if (m_subject && e->button() == Qt::LeftButton) {
+ if(!m_wasPressed) return;
+ m_wasPressed = false;
+
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img)
+ return;
+
+ m_selecting = false;
+
+ if(m_actualyMoveWhileSelected)
+ {
+ paintOutline();
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ transform();
+ TQApplication::restoreOverrideCursor();
+ }
+ }
+}
+
+void KisToolTransform::paintOutline()
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ KisCanvas *canvas = controller->kiscanvas();
+ KisCanvasPainter gc(canvas);
+ TQRect rc;
+
+ paintOutline(gc, rc);
+ }
+}
+
+void KisToolTransform::recalcOutline()
+{
+ double x,y;
+
+ m_sina = sin(m_a);
+ m_cosa = cos(m_a);
+
+ x = (m_startPos.x() - m_org_cenX) * m_scaleX;
+ y = (m_startPos.y() - m_org_cenY) * m_scaleY;
+ m_topleft = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
+
+ x = (m_endPos.x() - m_org_cenX) * m_scaleX;
+ y = (m_startPos.y() - m_org_cenY) * m_scaleY;
+ m_topright = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
+
+ x = (m_startPos.x() - m_org_cenX) * m_scaleX;
+ y = (m_endPos.y() - m_org_cenY) * m_scaleY;
+ m_bottomleft = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
+
+ x = (m_endPos.x() - m_org_cenX) * m_scaleX;
+ y = (m_endPos.y() - m_org_cenY) * m_scaleY;
+ m_bottomright = TQPoint(int(rotX(x,y) + m_translateX+0.5), int(rotY(x,y) + m_translateY+0.5));
+}
+
+void KisToolTransform::paintOutline(KisCanvasPainter& gc, const TQRect&)
+{
+ if (m_subject) {
+ KisCanvasController *controller = m_subject->canvasController();
+ RasterOp op = gc.rasterOp();
+ TQPen old = gc.pen();
+ TQPen pen(TQt::SolidLine);
+ pen.setWidth(1);
+ Q_ASSERT(controller);
+
+ recalcOutline();
+ TQPoint topleft = controller->windowToView(m_topleft);
+ TQPoint topright = controller->windowToView(m_topright);
+ TQPoint bottomleft = controller->windowToView(m_bottomleft);
+ TQPoint bottomright = controller->windowToView(m_bottomright);
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.drawRect(topleft.x()-4, topleft.y()-4, 8, 8);
+ gc.drawLine(topleft.x(), topleft.y(), (topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2);
+ gc.drawRect((topleft.x()+topright.x())/2-4, (topleft.y()+topright.y())/2-4, 8, 8);
+ gc.drawLine((topleft.x()+topright.x())/2, (topleft.y()+topright.y())/2, topright.x(), topright.y());
+ gc.drawRect(topright.x()-4, topright.y()-4, 8, 8);
+ gc.drawLine(topright.x(), topright.y(), (topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2);
+ gc.drawRect((topright.x()+bottomright.x())/2-4, (topright.y()+bottomright.y())/2-4, 8, 8);
+ gc.drawLine((topright.x()+bottomright.x())/2, (topright.y()+bottomright.y())/2,bottomright.x(), bottomright.y());
+ gc.drawRect(bottomright.x()-4, bottomright.y()-4, 8, 8);
+ gc.drawLine(bottomright.x(), bottomright.y(), (bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2);
+ gc.drawRect((bottomleft.x()+bottomright.x())/2-4, (bottomleft.y()+bottomright.y())/2-4, 8, 8);
+ gc.drawLine((bottomleft.x()+bottomright.x())/2, (bottomleft.y()+bottomright.y())/2, bottomleft.x(), bottomleft.y());
+ gc.drawRect(bottomleft.x()-4, bottomleft.y()-4, 8, 8);
+ gc.drawLine(bottomleft.x(), bottomleft.y(), (topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2);
+ gc.drawRect((topleft.x()+bottomleft.x())/2-4, (topleft.y()+bottomleft.y())/2-4, 8, 8);
+ gc.drawLine((topleft.x()+bottomleft.x())/2, (topleft.y()+bottomleft.y())/2, topleft.x(), topleft.y());
+ gc.setRasterOp(op);
+ gc.setPen(old);
+ }
+}
+
+void KisToolTransform::transform()
+{
+
+ KisImageSP img = m_subject->currentImg();
+
+ if (!img || !img->activeDevice())
+ return;
+
+ double tx = m_translateX - rotX(m_org_cenX * m_scaleX, m_org_cenY * m_scaleY);
+ double ty = m_translateY - rotY(m_org_cenX * m_scaleX, m_org_cenY * m_scaleY);
+ KisProgressDisplayInterface *progress = m_subject->progressDisplay();
+
+ // This mementoes the current state of the active device.
+ TransformCmd * transaction = new TransformCmd(this, img->activeDevice(), m_origDevice,
+ m_scaleX, m_scaleY, m_translateX, m_translateY, m_a, m_origSelection, m_startPos, m_endPos);
+
+ // Copy the original state back.
+ TQRect rc = m_origDevice->extent();
+ rc = rc.normalize();
+ img->activeDevice()->clear();
+ KisPainter gc(img->activeDevice());
+ gc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origDevice, rc.x(), rc.y(), rc.width(), rc.height());
+ gc.end();
+
+ // Also restore the original selection.
+ if(m_origSelection)
+ {
+ //TQRect rc = m_origSelection->extent();
+ TQRect rc = m_origSelection->selectedRect();
+ rc = rc.normalize();
+ img->activeDevice()->selection()->clear();
+ KisPainter sgc(img->activeDevice()->selection().data());
+ sgc.bitBlt(rc.x(), rc.y(), COMPOSITE_COPY, m_origSelection.data(), rc.x(), rc.y(), rc.width(), rc.height());
+ sgc.end();
+ }
+ else
+ if(img->activeDevice()->hasSelection())
+ img->activeDevice()->selection()->clear();
+
+ // Perform the transform. Since we copied the original state back, this doesn't degrade
+ // after many tweaks. Since we started the transaction before the copy back, the memento
+ // has the previous state.
+ KisTransformWorker t(img->activeDevice(), m_scaleX, m_scaleY, 0, 0, m_a, int(tx), int(ty), progress, m_filter);
+ t.run();
+
+ // If canceled, go back to the memento
+ if(t.isCanceled())
+ {
+ transaction->unexecute();
+ delete transaction;
+ return;
+ }
+
+ img->activeDevice()->setDirty(rc); // XXX: This is not enough - should union with new extent
+
+ // Else add the command -- this will have the memento from the previous state,
+ // and the transformed state from the original device we cached in our activated()
+ // method.
+ if (transaction) {
+ if (img->undo())
+ img->undoAdapter()->addCommand(transaction);
+ else
+ delete transaction;
+ }
+}
+
+void KisToolTransform::notifyCommandAdded( KCommand * command)
+{
+ TransformCmd * cmd = dynamic_cast<TransformCmd*>(command);
+ if (cmd == 0) {
+ // The last added command wasn't one of ours;
+ // we should reset to the new state of the canvas.
+ // In effect we should treat this as if the tool has been just activated
+ initHandles();
+ }
+}
+
+void KisToolTransform::notifyCommandExecuted( KCommand * command)
+{
+ Q_UNUSED(command);
+ TransformCmd * cmd=0;
+
+ if(m_subject->currentImg()->undoAdapter()->presentCommand())
+ cmd = dynamic_cast<TransformCmd*>(m_subject->currentImg()->undoAdapter()->presentCommand());
+
+ if (cmd == 0) {
+ // The command now on the top of the stack isn't one of ours
+ // We should treat this as if the tool has been just activated
+ initHandles();
+ }
+ else
+ {
+ // One of our commands is now on top
+ // We should ask for tool args and orig selection
+ cmd->transformArgs(m_scaleX, m_scaleY, m_translateX, m_translateY, m_a);
+ m_origSelection = cmd->origSelection(m_startPos, m_endPos);
+ m_origDevice = cmd->origDevice();
+ m_org_cenX = (m_startPos.x() + m_endPos.x()) / 2.0;
+ m_org_cenY = (m_startPos.y() + m_endPos.y()) / 2.0;
+ m_subject->canvasController() ->updateCanvas();
+ }
+}
+
+void KisToolTransform::slotSetFilter(const KisID &filterID)
+{
+ m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
+}
+
+void KisToolTransform::slotLayerActivated(KisLayerSP)
+{
+ activate();
+}
+
+
+TQWidget* KisToolTransform::createOptionWidget(TQWidget* parent)
+{
+
+ m_optWidget = new WdgToolTransform(parent);
+ TQ_CHECK_PTR(m_optWidget);
+
+ m_optWidget->cmbFilter->clear();
+ m_optWidget->cmbFilter->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
+
+ m_optWidget->cmbFilter->setCurrentText("Mitchell");
+ connect(m_optWidget->cmbFilter, TQT_SIGNAL(activated(const KisID &)),
+ this, TQT_SLOT(slotSetFilter(const KisID &)));
+
+ KisID filterID = m_optWidget->cmbFilter->currentItem();
+ m_filter = KisFilterStrategyRegistry::instance()->get(filterID);
+
+/*
+ connect(m_optWidget->intStartX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartX(int)));
+ connect(m_optWidget->intStartY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setStartY(int)));
+ connect(m_optWidget->intEndX, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndX(int)));
+ connect(m_optWidget->intEndY, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(setEndY(int)));
+*/
+ m_optWidget->intStartX->hide();
+ m_optWidget->intStartY->hide();
+ m_optWidget->intEndX->hide();
+ m_optWidget->intEndY->hide();
+ m_optWidget->textLabel1->hide();
+ m_optWidget->textLabel2->hide();
+ m_optWidget->textLabel3->hide();
+ m_optWidget->textLabel4->hide();
+ return m_optWidget;
+}
+
+TQWidget* KisToolTransform::optionWidget()
+{
+ return m_optWidget;
+}
+
+void KisToolTransform::setup(TDEActionCollection *collection)
+{
+ m_action = static_cast<TDERadioAction *>(collection->action(name()));
+
+ if (m_action == 0) {
+ m_action = new TDERadioAction(i18n("&Transform"),
+ "tool_transform",
+ 0,
+ this,
+ TQT_SLOT(activate()),
+ collection,
+ name());
+ TQ_CHECK_PTR(m_action);
+ m_action->setToolTip(i18n("Transform a layer or a selection"));
+ m_action->setExclusiveGroup("tools");
+ m_ownAction = true;
+ }
+}
+
+#include "kis_tool_transform.moc"
diff --git a/chalk/plugins/tools/tool_transform/tool_transform.cc b/chalk/plugins/tools/tool_transform/tool_transform.cc
deleted file mode 100644
index 82941e92c..000000000
--- a/chalk/plugins/tools/tool_transform/tool_transform.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * tool_transform.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-#include <vector>
-
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_tool_registry.h>
-
-#include "tool_transform.h"
-#include "kis_tool_transform.h"
-
-
-typedef KGenericFactory<ToolTransform> ToolTransformFactory;
-K_EXPORT_COMPONENT_FACTORY( chalktooltransform, ToolTransformFactory( "chalk" ) )
-
-
-ToolTransform::ToolTransform(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- setInstance(ToolTransformFactory::instance());
-
- if ( parent->inherits("KisToolRegistry") )
- {
- KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
- KisToolTransformFactory * f = new KisToolTransformFactory();
- TQ_CHECK_PTR(f);
- r->add(f);
- }
-
-}
-
-ToolTransform::~ToolTransform()
-{
-}
-
-#include "tool_transform.moc"
diff --git a/chalk/plugins/tools/tool_transform/tool_transform.cpp b/chalk/plugins/tools/tool_transform/tool_transform.cpp
new file mode 100644
index 000000000..0f0dde27d
--- /dev/null
+++ b/chalk/plugins/tools/tool_transform/tool_transform.cpp
@@ -0,0 +1,64 @@
+/*
+ * tool_transform.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <vector>
+
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_tool_registry.h>
+
+#include "tool_transform.h"
+#include "kis_tool_transform.h"
+
+
+typedef KGenericFactory<ToolTransform> ToolTransformFactory;
+K_EXPORT_COMPONENT_FACTORY( chalktooltransform, ToolTransformFactory( "chalk" ) )
+
+
+ToolTransform::ToolTransform(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(ToolTransformFactory::instance());
+
+ if ( parent->inherits("KisToolRegistry") )
+ {
+ KisToolRegistry * r = dynamic_cast<KisToolRegistry*>(parent);
+ KisToolTransformFactory * f = new KisToolTransformFactory();
+ TQ_CHECK_PTR(f);
+ r->add(f);
+ }
+
+}
+
+ToolTransform::~ToolTransform()
+{
+}
+
+#include "tool_transform.moc"
diff --git a/chalk/plugins/viewplugins/colorrange/Makefile.am b/chalk/plugins/viewplugins/colorrange/Makefile.am
index 1c8547e29..c072f78cb 100644
--- a/chalk/plugins/viewplugins/colorrange/Makefile.am
+++ b/chalk/plugins/viewplugins/colorrange/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkcolorrange.la
-chalkcolorrange_la_SOURCES = colorrange.cc dlg_colorrange.cc wdg_colorrange.ui
+chalkcolorrange_la_SOURCES = colorrange.cpp dlg_colorrange.cpp wdg_colorrange.ui
noinst_HEADERS = wdg_colorrange.h dlg_colorrange.h colorrange.h
chalkcolorrange_la_LIBADD = $(LIB_KOFFICEUI) ../../../libchalkcommon.la \
diff --git a/chalk/plugins/viewplugins/colorrange/colorrange.cc b/chalk/plugins/viewplugins/colorrange/colorrange.cpp
index be0648bab..be0648bab 100644
--- a/chalk/plugins/viewplugins/colorrange/colorrange.cc
+++ b/chalk/plugins/viewplugins/colorrange/colorrange.cpp
diff --git a/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cc b/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cc
deleted file mode 100644
index 453bbec27..000000000
--- a/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cc
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * dlg_colorrange.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqapplication.h>
-#include <tqpushbutton.h>
-#include <tqcheckbox.h>
-#include <tqslider.h>
-#include <tqcombobox.h>
-#include <tqpixmap.h>
-#include <tqimage.h>
-#include <tqlabel.h>
-#include <tqcolor.h>
-#include <tqradiobutton.h>
-
-#include <knuminput.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-#include <tdeaction.h>
-
-#include <kis_canvas_subject.h>
-#include <kis_iterators_pixel.h>
-#include <kis_layer.h>
-#include <kis_paint_device.h>
-#include <kis_selection.h>
-#include <kis_selection_manager.h>
-#include <kis_types.h>
-#include <kis_undo_adapter.h>
-#include <kis_view.h>
-#include <kis_colorspace.h>
-#include <kis_profile.h>
-#include <kis_color_conversions.h>
-#include <kis_selected_transaction.h>
-#include <kis_cursor.h>
-
-#include "dlg_colorrange.h"
-#include "wdg_colorrange.h"
-
-namespace {
-
-// XXX: Poynton says: hsv/hls is not what one ought to use for colour calculations.
-// Unfortunately, I don't know enough to be able to use anything else.
-
- bool isReddish(int h)
- {
- return ((h > 330 && h < 360) || ( h > 0 && h < 40));
- }
-
- bool isYellowish(int h)
- {
- return (h> 40 && h < 65);
- }
-
- bool isGreenish(int h)
- {
- return (h > 70 && h < 155);
- }
-
- bool isCyanish(int h)
- {
- return (h > 150 && h < 190);
- }
-
- bool isBlueish(int h)
- {
- return (h > 185 && h < 270);
- }
-
- bool isMagentaish(int h)
- {
- return (h > 265 && h < 330);
- }
-
- bool isHighlight(int v)
- {
- return (v > 200);
- }
-
- bool isMidTone(int v)
- {
- return (v > 100 && v < 200);
- }
-
- bool isShadow(int v)
- {
- return (v < 100);
- }
-
-}
-
-TQ_UINT32 matchColors(const TQColor & c, enumAction action)
-{
- int r = c.red();
- int g = c.green();
- int b = c.blue();
-
- int h, s, v;
- rgb_to_hsv(r, g, b, &h, &s, &v);
-
-
-
- // XXX: Map the degree in which the colors conform to the requirement
- // to a range of selectedness between 0 and 255
-
- // XXX: Implement out-of-gamut using lcms
-
- switch(action) {
-
- case REDS:
- if (isReddish(h))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case YELLOWS:
- if (isYellowish(h)) {
- return MAX_SELECTED;
- }
- else
- return MIN_SELECTED;
- case GREENS:
- if (isGreenish(h))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case CYANS:
- if (isCyanish(h))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case BLUES:
- if (isBlueish(h))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case MAGENTAS:
- if (isMagentaish(h))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case HIGHLIGHTS:
- if (isHighlight(v))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case MIDTONES:
- if (isMidTone(v))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- case SHADOWS:
- if (isShadow(v))
- return MAX_SELECTED;
- else
- return MIN_SELECTED;
- };
-
- return MIN_SELECTED;
-}
-
-
-
-DlgColorRange::DlgColorRange( KisView * view, KisPaintDeviceSP dev, TQWidget * parent, const char * name)
- : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
-{
- m_dev = dev;
- m_view = view;
-
- m_subject = view->canvasSubject();
-
- m_page = new WdgColorRange(this, "color_range");
- TQ_CHECK_PTR(m_page);
-
- setCaption(i18n("Color Range"));
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- if (m_dev->image()->undo()) m_transaction = new KisSelectedTransaction(i18n("Select by Color Range"), m_dev);
-
- if(! m_dev->hasSelection())
- m_dev->selection()->clear();
- m_selection = m_dev->selection();
-
- updatePreview();
-
- m_invert = false;
- m_mode = SELECTION_ADD;
- m_currentAction = REDS;
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
- connect(this, TQT_SIGNAL(cancelClicked()),
- this, TQT_SLOT(cancelClicked()));
-
- connect(m_page->chkInvert, TQT_SIGNAL(clicked()),
- this, TQT_SLOT(slotInvertClicked()));
-
- connect(m_page->cmbSelect, TQT_SIGNAL(activated(int)),
- this, TQT_SLOT(slotSelectionTypeChanged(int)));
-
- connect (m_page->radioAdd, TQT_SIGNAL(toggled(bool)),
- this, TQT_SLOT(slotAdd(bool)));
-
- connect (m_page->radioSubtract, TQT_SIGNAL(toggled(bool)),
- this, TQT_SLOT(slotSubtract(bool)));
-
- connect (m_page->bnSelect, TQT_SIGNAL(clicked()),
- this, TQT_SLOT(slotSelectClicked()));
-
- connect (m_page->bnDeselect, TQT_SIGNAL(clicked()),
- this, TQT_SLOT(slotDeselectClicked()));
-
-}
-
-DlgColorRange::~DlgColorRange()
-{
- delete m_page;
-}
-
-
-void DlgColorRange::updatePreview()
-{
- if (!m_selection) return;
-
- TQ_INT32 x, y, w, h;
- m_dev->exactBounds(x, y, w, h);
- TQPixmap pix = TQPixmap(m_selection->maskImage().smoothScale(350, 350, TQ_ScaleMin));
- m_subject->canvasController()->updateCanvas();
- m_page->pixSelection->setPixmap(pix);
-}
-
-void DlgColorRange::okClicked()
-{
- m_dev->setDirty();
- m_dev->emitSelectionChanged();
-
- if (m_dev->image()->undo()) m_subject->undoAdapter()->addCommand(m_transaction);
- accept();
-}
-
-void DlgColorRange::cancelClicked()
-{
- if (m_dev->image()->undo()) m_transaction->unexecute();
-
- m_subject->canvasController()->updateCanvas();
- reject();
-}
-
-void DlgColorRange::slotInvertClicked()
-{
- m_invert = m_page->chkInvert->isChecked();
-}
-
-void DlgColorRange::slotSelectionTypeChanged(int index)
-{
- m_currentAction = (enumAction)index;
-}
-
-void DlgColorRange::slotSubtract(bool on)
-{
- if (on)
- m_mode = SELECTION_SUBTRACT;
-}
-void DlgColorRange::slotAdd(bool on)
-{
- if (on)
- m_mode = SELECTION_ADD;
-}
-
-void DlgColorRange::slotSelectClicked()
-{
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- // XXX: Multithread this!
- TQ_INT32 x, y, w, h;
- m_dev->exactBounds(x, y, w, h);
- KisColorSpace * cs = m_dev->colorSpace();
- TQ_UINT8 opacity;
- for (int y2 = y; y2 < h - y; ++y2) {
- KisHLineIterator hiter = m_dev->createHLineIterator(x, y2, w, false);
- KisHLineIterator selIter = m_selection ->createHLineIterator(x, y2, w, true);
- while (!hiter.isDone()) {
- TQColor c;
-
- cs->toTQColor(hiter.rawData(), &c, &opacity);
- // Don't try to select transparent pixels.
- if (opacity > OPACITY_TRANSPARENT) {
- TQ_UINT8 match = matchColors(c, m_currentAction);
-
- if (match) {
- // Personally, I think the invert option a bit silly. But it's possible I don't quite understand it. BSAR.
- if (!m_invert) {
- if (m_mode == SELECTION_ADD) {
- *(selIter.rawData()) = match;
- }
- else if (m_mode == SELECTION_SUBTRACT) {
- TQ_UINT8 selectedness = *(selIter.rawData());
- if (match < selectedness) {
- *(selIter.rawData()) = selectedness - match;
- }
- else {
- *(selIter.rawData()) = 0;
- }
- }
- }
- else {
- if (m_mode == SELECTION_ADD) {
- TQ_UINT8 selectedness = *(selIter.rawData());
- if (match < selectedness) {
- *(selIter.rawData()) = selectedness - match;
- }
- else {
- *(selIter.rawData()) = 0;
- }
- }
- else if (m_mode == SELECTION_SUBTRACT) {
- *(selIter.rawData()) = match;
- }
- }
- }
- }
- ++hiter;
- ++selIter;
- }
- }
- updatePreview();
- TQApplication::restoreOverrideCursor();
-}
-
-void DlgColorRange::slotDeselectClicked()
-{
- m_dev->selection()->clear();
- updatePreview();
-}
-
-
-#include "dlg_colorrange.moc"
diff --git a/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cpp b/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cpp
new file mode 100644
index 000000000..82748f4c8
--- /dev/null
+++ b/chalk/plugins/viewplugins/colorrange/dlg_colorrange.cpp
@@ -0,0 +1,351 @@
+/*
+ * dlg_colorrange.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqapplication.h>
+#include <tqpushbutton.h>
+#include <tqcheckbox.h>
+#include <tqslider.h>
+#include <tqcombobox.h>
+#include <tqpixmap.h>
+#include <tqimage.h>
+#include <tqlabel.h>
+#include <tqcolor.h>
+#include <tqradiobutton.h>
+
+#include <knuminput.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+#include <tdeaction.h>
+
+#include <kis_canvas_subject.h>
+#include <kis_iterators_pixel.h>
+#include <kis_layer.h>
+#include <kis_paint_device.h>
+#include <kis_selection.h>
+#include <kis_selection_manager.h>
+#include <kis_types.h>
+#include <kis_undo_adapter.h>
+#include <kis_view.h>
+#include <kis_colorspace.h>
+#include <kis_profile.h>
+#include <kis_color_conversions.h>
+#include <kis_selected_transaction.h>
+#include <kis_cursor.h>
+
+#include "dlg_colorrange.h"
+#include "wdg_colorrange.h"
+
+namespace {
+
+// XXX: Poynton says: hsv/hls is not what one ought to use for colour calculations.
+// Unfortunately, I don't know enough to be able to use anything else.
+
+ bool isReddish(int h)
+ {
+ return ((h > 330 && h < 360) || ( h > 0 && h < 40));
+ }
+
+ bool isYellowish(int h)
+ {
+ return (h> 40 && h < 65);
+ }
+
+ bool isGreenish(int h)
+ {
+ return (h > 70 && h < 155);
+ }
+
+ bool isCyanish(int h)
+ {
+ return (h > 150 && h < 190);
+ }
+
+ bool isBlueish(int h)
+ {
+ return (h > 185 && h < 270);
+ }
+
+ bool isMagentaish(int h)
+ {
+ return (h > 265 && h < 330);
+ }
+
+ bool isHighlight(int v)
+ {
+ return (v > 200);
+ }
+
+ bool isMidTone(int v)
+ {
+ return (v > 100 && v < 200);
+ }
+
+ bool isShadow(int v)
+ {
+ return (v < 100);
+ }
+
+}
+
+TQ_UINT32 matchColors(const TQColor & c, enumAction action)
+{
+ int r = c.red();
+ int g = c.green();
+ int b = c.blue();
+
+ int h, s, v;
+ rgb_to_hsv(r, g, b, &h, &s, &v);
+
+
+
+ // XXX: Map the degree in which the colors conform to the requirement
+ // to a range of selectedness between 0 and 255
+
+ // XXX: Implement out-of-gamut using lcms
+
+ switch(action) {
+
+ case REDS:
+ if (isReddish(h))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case YELLOWS:
+ if (isYellowish(h)) {
+ return MAX_SELECTED;
+ }
+ else
+ return MIN_SELECTED;
+ case GREENS:
+ if (isGreenish(h))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case CYANS:
+ if (isCyanish(h))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case BLUES:
+ if (isBlueish(h))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case MAGENTAS:
+ if (isMagentaish(h))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case HIGHLIGHTS:
+ if (isHighlight(v))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case MIDTONES:
+ if (isMidTone(v))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ case SHADOWS:
+ if (isShadow(v))
+ return MAX_SELECTED;
+ else
+ return MIN_SELECTED;
+ };
+
+ return MIN_SELECTED;
+}
+
+
+
+DlgColorRange::DlgColorRange( KisView * view, KisPaintDeviceSP dev, TQWidget * parent, const char * name)
+ : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
+{
+ m_dev = dev;
+ m_view = view;
+
+ m_subject = view->canvasSubject();
+
+ m_page = new WdgColorRange(this, "color_range");
+ TQ_CHECK_PTR(m_page);
+
+ setCaption(i18n("Color Range"));
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ if (m_dev->image()->undo()) m_transaction = new KisSelectedTransaction(i18n("Select by Color Range"), m_dev);
+
+ if(! m_dev->hasSelection())
+ m_dev->selection()->clear();
+ m_selection = m_dev->selection();
+
+ updatePreview();
+
+ m_invert = false;
+ m_mode = SELECTION_ADD;
+ m_currentAction = REDS;
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+ connect(this, TQT_SIGNAL(cancelClicked()),
+ this, TQT_SLOT(cancelClicked()));
+
+ connect(m_page->chkInvert, TQT_SIGNAL(clicked()),
+ this, TQT_SLOT(slotInvertClicked()));
+
+ connect(m_page->cmbSelect, TQT_SIGNAL(activated(int)),
+ this, TQT_SLOT(slotSelectionTypeChanged(int)));
+
+ connect (m_page->radioAdd, TQT_SIGNAL(toggled(bool)),
+ this, TQT_SLOT(slotAdd(bool)));
+
+ connect (m_page->radioSubtract, TQT_SIGNAL(toggled(bool)),
+ this, TQT_SLOT(slotSubtract(bool)));
+
+ connect (m_page->bnSelect, TQT_SIGNAL(clicked()),
+ this, TQT_SLOT(slotSelectClicked()));
+
+ connect (m_page->bnDeselect, TQT_SIGNAL(clicked()),
+ this, TQT_SLOT(slotDeselectClicked()));
+
+}
+
+DlgColorRange::~DlgColorRange()
+{
+ delete m_page;
+}
+
+
+void DlgColorRange::updatePreview()
+{
+ if (!m_selection) return;
+
+ TQ_INT32 x, y, w, h;
+ m_dev->exactBounds(x, y, w, h);
+ TQPixmap pix = TQPixmap(m_selection->maskImage().smoothScale(350, 350, TQ_ScaleMin));
+ m_subject->canvasController()->updateCanvas();
+ m_page->pixSelection->setPixmap(pix);
+}
+
+void DlgColorRange::okClicked()
+{
+ m_dev->setDirty();
+ m_dev->emitSelectionChanged();
+
+ if (m_dev->image()->undo()) m_subject->undoAdapter()->addCommand(m_transaction);
+ accept();
+}
+
+void DlgColorRange::cancelClicked()
+{
+ if (m_dev->image()->undo()) m_transaction->unexecute();
+
+ m_subject->canvasController()->updateCanvas();
+ reject();
+}
+
+void DlgColorRange::slotInvertClicked()
+{
+ m_invert = m_page->chkInvert->isChecked();
+}
+
+void DlgColorRange::slotSelectionTypeChanged(int index)
+{
+ m_currentAction = (enumAction)index;
+}
+
+void DlgColorRange::slotSubtract(bool on)
+{
+ if (on)
+ m_mode = SELECTION_SUBTRACT;
+}
+void DlgColorRange::slotAdd(bool on)
+{
+ if (on)
+ m_mode = SELECTION_ADD;
+}
+
+void DlgColorRange::slotSelectClicked()
+{
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ // XXX: Multithread this!
+ TQ_INT32 x, y, w, h;
+ m_dev->exactBounds(x, y, w, h);
+ KisColorSpace * cs = m_dev->colorSpace();
+ TQ_UINT8 opacity;
+ for (int y2 = y; y2 < h - y; ++y2) {
+ KisHLineIterator hiter = m_dev->createHLineIterator(x, y2, w, false);
+ KisHLineIterator selIter = m_selection ->createHLineIterator(x, y2, w, true);
+ while (!hiter.isDone()) {
+ TQColor c;
+
+ cs->toTQColor(hiter.rawData(), &c, &opacity);
+ // Don't try to select transparent pixels.
+ if (opacity > OPACITY_TRANSPARENT) {
+ TQ_UINT8 match = matchColors(c, m_currentAction);
+
+ if (match) {
+ // Personally, I think the invert option a bit silly. But it's possible I don't quite understand it. BSAR.
+ if (!m_invert) {
+ if (m_mode == SELECTION_ADD) {
+ *(selIter.rawData()) = match;
+ }
+ else if (m_mode == SELECTION_SUBTRACT) {
+ TQ_UINT8 selectedness = *(selIter.rawData());
+ if (match < selectedness) {
+ *(selIter.rawData()) = selectedness - match;
+ }
+ else {
+ *(selIter.rawData()) = 0;
+ }
+ }
+ }
+ else {
+ if (m_mode == SELECTION_ADD) {
+ TQ_UINT8 selectedness = *(selIter.rawData());
+ if (match < selectedness) {
+ *(selIter.rawData()) = selectedness - match;
+ }
+ else {
+ *(selIter.rawData()) = 0;
+ }
+ }
+ else if (m_mode == SELECTION_SUBTRACT) {
+ *(selIter.rawData()) = match;
+ }
+ }
+ }
+ }
+ ++hiter;
+ ++selIter;
+ }
+ }
+ updatePreview();
+ TQApplication::restoreOverrideCursor();
+}
+
+void DlgColorRange::slotDeselectClicked()
+{
+ m_dev->selection()->clear();
+ updatePreview();
+}
+
+
+#include "dlg_colorrange.moc"
diff --git a/chalk/plugins/viewplugins/colorspaceconversion/Makefile.am b/chalk/plugins/viewplugins/colorspaceconversion/Makefile.am
index 7439813c2..06b2ab88f 100644
--- a/chalk/plugins/viewplugins/colorspaceconversion/Makefile.am
+++ b/chalk/plugins/viewplugins/colorspaceconversion/Makefile.am
@@ -14,7 +14,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkcolorspaceconversion.la
-chalkcolorspaceconversion_la_SOURCES = wdgconvertcolorspace.ui colorspaceconversion.cc dlg_colorspaceconversion.cc
+chalkcolorspaceconversion_la_SOURCES = wdgconvertcolorspace.ui colorspaceconversion.cpp dlg_colorspaceconversion.cpp
noinst_HEADERS = wdgconvertcolorspace.h dlg_colorspaceconversion.h colorspaceconversion.h
chalkcolorspaceconversion_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cc b/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cc
deleted file mode 100644
index d956ee460..000000000
--- a/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cc
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * colorspaceconversion.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <stdlib.h>
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqbuttongroup.h>
-#include <tqapplication.h>
-#include <tqcursor.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_cursor.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include "kis_meta_registry.h"
-#include <kis_view.h>
-#include <kis_paint_device.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_cmb_idlist.h>
-#include <squeezedcombobox.h>
-
-#include "colorspaceconversion.h"
-#include "dlg_colorspaceconversion.h"
-#include "wdgconvertcolorspace.h"
-
-typedef KGenericFactory<ColorSpaceConversion> ColorSpaceConversionFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkcolorspaceconversion, ColorSpaceConversionFactory( "chalk" ) )
-
-
-ColorSpaceConversion::ColorSpaceConversion(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
-
- if ( parent->inherits("KisView") )
- {
- m_view = (KisView*) parent;
-
- setInstance(ColorSpaceConversionFactory::instance());
- setXMLFile(locate("data","chalkplugins/colorspaceconversion.rc"), true);
-
- (void) new TDEAction(i18n("&Convert Image Type..."), 0, 0, this, TQT_SLOT(slotImgColorSpaceConversion()), actionCollection(), "imgcolorspaceconversion");
- (void) new TDEAction(i18n("&Convert Layer Type..."), 0, 0, this, TQT_SLOT(slotLayerColorSpaceConversion()), actionCollection(), "layercolorspaceconversion");
-
- }
-}
-
-ColorSpaceConversion::~ColorSpaceConversion()
-{
- m_view = 0;
-}
-
-void ColorSpaceConversion::slotImgColorSpaceConversion()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
-
- if (image->colorSpace()->willDegrade(TO_LAB16)) {
- if (KMessageBox::warningContinueCancel(m_view,
- i18n("This conversion will convert your %1 image through 16-bit L*a*b* and back.\n"
- "Watercolor and openEXR colorspaces will even be converted through 8-bit RGB.\n")
- .arg(image->colorSpace()->id().name()),
- i18n("Colorspace Conversion"),
- KGuiItem(i18n("Continue")),
- "lab16degradation") != KMessageBox::Continue) return;
-
- }
-
- DlgColorSpaceConversion * dlgColorSpaceConversion = new DlgColorSpaceConversion(m_view, "ColorSpaceConversion");
- TQ_CHECK_PTR(dlgColorSpaceConversion);
-
- dlgColorSpaceConversion->setCaption(i18n("Convert All Layers From ") + image->colorSpace()->id().name());
-
- if (dlgColorSpaceConversion->exec() == TQDialog::Accepted) {
- // XXX: Do the rest of the stuff
- KisID cspace = dlgColorSpaceConversion->m_page->cmbColorSpaces->currentItem();
- KisColorSpace * cs = KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace, dlgColorSpaceConversion->m_page->cmbDestProfile->currentText());
-
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- image->convertTo(cs, dlgColorSpaceConversion->m_page->grpIntent->selectedId());
- TQApplication::restoreOverrideCursor();
- }
- delete dlgColorSpaceConversion;
-}
-
-void ColorSpaceConversion::slotLayerColorSpaceConversion()
-{
-
- KisImageSP image = m_view->canvasSubject()->currentImg();
- if (!image) return;
-
- KisPaintDeviceSP dev = image->activeDevice();
- if (!dev) return;
-
- if (dev->colorSpace()->willDegrade(TO_LAB16)) {
- if (KMessageBox::warningContinueCancel(m_view,
- i18n("This conversion will convert your %1 layer through 16-bit L*a*b* and back.\n"
- "Watercolor and openEXR colorspaces will even be converted through 8-bit RGB.\n")
- .arg(dev->colorSpace()->id().name()),
- i18n("Colorspace Conversion"),
- KGuiItem(i18n("Continue")),
- "lab16degradation") != KMessageBox::Continue) return;
-
- }
-
- DlgColorSpaceConversion * dlgColorSpaceConversion = new DlgColorSpaceConversion(m_view, "ColorSpaceConversion");
- TQ_CHECK_PTR(dlgColorSpaceConversion);
-
- dlgColorSpaceConversion->setCaption(i18n("Convert Current Layer From") + dev->colorSpace()->id().name());
-
- if (dlgColorSpaceConversion->exec() == TQDialog::Accepted) {
- KisID cspace = dlgColorSpaceConversion->m_page->cmbColorSpaces->currentItem();
- KisColorSpace * cs = KisMetaRegistry::instance()->csRegistry() ->
- getColorSpace(cspace, dlgColorSpaceConversion->m_page->cmbDestProfile->currentText());
-
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
- dev->convertTo(cs, dlgColorSpaceConversion->m_page->grpIntent->selectedId());
- TQApplication::restoreOverrideCursor();
- }
- delete dlgColorSpaceConversion;
-}
-
-#include "colorspaceconversion.moc"
diff --git a/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cpp b/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cpp
new file mode 100644
index 000000000..377f0569d
--- /dev/null
+++ b/chalk/plugins/viewplugins/colorspaceconversion/colorspaceconversion.cpp
@@ -0,0 +1,155 @@
+/*
+ * colorspaceconversion.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqbuttongroup.h>
+#include <tqapplication.h>
+#include <tqcursor.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_cursor.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include "kis_meta_registry.h"
+#include <kis_view.h>
+#include <kis_paint_device.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_cmb_idlist.h>
+#include <squeezedcombobox.h>
+
+#include "colorspaceconversion.h"
+#include "dlg_colorspaceconversion.h"
+#include "wdgconvertcolorspace.h"
+
+typedef KGenericFactory<ColorSpaceConversion> ColorSpaceConversionFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkcolorspaceconversion, ColorSpaceConversionFactory( "chalk" ) )
+
+
+ColorSpaceConversion::ColorSpaceConversion(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+
+ if ( parent->inherits("KisView") )
+ {
+ m_view = (KisView*) parent;
+
+ setInstance(ColorSpaceConversionFactory::instance());
+ setXMLFile(locate("data","chalkplugins/colorspaceconversion.rc"), true);
+
+ (void) new TDEAction(i18n("&Convert Image Type..."), 0, 0, this, TQT_SLOT(slotImgColorSpaceConversion()), actionCollection(), "imgcolorspaceconversion");
+ (void) new TDEAction(i18n("&Convert Layer Type..."), 0, 0, this, TQT_SLOT(slotLayerColorSpaceConversion()), actionCollection(), "layercolorspaceconversion");
+
+ }
+}
+
+ColorSpaceConversion::~ColorSpaceConversion()
+{
+ m_view = 0;
+}
+
+void ColorSpaceConversion::slotImgColorSpaceConversion()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+
+ if (image->colorSpace()->willDegrade(TO_LAB16)) {
+ if (KMessageBox::warningContinueCancel(m_view,
+ i18n("This conversion will convert your %1 image through 16-bit L*a*b* and back.\n"
+ "Watercolor and openEXR colorspaces will even be converted through 8-bit RGB.\n")
+ .arg(image->colorSpace()->id().name()),
+ i18n("Colorspace Conversion"),
+ KGuiItem(i18n("Continue")),
+ "lab16degradation") != KMessageBox::Continue) return;
+
+ }
+
+ DlgColorSpaceConversion * dlgColorSpaceConversion = new DlgColorSpaceConversion(m_view, "ColorSpaceConversion");
+ TQ_CHECK_PTR(dlgColorSpaceConversion);
+
+ dlgColorSpaceConversion->setCaption(i18n("Convert All Layers From ") + image->colorSpace()->id().name());
+
+ if (dlgColorSpaceConversion->exec() == TQDialog::Accepted) {
+ // XXX: Do the rest of the stuff
+ KisID cspace = dlgColorSpaceConversion->m_page->cmbColorSpaces->currentItem();
+ KisColorSpace * cs = KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace, dlgColorSpaceConversion->m_page->cmbDestProfile->currentText());
+
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ image->convertTo(cs, dlgColorSpaceConversion->m_page->grpIntent->selectedId());
+ TQApplication::restoreOverrideCursor();
+ }
+ delete dlgColorSpaceConversion;
+}
+
+void ColorSpaceConversion::slotLayerColorSpaceConversion()
+{
+
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+ if (!image) return;
+
+ KisPaintDeviceSP dev = image->activeDevice();
+ if (!dev) return;
+
+ if (dev->colorSpace()->willDegrade(TO_LAB16)) {
+ if (KMessageBox::warningContinueCancel(m_view,
+ i18n("This conversion will convert your %1 layer through 16-bit L*a*b* and back.\n"
+ "Watercolor and openEXR colorspaces will even be converted through 8-bit RGB.\n")
+ .arg(dev->colorSpace()->id().name()),
+ i18n("Colorspace Conversion"),
+ KGuiItem(i18n("Continue")),
+ "lab16degradation") != KMessageBox::Continue) return;
+
+ }
+
+ DlgColorSpaceConversion * dlgColorSpaceConversion = new DlgColorSpaceConversion(m_view, "ColorSpaceConversion");
+ TQ_CHECK_PTR(dlgColorSpaceConversion);
+
+ dlgColorSpaceConversion->setCaption(i18n("Convert Current Layer From") + dev->colorSpace()->id().name());
+
+ if (dlgColorSpaceConversion->exec() == TQDialog::Accepted) {
+ KisID cspace = dlgColorSpaceConversion->m_page->cmbColorSpaces->currentItem();
+ KisColorSpace * cs = KisMetaRegistry::instance()->csRegistry() ->
+ getColorSpace(cspace, dlgColorSpaceConversion->m_page->cmbDestProfile->currentText());
+
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+ dev->convertTo(cs, dlgColorSpaceConversion->m_page->grpIntent->selectedId());
+ TQApplication::restoreOverrideCursor();
+ }
+ delete dlgColorSpaceConversion;
+}
+
+#include "colorspaceconversion.moc"
diff --git a/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cc b/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cc
deleted file mode 100644
index 8159ad73f..000000000
--- a/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * dlg_colorspaceconversion.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqptrlist.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "kis_meta_registry.h"
-#include <kis_colorspace_factory_registry.h>
-#include "kis_profile.h"
-#include "kis_colorspace.h"
-#include <kis_id.h>
-#include <kis_cmb_idlist.h>
-#include <squeezedcombobox.h>
-
-#include "wdgconvertcolorspace.h"
-#include "dlg_colorspaceconversion.h"
-
-DlgColorSpaceConversion::DlgColorSpaceConversion( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Image Size"), Ok | Cancel, Ok)
-{
- m_page = new WdgConvertColorSpace(this, "colorspace_conversion");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- m_page->cmbColorSpaces->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
-
- fillCmbDestProfile(m_page->cmbColorSpaces->currentItem());
-
- connect(m_page->cmbColorSpaces, TQT_SIGNAL(activated(const KisID &)),
- this, TQT_SLOT(fillCmbDestProfile(const KisID &)));
-
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
-}
-
-DlgColorSpaceConversion::~DlgColorSpaceConversion()
-{
- delete m_page;
-}
-
-// SLOTS
-
-void DlgColorSpaceConversion::okClicked()
-{
- accept();
-}
-
-
-void DlgColorSpaceConversion::fillCmbDestProfile(const KisID & s)
-{
- m_page->cmbDestProfile->clear();
-
- TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor(s);
- TQValueVector<KisProfile *> ::iterator it;
- for ( it = profileList.begin(); it != profileList.end(); ++it ) {
- m_page->cmbDestProfile->insertItem((*it)->productName());
-
- }
-}
-
-
-#include "dlg_colorspaceconversion.moc"
diff --git a/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cpp b/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cpp
new file mode 100644
index 000000000..259c6f470
--- /dev/null
+++ b/chalk/plugins/viewplugins/colorspaceconversion/dlg_colorspaceconversion.cpp
@@ -0,0 +1,91 @@
+/*
+ * dlg_colorspaceconversion.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqptrlist.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "kis_meta_registry.h"
+#include <kis_colorspace_factory_registry.h>
+#include "kis_profile.h"
+#include "kis_colorspace.h"
+#include <kis_id.h>
+#include <kis_cmb_idlist.h>
+#include <squeezedcombobox.h>
+
+#include "wdgconvertcolorspace.h"
+#include "dlg_colorspaceconversion.h"
+
+DlgColorSpaceConversion::DlgColorSpaceConversion( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Image Size"), Ok | Cancel, Ok)
+{
+ m_page = new WdgConvertColorSpace(this, "colorspace_conversion");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ m_page->cmbColorSpaces->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
+
+ fillCmbDestProfile(m_page->cmbColorSpaces->currentItem());
+
+ connect(m_page->cmbColorSpaces, TQT_SIGNAL(activated(const KisID &)),
+ this, TQT_SLOT(fillCmbDestProfile(const KisID &)));
+
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+}
+
+DlgColorSpaceConversion::~DlgColorSpaceConversion()
+{
+ delete m_page;
+}
+
+// SLOTS
+
+void DlgColorSpaceConversion::okClicked()
+{
+ accept();
+}
+
+
+void DlgColorSpaceConversion::fillCmbDestProfile(const KisID & s)
+{
+ m_page->cmbDestProfile->clear();
+
+ TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor(s);
+ TQValueVector<KisProfile *> ::iterator it;
+ for ( it = profileList.begin(); it != profileList.end(); ++it ) {
+ m_page->cmbDestProfile->insertItem((*it)->productName());
+
+ }
+}
+
+
+#include "dlg_colorspaceconversion.moc"
diff --git a/chalk/plugins/viewplugins/dropshadow/Makefile.am b/chalk/plugins/viewplugins/dropshadow/Makefile.am
index fb6c48ce4..3c9728e00 100644
--- a/chalk/plugins/viewplugins/dropshadow/Makefile.am
+++ b/chalk/plugins/viewplugins/dropshadow/Makefile.am
@@ -14,8 +14,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkdropshadow.la
chalkdropshadow_la_SOURCES = wdg_dropshadow.ui \
- kis_dropshadow.cc dlg_dropshadow.cc \
- kis_dropshadow_plugin.cc
+ kis_dropshadow.cpp dlg_dropshadow.cpp \
+ kis_dropshadow_plugin.cpp
noinst_HEADERS = wdg_dropshadow.h kis_dropshadow_plugin.h \
kis_dropshadow.h dlg_dropshadow.h
diff --git a/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cc b/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cc
deleted file mode 100644
index 59019489c..000000000
--- a/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cc
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * dlg_dropshadow.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqbutton.h>
-#include <tqbuttongroup.h>
-#include <tqcheckbox.h>
-#include <tqcolor.h>
-#include <tqcombobox.h>
-#include <tqlabel.h>
-#include <tqradiobutton.h>
-#include <tqslider.h>
-
-#include <kcolorbutton.h>
-#include <tdeconfig.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-
-#include "dlg_dropshadow.h"
-#include "wdg_dropshadow.h"
-
-DlgDropshadow::DlgDropshadow( const TQString & /*imageCS*/,
- const TQString & /*layerCS*/,
- TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Drop Shadow"), Ok | Cancel, Ok)
-{
- m_page = new WdgDropshadow(this, "dropshadow");
- TQ_CHECK_PTR(m_page);
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- TDEConfig * cfg = TDEGlobal::config();
- m_page->xOffsetSpinBox->setValue( cfg->readNumEntry("dropshadow_x", 8) );
- m_page->yOffsetSpinBox->setValue( cfg->readNumEntry("dropshadow_y", 8) );
- m_page->blurRadiusSpinBox->setValue( cfg->readNumEntry("dropshadow_blurRadius", 5) );
- TQColor black(0,0,0);
- m_page->shadowColorButton->setColor( cfg->readColorEntry("dropshadow_color", &black) );
- m_page->opacitySlider->setValue( cfg->readNumEntry("dropshadow_opacity", 80 ) );
- m_page->opacitySpinBox->setValue( cfg->readNumEntry("dropshadow_opacity", 80 ) );
- m_page->allowResizingCheckBox->setChecked( cfg->readBoolEntry("dropshadow_resizing", true ) );
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-}
-
-DlgDropshadow::~DlgDropshadow()
-{
- delete m_page;
-}
-
-TQ_INT32 DlgDropshadow::getXOffset()
-{
- return m_page->xOffsetSpinBox->value();
-}
-
-TQ_INT32 DlgDropshadow::getYOffset()
-{
- return m_page->yOffsetSpinBox->value();
-}
-
-TQ_INT32 DlgDropshadow::getBlurRadius()
-{
- return m_page->blurRadiusSpinBox->value();
-}
-
-TQ_UINT8 DlgDropshadow::getShadowOpacity()
-{
- double opacity = (double)m_page->opacitySpinBox->value();
- //convert percent to a 8 bit opacity value
- return (TQ_UINT8)(opacity / 100 * 255);
-}
-
-TQColor DlgDropshadow::getShadowColor()
-{
- return m_page->shadowColorButton->color();
-}
-
-bool DlgDropshadow::allowResizingChecked()
-{
- return m_page->allowResizingCheckBox->isChecked();
-}
-
-// SLOTS
-
-void DlgDropshadow::okClicked()
-{
- TDEConfig * cfg = TDEGlobal::config();
- cfg->writeEntry("dropshadow_x", m_page->xOffsetSpinBox->value());
- cfg->writeEntry("dropshadow_y", m_page->yOffsetSpinBox->value());
- cfg->writeEntry("dropshadow_blurRadius", m_page->blurRadiusSpinBox->value());
- cfg->writeEntry("dropshadow_color", m_page->shadowColorButton->color());
- cfg->writeEntry("dropshadow_opacity", m_page->opacitySpinBox->value());
- cfg->writeEntry("dropshadow_resizing", m_page->allowResizingCheckBox->isChecked());
-
- accept();
-}
-
-#include "dlg_dropshadow.moc"
diff --git a/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cpp b/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cpp
new file mode 100644
index 000000000..c82bbbad6
--- /dev/null
+++ b/chalk/plugins/viewplugins/dropshadow/dlg_dropshadow.cpp
@@ -0,0 +1,117 @@
+/*
+ * dlg_dropshadow.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ * Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqbutton.h>
+#include <tqbuttongroup.h>
+#include <tqcheckbox.h>
+#include <tqcolor.h>
+#include <tqcombobox.h>
+#include <tqlabel.h>
+#include <tqradiobutton.h>
+#include <tqslider.h>
+
+#include <kcolorbutton.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+
+#include "dlg_dropshadow.h"
+#include "wdg_dropshadow.h"
+
+DlgDropshadow::DlgDropshadow( const TQString & /*imageCS*/,
+ const TQString & /*layerCS*/,
+ TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Drop Shadow"), Ok | Cancel, Ok)
+{
+ m_page = new WdgDropshadow(this, "dropshadow");
+ TQ_CHECK_PTR(m_page);
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ TDEConfig * cfg = TDEGlobal::config();
+ m_page->xOffsetSpinBox->setValue( cfg->readNumEntry("dropshadow_x", 8) );
+ m_page->yOffsetSpinBox->setValue( cfg->readNumEntry("dropshadow_y", 8) );
+ m_page->blurRadiusSpinBox->setValue( cfg->readNumEntry("dropshadow_blurRadius", 5) );
+ TQColor black(0,0,0);
+ m_page->shadowColorButton->setColor( cfg->readColorEntry("dropshadow_color", &black) );
+ m_page->opacitySlider->setValue( cfg->readNumEntry("dropshadow_opacity", 80 ) );
+ m_page->opacitySpinBox->setValue( cfg->readNumEntry("dropshadow_opacity", 80 ) );
+ m_page->allowResizingCheckBox->setChecked( cfg->readBoolEntry("dropshadow_resizing", true ) );
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+}
+
+DlgDropshadow::~DlgDropshadow()
+{
+ delete m_page;
+}
+
+TQ_INT32 DlgDropshadow::getXOffset()
+{
+ return m_page->xOffsetSpinBox->value();
+}
+
+TQ_INT32 DlgDropshadow::getYOffset()
+{
+ return m_page->yOffsetSpinBox->value();
+}
+
+TQ_INT32 DlgDropshadow::getBlurRadius()
+{
+ return m_page->blurRadiusSpinBox->value();
+}
+
+TQ_UINT8 DlgDropshadow::getShadowOpacity()
+{
+ double opacity = (double)m_page->opacitySpinBox->value();
+ //convert percent to a 8 bit opacity value
+ return (TQ_UINT8)(opacity / 100 * 255);
+}
+
+TQColor DlgDropshadow::getShadowColor()
+{
+ return m_page->shadowColorButton->color();
+}
+
+bool DlgDropshadow::allowResizingChecked()
+{
+ return m_page->allowResizingCheckBox->isChecked();
+}
+
+// SLOTS
+
+void DlgDropshadow::okClicked()
+{
+ TDEConfig * cfg = TDEGlobal::config();
+ cfg->writeEntry("dropshadow_x", m_page->xOffsetSpinBox->value());
+ cfg->writeEntry("dropshadow_y", m_page->yOffsetSpinBox->value());
+ cfg->writeEntry("dropshadow_blurRadius", m_page->blurRadiusSpinBox->value());
+ cfg->writeEntry("dropshadow_color", m_page->shadowColorButton->color());
+ cfg->writeEntry("dropshadow_opacity", m_page->opacitySpinBox->value());
+ cfg->writeEntry("dropshadow_resizing", m_page->allowResizingCheckBox->isChecked());
+
+ accept();
+}
+
+#include "dlg_dropshadow.moc"
diff --git a/chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cc b/chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cpp
index 97c2c17ed..97c2c17ed 100644
--- a/chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cc
+++ b/chalk/plugins/viewplugins/dropshadow/kis_dropshadow.cpp
diff --git a/chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cc b/chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cpp
index 97a0b8a7a..97a0b8a7a 100644
--- a/chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cc
+++ b/chalk/plugins/viewplugins/dropshadow/kis_dropshadow_plugin.cpp
diff --git a/chalk/plugins/viewplugins/filtersgallery/Makefile.am b/chalk/plugins/viewplugins/filtersgallery/Makefile.am
index 6c3ca3e87..bd80954f6 100644
--- a/chalk/plugins/viewplugins/filtersgallery/Makefile.am
+++ b/chalk/plugins/viewplugins/filtersgallery/Makefile.am
@@ -11,8 +11,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkfiltersgallery_la_SOURCES = filters_gallery.cc \
- kis_dlg_filtersgallery.cc kis_wdg_filtersgallery.ui
+chalkfiltersgallery_la_SOURCES = filters_gallery.cpp \
+ kis_dlg_filtersgallery.cpp kis_wdg_filtersgallery.ui
kde_module_LTLIBRARIES = chalkfiltersgallery.la
noinst_HEADERS = filters_gallery.h kis_dlg_filtersgallery.h
diff --git a/chalk/plugins/viewplugins/filtersgallery/filters_gallery.cc b/chalk/plugins/viewplugins/filtersgallery/filters_gallery.cpp
index 337b55c02..337b55c02 100644
--- a/chalk/plugins/viewplugins/filtersgallery/filters_gallery.cc
+++ b/chalk/plugins/viewplugins/filtersgallery/filters_gallery.cpp
diff --git a/chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cc b/chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cpp
index e0bec7ec6..e0bec7ec6 100644
--- a/chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cc
+++ b/chalk/plugins/viewplugins/filtersgallery/kis_dlg_filtersgallery.cpp
diff --git a/chalk/plugins/viewplugins/histogram/Makefile.am b/chalk/plugins/viewplugins/histogram/Makefile.am
index f5f8db376..9afb9726c 100644
--- a/chalk/plugins/viewplugins/histogram/Makefile.am
+++ b/chalk/plugins/viewplugins/histogram/Makefile.am
@@ -13,7 +13,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkhistogram.la
-chalkhistogram_la_SOURCES = histogram.cc dlg_histogram.cc wdghistogram.ui kis_histogram_widget.cc
+chalkhistogram_la_SOURCES = histogram.cpp dlg_histogram.cpp wdghistogram.ui kis_histogram_widget.cpp
noinst_HEADERS = dlg_histogram.h histogram.h wdghistogram.h kis_histogram_widget.h
kde_services_DATA = chalkhistogram.desktop
diff --git a/chalk/plugins/viewplugins/histogram/dlg_histogram.cc b/chalk/plugins/viewplugins/histogram/dlg_histogram.cc
deleted file mode 100644
index 448a58cfc..000000000
--- a/chalk/plugins/viewplugins/histogram/dlg_histogram.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * dlg_histogram.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqbuttongroup.h>
-#include <tqpushbutton.h>
-#include <tqcheckbox.h>
-#include <tqslider.h>
-#include <tqcombobox.h>
-#include <tqpixmap.h>
-#include <tqimage.h>
-#include <tqlabel.h>
-
-#include <knuminput.h>
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include "kis_types.h"
-#include "kis_histogram.h"
-#include "kis_layer.h"
-#include "kis_paint_device.h"
-
-#include "dlg_histogram.h"
-#include "kis_histogram_widget.h"
-
-
-DlgHistogram::DlgHistogram( TQWidget * parent, const char * name)
- : super (parent, name, true, i18n("Histogram"), Ok | Cancel, Ok)
-{
- m_page = new KisHistogramWidget(this, "histogram");
- TQ_CHECK_PTR(m_page);
-
- setCaption(i18n("Histogram"));
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-}
-
-DlgHistogram::~DlgHistogram()
-{
- delete m_page;
-}
-
-void DlgHistogram::setPaintDevice(KisPaintDeviceSP dev)
-{
- m_page->setPaintDevice(dev);
-}
-
-void DlgHistogram::okClicked()
-{
- accept();
-}
-
-#include "dlg_histogram.moc"
diff --git a/chalk/plugins/viewplugins/histogram/dlg_histogram.cpp b/chalk/plugins/viewplugins/histogram/dlg_histogram.cpp
new file mode 100644
index 000000000..77ad06686
--- /dev/null
+++ b/chalk/plugins/viewplugins/histogram/dlg_histogram.cpp
@@ -0,0 +1,68 @@
+/*
+ * dlg_histogram.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqbuttongroup.h>
+#include <tqpushbutton.h>
+#include <tqcheckbox.h>
+#include <tqslider.h>
+#include <tqcombobox.h>
+#include <tqpixmap.h>
+#include <tqimage.h>
+#include <tqlabel.h>
+
+#include <knuminput.h>
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include "kis_types.h"
+#include "kis_histogram.h"
+#include "kis_layer.h"
+#include "kis_paint_device.h"
+
+#include "dlg_histogram.h"
+#include "kis_histogram_widget.h"
+
+
+DlgHistogram::DlgHistogram( TQWidget * parent, const char * name)
+ : super (parent, name, true, i18n("Histogram"), Ok | Cancel, Ok)
+{
+ m_page = new KisHistogramWidget(this, "histogram");
+ TQ_CHECK_PTR(m_page);
+
+ setCaption(i18n("Histogram"));
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+}
+
+DlgHistogram::~DlgHistogram()
+{
+ delete m_page;
+}
+
+void DlgHistogram::setPaintDevice(KisPaintDeviceSP dev)
+{
+ m_page->setPaintDevice(dev);
+}
+
+void DlgHistogram::okClicked()
+{
+ accept();
+}
+
+#include "dlg_histogram.moc"
diff --git a/chalk/plugins/viewplugins/histogram/histogram.cc b/chalk/plugins/viewplugins/histogram/histogram.cpp
index 8252a98db..8252a98db 100644
--- a/chalk/plugins/viewplugins/histogram/histogram.cc
+++ b/chalk/plugins/viewplugins/histogram/histogram.cpp
diff --git a/chalk/plugins/viewplugins/histogram/kis_histogram_widget.cc b/chalk/plugins/viewplugins/histogram/kis_histogram_widget.cpp
index c49838706..c49838706 100644
--- a/chalk/plugins/viewplugins/histogram/kis_histogram_widget.cc
+++ b/chalk/plugins/viewplugins/histogram/kis_histogram_widget.cpp
diff --git a/chalk/plugins/viewplugins/histogram_docker/Makefile.am b/chalk/plugins/viewplugins/histogram_docker/Makefile.am
index 6d2b905db..299920871 100644
--- a/chalk/plugins/viewplugins/histogram_docker/Makefile.am
+++ b/chalk/plugins/viewplugins/histogram_docker/Makefile.am
@@ -10,7 +10,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkhistogramdocker_la_SOURCES = histogramdocker.cc kis_imagerasteredcache.cc kis_cachedhistogram.cc kis_accumulating_producer.cc
+chalkhistogramdocker_la_SOURCES = histogramdocker.cpp kis_imagerasteredcache.cpp kis_cachedhistogram.cpp kis_accumulating_producer.cpp
kde_module_LTLIBRARIES = chalkhistogramdocker.la
noinst_HEADERS = histogramdocker.h kis_imagerasteredcache.h kis_cachedhistogram.h kis_accumulating_producer.h
diff --git a/chalk/plugins/viewplugins/histogram_docker/histogramdocker.cc b/chalk/plugins/viewplugins/histogram_docker/histogramdocker.cpp
index 25a7b9cff..25a7b9cff 100644
--- a/chalk/plugins/viewplugins/histogram_docker/histogramdocker.cc
+++ b/chalk/plugins/viewplugins/histogram_docker/histogramdocker.cpp
diff --git a/chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cc b/chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cpp
index 217a36d91..217a36d91 100644
--- a/chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cc
+++ b/chalk/plugins/viewplugins/histogram_docker/kis_accumulating_producer.cpp
diff --git a/chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cc b/chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cpp
index 1ad197f9d..1ad197f9d 100644
--- a/chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cc
+++ b/chalk/plugins/viewplugins/histogram_docker/kis_cachedhistogram.cpp
diff --git a/chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cc b/chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cpp
index 19599cd9c..19599cd9c 100644
--- a/chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cc
+++ b/chalk/plugins/viewplugins/histogram_docker/kis_imagerasteredcache.cpp
diff --git a/chalk/plugins/viewplugins/history_docker/Makefile.am b/chalk/plugins/viewplugins/history_docker/Makefile.am
index 53511b3d9..c77357f23 100644
--- a/chalk/plugins/viewplugins/history_docker/Makefile.am
+++ b/chalk/plugins/viewplugins/history_docker/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkhistorydocker_la_SOURCES = historydocker.cc
+chalkhistorydocker_la_SOURCES = historydocker.cpp
kde_module_LTLIBRARIES = chalkhistorydocker.la
noinst_HEADERS = historydocker.h
diff --git a/chalk/plugins/viewplugins/history_docker/historydocker.cc b/chalk/plugins/viewplugins/history_docker/historydocker.cpp
index 85e4df406..85e4df406 100644
--- a/chalk/plugins/viewplugins/history_docker/historydocker.cc
+++ b/chalk/plugins/viewplugins/history_docker/historydocker.cpp
diff --git a/chalk/plugins/viewplugins/imagesize/Makefile.am b/chalk/plugins/viewplugins/imagesize/Makefile.am
index 00d58340c..5fe1756ab 100644
--- a/chalk/plugins/viewplugins/imagesize/Makefile.am
+++ b/chalk/plugins/viewplugins/imagesize/Makefile.am
@@ -12,7 +12,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkimagesize_la_SOURCES = wdg_imagesize.ui wdg_layersize.ui imagesize.cc dlg_imagesize.cc dlg_layersize.cc wdg_resolution.ui
+chalkimagesize_la_SOURCES = wdg_imagesize.ui wdg_layersize.ui imagesize.cpp dlg_imagesize.cpp dlg_layersize.cpp wdg_resolution.ui
noinst_HEADERS = wdg_imagesize.h dlg_imagesize.h imagesize.h dlg_layersize.h
diff --git a/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cc b/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cc
deleted file mode 100644
index 8a9a8c098..000000000
--- a/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cc
+++ /dev/null
@@ -1,277 +0,0 @@
-/*
- * dlg_imagesize.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include <kis_cmb_idlist.h>
-#include <kis_filter_strategy.h>
-
-#include "dlg_imagesize.h"
-#include "wdg_imagesize.h"
-
-
-// XXX: I'm really real bad at arithmetic, let alone math. Here
-// be rounding errors. (Boudewijn)
-DlgImageSize::DlgImageSize( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Image Size"), Ok | Cancel, Ok)
-{
- m_lock = false;
-
- m_page = new WdgImageSize(this, "image_size");
- TQ_CHECK_PTR(m_page);
-
- m_page->cmbFilterType->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
- m_page->cmbFilterType->setCurrentText("Mitchell");
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- unblockAll();
-
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
-}
-
-DlgImageSize::~DlgImageSize()
-{
- delete m_page;
-}
-
-void DlgImageSize::hideScaleBox()
-{
- m_page->grpResizeScale->hide();
-}
-
-void DlgImageSize::setWidth(TQ_UINT32 w)
-{
- blockAll();
-
- m_page->lblWidthOriginal->setNum((int)w);
- m_page->intWidth->setValue(w);
- m_oldW = w;
- m_origW = w;
-
- unblockAll();
-}
-
-void DlgImageSize::setWidthPercent(TQ_UINT32 w)
-{
- blockAll();
-
- m_page->intWidthPercent->setValue(w);
- m_oldWPercent = w;
-
- unblockAll();
-}
-
-
-void DlgImageSize::setMaximumWidth(TQ_UINT32 w)
-{
- m_page->intWidth->setMaxValue(w);
- m_maxW = w;
-}
-
-TQ_INT32 DlgImageSize::width()
-{
- //return (TQ_INT32)tqRound(m_oldW);
- return (TQ_INT32)tqRound(m_page->intWidth->value());
-}
-
-void DlgImageSize::setHeight(TQ_UINT32 h)
-{
- blockAll();
-
- m_page->lblHeightOriginal->setNum((int)h);
- m_page->intHeight->setValue(h);
- m_oldH = h;
- m_origH = h;
-
- unblockAll();
-}
-
-
-void DlgImageSize::setHeightPercent(TQ_UINT32 h)
-{
- blockAll();
-
- m_page->intHeightPercent->setValue(h);
- m_oldHPercent = h;
-
- unblockAll();
-}
-
-
-
-void DlgImageSize::setMaximumHeight(TQ_UINT32 h)
-{
- m_page->intHeight->setMaxValue(h);
- m_maxH = h;
-}
-
-
-TQ_INT32 DlgImageSize::height()
-{
- //return (TQ_INT32)tqRound(m_oldH);
- return (TQ_INT32)tqRound(m_page->intHeight->value());
-}
-
-bool DlgImageSize::scale()
-{
- return m_page->radioScale->isChecked();
-}
-
-bool DlgImageSize::cropLayers()
-{
- return m_page->chkCrop->isChecked();
-}
-
-KisFilterStrategy *DlgImageSize::filterType()
-{
- KisID filterID = m_page->cmbFilterType->currentItem();
- KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->get(filterID);
- return filter;
-}
-
-// SLOTS
-
-void DlgImageSize::okClicked()
-{
- accept();
-}
-
-void DlgImageSize::slotWidthPixelsChanged(int w)
-{
- blockAll();
-
- double wPercent = double(w) * 100 / double(m_origW);
-
- m_page->intWidthPercent->setValue(tqRound(wPercent));
-
- // Set height in pixels and percent of necessary
- if (m_page->chkConstrain->isChecked()) {
- m_page->intHeightPercent->setValue(tqRound(wPercent));
-
- m_oldH = tqRound(m_origH * wPercent / 100);
- m_page->intHeight->setValue(tqRound(m_oldH));
-
- }
- m_oldW = w;
-
- unblockAll();
-}
-
-void DlgImageSize::slotHeightPixelsChanged(int h)
-{
- blockAll();
-
- double hPercent = double(h) * 100 / double(m_origH);
-
- m_page->intHeightPercent->setValue(tqRound(hPercent));
-
- // Set width in pixels and percent of necessary
- if (m_page->chkConstrain->isChecked()) {
- m_page->intWidthPercent->setValue(tqRound(hPercent));
-
- m_oldW = tqRound(m_origW * hPercent / 100);
- m_page->intWidth->setValue(tqRound(m_oldW));
-
- }
- m_oldH = h;
-
- unblockAll();
-}
-
-void DlgImageSize::slotWidthPercentChanged(int w)
-{
- blockAll();
-
- m_page->intWidth->setValue(tqRound(w * m_origW / 100));
-
- if (m_page->chkConstrain->isChecked()) {
- m_page->intHeightPercent->setValue(w);
- m_page->intHeight->setValue(tqRound( w * m_origH / 100));
- }
-
- unblockAll();
-}
-
-void DlgImageSize::slotHeightPercentChanged(int h)
-{
- blockAll();
-
- m_page->intHeight->setValue(tqRound(h * m_origH / 100));
- if (m_page->chkConstrain->isChecked()) {
- m_page->intWidthPercent->setValue(h);
- m_page->intWidth->setValue(tqRound( h * m_origW / 100));
- }
-
- unblockAll();
-
-}
-
-
-void DlgImageSize::blockAll()
-{
- // XXX: more efficient to use blockSignals?
- m_page->intWidth->disconnect();
- m_page->intHeight->disconnect();
- m_page->intWidthPercent->disconnect();
- m_page->intHeightPercent->disconnect();
-
-}
-
-void DlgImageSize::unblockAll()
-{
- // XXX: more efficient to use blockSignals?
- connect (m_page->intWidth, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotWidthPixelsChanged(int)));
-
- connect (m_page->intHeight, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotHeightPixelsChanged(int)));
-
- connect (m_page->intWidthPercent, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotWidthPercentChanged(int)));
-
- connect (m_page->intHeightPercent, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotHeightPercentChanged(int)));
-
-
-}
-
-#include "dlg_imagesize.moc"
diff --git a/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cpp b/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cpp
new file mode 100644
index 000000000..c455af8cc
--- /dev/null
+++ b/chalk/plugins/viewplugins/imagesize/dlg_imagesize.cpp
@@ -0,0 +1,277 @@
+/*
+ * dlg_imagesize.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include <kis_cmb_idlist.h>
+#include <kis_filter_strategy.h>
+
+#include "dlg_imagesize.h"
+#include "wdg_imagesize.h"
+
+
+// XXX: I'm really real bad at arithmetic, let alone math. Here
+// be rounding errors. (Boudewijn)
+DlgImageSize::DlgImageSize( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Image Size"), Ok | Cancel, Ok)
+{
+ m_lock = false;
+
+ m_page = new WdgImageSize(this, "image_size");
+ TQ_CHECK_PTR(m_page);
+
+ m_page->cmbFilterType->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
+ m_page->cmbFilterType->setCurrentText("Mitchell");
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ unblockAll();
+
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+}
+
+DlgImageSize::~DlgImageSize()
+{
+ delete m_page;
+}
+
+void DlgImageSize::hideScaleBox()
+{
+ m_page->grpResizeScale->hide();
+}
+
+void DlgImageSize::setWidth(TQ_UINT32 w)
+{
+ blockAll();
+
+ m_page->lblWidthOriginal->setNum((int)w);
+ m_page->intWidth->setValue(w);
+ m_oldW = w;
+ m_origW = w;
+
+ unblockAll();
+}
+
+void DlgImageSize::setWidthPercent(TQ_UINT32 w)
+{
+ blockAll();
+
+ m_page->intWidthPercent->setValue(w);
+ m_oldWPercent = w;
+
+ unblockAll();
+}
+
+
+void DlgImageSize::setMaximumWidth(TQ_UINT32 w)
+{
+ m_page->intWidth->setMaxValue(w);
+ m_maxW = w;
+}
+
+TQ_INT32 DlgImageSize::width()
+{
+ //return (TQ_INT32)tqRound(m_oldW);
+ return (TQ_INT32)tqRound(m_page->intWidth->value());
+}
+
+void DlgImageSize::setHeight(TQ_UINT32 h)
+{
+ blockAll();
+
+ m_page->lblHeightOriginal->setNum((int)h);
+ m_page->intHeight->setValue(h);
+ m_oldH = h;
+ m_origH = h;
+
+ unblockAll();
+}
+
+
+void DlgImageSize::setHeightPercent(TQ_UINT32 h)
+{
+ blockAll();
+
+ m_page->intHeightPercent->setValue(h);
+ m_oldHPercent = h;
+
+ unblockAll();
+}
+
+
+
+void DlgImageSize::setMaximumHeight(TQ_UINT32 h)
+{
+ m_page->intHeight->setMaxValue(h);
+ m_maxH = h;
+}
+
+
+TQ_INT32 DlgImageSize::height()
+{
+ //return (TQ_INT32)tqRound(m_oldH);
+ return (TQ_INT32)tqRound(m_page->intHeight->value());
+}
+
+bool DlgImageSize::scale()
+{
+ return m_page->radioScale->isChecked();
+}
+
+bool DlgImageSize::cropLayers()
+{
+ return m_page->chkCrop->isChecked();
+}
+
+KisFilterStrategy *DlgImageSize::filterType()
+{
+ KisID filterID = m_page->cmbFilterType->currentItem();
+ KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->get(filterID);
+ return filter;
+}
+
+// SLOTS
+
+void DlgImageSize::okClicked()
+{
+ accept();
+}
+
+void DlgImageSize::slotWidthPixelsChanged(int w)
+{
+ blockAll();
+
+ double wPercent = double(w) * 100 / double(m_origW);
+
+ m_page->intWidthPercent->setValue(tqRound(wPercent));
+
+ // Set height in pixels and percent of necessary
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intHeightPercent->setValue(tqRound(wPercent));
+
+ m_oldH = tqRound(m_origH * wPercent / 100);
+ m_page->intHeight->setValue(tqRound(m_oldH));
+
+ }
+ m_oldW = w;
+
+ unblockAll();
+}
+
+void DlgImageSize::slotHeightPixelsChanged(int h)
+{
+ blockAll();
+
+ double hPercent = double(h) * 100 / double(m_origH);
+
+ m_page->intHeightPercent->setValue(tqRound(hPercent));
+
+ // Set width in pixels and percent of necessary
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intWidthPercent->setValue(tqRound(hPercent));
+
+ m_oldW = tqRound(m_origW * hPercent / 100);
+ m_page->intWidth->setValue(tqRound(m_oldW));
+
+ }
+ m_oldH = h;
+
+ unblockAll();
+}
+
+void DlgImageSize::slotWidthPercentChanged(int w)
+{
+ blockAll();
+
+ m_page->intWidth->setValue(tqRound(w * m_origW / 100));
+
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intHeightPercent->setValue(w);
+ m_page->intHeight->setValue(tqRound( w * m_origH / 100));
+ }
+
+ unblockAll();
+}
+
+void DlgImageSize::slotHeightPercentChanged(int h)
+{
+ blockAll();
+
+ m_page->intHeight->setValue(tqRound(h * m_origH / 100));
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intWidthPercent->setValue(h);
+ m_page->intWidth->setValue(tqRound( h * m_origW / 100));
+ }
+
+ unblockAll();
+
+}
+
+
+void DlgImageSize::blockAll()
+{
+ // XXX: more efficient to use blockSignals?
+ m_page->intWidth->disconnect();
+ m_page->intHeight->disconnect();
+ m_page->intWidthPercent->disconnect();
+ m_page->intHeightPercent->disconnect();
+
+}
+
+void DlgImageSize::unblockAll()
+{
+ // XXX: more efficient to use blockSignals?
+ connect (m_page->intWidth, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotWidthPixelsChanged(int)));
+
+ connect (m_page->intHeight, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotHeightPixelsChanged(int)));
+
+ connect (m_page->intWidthPercent, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotWidthPercentChanged(int)));
+
+ connect (m_page->intHeightPercent, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotHeightPercentChanged(int)));
+
+
+}
+
+#include "dlg_imagesize.moc"
diff --git a/chalk/plugins/viewplugins/imagesize/dlg_layersize.cc b/chalk/plugins/viewplugins/imagesize/dlg_layersize.cc
deleted file mode 100644
index 1d30db6a0..000000000
--- a/chalk/plugins/viewplugins/imagesize/dlg_layersize.cc
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * dlg_layersize.cc - part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include <kis_cmb_idlist.h>
-#include <kis_filter_strategy.h>
-
-#include "dlg_layersize.h"
-#include "wdg_layersize.h"
-
-
-// XXX: I'm really real bad at arithmetic, let alone math. Here
-// be rounding errors. (Boudewijn)
-DlgLayerSize::DlgLayerSize( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Scale Layer"), Ok | Cancel, Ok)
-{
- m_lock = false;
-
- m_page = new WdgLayerSize(this, "layer_size");
- TQ_CHECK_PTR(m_page);
-
- m_page->cmbFilterType->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
- m_page->cmbFilterType->setCurrentText("Mitchell");
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- unblockAll();
-
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
-}
-
-DlgLayerSize::~DlgLayerSize()
-{
- delete m_page;
-}
-
-void DlgLayerSize::setWidth(TQ_UINT32 w)
-{
- blockAll();
-
- m_page->lblWidthOriginal->setNum((int)w);
- m_page->intWidth->setValue(w);
- m_oldW = w;
- m_origW = w;
-
- unblockAll();
-}
-
-void DlgLayerSize::setWidthPercent(TQ_UINT32 w)
-{
- blockAll();
-
- m_page->intWidthPercent->setValue(w);
- m_oldWPercent = w;
-
- unblockAll();
-}
-
-
-void DlgLayerSize::setMaximumWidth(TQ_UINT32 w)
-{
- m_page->intWidth->setMaxValue(w);
- m_maxW = w;
-}
-
-TQ_INT32 DlgLayerSize::width()
-{
- //return (TQ_INT32)tqRound(m_oldW);
- return (TQ_INT32)tqRound(m_page->intWidth->value());
-}
-
-void DlgLayerSize::setHeight(TQ_UINT32 h)
-{
- blockAll();
-
- m_page->lblHeightOriginal->setNum((int)h);
- m_page->intHeight->setValue(h);
- m_oldH = h;
- m_origH = h;
-
- unblockAll();
-}
-
-
-void DlgLayerSize::setHeightPercent(TQ_UINT32 h)
-{
- blockAll();
-
- m_page->intHeightPercent->setValue(h);
- m_oldHPercent = h;
-
- unblockAll();
-}
-
-void DlgLayerSize::setMaximumHeight(TQ_UINT32 h)
-{
- m_page->intHeight->setMaxValue(h);
- m_maxH = h;
-}
-
-TQ_INT32 DlgLayerSize::height()
-{
- //return (TQ_INT32)tqRound(m_oldH);
- return (TQ_INT32)tqRound(m_page->intHeight->value());
-}
-
-KisFilterStrategy *DlgLayerSize::filterType()
-{
- KisID filterID = m_page->cmbFilterType->currentItem();
- KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->get(filterID);
- return filter;
-}
-
-
-// SLOTS
-
-void DlgLayerSize::okClicked()
-{
- accept();
-}
-
-void DlgLayerSize::slotWidthPixelsChanged(int w)
-{
- blockAll();
-
- double wPercent = double(w) * 100 / double(m_origW);
-
- m_page->intWidthPercent->setValue(tqRound(wPercent));
-
- // Set height in pixels and percent of necessary
- if (m_page->chkConstrain->isChecked()) {
- m_page->intHeightPercent->setValue(tqRound(wPercent));
-
- m_oldH = tqRound(m_origH * wPercent / 100);
- m_page->intHeight->setValue(tqRound(m_oldH));
-
- }
- m_oldW = w;
-
- unblockAll();
-}
-
-void DlgLayerSize::slotHeightPixelsChanged(int h)
-{
- blockAll();
-
- double hPercent = double(h) * 100 / double(m_origH);
-
- m_page->intHeightPercent->setValue(tqRound(hPercent));
-
- // Set width in pixels and percent of necessary
- if (m_page->chkConstrain->isChecked()) {
- m_page->intWidthPercent->setValue(tqRound(hPercent));
-
- m_oldW = tqRound(m_origW * hPercent / 100);
- m_page->intWidth->setValue(tqRound(m_oldW));
-
- }
- m_oldH = h;
-
- unblockAll();
-}
-
-void DlgLayerSize::slotWidthPercentChanged(int w)
-{
- blockAll();
-
- m_page->intWidth->setValue(tqRound(w * m_origW / 100));
-
- if (m_page->chkConstrain->isChecked()) {
- m_page->intHeightPercent->setValue(w);
- m_page->intHeight->setValue(tqRound( w * m_origH / 100));
- }
-
- unblockAll();
-}
-
-void DlgLayerSize::slotHeightPercentChanged(int h)
-{
- blockAll();
-
- m_page->intHeight->setValue(tqRound(h * m_origH / 100));
- if (m_page->chkConstrain->isChecked()) {
- m_page->intWidthPercent->setValue(h);
- m_page->intWidth->setValue(tqRound( h * m_origW / 100));
- }
-
- unblockAll();
-
-}
-
-
-void DlgLayerSize::blockAll()
-{
- // XXX: more efficient to use blockSignals?
- m_page->intWidth->disconnect();
- m_page->intHeight->disconnect();
- m_page->intWidthPercent->disconnect();
- m_page->intHeightPercent->disconnect();
-
-}
-
-void DlgLayerSize::unblockAll()
-{
- // XXX: more efficient to use blockSignals?
- connect (m_page->intWidth, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotWidthPixelsChanged(int)));
-
- connect (m_page->intHeight, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotHeightPixelsChanged(int)));
-
- connect (m_page->intWidthPercent, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotWidthPercentChanged(int)));
-
- connect (m_page->intHeightPercent, TQT_SIGNAL(valueChanged(int)),
- this, TQT_SLOT(slotHeightPercentChanged(int)));
-
-
-}
-
-#include "dlg_layersize.moc"
diff --git a/chalk/plugins/viewplugins/imagesize/dlg_layersize.cpp b/chalk/plugins/viewplugins/imagesize/dlg_layersize.cpp
new file mode 100644
index 000000000..779798056
--- /dev/null
+++ b/chalk/plugins/viewplugins/imagesize/dlg_layersize.cpp
@@ -0,0 +1,261 @@
+/*
+ * dlg_layersize.cpp - part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include <kis_cmb_idlist.h>
+#include <kis_filter_strategy.h>
+
+#include "dlg_layersize.h"
+#include "wdg_layersize.h"
+
+
+// XXX: I'm really real bad at arithmetic, let alone math. Here
+// be rounding errors. (Boudewijn)
+DlgLayerSize::DlgLayerSize( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Scale Layer"), Ok | Cancel, Ok)
+{
+ m_lock = false;
+
+ m_page = new WdgLayerSize(this, "layer_size");
+ TQ_CHECK_PTR(m_page);
+
+ m_page->cmbFilterType->setIDList(KisFilterStrategyRegistry::instance()->listKeys());
+ m_page->cmbFilterType->setCurrentText("Mitchell");
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ unblockAll();
+
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+}
+
+DlgLayerSize::~DlgLayerSize()
+{
+ delete m_page;
+}
+
+void DlgLayerSize::setWidth(TQ_UINT32 w)
+{
+ blockAll();
+
+ m_page->lblWidthOriginal->setNum((int)w);
+ m_page->intWidth->setValue(w);
+ m_oldW = w;
+ m_origW = w;
+
+ unblockAll();
+}
+
+void DlgLayerSize::setWidthPercent(TQ_UINT32 w)
+{
+ blockAll();
+
+ m_page->intWidthPercent->setValue(w);
+ m_oldWPercent = w;
+
+ unblockAll();
+}
+
+
+void DlgLayerSize::setMaximumWidth(TQ_UINT32 w)
+{
+ m_page->intWidth->setMaxValue(w);
+ m_maxW = w;
+}
+
+TQ_INT32 DlgLayerSize::width()
+{
+ //return (TQ_INT32)tqRound(m_oldW);
+ return (TQ_INT32)tqRound(m_page->intWidth->value());
+}
+
+void DlgLayerSize::setHeight(TQ_UINT32 h)
+{
+ blockAll();
+
+ m_page->lblHeightOriginal->setNum((int)h);
+ m_page->intHeight->setValue(h);
+ m_oldH = h;
+ m_origH = h;
+
+ unblockAll();
+}
+
+
+void DlgLayerSize::setHeightPercent(TQ_UINT32 h)
+{
+ blockAll();
+
+ m_page->intHeightPercent->setValue(h);
+ m_oldHPercent = h;
+
+ unblockAll();
+}
+
+void DlgLayerSize::setMaximumHeight(TQ_UINT32 h)
+{
+ m_page->intHeight->setMaxValue(h);
+ m_maxH = h;
+}
+
+TQ_INT32 DlgLayerSize::height()
+{
+ //return (TQ_INT32)tqRound(m_oldH);
+ return (TQ_INT32)tqRound(m_page->intHeight->value());
+}
+
+KisFilterStrategy *DlgLayerSize::filterType()
+{
+ KisID filterID = m_page->cmbFilterType->currentItem();
+ KisFilterStrategy *filter = KisFilterStrategyRegistry::instance()->get(filterID);
+ return filter;
+}
+
+
+// SLOTS
+
+void DlgLayerSize::okClicked()
+{
+ accept();
+}
+
+void DlgLayerSize::slotWidthPixelsChanged(int w)
+{
+ blockAll();
+
+ double wPercent = double(w) * 100 / double(m_origW);
+
+ m_page->intWidthPercent->setValue(tqRound(wPercent));
+
+ // Set height in pixels and percent of necessary
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intHeightPercent->setValue(tqRound(wPercent));
+
+ m_oldH = tqRound(m_origH * wPercent / 100);
+ m_page->intHeight->setValue(tqRound(m_oldH));
+
+ }
+ m_oldW = w;
+
+ unblockAll();
+}
+
+void DlgLayerSize::slotHeightPixelsChanged(int h)
+{
+ blockAll();
+
+ double hPercent = double(h) * 100 / double(m_origH);
+
+ m_page->intHeightPercent->setValue(tqRound(hPercent));
+
+ // Set width in pixels and percent of necessary
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intWidthPercent->setValue(tqRound(hPercent));
+
+ m_oldW = tqRound(m_origW * hPercent / 100);
+ m_page->intWidth->setValue(tqRound(m_oldW));
+
+ }
+ m_oldH = h;
+
+ unblockAll();
+}
+
+void DlgLayerSize::slotWidthPercentChanged(int w)
+{
+ blockAll();
+
+ m_page->intWidth->setValue(tqRound(w * m_origW / 100));
+
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intHeightPercent->setValue(w);
+ m_page->intHeight->setValue(tqRound( w * m_origH / 100));
+ }
+
+ unblockAll();
+}
+
+void DlgLayerSize::slotHeightPercentChanged(int h)
+{
+ blockAll();
+
+ m_page->intHeight->setValue(tqRound(h * m_origH / 100));
+ if (m_page->chkConstrain->isChecked()) {
+ m_page->intWidthPercent->setValue(h);
+ m_page->intWidth->setValue(tqRound( h * m_origW / 100));
+ }
+
+ unblockAll();
+
+}
+
+
+void DlgLayerSize::blockAll()
+{
+ // XXX: more efficient to use blockSignals?
+ m_page->intWidth->disconnect();
+ m_page->intHeight->disconnect();
+ m_page->intWidthPercent->disconnect();
+ m_page->intHeightPercent->disconnect();
+
+}
+
+void DlgLayerSize::unblockAll()
+{
+ // XXX: more efficient to use blockSignals?
+ connect (m_page->intWidth, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotWidthPixelsChanged(int)));
+
+ connect (m_page->intHeight, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotHeightPixelsChanged(int)));
+
+ connect (m_page->intWidthPercent, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotWidthPercentChanged(int)));
+
+ connect (m_page->intHeightPercent, TQT_SIGNAL(valueChanged(int)),
+ this, TQT_SLOT(slotHeightPercentChanged(int)));
+
+
+}
+
+#include "dlg_layersize.moc"
diff --git a/chalk/plugins/viewplugins/imagesize/imagesize.cc b/chalk/plugins/viewplugins/imagesize/imagesize.cc
deleted file mode 100644
index c795924e1..000000000
--- a/chalk/plugins/viewplugins/imagesize/imagesize.cc
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * imagesize.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <stdlib.h>
-
-#include <tqslider.h>
-#include <tqrect.h>
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <kstdaction.h>
-
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_selection.h>
-#include <kis_selection_manager.h>
-#include <kis_transaction.h>
-#include <kis_canvas_controller.h>
-#include <kis_scale_visitor.h>
-
-#include "imagesize.h"
-#include "dlg_imagesize.h"
-#include "dlg_layersize.h"
-#include "kis_filter_strategy.h"
-
-typedef KGenericFactory<ImageSize> ImageSizeFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkimagesize, ImageSizeFactory( "chalk" ) )
-
-ImageSize::ImageSize(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- if ( parent->inherits("KisView") )
- {
- setInstance(ImageSizeFactory::instance());
- setXMLFile(locate("data","chalkplugins/imagesize.rc"), true);
-
- (void) new TDEAction(i18n("Change &Image Size..."), 0, "Shift-s", this, TQT_SLOT(slotImageSize()), actionCollection(), "imagesize");
- (void) new TDEAction(i18n("&Scale Layer..."), 0, 0, this, TQT_SLOT(slotLayerSize()), actionCollection(), "layerscale");
-
-
- m_view = (KisView*) parent;
- // Selection manager takes ownership?
- TDEAction * a = new TDEAction(i18n("&Scale Selection..."), 0, 0, this, TQT_SLOT(slotSelectionScale()), actionCollection(), "selectionscale");
- TQ_CHECK_PTR(a);
- m_view ->canvasSubject()-> selectionManager()->addSelectionAction(a);
- }
-}
-
-ImageSize::~ImageSize()
-{
- m_view = 0;
-}
-
-void ImageSize::slotImageSize()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgImageSize * dlgImageSize = new DlgImageSize(m_view, "ImageSize");
- TQ_CHECK_PTR(dlgImageSize);
-
- dlgImageSize->setCaption(i18n("Image Size"));
-
- KisConfig cfg;
-
- dlgImageSize->setWidth(image->width());
- dlgImageSize->setHeight(image->height());
-
- if (dlgImageSize->exec() == TQDialog::Accepted) {
- TQ_INT32 w = dlgImageSize->width();
- TQ_INT32 h = dlgImageSize->height();
-
- if (dlgImageSize->scale()) {
- m_view->scaleCurrentImage((double)w / ((double)(image->width())),
- (double)h / ((double)(image->height())),
- dlgImageSize->filterType());
- }
- else {
- m_view->resizeCurrentImage(w, h, dlgImageSize->cropLayers());
- }
- }
-
- delete dlgImageSize;
-}
-
-void ImageSize::slotLayerSize()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgLayerSize * dlgLayerSize = new DlgLayerSize(m_view, "LayerSize");
- TQ_CHECK_PTR(dlgLayerSize);
-
- dlgLayerSize->setCaption(i18n("Layer Size"));
-
- KisConfig cfg;
- KisPaintDeviceSP dev = image->activeDevice();
-
- TQRect rc = dev->exactBounds();
-
- dlgLayerSize->setWidth(rc.width());
- dlgLayerSize->setHeight(rc.height());
-
- if (dlgLayerSize->exec() == TQDialog::Accepted) {
- TQ_INT32 w = dlgLayerSize->width();
- TQ_INT32 h = dlgLayerSize->height();
-
- m_view->scaleLayer((double)w / ((double)(rc.width())),
- (double)h / ((double)(rc.height())),
- dlgLayerSize->filterType());
- }
- delete dlgLayerSize;
-}
-
-void ImageSize::slotSelectionScale()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- KisPaintDeviceSP layer = image->activeDevice();
-
- if (!layer) return;
-
- if (!layer->hasSelection()) return;
-
-
- DlgLayerSize * dlgLayerSize = new DlgLayerSize(m_view, "SelectionScale");
- TQ_CHECK_PTR(dlgLayerSize);
-
- dlgLayerSize->setCaption(i18n("Scale Selection"));
-
- KisConfig cfg;
- TQRect rc = layer->selection()->selectedRect();
-
- dlgLayerSize->setWidth(rc.width());
- dlgLayerSize->setHeight(rc.height());
-
- if (dlgLayerSize->exec() == TQDialog::Accepted) {
- TQ_INT32 w = dlgLayerSize->width();
- TQ_INT32 h = dlgLayerSize->height();
-
- KisScaleWorker worker (layer->selection().data(),
- (double)w / ((double)(rc.width())),
- (double)h / ((double)(rc.height())),
- dlgLayerSize->filterType());
- worker.run();
-
- m_view->getCanvasController()->updateCanvas();
-
- }
- delete dlgLayerSize;
-}
-
-
-#include "imagesize.moc"
diff --git a/chalk/plugins/viewplugins/imagesize/imagesize.cpp b/chalk/plugins/viewplugins/imagesize/imagesize.cpp
new file mode 100644
index 000000000..af9c2570f
--- /dev/null
+++ b/chalk/plugins/viewplugins/imagesize/imagesize.cpp
@@ -0,0 +1,190 @@
+/*
+ * imagesize.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <stdlib.h>
+
+#include <tqslider.h>
+#include <tqrect.h>
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kstdaction.h>
+
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_selection.h>
+#include <kis_selection_manager.h>
+#include <kis_transaction.h>
+#include <kis_canvas_controller.h>
+#include <kis_scale_visitor.h>
+
+#include "imagesize.h"
+#include "dlg_imagesize.h"
+#include "dlg_layersize.h"
+#include "kis_filter_strategy.h"
+
+typedef KGenericFactory<ImageSize> ImageSizeFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkimagesize, ImageSizeFactory( "chalk" ) )
+
+ImageSize::ImageSize(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ if ( parent->inherits("KisView") )
+ {
+ setInstance(ImageSizeFactory::instance());
+ setXMLFile(locate("data","chalkplugins/imagesize.rc"), true);
+
+ (void) new TDEAction(i18n("Change &Image Size..."), 0, "Shift-s", this, TQT_SLOT(slotImageSize()), actionCollection(), "imagesize");
+ (void) new TDEAction(i18n("&Scale Layer..."), 0, 0, this, TQT_SLOT(slotLayerSize()), actionCollection(), "layerscale");
+
+
+ m_view = (KisView*) parent;
+ // Selection manager takes ownership?
+ TDEAction * a = new TDEAction(i18n("&Scale Selection..."), 0, 0, this, TQT_SLOT(slotSelectionScale()), actionCollection(), "selectionscale");
+ TQ_CHECK_PTR(a);
+ m_view ->canvasSubject()-> selectionManager()->addSelectionAction(a);
+ }
+}
+
+ImageSize::~ImageSize()
+{
+ m_view = 0;
+}
+
+void ImageSize::slotImageSize()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgImageSize * dlgImageSize = new DlgImageSize(m_view, "ImageSize");
+ TQ_CHECK_PTR(dlgImageSize);
+
+ dlgImageSize->setCaption(i18n("Image Size"));
+
+ KisConfig cfg;
+
+ dlgImageSize->setWidth(image->width());
+ dlgImageSize->setHeight(image->height());
+
+ if (dlgImageSize->exec() == TQDialog::Accepted) {
+ TQ_INT32 w = dlgImageSize->width();
+ TQ_INT32 h = dlgImageSize->height();
+
+ if (dlgImageSize->scale()) {
+ m_view->scaleCurrentImage((double)w / ((double)(image->width())),
+ (double)h / ((double)(image->height())),
+ dlgImageSize->filterType());
+ }
+ else {
+ m_view->resizeCurrentImage(w, h, dlgImageSize->cropLayers());
+ }
+ }
+
+ delete dlgImageSize;
+}
+
+void ImageSize::slotLayerSize()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgLayerSize * dlgLayerSize = new DlgLayerSize(m_view, "LayerSize");
+ TQ_CHECK_PTR(dlgLayerSize);
+
+ dlgLayerSize->setCaption(i18n("Layer Size"));
+
+ KisConfig cfg;
+ KisPaintDeviceSP dev = image->activeDevice();
+
+ TQRect rc = dev->exactBounds();
+
+ dlgLayerSize->setWidth(rc.width());
+ dlgLayerSize->setHeight(rc.height());
+
+ if (dlgLayerSize->exec() == TQDialog::Accepted) {
+ TQ_INT32 w = dlgLayerSize->width();
+ TQ_INT32 h = dlgLayerSize->height();
+
+ m_view->scaleLayer((double)w / ((double)(rc.width())),
+ (double)h / ((double)(rc.height())),
+ dlgLayerSize->filterType());
+ }
+ delete dlgLayerSize;
+}
+
+void ImageSize::slotSelectionScale()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ KisPaintDeviceSP layer = image->activeDevice();
+
+ if (!layer) return;
+
+ if (!layer->hasSelection()) return;
+
+
+ DlgLayerSize * dlgLayerSize = new DlgLayerSize(m_view, "SelectionScale");
+ TQ_CHECK_PTR(dlgLayerSize);
+
+ dlgLayerSize->setCaption(i18n("Scale Selection"));
+
+ KisConfig cfg;
+ TQRect rc = layer->selection()->selectedRect();
+
+ dlgLayerSize->setWidth(rc.width());
+ dlgLayerSize->setHeight(rc.height());
+
+ if (dlgLayerSize->exec() == TQDialog::Accepted) {
+ TQ_INT32 w = dlgLayerSize->width();
+ TQ_INT32 h = dlgLayerSize->height();
+
+ KisScaleWorker worker (layer->selection().data(),
+ (double)w / ((double)(rc.width())),
+ (double)h / ((double)(rc.height())),
+ dlgLayerSize->filterType());
+ worker.run();
+
+ m_view->getCanvasController()->updateCanvas();
+
+ }
+ delete dlgLayerSize;
+}
+
+
+#include "imagesize.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/Makefile.am b/chalk/plugins/viewplugins/modify_selection/Makefile.am
index ea0f48429..a1eb18cb3 100644
--- a/chalk/plugins/viewplugins/modify_selection/Makefile.am
+++ b/chalk/plugins/viewplugins/modify_selection/Makefile.am
@@ -13,7 +13,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
$(all_includes)
chalkmodifyselection_la_SOURCES = wdg_grow_selection.ui wdg_shrink_selection.ui wdg_border_selection.ui \
-dlg_grow_selection.cc dlg_shrink_selection.cc dlg_border_selection.cc modify_selection.cc
+dlg_grow_selection.cpp dlg_shrink_selection.cpp dlg_border_selection.cpp modify_selection.cpp
noinst_HEADERS = wdg_grow_selection.h wdg_shrink_selection.h wdg_border_selection.h dlg_grow_selection.h \
dlg_shrink_selection.h dlg_border_selection.h modify_selection.h
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cc b/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cc
deleted file mode 100644
index 7cd1c335d..000000000
--- a/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * dlg_border_selection.cc - part of Chalk
- *
- * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_border_selection.h"
-#include "wdg_border_selection.h"
-
-DlgBorderSelection::DlgBorderSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Border Selection"), Ok | Cancel, Ok)
-{
- m_page = new WdgBorderSelection(this, "border_selection");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
-}
-
-DlgBorderSelection::~DlgBorderSelection()
-{
- delete m_page;
-}
-
-TQ_INT32 DlgBorderSelection::xradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-TQ_INT32 DlgBorderSelection::yradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-
-// SLOTS
-
-void DlgBorderSelection::okClicked()
-{
- accept();
-}
-
-#include "dlg_border_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cpp b/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cpp
new file mode 100644
index 000000000..8e2bc4de8
--- /dev/null
+++ b/chalk/plugins/viewplugins/modify_selection/dlg_border_selection.cpp
@@ -0,0 +1,76 @@
+/*
+ * dlg_border_selection.cpp - part of Chalk
+ *
+ * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_border_selection.h"
+#include "wdg_border_selection.h"
+
+DlgBorderSelection::DlgBorderSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Border Selection"), Ok | Cancel, Ok)
+{
+ m_page = new WdgBorderSelection(this, "border_selection");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
+}
+
+DlgBorderSelection::~DlgBorderSelection()
+{
+ delete m_page;
+}
+
+TQ_INT32 DlgBorderSelection::xradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+TQ_INT32 DlgBorderSelection::yradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+
+// SLOTS
+
+void DlgBorderSelection::okClicked()
+{
+ accept();
+}
+
+#include "dlg_border_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cc b/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cc
deleted file mode 100644
index 38c445b01..000000000
--- a/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * dlg_grow_selection.cc - part of Chalk
- *
- * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_grow_selection.h"
-#include "wdg_grow_selection.h"
-
-DlgGrowSelection::DlgGrowSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Grow Selection"), Ok | Cancel, Ok)
-{
- m_page = new WdgGrowSelection(this, "grow_selection");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
-}
-
-DlgGrowSelection::~DlgGrowSelection()
-{
- delete m_page;
-}
-
-TQ_INT32 DlgGrowSelection::xradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-TQ_INT32 DlgGrowSelection::yradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-
-// SLOTS
-
-void DlgGrowSelection::okClicked()
-{
- accept();
-}
-
-#include "dlg_grow_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cpp b/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cpp
new file mode 100644
index 000000000..ae590eba9
--- /dev/null
+++ b/chalk/plugins/viewplugins/modify_selection/dlg_grow_selection.cpp
@@ -0,0 +1,76 @@
+/*
+ * dlg_grow_selection.cpp - part of Chalk
+ *
+ * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_grow_selection.h"
+#include "wdg_grow_selection.h"
+
+DlgGrowSelection::DlgGrowSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Grow Selection"), Ok | Cancel, Ok)
+{
+ m_page = new WdgGrowSelection(this, "grow_selection");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
+}
+
+DlgGrowSelection::~DlgGrowSelection()
+{
+ delete m_page;
+}
+
+TQ_INT32 DlgGrowSelection::xradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+TQ_INT32 DlgGrowSelection::yradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+
+// SLOTS
+
+void DlgGrowSelection::okClicked()
+{
+ accept();
+}
+
+#include "dlg_grow_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cc b/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cc
deleted file mode 100644
index f0129e742..000000000
--- a/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * dlg_shrink_selection.cc - part of Chalk
- *
- * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_shrink_selection.h"
-#include "wdg_shrink_selection.h"
-
-DlgShrinkSelection::DlgShrinkSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Shrink Selection"), Ok | Cancel, Ok)
-{
- m_page = new WdgShrinkSelection(this, "shrink_selection");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
-}
-
-DlgShrinkSelection::~DlgShrinkSelection()
-{
- delete m_page;
-}
-
-TQ_INT32 DlgShrinkSelection::xradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-TQ_INT32 DlgShrinkSelection::yradius()
-{
- return m_page->radiusSpinBox->value();
-}
-
-bool DlgShrinkSelection::shrinkFromImageBorder()
-{
- return m_page->shrinkFromImageBorderCheckBox->isChecked();
-}
-
-
-// SLOTS
-
-void DlgShrinkSelection::okClicked()
-{
- accept();
-}
-
-#include "dlg_shrink_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cpp b/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cpp
new file mode 100644
index 000000000..ce4ce9d3b
--- /dev/null
+++ b/chalk/plugins/viewplugins/modify_selection/dlg_shrink_selection.cpp
@@ -0,0 +1,81 @@
+/*
+ * dlg_shrink_selection.cpp - part of Chalk
+ *
+ * Copyright (c) 2006 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_shrink_selection.h"
+#include "wdg_shrink_selection.h"
+
+DlgShrinkSelection::DlgShrinkSelection( TQWidget * parent, const char * name) : super (parent, name, true, i18n("Shrink Selection"), Ok | Cancel, Ok)
+{
+ m_page = new WdgShrinkSelection(this, "shrink_selection");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(okClicked()));
+}
+
+DlgShrinkSelection::~DlgShrinkSelection()
+{
+ delete m_page;
+}
+
+TQ_INT32 DlgShrinkSelection::xradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+TQ_INT32 DlgShrinkSelection::yradius()
+{
+ return m_page->radiusSpinBox->value();
+}
+
+bool DlgShrinkSelection::shrinkFromImageBorder()
+{
+ return m_page->shrinkFromImageBorderCheckBox->isChecked();
+}
+
+
+// SLOTS
+
+void DlgShrinkSelection::okClicked()
+{
+ accept();
+}
+
+#include "dlg_shrink_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/modify_selection.cc b/chalk/plugins/viewplugins/modify_selection/modify_selection.cc
deleted file mode 100644
index 92d50ef7a..000000000
--- a/chalk/plugins/viewplugins/modify_selection/modify_selection.cc
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * modify_selection.cc -- Part of Chalk
- *
- * Copyright (c) 2006 Michael Thaler (michael.thaler@physik.tu-muenchen.de)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <stdlib.h>
-
-#include <tqslider.h>
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <kstdaction.h>
-
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_selection.h>
-#include <kis_selection_manager.h>
-#include <kis_transaction.h>
-
-#include "modify_selection.h"
-#include "dlg_grow_selection.h"
-#include "dlg_shrink_selection.h"
-#include "dlg_border_selection.h"
-
-typedef KGenericFactory<ModifySelection> ModifySelectionFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkmodifyselection, ModifySelectionFactory( "chalk" ) )
-
-ModifySelection::ModifySelection(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- if ( parent->inherits("KisView") )
- {
- setInstance(ModifySelectionFactory::instance());
- setXMLFile(locate("data","chalkplugins/modify_selection.rc"), true);
-
- m_view = (KisView*) parent;
-
- // Selection manager takes ownership?
- TDEAction* a = new TDEAction(i18n("Grow Selection..."), 0, 0, this, TQT_SLOT(slotGrowSelection()), actionCollection(), "growselection");
- TDEAction* b = new TDEAction(i18n("Shrink Selection..."), 0, 0, this, TQT_SLOT(slotShrinkSelection()), actionCollection(), "shrinkselection");
- TDEAction* c = new TDEAction(i18n("Border Selection..."), 0, 0, this, TQT_SLOT(slotBorderSelection()), actionCollection(), "borderselection");
-
- TQ_CHECK_PTR(a);
- TQ_CHECK_PTR(b);
- TQ_CHECK_PTR(c);
-
- m_view ->canvasSubject()-> selectionManager()->addSelectionAction(a);
- m_view ->canvasSubject()-> selectionManager()->addSelectionAction(b);
- m_view ->canvasSubject()-> selectionManager()->addSelectionAction(c);
- }
-}
-
-ModifySelection::~ModifySelection()
-{
- m_view = 0;
-}
-
-void ModifySelection::slotGrowSelection()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgGrowSelection * dlgGrowSelection = new DlgGrowSelection(m_view, "GrowSelection");
- TQ_CHECK_PTR(dlgGrowSelection);
-
- dlgGrowSelection->setCaption(i18n("Grow Selection"));
-
- KisConfig cfg;
-
- if (dlgGrowSelection->exec() == TQDialog::Accepted) {
- TQ_INT32 xradius = dlgGrowSelection->xradius();
- TQ_INT32 yradius = dlgGrowSelection->yradius();
-
- m_view ->canvasSubject()-> selectionManager()->grow(xradius, yradius);
- }
-
- delete dlgGrowSelection;
-}
-
-void ModifySelection::slotShrinkSelection()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgShrinkSelection * dlgShrinkSelection = new DlgShrinkSelection(m_view, "ShrinkSelection");
- TQ_CHECK_PTR(dlgShrinkSelection);
-
- dlgShrinkSelection->setCaption(i18n("Shrink Selection"));
-
- KisConfig cfg;
-
- if (dlgShrinkSelection->exec() == TQDialog::Accepted) {
- TQ_INT32 xradius = dlgShrinkSelection->xradius();
- TQ_INT32 yradius = dlgShrinkSelection->yradius();
- bool shrinkFromImageBorder = dlgShrinkSelection->shrinkFromImageBorder();
-
- m_view ->canvasSubject()-> selectionManager()->shrink(xradius, yradius, shrinkFromImageBorder);
- }
-
- delete dlgShrinkSelection;
-}
-
-void ModifySelection::slotBorderSelection()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgBorderSelection * dlgBorderSelection = new DlgBorderSelection(m_view, "BorderSelection");
- TQ_CHECK_PTR(dlgBorderSelection);
-
- dlgBorderSelection->setCaption(i18n("Border Selection"));
-
- KisConfig cfg;
-
- if (dlgBorderSelection->exec() == TQDialog::Accepted) {
- TQ_INT32 xradius = dlgBorderSelection->xradius();
- TQ_INT32 yradius = dlgBorderSelection->yradius();
-
- m_view ->canvasSubject()-> selectionManager()->border(xradius, yradius);
- }
-
- delete dlgBorderSelection;
-}
-
-#include "modify_selection.moc"
diff --git a/chalk/plugins/viewplugins/modify_selection/modify_selection.cpp b/chalk/plugins/viewplugins/modify_selection/modify_selection.cpp
new file mode 100644
index 000000000..823899958
--- /dev/null
+++ b/chalk/plugins/viewplugins/modify_selection/modify_selection.cpp
@@ -0,0 +1,158 @@
+/*
+ * modify_selection.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2006 Michael Thaler (michael.thaler@physik.tu-muenchen.de)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <stdlib.h>
+
+#include <tqslider.h>
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kstdaction.h>
+
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_selection.h>
+#include <kis_selection_manager.h>
+#include <kis_transaction.h>
+
+#include "modify_selection.h"
+#include "dlg_grow_selection.h"
+#include "dlg_shrink_selection.h"
+#include "dlg_border_selection.h"
+
+typedef KGenericFactory<ModifySelection> ModifySelectionFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkmodifyselection, ModifySelectionFactory( "chalk" ) )
+
+ModifySelection::ModifySelection(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ if ( parent->inherits("KisView") )
+ {
+ setInstance(ModifySelectionFactory::instance());
+ setXMLFile(locate("data","chalkplugins/modify_selection.rc"), true);
+
+ m_view = (KisView*) parent;
+
+ // Selection manager takes ownership?
+ TDEAction* a = new TDEAction(i18n("Grow Selection..."), 0, 0, this, TQT_SLOT(slotGrowSelection()), actionCollection(), "growselection");
+ TDEAction* b = new TDEAction(i18n("Shrink Selection..."), 0, 0, this, TQT_SLOT(slotShrinkSelection()), actionCollection(), "shrinkselection");
+ TDEAction* c = new TDEAction(i18n("Border Selection..."), 0, 0, this, TQT_SLOT(slotBorderSelection()), actionCollection(), "borderselection");
+
+ TQ_CHECK_PTR(a);
+ TQ_CHECK_PTR(b);
+ TQ_CHECK_PTR(c);
+
+ m_view ->canvasSubject()-> selectionManager()->addSelectionAction(a);
+ m_view ->canvasSubject()-> selectionManager()->addSelectionAction(b);
+ m_view ->canvasSubject()-> selectionManager()->addSelectionAction(c);
+ }
+}
+
+ModifySelection::~ModifySelection()
+{
+ m_view = 0;
+}
+
+void ModifySelection::slotGrowSelection()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgGrowSelection * dlgGrowSelection = new DlgGrowSelection(m_view, "GrowSelection");
+ TQ_CHECK_PTR(dlgGrowSelection);
+
+ dlgGrowSelection->setCaption(i18n("Grow Selection"));
+
+ KisConfig cfg;
+
+ if (dlgGrowSelection->exec() == TQDialog::Accepted) {
+ TQ_INT32 xradius = dlgGrowSelection->xradius();
+ TQ_INT32 yradius = dlgGrowSelection->yradius();
+
+ m_view ->canvasSubject()-> selectionManager()->grow(xradius, yradius);
+ }
+
+ delete dlgGrowSelection;
+}
+
+void ModifySelection::slotShrinkSelection()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgShrinkSelection * dlgShrinkSelection = new DlgShrinkSelection(m_view, "ShrinkSelection");
+ TQ_CHECK_PTR(dlgShrinkSelection);
+
+ dlgShrinkSelection->setCaption(i18n("Shrink Selection"));
+
+ KisConfig cfg;
+
+ if (dlgShrinkSelection->exec() == TQDialog::Accepted) {
+ TQ_INT32 xradius = dlgShrinkSelection->xradius();
+ TQ_INT32 yradius = dlgShrinkSelection->yradius();
+ bool shrinkFromImageBorder = dlgShrinkSelection->shrinkFromImageBorder();
+
+ m_view ->canvasSubject()-> selectionManager()->shrink(xradius, yradius, shrinkFromImageBorder);
+ }
+
+ delete dlgShrinkSelection;
+}
+
+void ModifySelection::slotBorderSelection()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgBorderSelection * dlgBorderSelection = new DlgBorderSelection(m_view, "BorderSelection");
+ TQ_CHECK_PTR(dlgBorderSelection);
+
+ dlgBorderSelection->setCaption(i18n("Border Selection"));
+
+ KisConfig cfg;
+
+ if (dlgBorderSelection->exec() == TQDialog::Accepted) {
+ TQ_INT32 xradius = dlgBorderSelection->xradius();
+ TQ_INT32 yradius = dlgBorderSelection->yradius();
+
+ m_view ->canvasSubject()-> selectionManager()->border(xradius, yradius);
+ }
+
+ delete dlgBorderSelection;
+}
+
+#include "modify_selection.moc"
diff --git a/chalk/plugins/viewplugins/performancetest/Makefile.am b/chalk/plugins/viewplugins/performancetest/Makefile.am
index 47906073b..eebf1f4d6 100644
--- a/chalk/plugins/viewplugins/performancetest/Makefile.am
+++ b/chalk/plugins/viewplugins/performancetest/Makefile.am
@@ -13,7 +13,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkperftest.la
-chalkperftest_la_SOURCES = wdg_perftest.ui perftest.cc dlg_perftest.cc
+chalkperftest_la_SOURCES = wdg_perftest.ui perftest.cpp dlg_perftest.cpp
noinst_HEADERS = wdg_perftest.h dlg_perftest.h perftest.h
chalkperftest_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/performancetest/dlg_perftest.cc b/chalk/plugins/viewplugins/performancetest/dlg_perftest.cc
deleted file mode 100644
index b2a723069..000000000
--- a/chalk/plugins/viewplugins/performancetest/dlg_perftest.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * dlg_perftest.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqpushbutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_perftest.h"
-#include "wdg_perftest.h"
-
-
-DlgPerfTest::DlgPerfTest( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Performance Test"), Ok | Cancel, Ok)
-{
- m_lock = false;
-
- m_page = new WdgPerfTest(this, "perf_test");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
- connect(m_page->btnSelectAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(selectAllClicked()));
- connect(m_page->btnDeselectAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(deselectAllClicked()));
-}
-
-DlgPerfTest::~DlgPerfTest()
-{
- delete m_page;
-}
-
-WdgPerfTest * DlgPerfTest::page()
-{
- return m_page;
-}
-
-// SLOTS
-
-void DlgPerfTest::okClicked()
-{
- accept();
-}
-
-void DlgPerfTest::setAllTestCheckBoxes(bool checked)
-{
- m_page->chkBitBlt->setChecked(checked);
- m_page->chkFill->setChecked(checked);
- m_page->chkGradient->setChecked(checked);
- m_page->chkPixel->setChecked(checked);
- m_page->chkShape->setChecked(checked);
- m_page->chkLayer->setChecked(checked);
- m_page->chkScale->setChecked(checked);
- m_page->chkRotate->setChecked(checked);
- m_page->chkRender->setChecked(checked);
- m_page->chkSelection->setChecked(checked);
- m_page->chkColorConversion->setChecked(checked);
- m_page->chkFilter->setChecked(checked);
- m_page->chkReadBytes->setChecked(checked);
- m_page->chkWriteBytes->setChecked(checked);
- m_page->chkIterators->setChecked(checked);
- m_page->chkPaintView->setChecked(checked);
- m_page->chkPaintViewFPS->setChecked(checked);
-}
-
-void DlgPerfTest::selectAllClicked()
-{
- setAllTestCheckBoxes(true);
-}
-
-void DlgPerfTest::deselectAllClicked()
-{
- setAllTestCheckBoxes(false);
-}
-
-
-#include "dlg_perftest.moc"
diff --git a/chalk/plugins/viewplugins/performancetest/dlg_perftest.cpp b/chalk/plugins/viewplugins/performancetest/dlg_perftest.cpp
new file mode 100644
index 000000000..326d97272
--- /dev/null
+++ b/chalk/plugins/viewplugins/performancetest/dlg_perftest.cpp
@@ -0,0 +1,110 @@
+/*
+ * dlg_perftest.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqpushbutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_perftest.h"
+#include "wdg_perftest.h"
+
+
+DlgPerfTest::DlgPerfTest( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Performance Test"), Ok | Cancel, Ok)
+{
+ m_lock = false;
+
+ m_page = new WdgPerfTest(this, "perf_test");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+ connect(m_page->btnSelectAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(selectAllClicked()));
+ connect(m_page->btnDeselectAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(deselectAllClicked()));
+}
+
+DlgPerfTest::~DlgPerfTest()
+{
+ delete m_page;
+}
+
+WdgPerfTest * DlgPerfTest::page()
+{
+ return m_page;
+}
+
+// SLOTS
+
+void DlgPerfTest::okClicked()
+{
+ accept();
+}
+
+void DlgPerfTest::setAllTestCheckBoxes(bool checked)
+{
+ m_page->chkBitBlt->setChecked(checked);
+ m_page->chkFill->setChecked(checked);
+ m_page->chkGradient->setChecked(checked);
+ m_page->chkPixel->setChecked(checked);
+ m_page->chkShape->setChecked(checked);
+ m_page->chkLayer->setChecked(checked);
+ m_page->chkScale->setChecked(checked);
+ m_page->chkRotate->setChecked(checked);
+ m_page->chkRender->setChecked(checked);
+ m_page->chkSelection->setChecked(checked);
+ m_page->chkColorConversion->setChecked(checked);
+ m_page->chkFilter->setChecked(checked);
+ m_page->chkReadBytes->setChecked(checked);
+ m_page->chkWriteBytes->setChecked(checked);
+ m_page->chkIterators->setChecked(checked);
+ m_page->chkPaintView->setChecked(checked);
+ m_page->chkPaintViewFPS->setChecked(checked);
+}
+
+void DlgPerfTest::selectAllClicked()
+{
+ setAllTestCheckBoxes(true);
+}
+
+void DlgPerfTest::deselectAllClicked()
+{
+ setAllTestCheckBoxes(false);
+}
+
+
+#include "dlg_perftest.moc"
diff --git a/chalk/plugins/viewplugins/performancetest/perftest.cc b/chalk/plugins/viewplugins/performancetest/perftest.cc
deleted file mode 100644
index f728043cd..000000000
--- a/chalk/plugins/viewplugins/performancetest/perftest.cc
+++ /dev/null
@@ -1,1198 +0,0 @@
-/*
- * perftest.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <math.h>
-
-#include <stdlib.h>
-
-#include <tqslider.h>
-#include <tqpoint.h>
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-#include <tqtextedit.h>
-#include <tqdatetime.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <kdialogbase.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <knuminput.h>
-
-#include <tqcolor.h>
-
-#include "kis_meta_registry.h"
-#include <kis_resourceserver.h>
-#include "kis_cursor.h"
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_selection.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_colorspace.h>
-#include <kis_painter.h>
-#include <kis_fill_painter.h>
-#include <kis_id.h>
-#include <kis_paint_device.h>
-#include <kis_iterators_pixel.h>
-#include "perftest.h"
-#include "kis_filter_config_widget.h"
-#include "kis_factory.h"
-
-#include "dlg_perftest.h"
-#include "wdg_perftest.h"
-
-#define USE_CALLGRIND 0
-
-#if USE_CALLGRIND
-#include <valgrind/callgrind.h>
-#endif
-
-
-typedef KGenericFactory<PerfTest> PerfTestFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkperftest, PerfTestFactory( "chalk" ) )
-
-PerfTest::PerfTest(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- if ( parent->inherits("KisView") )
- {
- setInstance(PerfTestFactory::instance());
- setXMLFile(locate("data","chalkplugins/perftest.rc"), true);
-
- (void) new TDEAction(i18n("&Performance Test..."), 0, 0, this, TQT_SLOT(slotPerfTest()), actionCollection(), "perf_test");
-
- m_view = (KisView*) parent;
- }
-}
-
-PerfTest::~PerfTest()
-{
- m_view = 0;
-}
-
-void PerfTest::slotPerfTest()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgPerfTest * dlgPerfTest = new DlgPerfTest(m_view, "PerfTest");
- TQ_CHECK_PTR(dlgPerfTest);
-
- dlgPerfTest->setCaption(i18n("Performance Test"));
-
- TQString report = TQString("");
-
- if (dlgPerfTest->exec() == TQDialog::Accepted) {
-
- TQ_INT32 testCount = (TQ_INT32)tqRound(dlgPerfTest->page()->intTestCount->value());
-
- if (dlgPerfTest->page()->chkBitBlt->isChecked()) {
- kdDebug() << "bltTest:\n";
- TQString s = bltTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkFill->isChecked()) {
- kdDebug() << "Filltest\n";
- TQString s= fillTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkGradient->isChecked()) {
- kdDebug() << "Gradienttest\n";
- TQString s = gradientTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkPixel->isChecked()) {
- kdDebug() << "Pixeltest\n";
- TQString s = pixelTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkShape->isChecked()) {
- kdDebug() << "Shapetest\n";
- TQString s = shapeTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkLayer->isChecked()) {
- kdDebug() << "LayerTest\n";
- TQString s = layerTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkScale->isChecked()) {
- kdDebug() << "Scaletest\n";
- TQString s = scaleTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkRotate->isChecked()) {
- kdDebug() << "Rotatetest\n";
- TQString s = rotateTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkRender->isChecked()) {
- kdDebug() << "Rendertest\n";
- TQString s = renderTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkSelection->isChecked()) {
- kdDebug() << "Selectiontest\n";
- TQString s = selectionTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkColorConversion->isChecked()) {
- kdDebug() << "Colorconversiontest\n";
- TQString s = colorConversionTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkFilter-> isChecked()) {
- kdDebug() << "filtertest\n";
- TQString s = filterTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkReadBytes->isChecked()) {
- kdDebug() << "Readbytes test\n";
- TQString s = readBytesTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkWriteBytes-> isChecked()) {
- kdDebug() << "Writebytes test\n";
- TQString s = writeBytesTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkIterators->isChecked()) {
- kdDebug() << "Iterators test\n";
- TQString s = iteratorTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkPaintView->isChecked()) {
- kdDebug() << "paintview test\n";
- TQString s = paintViewTest(testCount);
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- if (dlgPerfTest->page()->chkPaintViewFPS->isChecked()) {
- kdDebug() << "paint current view (fps) test\n";
- TQString s = paintViewFPSTest();
- report = report.append(s);
- kdDebug() << s << "\n";
- }
- KDialogBase * d = new KDialogBase(m_view, "", true, "", KDialogBase::Ok);
- TQ_CHECK_PTR(d);
-
- d->setCaption("Performance test results");
- TQTextEdit * e = new TQTextEdit(d);
- TQ_CHECK_PTR(e);
- d->setMainWidget(e);
- e->setText(report);
- e->setMinimumWidth(600);
- e->setMinimumHeight(600);
- d->exec();
- delete d;
-
- }
- delete dlgPerfTest;
-}
-
-TQString PerfTest::bltTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* bitBlt test\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
-
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
-
- kdDebug() << "Image->" << (*it).name() << "\n";
-
- report = report.append( " Testing blitting on " + (*it).name() + "\n");
-
- KisImageSP img = doc->newImage("blt-" + (*it).name(), 1000, 1000,
- KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
-
- report = report.append(doBlit(COMPOSITE_OVER, *it, OPACITY_OPAQUE, testCount, img));
- report = report.append( "\n");
- report = report.append(doBlit(COMPOSITE_OVER, *it, OPACITY_OPAQUE / 2, testCount, img));
- report = report.append( "\n");
- report = report.append(doBlit(COMPOSITE_COPY, *it, OPACITY_OPAQUE, testCount, img));
- report = report.append( "\n");
- report = report.append(doBlit(COMPOSITE_COPY, *it, OPACITY_OPAQUE / 2, testCount, img));
- report = report.append( "\n");
- }
-
- return report;
-
-
-}
-
-
-TQString PerfTest::doBlit(const KisCompositeOp& op,
- KisID cspace,
- TQ_UINT8 opacity,
- TQ_UINT32 testCount,
- KisImageSP img)
-{
-
- TQTime t;
- TQString report;
-
- // ------------------------------------------------------------------------------
- // Small
-
- KisPaintDeviceSP small = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "small blit");
- TQ_CHECK_PTR(small);
-
- KisFillPainter pf(small.data()) ;
- pf.fillRect(0, 0, 32, 32, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- pf.end();
-
- t.restart();
- KisPainter p(img->activeDevice());
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.bitBlt(0, 0, op, small.data(),0,0,32, 32);
- }
- p.end();
-
- report = report.append(TQString(" %1 blits of rectangles < tilesize with opacity %2 and composite op %3: %4ms\n")
- .arg(testCount)
- .arg(opacity)
- .arg(op.id().name())
- .arg(t.elapsed()));
-
-
- // ------------------------------------------------------------------------------
- // Medium
- KisPaintDeviceSP medium = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "medium blit");
- TQ_CHECK_PTR(medium);
-
- pf.begin(medium.data()) ;
- pf.fillRect(0, 0, 64 * 3, 64 * 3, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- pf.end();
-
- t.restart();
- p.begin(img->activeDevice().data());
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.bitBlt(0, 0, op, medium.data(),0,0,96, 96);
- }
- p.end();
-
- report = report.append(TQString(" %1 blits of rectangles 3 * tilesize with opacity %2 and composite op %3: %4ms\n")
- .arg(testCount)
- .arg(opacity)
- .arg(op.id().name())
- .arg(t.elapsed()));
-
-
- // ------------------------------------------------------------------------------
- // Big
- KisPaintDeviceSP big = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "big blit");
- TQ_CHECK_PTR(big);
-
- pf.begin(big.data()) ;
- pf.fillRect(0, 0, 800, 800, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- pf.end();
-
- t.restart();
- p.begin(img->activeDevice().data());
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.bitBlt(0, 0, op, big.data(),0,0,800,800);
-
- }
- p.end();
- report = report.append(TQString(" %1 blits of rectangles 800 x 800 with opacity %2 and composite op %3: %4ms\n")
- .arg(testCount)
- .arg(opacity)
- .arg(op.id().name())
- .arg(t.elapsed()));
-
-
- // ------------------------------------------------------------------------------
- // Outside
-
- KisPaintDeviceSP outside = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "outside blit");
- TQ_CHECK_PTR(outside);
- pf.begin(outside.data()) ;
- pf.fillRect(0, 0, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- pf.end();
-
- t.restart();
- p.begin(img->activeDevice().data());
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.bitBlt(600, 600, op, outside.data(),0,0,500,500);
-
- }
- p.end();
- report = report.append(TQString(" %1 blits of rectangles 500 x 500 at 600,600 with opacity %2 and composite op %3: %4ms\n")
- .arg(testCount)
- .arg(opacity)
- .arg(op.id().name())
- .arg(t.elapsed()));
-
- // ------------------------------------------------------------------------------
- // Small with varied source opacity
-
- KisPaintDeviceSP small_with_alpha = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "small blit with alpha");
- TQ_CHECK_PTR(small_with_alpha);
-
- pf.begin(small_with_alpha.data()) ;
- pf.fillRect(0, 0, 32, 32, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_TRANSPARENT);
- pf.fillRect(4, 4, 24, 24, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
- pf.fillRect(8, 8, 16, 16, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE);
- pf.end();
-
- t.restart();
- p.begin(img->activeDevice().data());
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.bitBlt(0, 0, op, small_with_alpha.data(), 0, 0, 32, 32);
- }
- p.end();
-
- report = report.append(TQString(" %1 blits of rectangles < tilesize with source alpha, with opacity %2 and composite op %3: %4ms\n")
- .arg(testCount)
- .arg(opacity)
- .arg(op.id().name())
- .arg(t.elapsed()));
-
- return report;
-
-}
-
-TQString PerfTest::fillTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* Fill test\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
-
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
- kdDebug() << "Filltest on " << (*it).name() + "\n";
-
- report = report.append( " Testing blitting on " + (*it).name() + "\n");
-
- KisImageSP img = doc->newImage("fill-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
- KisPaintDeviceSP l = img->activeDevice();
-
- // Rect fill
- KisFillPainter p(l.data());
- TQTime t;
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.eraseRect(0, 0, 1000, 1000);
- }
- report = report.append(TQString(" Erased 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.eraseRect(50, 50, 500, 500);
- }
- report = report.append(TQString(" Erased 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.eraseRect(-50, -50, 1100, 1100);
- }
- report = report.append(TQString(" Erased rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- // Opaque Rect fill
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- }
- report = report.append(TQString(" Opaque fill 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(50, 50, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- }
- report = report.append(TQString(" Opaque fill 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(-50, -50, 1100, 1100, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- }
- report = report.append(TQString(" Opaque fill rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- // Transparent rect fill
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
- }
- report = report.append(TQString(" Opaque fill 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(50, 50, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
- }
- report = report.append(TQString(" Opaque fill 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.fillRect(-50, -50, 1100, 1100, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
- }
- report = report.append(TQString(" Opaque fill rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- // Colour fill
-
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.eraseRect(0, 0, 1000, 1000);
-// p.paintEllipse(500, 1000, 100, 0, 0);
- p.setPaintColor(KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.setFillThreshold(15);
- p.setCompositeOp(COMPOSITE_OVER);
- p.fillColor(0,0);
- }
- report = report.append(TQString(" Opaque floodfill of whole circle (incl. erase and painting of circle) %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
- // Pattern fill
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- p.eraseRect(0, 0, 1000, 1000);
-// p.paintEllipse(500, 1000, 100, 0, 0);
- p.setPaintColor(KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- KisResourceServerBase* r = KisResourceServerRegistry::instance()->get("PatternServer");
- TQ_CHECK_PTR(r);
- p.setPattern((KisPattern*)r->resources().first());
- p.setFillThreshold(15);
- p.setCompositeOp(COMPOSITE_OVER);
- p.fillPattern(0,0);
- }
- report = report.append(TQString(" Opaque patternfill of whole circle (incl. erase and painting of circle) %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
-
-
- }
-
-
-
- return report;
-
-}
-
-TQString PerfTest::gradientTest(TQ_UINT32 testCount)
-{
- return TQString("Gradient test\n");
-}
-
-TQString PerfTest::pixelTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* pixel/setpixel test\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
-
-
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
- report = report.append( " Testing pixel/setpixel on " + (*it).name() + "\n");
-
- KisImageSP img = doc->newImage("fill-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
-
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- TQColor c = TQt::black;
- TQ_UINT8 opacity = OPACITY_OPAQUE;
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- for (TQ_UINT32 x = 0; x < 1000; ++x) {
- for (TQ_UINT32 y = 0; y < 1000; ++y) {
- l->pixel(x, y, &c, &opacity);
- }
- }
- }
- report = report.append(TQString(" read 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- c= TQt::black;
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- for (TQ_UINT32 x = 0; x < 1000; ++x) {
- for (TQ_UINT32 y = 0; y < 1000; ++y) {
- l->setPixel(x, y, c, 128);
- }
- }
- }
- report = report.append(TQString(" written 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- }
-
-
-
-
- return report;
-
-}
-
-TQString PerfTest::shapeTest(TQ_UINT32 testCount)
-{
- return TQString("Shape test\n");
-}
-
-TQString PerfTest::layerTest(TQ_UINT32 testCount)
-{
- return TQString("Layer test\n");
-}
-
-TQString PerfTest::scaleTest(TQ_UINT32 testCount)
-{
- return TQString("Scale test\n");
-}
-
-TQString PerfTest::rotateTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* Rotate test\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
-
- doc->undoAdapter()->setUndo( false );
- TQTime t;
-
- for (uint i = 0; i < testCount; ++i) {
- for (double angle = 0; angle < 360; ++angle) {
- kdDebug() << "Rotating " << (*it).name() << " at " << angle << " degrees\n";
- KisImage * img = doc->newImage("cs-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
- img->rotate(angle, m_view->canvasSubject()->progressDisplay());
- kdDebug() << "Size: " << img->projection()->extent() << endl;
- delete img;
- }
- }
- report = report.append(TQString(" rotated 1000 x 1000 pixels over 360 degrees, degree by degree, %1 times: %2\n").arg(testCount).arg(t.elapsed()));
- }
- return report;
-}
-
-TQString PerfTest::renderTest(TQ_UINT32 restCount)
-{
- return TQString("Render test\n");
-}
-
-TQString PerfTest::selectionTest(TQ_UINT32 testCount)
-{
- return TQString("Selection test\n");
-}
-
-TQString PerfTest::colorConversionTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* Colorspace conversion test\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
-
- KisImage * img = doc->newImage("cs-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
-
- TQTime t;
-
- KisIDList l2 = KisMetaRegistry::instance()->csRegistry()->listKeys();
- for (KisIDList::Iterator it2 = l2.begin(); it2 != l2.end(); ++it2) {
- kdDebug() << "test conversion from " << (*it).name() << " to " << (*it2).name() << endl;
-
- t.restart();
- for (uint i = 0; i < testCount; ++i) {
- KisImage * img2 = new KisImage(*img);
- img2->convertTo(KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it2,""));
- delete img2;
- }
- report = report.append(TQString(" converted from " + (*it).name() + " to " + (*it2).name() + " 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- }
-
- delete img;
-
- }
- return report;
-
-}
-
-TQString PerfTest::filterTest(TQ_UINT32 testCount)
-{
-
- TQString report = TQString("* Filter test\n");
-
- KisIDList filters = KisFilterRegistry::instance()->listKeys();
- KisDoc * doc = m_view->canvasSubject()->document();
- KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
-
- for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
- report = report.append( " Testing filtering on " + (*it).name() + "\n");
-
- KisImageSP img = doc->newImage("filter-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
-
- for (KisIDList::Iterator it = filters.begin(); it != filters.end(); ++it) {
-
- KisFilterSP f = KisFilterRegistry::instance()->get(*it);
- t.restart();
- kdDebug() << "test filter " << f->id().name() << " on " << img->colorSpace()->id().name() << endl;
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- f->enableProgress();
- f->process(l.data(), l.data(), f->configuration(f->createConfigurationWidget(m_view, l.data())), TQRect(0, 0, 1000, 1000));
- f->disableProgress();
- }
- report = report.append(TQString(" filtered " + (*it).name() + "1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
-
- }
-
- }
- return report;
-
-}
-
-TQString PerfTest::readBytesTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* Read bytes test\n\n");
-
- // On default tiles
- KisDoc * doc = m_view->canvasSubject()->document();
- KisImageSP img = doc->newImage("Readbytes ", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA",""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- TQ_UINT8 * newData = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
- TQ_CHECK_PTR(newData);
- l->readBytes(newData, 0, 0, 1000, 1000);
- delete[] newData;
- }
-
- report = report.append(TQString(" read 1000 x 1000 pixels %1 times from empty image: %2\n").arg(testCount).arg(t.elapsed()));
-
- // On tiles with data
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- TQ_UINT8 * newData = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
- TQ_CHECK_PTR(newData);
- l->readBytes(newData, 0, 0, 1000, 1000);
- delete[] newData;
- }
-
- report = report.append(TQString(" read 1000 x 1000 pixels %1 times from filled image: %2\n").arg(testCount).arg(t.elapsed()));
-
- return report;
-}
-
-
-TQString PerfTest::writeBytesTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* Write bytes test");
-
- // On default tiles
- KisDoc * doc = m_view->canvasSubject()->document();
- KisImageSP img = doc->newImage("Writebytes ", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
-
- TQ_UINT8 * data = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
- TQ_CHECK_PTR(data);
- l->readBytes(data, 0, 0, 1000, 1000);
-
- TQTime t;
- t.restart();
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- l->writeBytes(data, 0, 0, 1000, 1000);
- }
- delete[] data;
- report = report.append(TQString(" written 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
- return report;
-
-
-}
-
-/////// Iterator tests
-
-
-TQString hlineRODefault(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- int adv;
-
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, false);
- while(! hiter.isDone())
- {
- adv = hiter.nConseqHPixels();
- hiter += adv;
- }
- }
-
- }
-
- return TQString(" hline iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-
-
-}
-
-TQString hlineRO(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- int adv;
-
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, false);
- while(! hiter.isDone())
- {
- adv = hiter.nConseqHPixels();
- hiter += adv;
- }
- }
-
- }
-
- return TQString(" hline iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString hlineWRDefault(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- int adv;
-
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, true);
- while(! hiter.isDone())
- {
- adv = hiter.nConseqHPixels();
- hiter += adv;
- }
- }
-
- }
-
- return TQString(" hline iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString hlineWR(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- int adv;
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, true);
- while(! hiter.isDone())
- {
- adv = hiter.nConseqHPixels();
- hiter += adv;
- }
- }
-
- }
-
- return TQString(" hline iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-
-TQString vlineRODefault(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
- while(! hiter.isDone())
- {
- ++hiter;
- }
- }
-
- }
-
- return TQString(" vline iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString vlineRO(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
- while(! hiter.isDone())
- {
- ++hiter;
- }
- }
-
- }
-
- return TQString(" vline iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString vlineWRDefault(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
-
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
- while(! hiter.isDone())
- {
- ++hiter;
- }
- }
-
- }
-
- return TQString(" vline iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-}
-
-TQString vlineWR(KisDoc * doc, TQ_UINT32 testCount)
-{
-
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
- {
- KisHLineIterator hiter = l->createHLineIterator(y2, 0, 1000, true);
- while(! hiter.isDone())
- {
- ++hiter;
- }
- }
-
- }
-
- return TQString(" vline iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString rectRODefault(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-;
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, false);
- while(! r.isDone())
- {
- ++r;
- }
- }
-
- return TQString(" rect iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-
-
-}
-
-TQString rectRO(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, false);
- while(! r.isDone())
- {
- ++r;
- }
- }
-
- return TQString(" rect iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString rectWRDefault(KisDoc * doc, TQ_UINT32 testCount)
-{
-
-
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- TQTime t;
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, true);
- while(! r.isDone())
- {
- ++r;
- }
- }
-
- return TQString(" rect iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
-
-}
-
-TQString rectWR(KisDoc * doc, TQ_UINT32 testCount)
-{
- KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
-
- TQTime t;
- t.restart();
-
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, true);
- while(! r.isDone())
- {
- ++r;
- }
- }
-
-
- return TQString(" rect iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
-
-
-}
-TQString PerfTest::iteratorTest(TQ_UINT32 testCount)
-{
- TQString report = "Iterator test";
-
- KisDoc * doc = m_view->canvasSubject()->document();
-
- report = report.append(hlineRODefault(doc, testCount));
- report = report.append(hlineRO(doc, testCount));
- report = report.append(hlineWRDefault(doc, testCount));
- report = report.append(hlineWR(doc, testCount));
-
- report = report.append(vlineRODefault(doc, testCount));
- report = report.append(vlineRO(doc, testCount));
- report = report.append(vlineWRDefault(doc, testCount));
- report = report.append(vlineWR(doc, testCount));
-
- report = report.append(rectRODefault(doc, testCount));
- report = report.append(rectRO(doc, testCount));
- report = report.append(rectWRDefault(doc, testCount));
- report = report.append(rectWR(doc, testCount));
-
- return report;
-
-
-}
-
-TQString PerfTest::paintViewTest(TQ_UINT32 testCount)
-{
- TQString report = TQString("* paintView test\n\n");
-
- KisDoc * doc = m_view->canvasSubject()->document();
-
- KisImageSP img = doc->currentImage();
- img->resize(512,512);
-
-
- KisPaintDeviceSP l = img->activeDevice();
-
- KisFillPainter p(l.data());
- p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- TQTime t;
- t.restart();
-
-#if USE_CALLGRIND
- CALLGRIND_ZERO_STATS();
-#endif
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- m_view->getCanvasController()->updateCanvas(TQRect(0, 0, 512, 512));
- }
-
-#if USE_CALLGRIND
- CALLGRIND_DUMP_STATS();
-#endif
-
- report = report.append(TQString(" painted a 512 x 512 image %1 times: %2 ms\n").arg(testCount).arg(t.elapsed()));
-
- img->newLayer("layer 2", OPACITY_OPAQUE);
- l = img->activeDevice();
-
- p.begin(l.data());
- p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- img->newLayer("layer 3", OPACITY_OPAQUE);
- l = img->activeDevice();
-
- p.begin(l.data());
- p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
- p.end();
-
- t.restart();
-
- for (TQ_UINT32 i = 0; i < testCount; ++i) {
- m_view->getCanvasController()->updateCanvas(TQRect(0, 0, 512, 512));
- }
-
- report = report.append(TQString(" painted a 512 x 512 image with 3 layers %1 times: %2 ms\n").arg(testCount).arg(t.elapsed()));
-
- return report;
-}
-
-TQString PerfTest::paintViewFPSTest()
-{
- TQString report = TQString("* paintView (fps) test\n\n");
-
- TQTime t;
- t.restart();
-
-#if USE_CALLGRIND
- CALLGRIND_ZERO_STATS();
-#endif
-
- int numViewsPainted = 0;
- const int millisecondsPerSecond = 1000;
-
- while (t.elapsed() < millisecondsPerSecond) {
- m_view->getCanvasController()->updateCanvas();
- numViewsPainted++;
- }
-
-#if USE_CALLGRIND
- CALLGRIND_DUMP_STATS();
-#endif
-
- report = report.append(TQString(" painted current view at %1 frames per second\n").arg(numViewsPainted));
-
- return report;
-}
-
-#include "perftest.moc"
diff --git a/chalk/plugins/viewplugins/performancetest/perftest.cpp b/chalk/plugins/viewplugins/performancetest/perftest.cpp
new file mode 100644
index 000000000..fa5445516
--- /dev/null
+++ b/chalk/plugins/viewplugins/performancetest/perftest.cpp
@@ -0,0 +1,1198 @@
+/*
+ * perftest.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <math.h>
+
+#include <stdlib.h>
+
+#include <tqslider.h>
+#include <tqpoint.h>
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+#include <tqtextedit.h>
+#include <tqdatetime.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <kdialogbase.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <knuminput.h>
+
+#include <tqcolor.h>
+
+#include "kis_meta_registry.h"
+#include <kis_resourceserver.h>
+#include "kis_cursor.h"
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_selection.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_colorspace.h>
+#include <kis_painter.h>
+#include <kis_fill_painter.h>
+#include <kis_id.h>
+#include <kis_paint_device.h>
+#include <kis_iterators_pixel.h>
+#include "perftest.h"
+#include "kis_filter_config_widget.h"
+#include "kis_factory.h"
+
+#include "dlg_perftest.h"
+#include "wdg_perftest.h"
+
+#define USE_CALLGRIND 0
+
+#if USE_CALLGRIND
+#include <valgrind/callgrind.h>
+#endif
+
+
+typedef KGenericFactory<PerfTest> PerfTestFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkperftest, PerfTestFactory( "chalk" ) )
+
+PerfTest::PerfTest(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ if ( parent->inherits("KisView") )
+ {
+ setInstance(PerfTestFactory::instance());
+ setXMLFile(locate("data","chalkplugins/perftest.rc"), true);
+
+ (void) new TDEAction(i18n("&Performance Test..."), 0, 0, this, TQT_SLOT(slotPerfTest()), actionCollection(), "perf_test");
+
+ m_view = (KisView*) parent;
+ }
+}
+
+PerfTest::~PerfTest()
+{
+ m_view = 0;
+}
+
+void PerfTest::slotPerfTest()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgPerfTest * dlgPerfTest = new DlgPerfTest(m_view, "PerfTest");
+ TQ_CHECK_PTR(dlgPerfTest);
+
+ dlgPerfTest->setCaption(i18n("Performance Test"));
+
+ TQString report = TQString("");
+
+ if (dlgPerfTest->exec() == TQDialog::Accepted) {
+
+ TQ_INT32 testCount = (TQ_INT32)tqRound(dlgPerfTest->page()->intTestCount->value());
+
+ if (dlgPerfTest->page()->chkBitBlt->isChecked()) {
+ kdDebug() << "bltTest:\n";
+ TQString s = bltTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkFill->isChecked()) {
+ kdDebug() << "Filltest\n";
+ TQString s= fillTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkGradient->isChecked()) {
+ kdDebug() << "Gradienttest\n";
+ TQString s = gradientTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkPixel->isChecked()) {
+ kdDebug() << "Pixeltest\n";
+ TQString s = pixelTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkShape->isChecked()) {
+ kdDebug() << "Shapetest\n";
+ TQString s = shapeTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkLayer->isChecked()) {
+ kdDebug() << "LayerTest\n";
+ TQString s = layerTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkScale->isChecked()) {
+ kdDebug() << "Scaletest\n";
+ TQString s = scaleTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkRotate->isChecked()) {
+ kdDebug() << "Rotatetest\n";
+ TQString s = rotateTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkRender->isChecked()) {
+ kdDebug() << "Rendertest\n";
+ TQString s = renderTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkSelection->isChecked()) {
+ kdDebug() << "Selectiontest\n";
+ TQString s = selectionTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkColorConversion->isChecked()) {
+ kdDebug() << "Colorconversiontest\n";
+ TQString s = colorConversionTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkFilter-> isChecked()) {
+ kdDebug() << "filtertest\n";
+ TQString s = filterTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkReadBytes->isChecked()) {
+ kdDebug() << "Readbytes test\n";
+ TQString s = readBytesTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkWriteBytes-> isChecked()) {
+ kdDebug() << "Writebytes test\n";
+ TQString s = writeBytesTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkIterators->isChecked()) {
+ kdDebug() << "Iterators test\n";
+ TQString s = iteratorTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkPaintView->isChecked()) {
+ kdDebug() << "paintview test\n";
+ TQString s = paintViewTest(testCount);
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ if (dlgPerfTest->page()->chkPaintViewFPS->isChecked()) {
+ kdDebug() << "paint current view (fps) test\n";
+ TQString s = paintViewFPSTest();
+ report = report.append(s);
+ kdDebug() << s << "\n";
+ }
+ KDialogBase * d = new KDialogBase(m_view, "", true, "", KDialogBase::Ok);
+ TQ_CHECK_PTR(d);
+
+ d->setCaption("Performance test results");
+ TQTextEdit * e = new TQTextEdit(d);
+ TQ_CHECK_PTR(e);
+ d->setMainWidget(e);
+ e->setText(report);
+ e->setMinimumWidth(600);
+ e->setMinimumHeight(600);
+ d->exec();
+ delete d;
+
+ }
+ delete dlgPerfTest;
+}
+
+TQString PerfTest::bltTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* bitBlt test\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+
+ kdDebug() << "Image->" << (*it).name() << "\n";
+
+ report = report.append( " Testing blitting on " + (*it).name() + "\n");
+
+ KisImageSP img = doc->newImage("blt-" + (*it).name(), 1000, 1000,
+ KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+
+ report = report.append(doBlit(COMPOSITE_OVER, *it, OPACITY_OPAQUE, testCount, img));
+ report = report.append( "\n");
+ report = report.append(doBlit(COMPOSITE_OVER, *it, OPACITY_OPAQUE / 2, testCount, img));
+ report = report.append( "\n");
+ report = report.append(doBlit(COMPOSITE_COPY, *it, OPACITY_OPAQUE, testCount, img));
+ report = report.append( "\n");
+ report = report.append(doBlit(COMPOSITE_COPY, *it, OPACITY_OPAQUE / 2, testCount, img));
+ report = report.append( "\n");
+ }
+
+ return report;
+
+
+}
+
+
+TQString PerfTest::doBlit(const KisCompositeOp& op,
+ KisID cspace,
+ TQ_UINT8 opacity,
+ TQ_UINT32 testCount,
+ KisImageSP img)
+{
+
+ TQTime t;
+ TQString report;
+
+ // ------------------------------------------------------------------------------
+ // Small
+
+ KisPaintDeviceSP small = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "small blit");
+ TQ_CHECK_PTR(small);
+
+ KisFillPainter pf(small.data()) ;
+ pf.fillRect(0, 0, 32, 32, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ pf.end();
+
+ t.restart();
+ KisPainter p(img->activeDevice());
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.bitBlt(0, 0, op, small.data(),0,0,32, 32);
+ }
+ p.end();
+
+ report = report.append(TQString(" %1 blits of rectangles < tilesize with opacity %2 and composite op %3: %4ms\n")
+ .arg(testCount)
+ .arg(opacity)
+ .arg(op.id().name())
+ .arg(t.elapsed()));
+
+
+ // ------------------------------------------------------------------------------
+ // Medium
+ KisPaintDeviceSP medium = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "medium blit");
+ TQ_CHECK_PTR(medium);
+
+ pf.begin(medium.data()) ;
+ pf.fillRect(0, 0, 64 * 3, 64 * 3, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ pf.end();
+
+ t.restart();
+ p.begin(img->activeDevice().data());
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.bitBlt(0, 0, op, medium.data(),0,0,96, 96);
+ }
+ p.end();
+
+ report = report.append(TQString(" %1 blits of rectangles 3 * tilesize with opacity %2 and composite op %3: %4ms\n")
+ .arg(testCount)
+ .arg(opacity)
+ .arg(op.id().name())
+ .arg(t.elapsed()));
+
+
+ // ------------------------------------------------------------------------------
+ // Big
+ KisPaintDeviceSP big = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "big blit");
+ TQ_CHECK_PTR(big);
+
+ pf.begin(big.data()) ;
+ pf.fillRect(0, 0, 800, 800, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ pf.end();
+
+ t.restart();
+ p.begin(img->activeDevice().data());
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.bitBlt(0, 0, op, big.data(),0,0,800,800);
+
+ }
+ p.end();
+ report = report.append(TQString(" %1 blits of rectangles 800 x 800 with opacity %2 and composite op %3: %4ms\n")
+ .arg(testCount)
+ .arg(opacity)
+ .arg(op.id().name())
+ .arg(t.elapsed()));
+
+
+ // ------------------------------------------------------------------------------
+ // Outside
+
+ KisPaintDeviceSP outside = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "outside blit");
+ TQ_CHECK_PTR(outside);
+ pf.begin(outside.data()) ;
+ pf.fillRect(0, 0, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ pf.end();
+
+ t.restart();
+ p.begin(img->activeDevice().data());
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.bitBlt(600, 600, op, outside.data(),0,0,500,500);
+
+ }
+ p.end();
+ report = report.append(TQString(" %1 blits of rectangles 500 x 500 at 600,600 with opacity %2 and composite op %3: %4ms\n")
+ .arg(testCount)
+ .arg(opacity)
+ .arg(op.id().name())
+ .arg(t.elapsed()));
+
+ // ------------------------------------------------------------------------------
+ // Small with varied source opacity
+
+ KisPaintDeviceSP small_with_alpha = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getColorSpace(cspace,""), "small blit with alpha");
+ TQ_CHECK_PTR(small_with_alpha);
+
+ pf.begin(small_with_alpha.data()) ;
+ pf.fillRect(0, 0, 32, 32, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_TRANSPARENT);
+ pf.fillRect(4, 4, 24, 24, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
+ pf.fillRect(8, 8, 16, 16, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE);
+ pf.end();
+
+ t.restart();
+ p.begin(img->activeDevice().data());
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.bitBlt(0, 0, op, small_with_alpha.data(), 0, 0, 32, 32);
+ }
+ p.end();
+
+ report = report.append(TQString(" %1 blits of rectangles < tilesize with source alpha, with opacity %2 and composite op %3: %4ms\n")
+ .arg(testCount)
+ .arg(opacity)
+ .arg(op.id().name())
+ .arg(t.elapsed()));
+
+ return report;
+
+}
+
+TQString PerfTest::fillTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* Fill test\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+ kdDebug() << "Filltest on " << (*it).name() + "\n";
+
+ report = report.append( " Testing blitting on " + (*it).name() + "\n");
+
+ KisImageSP img = doc->newImage("fill-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ // Rect fill
+ KisFillPainter p(l.data());
+ TQTime t;
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.eraseRect(0, 0, 1000, 1000);
+ }
+ report = report.append(TQString(" Erased 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.eraseRect(50, 50, 500, 500);
+ }
+ report = report.append(TQString(" Erased 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.eraseRect(-50, -50, 1100, 1100);
+ }
+ report = report.append(TQString(" Erased rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ // Opaque Rect fill
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ }
+ report = report.append(TQString(" Opaque fill 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(50, 50, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ }
+ report = report.append(TQString(" Opaque fill 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(-50, -50, 1100, 1100, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ }
+ report = report.append(TQString(" Opaque fill rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ // Transparent rect fill
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
+ }
+ report = report.append(TQString(" Opaque fill 1000 x 1000 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(50, 50, 500, 500, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
+ }
+ report = report.append(TQString(" Opaque fill 500 x 500 layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.fillRect(-50, -50, 1100, 1100, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()), OPACITY_OPAQUE / 2);
+ }
+ report = report.append(TQString(" Opaque fill rect bigger than layer %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ // Colour fill
+
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.eraseRect(0, 0, 1000, 1000);
+// p.paintEllipse(500, 1000, 100, 0, 0);
+ p.setPaintColor(KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.setFillThreshold(15);
+ p.setCompositeOp(COMPOSITE_OVER);
+ p.fillColor(0,0);
+ }
+ report = report.append(TQString(" Opaque floodfill of whole circle (incl. erase and painting of circle) %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+ // Pattern fill
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ p.eraseRect(0, 0, 1000, 1000);
+// p.paintEllipse(500, 1000, 100, 0, 0);
+ p.setPaintColor(KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ KisResourceServerBase* r = KisResourceServerRegistry::instance()->get("PatternServer");
+ TQ_CHECK_PTR(r);
+ p.setPattern((KisPattern*)r->resources().first());
+ p.setFillThreshold(15);
+ p.setCompositeOp(COMPOSITE_OVER);
+ p.fillPattern(0,0);
+ }
+ report = report.append(TQString(" Opaque patternfill of whole circle (incl. erase and painting of circle) %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+
+
+ }
+
+
+
+ return report;
+
+}
+
+TQString PerfTest::gradientTest(TQ_UINT32 testCount)
+{
+ return TQString("Gradient test\n");
+}
+
+TQString PerfTest::pixelTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* pixel/setpixel test\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+
+
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+ report = report.append( " Testing pixel/setpixel on " + (*it).name() + "\n");
+
+ KisImageSP img = doc->newImage("fill-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ TQColor c = TQt::black;
+ TQ_UINT8 opacity = OPACITY_OPAQUE;
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ for (TQ_UINT32 x = 0; x < 1000; ++x) {
+ for (TQ_UINT32 y = 0; y < 1000; ++y) {
+ l->pixel(x, y, &c, &opacity);
+ }
+ }
+ }
+ report = report.append(TQString(" read 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ c= TQt::black;
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ for (TQ_UINT32 x = 0; x < 1000; ++x) {
+ for (TQ_UINT32 y = 0; y < 1000; ++y) {
+ l->setPixel(x, y, c, 128);
+ }
+ }
+ }
+ report = report.append(TQString(" written 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ }
+
+
+
+
+ return report;
+
+}
+
+TQString PerfTest::shapeTest(TQ_UINT32 testCount)
+{
+ return TQString("Shape test\n");
+}
+
+TQString PerfTest::layerTest(TQ_UINT32 testCount)
+{
+ return TQString("Layer test\n");
+}
+
+TQString PerfTest::scaleTest(TQ_UINT32 testCount)
+{
+ return TQString("Scale test\n");
+}
+
+TQString PerfTest::rotateTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* Rotate test\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+
+ doc->undoAdapter()->setUndo( false );
+ TQTime t;
+
+ for (uint i = 0; i < testCount; ++i) {
+ for (double angle = 0; angle < 360; ++angle) {
+ kdDebug() << "Rotating " << (*it).name() << " at " << angle << " degrees\n";
+ KisImage * img = doc->newImage("cs-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+ img->rotate(angle, m_view->canvasSubject()->progressDisplay());
+ kdDebug() << "Size: " << img->projection()->extent() << endl;
+ delete img;
+ }
+ }
+ report = report.append(TQString(" rotated 1000 x 1000 pixels over 360 degrees, degree by degree, %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+ }
+ return report;
+}
+
+TQString PerfTest::renderTest(TQ_UINT32 restCount)
+{
+ return TQString("Render test\n");
+}
+
+TQString PerfTest::selectionTest(TQ_UINT32 testCount)
+{
+ return TQString("Selection test\n");
+}
+
+TQString PerfTest::colorConversionTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* Colorspace conversion test\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+
+ KisImage * img = doc->newImage("cs-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+
+ TQTime t;
+
+ KisIDList l2 = KisMetaRegistry::instance()->csRegistry()->listKeys();
+ for (KisIDList::Iterator it2 = l2.begin(); it2 != l2.end(); ++it2) {
+ kdDebug() << "test conversion from " << (*it).name() << " to " << (*it2).name() << endl;
+
+ t.restart();
+ for (uint i = 0; i < testCount; ++i) {
+ KisImage * img2 = new KisImage(*img);
+ img2->convertTo(KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it2,""));
+ delete img2;
+ }
+ report = report.append(TQString(" converted from " + (*it).name() + " to " + (*it2).name() + " 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ }
+
+ delete img;
+
+ }
+ return report;
+
+}
+
+TQString PerfTest::filterTest(TQ_UINT32 testCount)
+{
+
+ TQString report = TQString("* Filter test\n");
+
+ KisIDList filters = KisFilterRegistry::instance()->listKeys();
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisIDList l = KisMetaRegistry::instance()->csRegistry()->listKeys();
+
+ for (KisIDList::Iterator it = l.begin(); it != l.end(); ++it) {
+ report = report.append( " Testing filtering on " + (*it).name() + "\n");
+
+ KisImageSP img = doc->newImage("filter-" + (*it).name(), 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(*it,""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+
+ for (KisIDList::Iterator it = filters.begin(); it != filters.end(); ++it) {
+
+ KisFilterSP f = KisFilterRegistry::instance()->get(*it);
+ t.restart();
+ kdDebug() << "test filter " << f->id().name() << " on " << img->colorSpace()->id().name() << endl;
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ f->enableProgress();
+ f->process(l.data(), l.data(), f->configuration(f->createConfigurationWidget(m_view, l.data())), TQRect(0, 0, 1000, 1000));
+ f->disableProgress();
+ }
+ report = report.append(TQString(" filtered " + (*it).name() + "1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+
+ }
+
+ }
+ return report;
+
+}
+
+TQString PerfTest::readBytesTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* Read bytes test\n\n");
+
+ // On default tiles
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisImageSP img = doc->newImage("Readbytes ", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA",""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ TQ_UINT8 * newData = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
+ TQ_CHECK_PTR(newData);
+ l->readBytes(newData, 0, 0, 1000, 1000);
+ delete[] newData;
+ }
+
+ report = report.append(TQString(" read 1000 x 1000 pixels %1 times from empty image: %2\n").arg(testCount).arg(t.elapsed()));
+
+ // On tiles with data
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ TQ_UINT8 * newData = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
+ TQ_CHECK_PTR(newData);
+ l->readBytes(newData, 0, 0, 1000, 1000);
+ delete[] newData;
+ }
+
+ report = report.append(TQString(" read 1000 x 1000 pixels %1 times from filled image: %2\n").arg(testCount).arg(t.elapsed()));
+
+ return report;
+}
+
+
+TQString PerfTest::writeBytesTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* Write bytes test");
+
+ // On default tiles
+ KisDoc * doc = m_view->canvasSubject()->document();
+ KisImageSP img = doc->newImage("Writebytes ", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+
+ TQ_UINT8 * data = new TQ_UINT8[1000 * 1000 * l->pixelSize()];
+ TQ_CHECK_PTR(data);
+ l->readBytes(data, 0, 0, 1000, 1000);
+
+ TQTime t;
+ t.restart();
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ l->writeBytes(data, 0, 0, 1000, 1000);
+ }
+ delete[] data;
+ report = report.append(TQString(" written 1000 x 1000 pixels %1 times: %2\n").arg(testCount).arg(t.elapsed()));
+ return report;
+
+
+}
+
+/////// Iterator tests
+
+
+TQString hlineRODefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ int adv;
+
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, false);
+ while(! hiter.isDone())
+ {
+ adv = hiter.nConseqHPixels();
+ hiter += adv;
+ }
+ }
+
+ }
+
+ return TQString(" hline iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+
+
+}
+
+TQString hlineRO(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ int adv;
+
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, false);
+ while(! hiter.isDone())
+ {
+ adv = hiter.nConseqHPixels();
+ hiter += adv;
+ }
+ }
+
+ }
+
+ return TQString(" hline iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString hlineWRDefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ int adv;
+
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, true);
+ while(! hiter.isDone())
+ {
+ adv = hiter.nConseqHPixels();
+ hiter += adv;
+ }
+ }
+
+ }
+
+ return TQString(" hline iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString hlineWR(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ int adv;
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisHLineIterator hiter = l->createHLineIterator(0, y2, 1000, true);
+ while(! hiter.isDone())
+ {
+ adv = hiter.nConseqHPixels();
+ hiter += adv;
+ }
+ }
+
+ }
+
+ return TQString(" hline iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+
+TQString vlineRODefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
+ while(! hiter.isDone())
+ {
+ ++hiter;
+ }
+ }
+
+ }
+
+ return TQString(" vline iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString vlineRO(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
+ while(! hiter.isDone())
+ {
+ ++hiter;
+ }
+ }
+
+ }
+
+ return TQString(" vline iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString vlineWRDefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisVLineIterator hiter = l->createVLineIterator(y2, 0, 1000, true);
+ while(! hiter.isDone())
+ {
+ ++hiter;
+ }
+ }
+
+ }
+
+ return TQString(" vline iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+}
+
+TQString vlineWR(KisDoc * doc, TQ_UINT32 testCount)
+{
+
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ for(TQ_INT32 y2 = 0; y2 < 0 + 1000; y2++)
+ {
+ KisHLineIterator hiter = l->createHLineIterator(y2, 0, 1000, true);
+ while(! hiter.isDone())
+ {
+ ++hiter;
+ }
+ }
+
+ }
+
+ return TQString(" vline iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString rectRODefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+;
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, false);
+ while(! r.isDone())
+ {
+ ++r;
+ }
+ }
+
+ return TQString(" rect iterated read-only 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+
+
+}
+
+TQString rectRO(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, false);
+ while(! r.isDone())
+ {
+ ++r;
+ }
+ }
+
+ return TQString(" rect iterated read-only 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString rectWRDefault(KisDoc * doc, TQ_UINT32 testCount)
+{
+
+
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ TQTime t;
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, true);
+ while(! r.isDone())
+ {
+ ++r;
+ }
+ }
+
+ return TQString(" rect iterated writable 1000 x 1000 pixels %1 times over default tile: %2\n").arg(testCount).arg(t.elapsed());
+
+}
+
+TQString rectWR(KisDoc * doc, TQ_UINT32 testCount)
+{
+ KisImageSP img = doc->newImage("", 1000, 1000, KisMetaRegistry::instance()->csRegistry()->getColorSpace(KisID("RGBA", ""),""));
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 1000, 1000, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+
+ TQTime t;
+ t.restart();
+
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ KisRectIterator r = l->createRectIterator(0, 0, 1000, 1000, true);
+ while(! r.isDone())
+ {
+ ++r;
+ }
+ }
+
+
+ return TQString(" rect iterated writable 1000 x 1000 pixels %1 times over existing tile: %2\n").arg(testCount).arg(t.elapsed());
+
+
+}
+TQString PerfTest::iteratorTest(TQ_UINT32 testCount)
+{
+ TQString report = "Iterator test";
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+
+ report = report.append(hlineRODefault(doc, testCount));
+ report = report.append(hlineRO(doc, testCount));
+ report = report.append(hlineWRDefault(doc, testCount));
+ report = report.append(hlineWR(doc, testCount));
+
+ report = report.append(vlineRODefault(doc, testCount));
+ report = report.append(vlineRO(doc, testCount));
+ report = report.append(vlineWRDefault(doc, testCount));
+ report = report.append(vlineWR(doc, testCount));
+
+ report = report.append(rectRODefault(doc, testCount));
+ report = report.append(rectRO(doc, testCount));
+ report = report.append(rectWRDefault(doc, testCount));
+ report = report.append(rectWR(doc, testCount));
+
+ return report;
+
+
+}
+
+TQString PerfTest::paintViewTest(TQ_UINT32 testCount)
+{
+ TQString report = TQString("* paintView test\n\n");
+
+ KisDoc * doc = m_view->canvasSubject()->document();
+
+ KisImageSP img = doc->currentImage();
+ img->resize(512,512);
+
+
+ KisPaintDeviceSP l = img->activeDevice();
+
+ KisFillPainter p(l.data());
+ p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ TQTime t;
+ t.restart();
+
+#if USE_CALLGRIND
+ CALLGRIND_ZERO_STATS();
+#endif
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ m_view->getCanvasController()->updateCanvas(TQRect(0, 0, 512, 512));
+ }
+
+#if USE_CALLGRIND
+ CALLGRIND_DUMP_STATS();
+#endif
+
+ report = report.append(TQString(" painted a 512 x 512 image %1 times: %2 ms\n").arg(testCount).arg(t.elapsed()));
+
+ img->newLayer("layer 2", OPACITY_OPAQUE);
+ l = img->activeDevice();
+
+ p.begin(l.data());
+ p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ img->newLayer("layer 3", OPACITY_OPAQUE);
+ l = img->activeDevice();
+
+ p.begin(l.data());
+ p.fillRect(0, 0, 512, 512, KisColor(TQt::black, KisMetaRegistry::instance()->csRegistry()->getRGB8()));
+ p.end();
+
+ t.restart();
+
+ for (TQ_UINT32 i = 0; i < testCount; ++i) {
+ m_view->getCanvasController()->updateCanvas(TQRect(0, 0, 512, 512));
+ }
+
+ report = report.append(TQString(" painted a 512 x 512 image with 3 layers %1 times: %2 ms\n").arg(testCount).arg(t.elapsed()));
+
+ return report;
+}
+
+TQString PerfTest::paintViewFPSTest()
+{
+ TQString report = TQString("* paintView (fps) test\n\n");
+
+ TQTime t;
+ t.restart();
+
+#if USE_CALLGRIND
+ CALLGRIND_ZERO_STATS();
+#endif
+
+ int numViewsPainted = 0;
+ const int millisecondsPerSecond = 1000;
+
+ while (t.elapsed() < millisecondsPerSecond) {
+ m_view->getCanvasController()->updateCanvas();
+ numViewsPainted++;
+ }
+
+#if USE_CALLGRIND
+ CALLGRIND_DUMP_STATS();
+#endif
+
+ report = report.append(TQString(" painted current view at %1 frames per second\n").arg(numViewsPainted));
+
+ return report;
+}
+
+#include "perftest.moc"
diff --git a/chalk/plugins/viewplugins/rotateimage/Makefile.am b/chalk/plugins/viewplugins/rotateimage/Makefile.am
index 757682e4d..bccf04096 100644
--- a/chalk/plugins/viewplugins/rotateimage/Makefile.am
+++ b/chalk/plugins/viewplugins/rotateimage/Makefile.am
@@ -13,7 +13,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkrotateimage.la
-chalkrotateimage_la_SOURCES = wdg_rotateimage.ui rotateimage.cc dlg_rotateimage.cc
+chalkrotateimage_la_SOURCES = wdg_rotateimage.ui rotateimage.cpp dlg_rotateimage.cpp
noinst_HEADERS = wdg_rotateimage.h dlg_rotateimage.h rotateimage.h
chalkrotateimage_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cc b/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cc
deleted file mode 100644
index 84c11ffb5..000000000
--- a/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * dlg_rotateimage.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqgroupbox.h>
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_rotateimage.h"
-#include "wdg_rotateimage.h"
-
-
-DlgRotateImage::DlgRotateImage( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Rotate Image"), Ok | Cancel, Ok)
-{
- m_lock = false;
-
- m_page = new WdgRotateImage(this, "rotate_image");
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
- connect( m_page->doubleCustom, TQT_SIGNAL( valueChanged ( double ) ),
- this, TQT_SLOT( slotAngleValueChanged( double ) ) );
-
-}
-
-DlgRotateImage::~DlgRotateImage()
-{
- delete m_page;
-}
-
-void DlgRotateImage::slotAngleValueChanged( double )
-{
- m_page->radioCustom->setChecked(true);
-}
-
-void DlgRotateImage::setAngle(double angle)
-{
- if (angle == 90) {
- m_page->radio90->setChecked(true);
- }
- else if (angle == 180) {
- m_page->radio180->setChecked(true);
- }
- else if (angle == 270) {
- m_page->radio270->setChecked(true);
- }
- else {
- m_page->radioCustom->setChecked(true);
- m_page->doubleCustom->setValue(angle);
- }
-
- if (m_oldAngle != angle)
- resetPreview();
-
- m_oldAngle = angle;
-
-}
-
-double DlgRotateImage::angle()
-{
- double angle = 0;
- if (m_page->radio90->isChecked()) {
- angle = 90;
- }
- else if (m_page->radio180->isChecked()) {
- angle = 180;
- }
- else if (m_page->radio270->isChecked()) {
- angle = 270;
- }
- else {
- angle = tqRound(m_page->doubleCustom->value());
- }
- if (m_page->radioCW->isChecked()) {
- return angle;
- }
- else {
- return -angle;
- }
-}
-
-void DlgRotateImage::setDirection (enumRotationDirection direction)
-{
- if (direction == CLOCKWISE) {
- m_page->radioCW->setChecked(true);
- }
- else if (direction== COUNTERCLOCKWISE) {
- m_page->radioCCW->setChecked(true);
- }
-}
-
-enumRotationDirection DlgRotateImage::direction()
-{
- if (m_page->radioCCW->isChecked()) {
- return COUNTERCLOCKWISE;
- }
- else {
- return CLOCKWISE;
- }
-}
-
-void DlgRotateImage::okClicked()
-{
- accept();
-}
-
-void DlgRotateImage::resetPreview()
-{
- // Code to update preview here.
-}
-
-#include "dlg_rotateimage.moc"
diff --git a/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cpp b/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cpp
new file mode 100644
index 000000000..e7c3a8ce9
--- /dev/null
+++ b/chalk/plugins/viewplugins/rotateimage/dlg_rotateimage.cpp
@@ -0,0 +1,147 @@
+/*
+ * dlg_rotateimage.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqgroupbox.h>
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_rotateimage.h"
+#include "wdg_rotateimage.h"
+
+
+DlgRotateImage::DlgRotateImage( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Rotate Image"), Ok | Cancel, Ok)
+{
+ m_lock = false;
+
+ m_page = new WdgRotateImage(this, "rotate_image");
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+ connect( m_page->doubleCustom, TQT_SIGNAL( valueChanged ( double ) ),
+ this, TQT_SLOT( slotAngleValueChanged( double ) ) );
+
+}
+
+DlgRotateImage::~DlgRotateImage()
+{
+ delete m_page;
+}
+
+void DlgRotateImage::slotAngleValueChanged( double )
+{
+ m_page->radioCustom->setChecked(true);
+}
+
+void DlgRotateImage::setAngle(double angle)
+{
+ if (angle == 90) {
+ m_page->radio90->setChecked(true);
+ }
+ else if (angle == 180) {
+ m_page->radio180->setChecked(true);
+ }
+ else if (angle == 270) {
+ m_page->radio270->setChecked(true);
+ }
+ else {
+ m_page->radioCustom->setChecked(true);
+ m_page->doubleCustom->setValue(angle);
+ }
+
+ if (m_oldAngle != angle)
+ resetPreview();
+
+ m_oldAngle = angle;
+
+}
+
+double DlgRotateImage::angle()
+{
+ double angle = 0;
+ if (m_page->radio90->isChecked()) {
+ angle = 90;
+ }
+ else if (m_page->radio180->isChecked()) {
+ angle = 180;
+ }
+ else if (m_page->radio270->isChecked()) {
+ angle = 270;
+ }
+ else {
+ angle = tqRound(m_page->doubleCustom->value());
+ }
+ if (m_page->radioCW->isChecked()) {
+ return angle;
+ }
+ else {
+ return -angle;
+ }
+}
+
+void DlgRotateImage::setDirection (enumRotationDirection direction)
+{
+ if (direction == CLOCKWISE) {
+ m_page->radioCW->setChecked(true);
+ }
+ else if (direction== COUNTERCLOCKWISE) {
+ m_page->radioCCW->setChecked(true);
+ }
+}
+
+enumRotationDirection DlgRotateImage::direction()
+{
+ if (m_page->radioCCW->isChecked()) {
+ return COUNTERCLOCKWISE;
+ }
+ else {
+ return CLOCKWISE;
+ }
+}
+
+void DlgRotateImage::okClicked()
+{
+ accept();
+}
+
+void DlgRotateImage::resetPreview()
+{
+ // Code to update preview here.
+}
+
+#include "dlg_rotateimage.moc"
diff --git a/chalk/plugins/viewplugins/rotateimage/rotateimage.cc b/chalk/plugins/viewplugins/rotateimage/rotateimage.cc
deleted file mode 100644
index 8a0985cc3..000000000
--- a/chalk/plugins/viewplugins/rotateimage/rotateimage.cc
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * rotateimage.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <stdlib.h>
-
-#include <tqslider.h>
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_selection.h>
-
-#include "rotateimage.h"
-#include "dlg_rotateimage.h"
-
-typedef KGenericFactory<RotateImage> RotateImageFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkrotateimage, RotateImageFactory( "chalk" ) )
-
-// XXX: this plugin could also provide layer scaling/resizing
-RotateImage::RotateImage(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
-
- if ( parent->inherits("KisView") ) {
- setInstance(RotateImageFactory::instance());
- setXMLFile(locate("data","chalkplugins/rotateimage.rc"), true);
- m_view = (KisView*) parent;
- (void) new TDEAction(i18n("&Rotate Image..."), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage()), actionCollection(), "rotateimage");
- (void) new TDEAction(i18n("Rotate Image CW"), "object-rotate-right", 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage90()), actionCollection(), "rotateImageCW90");
- (void) new TDEAction(i18n("Rotate Image 1&80"), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage180()), actionCollection(), "rotateImage180");
- (void) new TDEAction(i18n("Rotate Image CCW"), "object-rotate-left", 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage270()), actionCollection(), "rotateImageCCW90");
-
- (void) new TDEAction(i18n("&Rotate Layer..."), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateLayer()), actionCollection(), "rotatelayer");
-
- (void)new TDEAction(i18n("Rotate 1&80"), 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayer180()), actionCollection(), "rotateLayer180");
- (void)new TDEAction(i18n("Rotate CCW"), "object-rotate-left", 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayerLeft90()), actionCollection(), "rotateLayerCCW90");
- (void)new TDEAction(i18n("Rotate CW"), "object-rotate-right", 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayerRight90()), actionCollection(), "rotateLayerCW90");
- }
-}
-
-RotateImage::~RotateImage()
-{
- m_view = 0;
-}
-
-void RotateImage::slotRotateImage()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgRotateImage * dlgRotateImage = new DlgRotateImage(m_view, "RotateImage");
- TQ_CHECK_PTR(dlgRotateImage);
-
- dlgRotateImage->setCaption(i18n("Rotate Image"));
-
- if (dlgRotateImage->exec() == TQDialog::Accepted) {
- double angle = dlgRotateImage->angle();
- angle *= M_PI/180;
- m_view->rotateCurrentImage(angle);
- }
- delete dlgRotateImage;
-}
-
-void RotateImage::slotRotateImage90()
-{
- m_view->rotateCurrentImage( M_PI/2);
-}
-
-void RotateImage::slotRotateImage180()
-{
- m_view->rotateCurrentImage( M_PI );
-}
-
-
-void RotateImage::slotRotateImage270()
-{
- m_view->rotateCurrentImage( - M_PI/2 + M_PI*2 );
-}
-
-void RotateImage::slotRotateLayer()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgRotateImage * dlgRotateImage = new DlgRotateImage(m_view, "RotateLayer");
- TQ_CHECK_PTR(dlgRotateImage);
-
- dlgRotateImage->setCaption(i18n("Rotate Layer"));
-
- if (dlgRotateImage->exec() == TQDialog::Accepted) {
- double angle = dlgRotateImage->angle();
- angle *= M_PI/180;
- m_view->rotateLayer(angle);
- }
- delete dlgRotateImage;
-}
-
-#include "rotateimage.moc"
diff --git a/chalk/plugins/viewplugins/rotateimage/rotateimage.cpp b/chalk/plugins/viewplugins/rotateimage/rotateimage.cpp
new file mode 100644
index 000000000..f58f78168
--- /dev/null
+++ b/chalk/plugins/viewplugins/rotateimage/rotateimage.cpp
@@ -0,0 +1,134 @@
+/*
+ * rotateimage.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <stdlib.h>
+
+#include <tqslider.h>
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_selection.h>
+
+#include "rotateimage.h"
+#include "dlg_rotateimage.h"
+
+typedef KGenericFactory<RotateImage> RotateImageFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkrotateimage, RotateImageFactory( "chalk" ) )
+
+// XXX: this plugin could also provide layer scaling/resizing
+RotateImage::RotateImage(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+
+ if ( parent->inherits("KisView") ) {
+ setInstance(RotateImageFactory::instance());
+ setXMLFile(locate("data","chalkplugins/rotateimage.rc"), true);
+ m_view = (KisView*) parent;
+ (void) new TDEAction(i18n("&Rotate Image..."), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage()), actionCollection(), "rotateimage");
+ (void) new TDEAction(i18n("Rotate Image CW"), "object-rotate-right", 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage90()), actionCollection(), "rotateImageCW90");
+ (void) new TDEAction(i18n("Rotate Image 1&80"), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage180()), actionCollection(), "rotateImage180");
+ (void) new TDEAction(i18n("Rotate Image CCW"), "object-rotate-left", 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateImage270()), actionCollection(), "rotateImageCCW90");
+
+ (void) new TDEAction(i18n("&Rotate Layer..."), 0, 0, TQT_TQOBJECT(this), TQT_SLOT(slotRotateLayer()), actionCollection(), "rotatelayer");
+
+ (void)new TDEAction(i18n("Rotate 1&80"), 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayer180()), actionCollection(), "rotateLayer180");
+ (void)new TDEAction(i18n("Rotate CCW"), "object-rotate-left", 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayerLeft90()), actionCollection(), "rotateLayerCCW90");
+ (void)new TDEAction(i18n("Rotate CW"), "object-rotate-right", 0, TQT_TQOBJECT(m_view), TQT_SLOT(rotateLayerRight90()), actionCollection(), "rotateLayerCW90");
+ }
+}
+
+RotateImage::~RotateImage()
+{
+ m_view = 0;
+}
+
+void RotateImage::slotRotateImage()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgRotateImage * dlgRotateImage = new DlgRotateImage(m_view, "RotateImage");
+ TQ_CHECK_PTR(dlgRotateImage);
+
+ dlgRotateImage->setCaption(i18n("Rotate Image"));
+
+ if (dlgRotateImage->exec() == TQDialog::Accepted) {
+ double angle = dlgRotateImage->angle();
+ angle *= M_PI/180;
+ m_view->rotateCurrentImage(angle);
+ }
+ delete dlgRotateImage;
+}
+
+void RotateImage::slotRotateImage90()
+{
+ m_view->rotateCurrentImage( M_PI/2);
+}
+
+void RotateImage::slotRotateImage180()
+{
+ m_view->rotateCurrentImage( M_PI );
+}
+
+
+void RotateImage::slotRotateImage270()
+{
+ m_view->rotateCurrentImage( - M_PI/2 + M_PI*2 );
+}
+
+void RotateImage::slotRotateLayer()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgRotateImage * dlgRotateImage = new DlgRotateImage(m_view, "RotateLayer");
+ TQ_CHECK_PTR(dlgRotateImage);
+
+ dlgRotateImage->setCaption(i18n("Rotate Layer"));
+
+ if (dlgRotateImage->exec() == TQDialog::Accepted) {
+ double angle = dlgRotateImage->angle();
+ angle *= M_PI/180;
+ m_view->rotateLayer(angle);
+ }
+ delete dlgRotateImage;
+}
+
+#include "rotateimage.moc"
diff --git a/chalk/plugins/viewplugins/scripting/Makefile.am b/chalk/plugins/viewplugins/scripting/Makefile.am
index 1f0c431d4..2b4270197 100644
--- a/chalk/plugins/viewplugins/scripting/Makefile.am
+++ b/chalk/plugins/viewplugins/scripting/Makefile.am
@@ -15,7 +15,7 @@ INCLUDES = -I$(top_srcdir)/chalk/sdk \
$(KOFFICE_INCLUDES) \
$(all_includes)
-chalkscripting_la_SOURCES = scripting.cc
+chalkscripting_la_SOURCES = scripting.cpp
kde_module_LTLIBRARIES = chalkscripting.la
noinst_HEADERS = scripting.h
diff --git a/chalk/plugins/viewplugins/scripting/scripting.cc b/chalk/plugins/viewplugins/scripting/scripting.cpp
index 207bc0ce3..207bc0ce3 100644
--- a/chalk/plugins/viewplugins/scripting/scripting.cc
+++ b/chalk/plugins/viewplugins/scripting/scripting.cpp
diff --git a/chalk/plugins/viewplugins/selectopaque/Makefile.am b/chalk/plugins/viewplugins/selectopaque/Makefile.am
index 7814c7afd..dab67d5ec 100644
--- a/chalk/plugins/viewplugins/selectopaque/Makefile.am
+++ b/chalk/plugins/viewplugins/selectopaque/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkselectopaque.la
-chalkselectopaque_la_SOURCES = selectopaque.cc
+chalkselectopaque_la_SOURCES = selectopaque.cpp
noinst_HEADERS = selectopaque.h
chalkselectopaque_la_LIBADD = $(LIB_KOFFICEUI) ../../../libchalkcommon.la \
diff --git a/chalk/plugins/viewplugins/selectopaque/selectopaque.cc b/chalk/plugins/viewplugins/selectopaque/selectopaque.cpp
index 61d856344..61d856344 100644
--- a/chalk/plugins/viewplugins/selectopaque/selectopaque.cc
+++ b/chalk/plugins/viewplugins/selectopaque/selectopaque.cpp
diff --git a/chalk/plugins/viewplugins/separate_channels/Makefile.am b/chalk/plugins/viewplugins/separate_channels/Makefile.am
index d6a2fa77e..03117232e 100644
--- a/chalk/plugins/viewplugins/separate_channels/Makefile.am
+++ b/chalk/plugins/viewplugins/separate_channels/Makefile.am
@@ -12,8 +12,8 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkseparatechannels.la
chalkseparatechannels_la_SOURCES = wdg_separations.ui \
- kis_channel_separator.cc dlg_separate.cc \
- kis_separate_channels_plugin.cc
+ kis_channel_separator.cpp dlg_separate.cpp \
+ kis_separate_channels_plugin.cpp
noinst_HEADERS = wdg_separations.h kis_separate_channels_plugin.h \
kis_channel_separator.h dlg_separate.h
diff --git a/chalk/plugins/viewplugins/separate_channels/dlg_separate.cc b/chalk/plugins/viewplugins/separate_channels/dlg_separate.cc
deleted file mode 100644
index 6d2a59c32..000000000
--- a/chalk/plugins/viewplugins/separate_channels/dlg_separate.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * dlg_separate.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqbuttongroup.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqbutton.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_separate.h"
-#include "wdg_separations.h"
-
-DlgSeparate::DlgSeparate( const TQString & imageCS,
- const TQString & layerCS,
- TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Separate Image"), Ok | Cancel, Ok),
- m_imageCS(imageCS),
- m_layerCS(layerCS)
-{
- m_page = new WdgSeparations(this, "separate_image");
- TQ_CHECK_PTR(m_page);
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- m_page->lblColormodel->setText(layerCS);
- m_page->grpOutput->hide();
- connect(m_page->grpSource, TQT_SIGNAL(clicked(int)), this, TQT_SLOT(slotSetColorSpaceLabel(int)));
- connect(m_page->chkColors, TQT_SIGNAL(toggled(bool)), m_page->chkDownscale, TQT_SLOT(setDisabled(bool)));
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-}
-
-DlgSeparate::~DlgSeparate()
-{
- delete m_page;
-}
-
-
-
-enumSepAlphaOptions DlgSeparate::getAlphaOptions()
-{
- return (enumSepAlphaOptions)m_page->grpAlpha->selectedId();
-}
-
-enumSepSource DlgSeparate::getSource()
-{
- return (enumSepSource)m_page->grpSource->selectedId();
-}
-
-enumSepOutput DlgSeparate::getOutput()
-{
- return (enumSepOutput)m_page->grpOutput->selectedId();
-}
-
-
-bool DlgSeparate::getDownscale()
-{
- return m_page->chkDownscale->isChecked();
-}
-
-bool DlgSeparate::getToColor()
-{
- return m_page->chkColors->isChecked();
-}
-
-// SLOTS
-
-void DlgSeparate::okClicked()
-{
- accept();
-}
-
-void DlgSeparate::slotSetColorSpaceLabel(int buttonid)
-{
- if (buttonid == 0) {
- m_page->lblColormodel->setText(m_layerCS);
- }
- else {
- m_page->lblColormodel->setText(m_imageCS);
- }
-}
-void DlgSeparate::enableDownscale(bool enable) {
- m_page->chkDownscale->setEnabled(enable);
-}
-
-#include "dlg_separate.moc"
diff --git a/chalk/plugins/viewplugins/separate_channels/dlg_separate.cpp b/chalk/plugins/viewplugins/separate_channels/dlg_separate.cpp
new file mode 100644
index 000000000..d650a045a
--- /dev/null
+++ b/chalk/plugins/viewplugins/separate_channels/dlg_separate.cpp
@@ -0,0 +1,110 @@
+/*
+ * dlg_separate.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqbuttongroup.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqbutton.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_separate.h"
+#include "wdg_separations.h"
+
+DlgSeparate::DlgSeparate( const TQString & imageCS,
+ const TQString & layerCS,
+ TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Separate Image"), Ok | Cancel, Ok),
+ m_imageCS(imageCS),
+ m_layerCS(layerCS)
+{
+ m_page = new WdgSeparations(this, "separate_image");
+ TQ_CHECK_PTR(m_page);
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ m_page->lblColormodel->setText(layerCS);
+ m_page->grpOutput->hide();
+ connect(m_page->grpSource, TQT_SIGNAL(clicked(int)), this, TQT_SLOT(slotSetColorSpaceLabel(int)));
+ connect(m_page->chkColors, TQT_SIGNAL(toggled(bool)), m_page->chkDownscale, TQT_SLOT(setDisabled(bool)));
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+}
+
+DlgSeparate::~DlgSeparate()
+{
+ delete m_page;
+}
+
+
+
+enumSepAlphaOptions DlgSeparate::getAlphaOptions()
+{
+ return (enumSepAlphaOptions)m_page->grpAlpha->selectedId();
+}
+
+enumSepSource DlgSeparate::getSource()
+{
+ return (enumSepSource)m_page->grpSource->selectedId();
+}
+
+enumSepOutput DlgSeparate::getOutput()
+{
+ return (enumSepOutput)m_page->grpOutput->selectedId();
+}
+
+
+bool DlgSeparate::getDownscale()
+{
+ return m_page->chkDownscale->isChecked();
+}
+
+bool DlgSeparate::getToColor()
+{
+ return m_page->chkColors->isChecked();
+}
+
+// SLOTS
+
+void DlgSeparate::okClicked()
+{
+ accept();
+}
+
+void DlgSeparate::slotSetColorSpaceLabel(int buttonid)
+{
+ if (buttonid == 0) {
+ m_page->lblColormodel->setText(m_layerCS);
+ }
+ else {
+ m_page->lblColormodel->setText(m_imageCS);
+ }
+}
+void DlgSeparate::enableDownscale(bool enable) {
+ m_page->chkDownscale->setEnabled(enable);
+}
+
+#include "dlg_separate.moc"
diff --git a/chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cc b/chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cpp
index ba8c6b84a..ba8c6b84a 100644
--- a/chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cc
+++ b/chalk/plugins/viewplugins/separate_channels/kis_channel_separator.cpp
diff --git a/chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cc b/chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cpp
index db356a164..db356a164 100644
--- a/chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cc
+++ b/chalk/plugins/viewplugins/separate_channels/kis_separate_channels_plugin.cpp
diff --git a/chalk/plugins/viewplugins/shearimage/Makefile.am b/chalk/plugins/viewplugins/shearimage/Makefile.am
index 7134779c3..b96067895 100644
--- a/chalk/plugins/viewplugins/shearimage/Makefile.am
+++ b/chalk/plugins/viewplugins/shearimage/Makefile.am
@@ -15,7 +15,7 @@ kde_module_LTLIBRARIES = chalkshearimage.la
kde_services_DATA = chalkshearimage.desktop
-chalkshearimage_la_SOURCES = wdg_shearimage.ui shearimage.cc dlg_shearimage.cc
+chalkshearimage_la_SOURCES = wdg_shearimage.ui shearimage.cpp dlg_shearimage.cpp
noinst_HEADERS = wdg_shearimage.h dlg_shearimage.h shearimage.h
chalkshearimage_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cc b/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cc
deleted file mode 100644
index e7a63180b..000000000
--- a/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * dlg_shearimage.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <math.h>
-
-#include <iostream>
-
-using namespace std;
-
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kdebug.h>
-
-#include "dlg_shearimage.h"
-#include "wdg_shearimage.h"
-
-
-DlgShearImage::DlgShearImage( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Shear Image"), Ok | Cancel, Ok)
-{
- m_lock = false;
-
- m_page = new WdgShearImage(this, "shear_image");
- m_page->layout()->setMargin(0);
- TQ_CHECK_PTR(m_page);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-
-}
-
-DlgShearImage::~DlgShearImage()
-{
- delete m_page;
-}
-
-void DlgShearImage::setAngleX(TQ_UINT32 angle)
-{
- m_page->shearAngleX->setValue(angle);
- m_oldAngle = angle;
-
-}
-
-void DlgShearImage::setAngleY(TQ_UINT32 angle)
-{
- m_page->shearAngleY->setValue(angle);
- m_oldAngle = angle;
-
-}
-
-TQ_INT32 DlgShearImage::angleX()
-{
- return (TQ_INT32)tqRound(m_page->shearAngleX->value());
-}
-
-TQ_INT32 DlgShearImage::angleY()
-{
- return (TQ_INT32)tqRound(m_page->shearAngleY->value());
-}
-
-// SLOTS
-
-void DlgShearImage::okClicked()
-{
- accept();
-}
-
-#include "dlg_shearimage.moc"
diff --git a/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cpp b/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cpp
new file mode 100644
index 000000000..d295493d0
--- /dev/null
+++ b/chalk/plugins/viewplugins/shearimage/dlg_shearimage.cpp
@@ -0,0 +1,96 @@
+/*
+ * dlg_shearimage.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <math.h>
+
+#include <iostream>
+
+using namespace std;
+
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kdebug.h>
+
+#include "dlg_shearimage.h"
+#include "wdg_shearimage.h"
+
+
+DlgShearImage::DlgShearImage( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Shear Image"), Ok | Cancel, Ok)
+{
+ m_lock = false;
+
+ m_page = new WdgShearImage(this, "shear_image");
+ m_page->layout()->setMargin(0);
+ TQ_CHECK_PTR(m_page);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+
+}
+
+DlgShearImage::~DlgShearImage()
+{
+ delete m_page;
+}
+
+void DlgShearImage::setAngleX(TQ_UINT32 angle)
+{
+ m_page->shearAngleX->setValue(angle);
+ m_oldAngle = angle;
+
+}
+
+void DlgShearImage::setAngleY(TQ_UINT32 angle)
+{
+ m_page->shearAngleY->setValue(angle);
+ m_oldAngle = angle;
+
+}
+
+TQ_INT32 DlgShearImage::angleX()
+{
+ return (TQ_INT32)tqRound(m_page->shearAngleX->value());
+}
+
+TQ_INT32 DlgShearImage::angleY()
+{
+ return (TQ_INT32)tqRound(m_page->shearAngleY->value());
+}
+
+// SLOTS
+
+void DlgShearImage::okClicked()
+{
+ accept();
+}
+
+#include "dlg_shearimage.moc"
diff --git a/chalk/plugins/viewplugins/shearimage/shearimage.cc b/chalk/plugins/viewplugins/shearimage/shearimage.cc
deleted file mode 100644
index 8e20b58d6..000000000
--- a/chalk/plugins/viewplugins/shearimage/shearimage.cc
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * shearimage.cc -- Part of Chalk
- *
- * Copyright (c) 2004 Michael Thaler
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include <math.h>
-
-#include <stdlib.h>
-
-#include <tqslider.h>
-#include <tqpoint.h>
-
-#include <tdelocale.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <tdemessagebox.h>
-#include <kstandarddirs.h>
-#include <tdetempfile.h>
-#include <kdebug.h>
-#include <kgenericfactory.h>
-
-#include <kis_doc.h>
-#include <kis_config.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_global.h>
-#include <kis_types.h>
-#include <kis_view.h>
-#include <kis_selection.h>
-
-#include "shearimage.h"
-#include "dlg_shearimage.h"
-
-typedef KGenericFactory<ShearImage> ShearImageFactory;
-K_EXPORT_COMPONENT_FACTORY( chalkshearimage, ShearImageFactory( "chalk" ) )
-
-// XXX: this plugin could also provide layer scaling/resizing
-ShearImage::ShearImage(TQObject *parent, const char *name, const TQStringList &)
- : KParts::Plugin(parent, name)
-{
- if ( parent->inherits("KisView") )
- {
- setInstance(ShearImageFactory::instance());
- setXMLFile(locate("data","chalkplugins/shearimage.rc"), true);
-
- (void) new TDEAction(i18n("&Shear Image..."), 0, 0, this, TQT_SLOT(slotShearImage()), actionCollection(), "shearimage");
- (void) new TDEAction(i18n("&Shear Layer..."), 0, 0, this, TQT_SLOT(slotShearLayer()), actionCollection(), "shearlayer");
-
- m_view = (KisView*) parent;
- }
-}
-
-ShearImage::~ShearImage()
-{
- m_view = 0;
-}
-
-void ShearImage::slotShearImage()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgShearImage * dlgShearImage = new DlgShearImage(m_view, "ShearImage");
- TQ_CHECK_PTR(dlgShearImage);
-
- dlgShearImage->setCaption(i18n("Shear Image"));
-
- if (dlgShearImage->exec() == TQDialog::Accepted) {
- TQ_INT32 angleX = dlgShearImage->angleX();
- TQ_INT32 angleY = dlgShearImage->angleY();
- m_view->shearCurrentImage(angleX, angleY);
- }
- delete dlgShearImage;
-}
-
-void ShearImage::slotShearLayer()
-{
- KisImageSP image = m_view->canvasSubject()->currentImg();
-
- if (!image) return;
-
- DlgShearImage * dlgShearImage = new DlgShearImage(m_view, "ShearLayer");
- TQ_CHECK_PTR(dlgShearImage);
-
- dlgShearImage->setCaption(i18n("Shear Layer"));
-
- if (dlgShearImage->exec() == TQDialog::Accepted) {
- TQ_INT32 angleX = dlgShearImage->angleX();
- TQ_INT32 angleY = dlgShearImage->angleY();
- m_view->shearLayer(angleX, angleY);
-
- }
- delete dlgShearImage;
-}
-
-#include "shearimage.moc"
diff --git a/chalk/plugins/viewplugins/shearimage/shearimage.cpp b/chalk/plugins/viewplugins/shearimage/shearimage.cpp
new file mode 100644
index 000000000..2596e62ee
--- /dev/null
+++ b/chalk/plugins/viewplugins/shearimage/shearimage.cpp
@@ -0,0 +1,113 @@
+/*
+ * shearimage.cpp -- Part of Chalk
+ *
+ * Copyright (c) 2004 Michael Thaler
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#include <math.h>
+
+#include <stdlib.h>
+
+#include <tqslider.h>
+#include <tqpoint.h>
+
+#include <tdelocale.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <tdemessagebox.h>
+#include <kstandarddirs.h>
+#include <tdetempfile.h>
+#include <kdebug.h>
+#include <kgenericfactory.h>
+
+#include <kis_doc.h>
+#include <kis_config.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_global.h>
+#include <kis_types.h>
+#include <kis_view.h>
+#include <kis_selection.h>
+
+#include "shearimage.h"
+#include "dlg_shearimage.h"
+
+typedef KGenericFactory<ShearImage> ShearImageFactory;
+K_EXPORT_COMPONENT_FACTORY( chalkshearimage, ShearImageFactory( "chalk" ) )
+
+// XXX: this plugin could also provide layer scaling/resizing
+ShearImage::ShearImage(TQObject *parent, const char *name, const TQStringList &)
+ : KParts::Plugin(parent, name)
+{
+ if ( parent->inherits("KisView") )
+ {
+ setInstance(ShearImageFactory::instance());
+ setXMLFile(locate("data","chalkplugins/shearimage.rc"), true);
+
+ (void) new TDEAction(i18n("&Shear Image..."), 0, 0, this, TQT_SLOT(slotShearImage()), actionCollection(), "shearimage");
+ (void) new TDEAction(i18n("&Shear Layer..."), 0, 0, this, TQT_SLOT(slotShearLayer()), actionCollection(), "shearlayer");
+
+ m_view = (KisView*) parent;
+ }
+}
+
+ShearImage::~ShearImage()
+{
+ m_view = 0;
+}
+
+void ShearImage::slotShearImage()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgShearImage * dlgShearImage = new DlgShearImage(m_view, "ShearImage");
+ TQ_CHECK_PTR(dlgShearImage);
+
+ dlgShearImage->setCaption(i18n("Shear Image"));
+
+ if (dlgShearImage->exec() == TQDialog::Accepted) {
+ TQ_INT32 angleX = dlgShearImage->angleX();
+ TQ_INT32 angleY = dlgShearImage->angleY();
+ m_view->shearCurrentImage(angleX, angleY);
+ }
+ delete dlgShearImage;
+}
+
+void ShearImage::slotShearLayer()
+{
+ KisImageSP image = m_view->canvasSubject()->currentImg();
+
+ if (!image) return;
+
+ DlgShearImage * dlgShearImage = new DlgShearImage(m_view, "ShearLayer");
+ TQ_CHECK_PTR(dlgShearImage);
+
+ dlgShearImage->setCaption(i18n("Shear Layer"));
+
+ if (dlgShearImage->exec() == TQDialog::Accepted) {
+ TQ_INT32 angleX = dlgShearImage->angleX();
+ TQ_INT32 angleY = dlgShearImage->angleY();
+ m_view->shearLayer(angleX, angleY);
+
+ }
+ delete dlgShearImage;
+}
+
+#include "shearimage.moc"
diff --git a/chalk/plugins/viewplugins/substrate/Makefile.am b/chalk/plugins/viewplugins/substrate/Makefile.am
index 8c0e6ef6e..c868d28b0 100644
--- a/chalk/plugins/viewplugins/substrate/Makefile.am
+++ b/chalk/plugins/viewplugins/substrate/Makefile.am
@@ -14,7 +14,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalksubstrate.la
-chalksubstrate_la_SOURCES = substrate.cc dlg_substrate.cc wdgsubstrate.ui kis_repeating_substrate.cc
+chalksubstrate_la_SOURCES = substrate.cpp dlg_substrate.cpp wdgsubstrate.ui kis_repeating_substrate.cpp
noinst_HEADERS = wdgsubstrate.h dlg_substrate.h kis_repeating_substrate.h substrate.h
chalksubstrate_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/substrate/dlg_substrate.cc b/chalk/plugins/viewplugins/substrate/dlg_substrate.cc
deleted file mode 100644
index a0dbc5aa2..000000000
--- a/chalk/plugins/viewplugins/substrate/dlg_substrate.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * dlg_substrate.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tdelocale.h>
-
-#include "dlg_substrate.h"
-#include "wdgsubstrate.h"
-
-
-DlgSubstrate::DlgSubstrate( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
-{
- m_previewPix = TQPixmap();
- m_page = new WdgSubstrate(this, "substrate");
- TQ_CHECK_PTR(m_page);
- setCaption(i18n("Substrate"));
- setMainWidget(m_page);
- resize(m_page -> size());
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-}
-
-DlgSubstrate::~DlgSubstrate()
-{
- delete m_page;
-}
-
-void DlgSubstrate::setPixmap(TQPixmap pix)
-{
- m_previewPix = pix;
- m_previewPix.detach();
-}
-
-void DlgSubstrate::okClicked()
-{
- accept();
-}
-
-#include "dlg_substrate.moc"
-
diff --git a/chalk/plugins/viewplugins/substrate/dlg_substrate.cpp b/chalk/plugins/viewplugins/substrate/dlg_substrate.cpp
new file mode 100644
index 000000000..78847f056
--- /dev/null
+++ b/chalk/plugins/viewplugins/substrate/dlg_substrate.cpp
@@ -0,0 +1,59 @@
+/*
+ * dlg_substrate.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tdelocale.h>
+
+#include "dlg_substrate.h"
+#include "wdgsubstrate.h"
+
+
+DlgSubstrate::DlgSubstrate( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
+{
+ m_previewPix = TQPixmap();
+ m_page = new WdgSubstrate(this, "substrate");
+ TQ_CHECK_PTR(m_page);
+ setCaption(i18n("Substrate"));
+ setMainWidget(m_page);
+ resize(m_page -> size());
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+}
+
+DlgSubstrate::~DlgSubstrate()
+{
+ delete m_page;
+}
+
+void DlgSubstrate::setPixmap(TQPixmap pix)
+{
+ m_previewPix = pix;
+ m_previewPix.detach();
+}
+
+void DlgSubstrate::okClicked()
+{
+ accept();
+}
+
+#include "dlg_substrate.moc"
+
diff --git a/chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cc b/chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cpp
index e69de29bb..e69de29bb 100644
--- a/chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cc
+++ b/chalk/plugins/viewplugins/substrate/kis_repeating_substrate.cpp
diff --git a/chalk/plugins/viewplugins/substrate/substrate.cc b/chalk/plugins/viewplugins/substrate/substrate.cpp
index ce13710be..ce13710be 100644
--- a/chalk/plugins/viewplugins/substrate/substrate.cc
+++ b/chalk/plugins/viewplugins/substrate/substrate.cpp
diff --git a/chalk/plugins/viewplugins/variations/Makefile.am b/chalk/plugins/viewplugins/variations/Makefile.am
index 21d4e63f6..cd75fc9cf 100644
--- a/chalk/plugins/viewplugins/variations/Makefile.am
+++ b/chalk/plugins/viewplugins/variations/Makefile.am
@@ -14,7 +14,7 @@ INCLUDES = -I$(srcdir)/../../../sdk \
kde_module_LTLIBRARIES = chalkvariations.la
-chalkvariations_la_SOURCES = variations.cc dlg_variations.cc wdg_variations.ui
+chalkvariations_la_SOURCES = variations.cpp dlg_variations.cpp wdg_variations.ui
noinst_HEADERS = wdg_variations.h
chalkvariations_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT) -ltdecore -ltdeui -lkjs -ltdefx -ltdeio -ltdeparts
diff --git a/chalk/plugins/viewplugins/variations/dlg_variations.cc b/chalk/plugins/viewplugins/variations/dlg_variations.cc
deleted file mode 100644
index afa6a3d74..000000000
--- a/chalk/plugins/viewplugins/variations/dlg_variations.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * dlg_variations.cc - part of KimageShop^WKrayon^WChalk
- *
- * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tdelocale.h>
-
-#include "dlg_variations.h"
-#include "wdg_variations.h"
-
-
-DlgVariations::DlgVariations( TQWidget * parent,
- const char * name)
- : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
-{
- m_previewPix = TQPixmap();
- m_page = new WdgVariations(this, "variations");
- TQ_CHECK_PTR(m_page);
- setCaption(i18n("Variations"));
- setMainWidget(m_page);
- resize(m_page -> size());
-
- connect(this, TQT_SIGNAL(okClicked()),
- this, TQT_SLOT(okClicked()));
-}
-
-DlgVariations::~DlgVariations()
-{
- delete m_page;
-}
-
-void DlgVariations::setPixmap(TQPixmap pix)
-{
- m_previewPix = pix;
- m_previewPix.detach();
-}
-
-void DlgVariations::okClicked()
-{
- accept();
-}
-
-#include "dlg_variations.moc"
diff --git a/chalk/plugins/viewplugins/variations/dlg_variations.cpp b/chalk/plugins/viewplugins/variations/dlg_variations.cpp
new file mode 100644
index 000000000..4decbbd41
--- /dev/null
+++ b/chalk/plugins/viewplugins/variations/dlg_variations.cpp
@@ -0,0 +1,58 @@
+/*
+ * dlg_variations.cpp - part of KimageShop^WKrayon^WChalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tdelocale.h>
+
+#include "dlg_variations.h"
+#include "wdg_variations.h"
+
+
+DlgVariations::DlgVariations( TQWidget * parent,
+ const char * name)
+ : super (parent, name, true, i18n("Color Range"), Ok | Cancel, Ok)
+{
+ m_previewPix = TQPixmap();
+ m_page = new WdgVariations(this, "variations");
+ TQ_CHECK_PTR(m_page);
+ setCaption(i18n("Variations"));
+ setMainWidget(m_page);
+ resize(m_page -> size());
+
+ connect(this, TQT_SIGNAL(okClicked()),
+ this, TQT_SLOT(okClicked()));
+}
+
+DlgVariations::~DlgVariations()
+{
+ delete m_page;
+}
+
+void DlgVariations::setPixmap(TQPixmap pix)
+{
+ m_previewPix = pix;
+ m_previewPix.detach();
+}
+
+void DlgVariations::okClicked()
+{
+ accept();
+}
+
+#include "dlg_variations.moc"
diff --git a/chalk/plugins/viewplugins/variations/variations.cc b/chalk/plugins/viewplugins/variations/variations.cpp
index 5e2d65ba8..5e2d65ba8 100644
--- a/chalk/plugins/viewplugins/variations/variations.cc
+++ b/chalk/plugins/viewplugins/variations/variations.cpp
diff --git a/chalk/sdk/Makefile.am b/chalk/sdk/Makefile.am
index 0c7f4c186..869b2c362 100644
--- a/chalk/sdk/Makefile.am
+++ b/chalk/sdk/Makefile.am
@@ -4,7 +4,7 @@ INCLUDES = $(KOFFICE_INCLUDES) $(KOPAINTER_INCLUDES) \
$(all_includes)
noinst_LTLIBRARIES = libchalksdk.la
-libchalksdk_la_SOURCES = kis_progress_subject.cc
+libchalksdk_la_SOURCES = kis_progress_subject.cpp
libchalksdk_la_METASOURCES = AUTO
include_HEADERS = \
diff --git a/chalk/sdk/kis_progress_subject.cc b/chalk/sdk/kis_progress_subject.cpp
index fa53086b8..fa53086b8 100644
--- a/chalk/sdk/kis_progress_subject.cc
+++ b/chalk/sdk/kis_progress_subject.cpp
diff --git a/chalk/ui/Makefile.am b/chalk/ui/Makefile.am
index 34f67c916..3a2bff125 100644
--- a/chalk/ui/Makefile.am
+++ b/chalk/ui/Makefile.am
@@ -13,34 +13,34 @@ libchalkui_la_LDFLAGS = -version-info 1:0:0 -no-undefined $(all_libraries)
libchalkui_la_LIBADD = ../sdk/libchalksdk.la ../core/libchalkimage.la ../chalkcolor/libchalkcolor.la \
$(LCMS_LIBS) $(LIB_KOFFICEUI) $(LIB_KOPAINTER) $(LIB_KOPALETTE) $(LIB_XINPUTEXT) $(GLLIB)
-libchalkui_la_SOURCES = kis_import_catcher.cc kis_histogram_view.cc imageviewer.cc kcurve.cc \
- kis_autobrush.cc kis_autogradient.cc kis_boundary_painter.cc kis_brush_chooser.cc \
- kis_canvas.cc kis_canvas_painter.cc kis_clipboard.cc kis_cmb_composite.cc \
- kis_cmb_idlist.cc kis_color_cup.cc kis_config.cc kis_controlframe.cc kis_cursor.cc \
- kis_dlg_apply_profile.cc kis_dlg_image_properties.cc kis_dlg_layer_properties.cc \
- kis_dlg_new_layer.cc kis_dlg_preferences.cc kis_doc.cc kis_doc_iface.cc kis_doc_iface.skel \
- kis_double_widget.cc kis_factory.cc kis_filter_manager.cc kis_gradient_chooser.cc \
- kis_gradient_slider_widget.cc kis_icon_item.cc kis_iconwidget.cc kis_int_spinbox.cc \
- kis_itemchooser.cc kis_label_cursor_pos.cc kis_label_progress.cc kis_label_zoom.cc \
- kis_layerbox.cc kis_layerlist.cc kis_multi_bool_filter_widget.cc \
- kis_multi_double_filter_widget.cc kis_multi_integer_filter_widget.cc kis_opengl_canvas.cc \
- kis_opengl_canvas_painter.cc kis_opengl_image_context.cc kis_paintop_box.cc kis_palette_view.cc \
- kis_palette_widget.cc kis_part_layer.cc kis_pattern_chooser.cc kis_previewdialog.cc \
- kis_previewwidget.cc kis_qpaintdevice_canvas.cc kis_qpaintdevice_canvas_painter.cc \
- kis_resource_mediator.cc kis_resourceserver.cc kis_ruler.cc kis_selection_manager.cc \
- kis_selection_options.cc kis_text_brush.cc kis_tool.cc kis_tool_dummy.cc kis_tool_freehand.cc \
- kis_tool_manager.cc kis_tool_non_paint.cc kis_tool_paint.cc kis_tool_registry.cc \
- kis_tool_shape.cc kis_birdeye_box.cc kis_view.cc kis_view_iface.cc kis_custom_brush.cc \
- kis_custom_palette.cc kis_custom_pattern.cc kis_custom_image_widget.cc kis_view_iface.skel \
+libchalkui_la_SOURCES = kis_import_catcher.cpp kis_histogram_view.cpp imageviewer.cpp kcurve.cpp \
+ kis_autobrush.cpp kis_autogradient.cpp kis_boundary_painter.cpp kis_brush_chooser.cpp \
+ kis_canvas.cpp kis_canvas_painter.cpp kis_clipboard.cpp kis_cmb_composite.cpp \
+ kis_cmb_idlist.cpp kis_color_cup.cpp kis_config.cpp kis_controlframe.cpp kis_cursor.cpp \
+ kis_dlg_apply_profile.cpp kis_dlg_image_properties.cpp kis_dlg_layer_properties.cpp \
+ kis_dlg_new_layer.cpp kis_dlg_preferences.cpp kis_doc.cpp kis_doc_iface.cpp kis_doc_iface.skel \
+ kis_double_widget.cpp kis_factory.cpp kis_filter_manager.cpp kis_gradient_chooser.cpp \
+ kis_gradient_slider_widget.cpp kis_icon_item.cpp kis_iconwidget.cpp kis_int_spinbox.cpp \
+ kis_itemchooser.cpp kis_label_cursor_pos.cpp kis_label_progress.cpp kis_label_zoom.cpp \
+ kis_layerbox.cpp kis_layerlist.cpp kis_multi_bool_filter_widget.cpp \
+ kis_multi_double_filter_widget.cpp kis_multi_integer_filter_widget.cpp kis_opengl_canvas.cpp \
+ kis_opengl_canvas_painter.cpp kis_opengl_image_context.cpp kis_paintop_box.cpp kis_palette_view.cpp \
+ kis_palette_widget.cpp kis_part_layer.cpp kis_pattern_chooser.cpp kis_previewdialog.cpp \
+ kis_previewwidget.cpp kis_qpaintdevice_canvas.cpp kis_qpaintdevice_canvas_painter.cpp \
+ kis_resource_mediator.cpp kis_resourceserver.cpp kis_ruler.cpp kis_selection_manager.cpp \
+ kis_selection_options.cpp kis_text_brush.cpp kis_tool.cpp kis_tool_dummy.cpp kis_tool_freehand.cpp \
+ kis_tool_manager.cpp kis_tool_non_paint.cpp kis_tool_paint.cpp kis_tool_registry.cpp \
+ kis_tool_shape.cpp kis_birdeye_box.cpp kis_view.cpp kis_view_iface.cpp kis_custom_brush.cpp \
+ kis_custom_palette.cpp kis_custom_pattern.cpp kis_custom_image_widget.cpp kis_view_iface.skel \
kobirdeyepanel.cpp kis_matrix_widget.ui kis_previewwidgetbase.ui layerlist.cpp \
wdgapplyprofile.ui wdgautobrush.ui wdgautogradient.ui wdgbirdeye.ui wdgcolorsettings.ui \
wdgdisplaysettings.ui wdggeneralsettings.ui wdglayerproperties.ui wdglayerbox.ui \
wdgnewimage.ui wdgperformancesettings.ui wdgselectionoptions.ui wdgshapeoptions.ui \
wdgpressuresettings.ui wdgcustombrush.ui wdgcustompalette.ui wdgcustompattern.ui \
- wdgtextbrush.ui kis_dlg_adjustment_layer.cc kis_filters_listview.cc \
+ wdgtextbrush.ui kis_dlg_adjustment_layer.cpp kis_filters_listview.cpp \
wdgpalettechooser.ui wdggridsettings.ui kis_grid_manager.cpp wdgtabletdevicesettings.ui \
- wdgtabletsettings.ui kis_input_device.cc kis_part_layer_handler.cc \
- kis_dlg_adj_layer_props.cc squeezedcombobox.cpp kis_perspective_grid_manager.cpp \
+ wdgtabletsettings.ui kis_input_device.cpp kis_part_layer_handler.cpp \
+ kis_dlg_adj_layer_props.cpp squeezedcombobox.cpp kis_perspective_grid_manager.cpp \
kis_grid_drawer.cpp
noinst_HEADERS = kis_aboutdata.h imageviewer.h layerlist.h kcurve.h \
diff --git a/chalk/ui/imageviewer.cc b/chalk/ui/imageviewer.cpp
index 5e74c8fe8..5e74c8fe8 100644
--- a/chalk/ui/imageviewer.cc
+++ b/chalk/ui/imageviewer.cpp
diff --git a/chalk/ui/kcurve.cc b/chalk/ui/kcurve.cpp
index b6bd51629..b6bd51629 100644
--- a/chalk/ui/kcurve.cc
+++ b/chalk/ui/kcurve.cpp
diff --git a/chalk/ui/kis_autobrush.cc b/chalk/ui/kis_autobrush.cpp
index c7127928d..c7127928d 100644
--- a/chalk/ui/kis_autobrush.cc
+++ b/chalk/ui/kis_autobrush.cpp
diff --git a/chalk/ui/kis_autogradient.cc b/chalk/ui/kis_autogradient.cpp
index bd5b80fb4..bd5b80fb4 100644
--- a/chalk/ui/kis_autogradient.cc
+++ b/chalk/ui/kis_autogradient.cpp
diff --git a/chalk/ui/kis_birdeye_box.cc b/chalk/ui/kis_birdeye_box.cpp
index 2b816f9cb..2b816f9cb 100644
--- a/chalk/ui/kis_birdeye_box.cc
+++ b/chalk/ui/kis_birdeye_box.cpp
diff --git a/chalk/ui/kis_boundary_painter.cc b/chalk/ui/kis_boundary_painter.cpp
index 2b842e53c..2b842e53c 100644
--- a/chalk/ui/kis_boundary_painter.cc
+++ b/chalk/ui/kis_boundary_painter.cpp
diff --git a/chalk/ui/kis_brush_chooser.cc b/chalk/ui/kis_brush_chooser.cpp
index db9aba981..db9aba981 100644
--- a/chalk/ui/kis_brush_chooser.cc
+++ b/chalk/ui/kis_brush_chooser.cpp
diff --git a/chalk/ui/kis_canvas.cc b/chalk/ui/kis_canvas.cpp
index 63ae4ab06..63ae4ab06 100644
--- a/chalk/ui/kis_canvas.cc
+++ b/chalk/ui/kis_canvas.cpp
diff --git a/chalk/ui/kis_canvas_painter.cc b/chalk/ui/kis_canvas_painter.cpp
index 9b3666e89..9b3666e89 100644
--- a/chalk/ui/kis_canvas_painter.cc
+++ b/chalk/ui/kis_canvas_painter.cpp
diff --git a/chalk/ui/kis_clipboard.cc b/chalk/ui/kis_clipboard.cpp
index bb80e75e0..bb80e75e0 100644
--- a/chalk/ui/kis_clipboard.cc
+++ b/chalk/ui/kis_clipboard.cpp
diff --git a/chalk/ui/kis_cmb_composite.cc b/chalk/ui/kis_cmb_composite.cc
deleted file mode 100644
index 66e3a6b39..000000000
--- a/chalk/ui/kis_cmb_composite.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * kis_cmb_composite.cc - part of KImageShop/Krayon/Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include "kis_cmb_composite.h"
-
-KisCmbComposite::KisCmbComposite(TQWidget * parent, const char * name)
- : super( false, parent, name )
-{
- connect(this, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotOpActivated(int)));
- connect(this, TQT_SIGNAL(highlighted(int)), this, TQT_SLOT(slotOpHighlighted(int)));
-}
-
-KisCmbComposite::~KisCmbComposite()
-{
-}
-
-void KisCmbComposite::setCompositeOpList(const KisCompositeOpList & list)
-{
- super::clear();
- m_list = list;
- KisCompositeOpList::iterator it;
- for( it = m_list.begin(); it != m_list.end(); ++it )
- insertItem((*it).id().name());
-}
-
-KisCompositeOp KisCmbComposite::currentItem() const
-{
- TQ_UINT32 i = super::currentItem();
- if (i > m_list.count()) return KisCompositeOp();
-
- return m_list[i];
-}
-
-void KisCmbComposite::setCurrentItem(const KisCompositeOp& op)
-{
- if (m_list.find(op) != m_list.end()) {
- super::setCurrentText(op.id().name());
- }
-}
-
-void KisCmbComposite::setCurrentText(const TQString & s)
-{
- KisCompositeOpList::iterator it;
- for( it = m_list.begin(); it != m_list.end(); ++it )
- if ((*it).id().id() == s) {
- super::setCurrentText((*it).id().name());
- }
-}
-
-void KisCmbComposite::slotOpActivated(int i)
-{
- if ((TQ_UINT32)i > m_list.count()) return;
-
- emit activated(m_list[i]);
-}
-
-void KisCmbComposite::slotOpHighlighted(int i)
-{
- if ((TQ_UINT32)i > m_list.count()) return;
-
- emit highlighted(m_list[i]);
-}
-
-
-#include "kis_cmb_composite.moc"
-
diff --git a/chalk/ui/kis_cmb_composite.cpp b/chalk/ui/kis_cmb_composite.cpp
new file mode 100644
index 000000000..631f602e9
--- /dev/null
+++ b/chalk/ui/kis_cmb_composite.cpp
@@ -0,0 +1,88 @@
+/*
+ * kis_cmb_composite.cpp - part of KImageShop/Krayon/Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include "kis_cmb_composite.h"
+
+KisCmbComposite::KisCmbComposite(TQWidget * parent, const char * name)
+ : super( false, parent, name )
+{
+ connect(this, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotOpActivated(int)));
+ connect(this, TQT_SIGNAL(highlighted(int)), this, TQT_SLOT(slotOpHighlighted(int)));
+}
+
+KisCmbComposite::~KisCmbComposite()
+{
+}
+
+void KisCmbComposite::setCompositeOpList(const KisCompositeOpList & list)
+{
+ super::clear();
+ m_list = list;
+ KisCompositeOpList::iterator it;
+ for( it = m_list.begin(); it != m_list.end(); ++it )
+ insertItem((*it).id().name());
+}
+
+KisCompositeOp KisCmbComposite::currentItem() const
+{
+ TQ_UINT32 i = super::currentItem();
+ if (i > m_list.count()) return KisCompositeOp();
+
+ return m_list[i];
+}
+
+void KisCmbComposite::setCurrentItem(const KisCompositeOp& op)
+{
+ if (m_list.find(op) != m_list.end()) {
+ super::setCurrentText(op.id().name());
+ }
+}
+
+void KisCmbComposite::setCurrentText(const TQString & s)
+{
+ KisCompositeOpList::iterator it;
+ for( it = m_list.begin(); it != m_list.end(); ++it )
+ if ((*it).id().id() == s) {
+ super::setCurrentText((*it).id().name());
+ }
+}
+
+void KisCmbComposite::slotOpActivated(int i)
+{
+ if ((TQ_UINT32)i > m_list.count()) return;
+
+ emit activated(m_list[i]);
+}
+
+void KisCmbComposite::slotOpHighlighted(int i)
+{
+ if ((TQ_UINT32)i > m_list.count()) return;
+
+ emit highlighted(m_list[i]);
+}
+
+
+#include "kis_cmb_composite.moc"
+
diff --git a/chalk/ui/kis_cmb_idlist.cc b/chalk/ui/kis_cmb_idlist.cc
deleted file mode 100644
index 92dc608f6..000000000
--- a/chalk/ui/kis_cmb_idlist.cc
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * kis_cmb_idlist.cc - part of KImageShop/Krayon/Chalk
- *
- * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqcombobox.h>
-
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include "kis_id.h"
-#include "kis_cmb_idlist.h"
-
-KisCmbIDList::KisCmbIDList(TQWidget * parent, const char * name)
- : super( false, parent, name )
-{
- connect(this, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotIDActivated(int)));
- connect(this, TQT_SIGNAL(highlighted(int)), this, TQT_SLOT(slotIDHighlighted(int)));
-}
-
-KisCmbIDList::~KisCmbIDList()
-{
-}
-
-
-void KisCmbIDList::setIDList(const KisIDList & list)
-{
- m_list = list;
- KisIDList::iterator it;
- for( it = m_list.begin(); it != m_list.end(); ++it )
- insertItem((*it).name());
-}
-
-
-KisID KisCmbIDList::currentItem() const
-{
- TQ_UINT32 i = super::currentItem();
- if (i > m_list.count()) return KisID();
-
- return m_list[i];
-}
-
-void KisCmbIDList::setCurrent(const KisID id)
-{
- if (m_list.find(id) != m_list.end())
- super::setCurrentText(id.name());
- else {
- m_list.push_back(id);
- insertItem(id.name());
- super::setCurrentText(id.name());
- }
-}
-
-void KisCmbIDList::setCurrentText(const TQString & s)
-{
- KisIDList::iterator it;
- for( it = m_list.begin(); it != m_list.end(); ++it )
- if ((*it).id() == s) {
- super::setCurrentText((*it).name());
- }
-}
-
-void KisCmbIDList::slotIDActivated(int i)
-{
- if ((uint)i > m_list.count()) return;
-
- emit activated(m_list[i]);
-
-}
-
-void KisCmbIDList::slotIDHighlighted(int i)
-{
- if ((uint)i > m_list.count()) return;
-
- emit highlighted(m_list[i]);
-
-}
-
-
-
-#include "kis_cmb_idlist.moc"
-
diff --git a/chalk/ui/kis_cmb_idlist.cpp b/chalk/ui/kis_cmb_idlist.cpp
new file mode 100644
index 000000000..39937752a
--- /dev/null
+++ b/chalk/ui/kis_cmb_idlist.cpp
@@ -0,0 +1,97 @@
+/*
+ * kis_cmb_idlist.cpp - part of KImageShop/Krayon/Chalk
+ *
+ * Copyright (c) 2005 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqcombobox.h>
+
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include "kis_id.h"
+#include "kis_cmb_idlist.h"
+
+KisCmbIDList::KisCmbIDList(TQWidget * parent, const char * name)
+ : super( false, parent, name )
+{
+ connect(this, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotIDActivated(int)));
+ connect(this, TQT_SIGNAL(highlighted(int)), this, TQT_SLOT(slotIDHighlighted(int)));
+}
+
+KisCmbIDList::~KisCmbIDList()
+{
+}
+
+
+void KisCmbIDList::setIDList(const KisIDList & list)
+{
+ m_list = list;
+ KisIDList::iterator it;
+ for( it = m_list.begin(); it != m_list.end(); ++it )
+ insertItem((*it).name());
+}
+
+
+KisID KisCmbIDList::currentItem() const
+{
+ TQ_UINT32 i = super::currentItem();
+ if (i > m_list.count()) return KisID();
+
+ return m_list[i];
+}
+
+void KisCmbIDList::setCurrent(const KisID id)
+{
+ if (m_list.find(id) != m_list.end())
+ super::setCurrentText(id.name());
+ else {
+ m_list.push_back(id);
+ insertItem(id.name());
+ super::setCurrentText(id.name());
+ }
+}
+
+void KisCmbIDList::setCurrentText(const TQString & s)
+{
+ KisIDList::iterator it;
+ for( it = m_list.begin(); it != m_list.end(); ++it )
+ if ((*it).id() == s) {
+ super::setCurrentText((*it).name());
+ }
+}
+
+void KisCmbIDList::slotIDActivated(int i)
+{
+ if ((uint)i > m_list.count()) return;
+
+ emit activated(m_list[i]);
+
+}
+
+void KisCmbIDList::slotIDHighlighted(int i)
+{
+ if ((uint)i > m_list.count()) return;
+
+ emit highlighted(m_list[i]);
+
+}
+
+
+
+#include "kis_cmb_idlist.moc"
+
diff --git a/chalk/ui/kis_color_cup.cc b/chalk/ui/kis_color_cup.cpp
index ae0ddfacb..ae0ddfacb 100644
--- a/chalk/ui/kis_color_cup.cc
+++ b/chalk/ui/kis_color_cup.cpp
diff --git a/chalk/ui/kis_config.cc b/chalk/ui/kis_config.cpp
index 64939c4a6..64939c4a6 100644
--- a/chalk/ui/kis_config.cc
+++ b/chalk/ui/kis_config.cpp
diff --git a/chalk/ui/kis_controlframe.cc b/chalk/ui/kis_controlframe.cc
deleted file mode 100644
index 6c57a7e6a..000000000
--- a/chalk/ui/kis_controlframe.cc
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * kis_controlframe.cc - part of Chalk
- *
- * Copyright (c) 1999 Matthias Elter <elter@kde.org>
- * Copyright (c) 2003 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2004 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.g
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <stdlib.h>
-
-#include <tqapplication.h>
-#include <tqlayout.h>
-#include <tqtabwidget.h>
-#include <tqframe.h>
-#include <tqwidget.h>
-#include <tqevent.h>
-
-#include <tdetoolbar.h>
-#include <tdemainwindow.h>
-#include <tdeglobalsettings.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <koFrameButton.h>
-#include <tdeactioncollection.h>
-
-#include "kis_resourceserver.h"
-#include "kis_controlframe.h"
-#include "kis_resource_mediator.h"
-#include "kis_itemchooser.h"
-#include "kis_pattern_chooser.h"
-#include "kis_gradient_chooser.h"
-#include "kis_icon_item.h"
-#include "kis_iconwidget.h"
-#include "kis_brush.h"
-#include "kis_pattern.h"
-#include "kis_gradient.h"
-#include "kis_brush_chooser.h"
-#include "kis_view.h"
-#include "kis_autobrush.h"
-#include "kis_autogradient.h"
-#include "kis_config.h"
-#include "kis_paintop_box.h"
-#include "kis_custom_brush.h"
-#include "kis_custom_pattern.h"
-#ifdef HAVE_TEXT_BRUSH
-#include "kis_text_brush.h"
-#endif
-KisPopupFrame::KisPopupFrame(TQWidget * parent, const char* name)
- : TQPopupMenu(parent, name)
-{
- setFocusPolicy(TQ_StrongFocus);
-}
-
-void KisPopupFrame::keyPressEvent(TQKeyEvent * e)
-{
- if (e->key()== TQt::Key_Escape)
- {
- hide();
- e->accept();
- }
- else {
- e->ignore();
- }
-}
-
-
-KisControlFrame::KisControlFrame( TDEMainWindow * /*window*/, KisView * view, const char* name )
- : TQObject(view, name)
- //: TDEToolBar ( window, TQt::DockTop, false, name, true, true )
- , m_view(view)
- , m_brushWidget(0)
- , m_patternWidget(0)
- , m_gradientWidget(0)
- , m_brushChooserPopup(0)
- , m_patternChooserPopup(0)
- , m_gradientChooserPopup(0)
- , m_brushMediator(0)
- , m_patternMediator(0)
- , m_gradientMediator(0)
- , m_paintopBox(0)
-{
-
- KisConfig cfg;
- m_font = TDEGlobalSettings::generalFont();
- m_font.setPointSize((int)cfg.dockerFontSize());
-
- m_brushWidget = new KisIconWidget(view, "brushes");
- m_brushWidget->setTextLabel( i18n("Brush Shapes") );
- // XXX: An action without a slot -- that's silly, what kind of action could we use here?
- TDEAction * action = new KWidgetAction(m_brushWidget,
- i18n("&Brush"),
- 0,
- TQT_TQOBJECT(view),
- 0,
- view->actionCollection(),
- "brushes");
-
-
- m_patternWidget = new KisIconWidget(view, "patterns");
- m_patternWidget->setTextLabel( i18n("Fill Patterns") );
- action = new KWidgetAction(m_patternWidget,
- i18n("&Patterns"),
- 0,
- TQT_TQOBJECT(view),
- 0,
- view->actionCollection(),
- "patterns");
-
- m_gradientWidget = new KisIconWidget(view, "gradients");
- m_gradientWidget->setTextLabel( i18n("Gradients") );
- action = new KWidgetAction(m_gradientWidget,
- i18n("&Gradients"),
- 0,
- TQT_TQOBJECT(view),
- 0,
- view->actionCollection(),
- "gradients");
-
- m_paintopBox = new KisPaintopBox( view, view, "paintopbox" );
- action = new KWidgetAction(m_paintopBox,
- i18n("&Painter's Tools"),
- 0,
- TQT_TQOBJECT(view),
- 0,
- view->actionCollection(),
- "paintops");
-
- m_brushWidget->setFixedSize( 26, 26 );
- m_patternWidget->setFixedSize( 26, 26 );
- m_gradientWidget->setFixedSize( 26, 26 );
-
- createBrushesChooser(m_view);
- createPatternsChooser(m_view);
- createGradientsChooser(m_view);
-
- m_brushWidget->setPopup(m_brushChooserPopup);
- m_brushWidget->setPopupDelay(1);
- m_patternWidget->setPopup(m_patternChooserPopup);
- m_patternWidget->setPopupDelay(1);
- m_gradientWidget->setPopup(m_gradientChooserPopup);
- m_gradientWidget->setPopupDelay(1);
-}
-
-
-void KisControlFrame::slotSetBrush(KoIconItem *item)
-{
- if (item)
- m_brushWidget->slotSetItem(*item);
-}
-
-void KisControlFrame::slotSetPattern(KoIconItem *item)
-{
- if (item)
- m_patternWidget->slotSetItem(*item);
-}
-
-void KisControlFrame::slotSetGradient(KoIconItem *item)
-{
- if (item)
- m_gradientWidget->slotSetItem(*item);
-}
-
-void KisControlFrame::slotBrushChanged(KisBrush * brush)
-{
- KisIconItem *item;
-
- if((item = m_brushMediator->itemFor(brush)))
- {
- slotSetBrush(item);
- } else {
- slotSetBrush( new KisIconItem(brush) );
- }
-
-}
-
-void KisControlFrame::slotPatternChanged(KisPattern * pattern)
-{
- KisIconItem *item;
- if (!pattern)
- return;
-
- if ( (item = m_patternMediator->itemFor(pattern)) )
- slotSetPattern(item);
- else
- slotSetPattern( new KisIconItem(pattern) );
-}
-
-
-void KisControlFrame::slotGradientChanged(KisGradient * gradient)
-{
- KisIconItem *item;
- if (!gradient)
- return;
-
- if ( (item = m_gradientMediator->itemFor(gradient)) )
- slotSetGradient(item);
- else
- slotSetGradient( new KisIconItem(gradient) );
-}
-
-void KisControlFrame::createBrushesChooser(KisView * view)
-{
-
- m_brushChooserPopup = new KisPopupFrame(m_brushWidget, "brush_chooser_popup");
-
- TQHBoxLayout * l = new TQHBoxLayout(m_brushChooserPopup, 2, 2, "brushpopuplayout");
-
- TQTabWidget * m_brushesTab = new TQTabWidget(m_brushChooserPopup, "brushestab");
- m_brushesTab->setTabShape(TQTabWidget::Triangular);
- m_brushesTab->setFocusPolicy(TQ_NoFocus);
- m_brushesTab->setFont(m_font);
- m_brushesTab->setMargin(1);
-
- l->add(m_brushesTab);
-
- KisAutobrush * m_autobrush = new KisAutobrush(m_brushesTab, "autobrush", i18n("Autobrush"));
- m_brushesTab->addTab( m_autobrush, i18n("Autobrush"));
- connect(m_autobrush, TQT_SIGNAL(activatedResource(KisResource*)), m_view, TQT_SLOT(brushActivated( KisResource* )));
-
- KisBrushChooser * m_brushChooser = new KisBrushChooser(m_brushesTab, "brush_chooser");
- m_brushesTab->addTab( m_brushChooser, i18n("Predefined Brushes"));
-
- KisCustomBrush* customBrushes = new KisCustomBrush(m_brushesTab, "custombrush",
- i18n("Custom Brush"), m_view);
- m_brushesTab->addTab( customBrushes, i18n("Custom Brush"));
- connect(customBrushes, TQT_SIGNAL(activatedResource(KisResource*)),
- m_view, TQT_SLOT(brushActivated(KisResource*)));
-#ifdef HAVE_TEXT_BRUSH
- KisTextBrush* textBrushes = new KisTextBrush(m_brushesTab, "textbrush",
- i18n("Text Brush")/*, m_view*/);
- m_brushesTab->addTab( textBrushes, i18n("Text Brush"));
- connect(textBrushes, TQT_SIGNAL(activatedResource(KisResource*)),
- m_view, TQT_SLOT(brushActivated(KisResource*)));
-#endif
-
- m_brushChooser->setFont(m_font);
- m_brushMediator = new KisResourceMediator( m_brushChooser, this);
- connect(m_brushMediator, TQT_SIGNAL(activatedResource(KisResource*)), m_view, TQT_SLOT(brushActivated(KisResource*)));
-
- KisResourceServerBase* rServer;
- rServer = KisResourceServerRegistry::instance()->get("ImagePipeBrushServer");
- m_brushMediator->connectServer(rServer);
- rServer = KisResourceServerRegistry::instance()->get("BrushServer");
- m_brushMediator->connectServer(rServer);
-
- KisControlFrame::connect(view, TQT_SIGNAL(brushChanged(KisBrush *)), this, TQT_SLOT(slotBrushChanged( KisBrush *)));
- m_brushChooser->setCurrent( 0 );
- m_brushMediator->setActiveItem( m_brushChooser->currentItem() );
- customBrushes->setResourceServer(rServer);
-
- m_autobrush->activate();
-}
-
-void KisControlFrame::createPatternsChooser(KisView * view)
-{
- m_patternChooserPopup = new KisPopupFrame(m_patternWidget, "pattern_chooser_popup");
-
- TQHBoxLayout * l2 = new TQHBoxLayout(m_patternChooserPopup, 2, 2, "patternpopuplayout");
-
- TQTabWidget * m_patternsTab = new TQTabWidget(m_patternChooserPopup, "patternstab");
- m_patternsTab->setTabShape(TQTabWidget::Triangular);
- m_patternsTab->setFocusPolicy(TQ_NoFocus);
- m_patternsTab->setFont(m_font);
- m_patternsTab->setMargin(1);
- l2->add( m_patternsTab );
-
- KisPatternChooser * chooser = new KisPatternChooser(m_patternChooserPopup, "pattern_chooser");
- chooser->setFont(m_font);
- chooser->setMinimumSize(200, 150);
- m_patternsTab->addTab(chooser, i18n("Patterns"));
-
- KisCustomPattern* customPatterns = new KisCustomPattern(m_patternsTab, "custompatterns",
- i18n("Custom Pattern"), m_view);
- customPatterns->setFont(m_font);
- m_patternsTab->addTab( customPatterns, i18n("Custom Pattern"));
-
-
- m_patternMediator = new KisResourceMediator( chooser, TQT_TQOBJECT(view));
- connect( m_patternMediator, TQT_SIGNAL(activatedResource(KisResource*)), view, TQT_SLOT(patternActivated(KisResource*)));
- connect(customPatterns, TQT_SIGNAL(activatedResource(KisResource*)),
- TQT_TQOBJECT(view), TQT_SLOT(patternActivated(KisResource*)));
-
- KisResourceServerBase* rServer;
- rServer = KisResourceServerRegistry::instance()->get("PatternServer");
- m_patternMediator->connectServer(rServer);
-
- KisControlFrame::connect(view, TQT_SIGNAL(patternChanged(KisPattern *)), this, TQT_SLOT(slotPatternChanged( KisPattern *)));
- chooser->setCurrent( 0 );
- m_patternMediator->setActiveItem( chooser->currentItem() );
-
- customPatterns->setResourceServer(rServer);
-}
-
-
-void KisControlFrame::createGradientsChooser(KisView * view)
-{
- m_gradientChooserPopup = new KisPopupFrame(m_gradientWidget, "gradient_chooser_popup");
-
- TQHBoxLayout * l2 = new TQHBoxLayout(m_gradientChooserPopup, 2, 2, "gradientpopuplayout");
-
- TQTabWidget * m_gradientTab = new TQTabWidget(m_gradientChooserPopup, "gradientstab");
- m_gradientTab->setTabShape(TQTabWidget::Triangular);
- m_gradientTab->setFocusPolicy(TQ_NoFocus);
- m_gradientTab->setFont(m_font);
- m_gradientTab->setMargin(1);
-
- l2->add( m_gradientTab);
-
- KisGradientChooser * m_gradientChooser = new KisGradientChooser(m_view, m_gradientChooserPopup, "gradient_chooser");
- m_gradientChooser->setFont(m_font);
- m_gradientChooser->setMinimumSize(200, 150);
- m_gradientTab->addTab( m_gradientChooser, i18n("Gradients"));
-
- m_gradientMediator = new KisResourceMediator( m_gradientChooser, TQT_TQOBJECT(view));
- connect(m_gradientMediator, TQT_SIGNAL(activatedResource(KisResource*)), view, TQT_SLOT(gradientActivated(KisResource*)));
-
- KisResourceServerBase* rServer;
- rServer = KisResourceServerRegistry::instance()->get("GradientServer");
- m_gradientMediator->connectServer(rServer);
-
- connect(view, TQT_SIGNAL(gradientChanged(KisGradient *)), this, TQT_SLOT(slotGradientChanged( KisGradient *)));
- m_gradientChooser->setCurrent( 0 );
- m_gradientMediator->setActiveItem( m_gradientChooser->currentItem() );
-}
-
-
-#include "kis_controlframe.moc"
-
diff --git a/chalk/ui/kis_controlframe.cpp b/chalk/ui/kis_controlframe.cpp
new file mode 100644
index 000000000..e5a8ce1bb
--- /dev/null
+++ b/chalk/ui/kis_controlframe.cpp
@@ -0,0 +1,343 @@
+/*
+ * kis_controlframe.cpp - part of Chalk
+ *
+ * Copyright (c) 1999 Matthias Elter <elter@kde.org>
+ * Copyright (c) 2003 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2004 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.g
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <stdlib.h>
+
+#include <tqapplication.h>
+#include <tqlayout.h>
+#include <tqtabwidget.h>
+#include <tqframe.h>
+#include <tqwidget.h>
+#include <tqevent.h>
+
+#include <tdetoolbar.h>
+#include <tdemainwindow.h>
+#include <tdeglobalsettings.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <koFrameButton.h>
+#include <tdeactioncollection.h>
+
+#include "kis_resourceserver.h"
+#include "kis_controlframe.h"
+#include "kis_resource_mediator.h"
+#include "kis_itemchooser.h"
+#include "kis_pattern_chooser.h"
+#include "kis_gradient_chooser.h"
+#include "kis_icon_item.h"
+#include "kis_iconwidget.h"
+#include "kis_brush.h"
+#include "kis_pattern.h"
+#include "kis_gradient.h"
+#include "kis_brush_chooser.h"
+#include "kis_view.h"
+#include "kis_autobrush.h"
+#include "kis_autogradient.h"
+#include "kis_config.h"
+#include "kis_paintop_box.h"
+#include "kis_custom_brush.h"
+#include "kis_custom_pattern.h"
+#ifdef HAVE_TEXT_BRUSH
+#include "kis_text_brush.h"
+#endif
+KisPopupFrame::KisPopupFrame(TQWidget * parent, const char* name)
+ : TQPopupMenu(parent, name)
+{
+ setFocusPolicy(TQ_StrongFocus);
+}
+
+void KisPopupFrame::keyPressEvent(TQKeyEvent * e)
+{
+ if (e->key()== TQt::Key_Escape)
+ {
+ hide();
+ e->accept();
+ }
+ else {
+ e->ignore();
+ }
+}
+
+
+KisControlFrame::KisControlFrame( TDEMainWindow * /*window*/, KisView * view, const char* name )
+ : TQObject(view, name)
+ //: TDEToolBar ( window, TQt::DockTop, false, name, true, true )
+ , m_view(view)
+ , m_brushWidget(0)
+ , m_patternWidget(0)
+ , m_gradientWidget(0)
+ , m_brushChooserPopup(0)
+ , m_patternChooserPopup(0)
+ , m_gradientChooserPopup(0)
+ , m_brushMediator(0)
+ , m_patternMediator(0)
+ , m_gradientMediator(0)
+ , m_paintopBox(0)
+{
+
+ KisConfig cfg;
+ m_font = TDEGlobalSettings::generalFont();
+ m_font.setPointSize((int)cfg.dockerFontSize());
+
+ m_brushWidget = new KisIconWidget(view, "brushes");
+ m_brushWidget->setTextLabel( i18n("Brush Shapes") );
+ // XXX: An action without a slot -- that's silly, what kind of action could we use here?
+ TDEAction * action = new KWidgetAction(m_brushWidget,
+ i18n("&Brush"),
+ 0,
+ TQT_TQOBJECT(view),
+ 0,
+ view->actionCollection(),
+ "brushes");
+
+
+ m_patternWidget = new KisIconWidget(view, "patterns");
+ m_patternWidget->setTextLabel( i18n("Fill Patterns") );
+ action = new KWidgetAction(m_patternWidget,
+ i18n("&Patterns"),
+ 0,
+ TQT_TQOBJECT(view),
+ 0,
+ view->actionCollection(),
+ "patterns");
+
+ m_gradientWidget = new KisIconWidget(view, "gradients");
+ m_gradientWidget->setTextLabel( i18n("Gradients") );
+ action = new KWidgetAction(m_gradientWidget,
+ i18n("&Gradients"),
+ 0,
+ TQT_TQOBJECT(view),
+ 0,
+ view->actionCollection(),
+ "gradients");
+
+ m_paintopBox = new KisPaintopBox( view, view, "paintopbox" );
+ action = new KWidgetAction(m_paintopBox,
+ i18n("&Painter's Tools"),
+ 0,
+ TQT_TQOBJECT(view),
+ 0,
+ view->actionCollection(),
+ "paintops");
+
+ m_brushWidget->setFixedSize( 26, 26 );
+ m_patternWidget->setFixedSize( 26, 26 );
+ m_gradientWidget->setFixedSize( 26, 26 );
+
+ createBrushesChooser(m_view);
+ createPatternsChooser(m_view);
+ createGradientsChooser(m_view);
+
+ m_brushWidget->setPopup(m_brushChooserPopup);
+ m_brushWidget->setPopupDelay(1);
+ m_patternWidget->setPopup(m_patternChooserPopup);
+ m_patternWidget->setPopupDelay(1);
+ m_gradientWidget->setPopup(m_gradientChooserPopup);
+ m_gradientWidget->setPopupDelay(1);
+}
+
+
+void KisControlFrame::slotSetBrush(KoIconItem *item)
+{
+ if (item)
+ m_brushWidget->slotSetItem(*item);
+}
+
+void KisControlFrame::slotSetPattern(KoIconItem *item)
+{
+ if (item)
+ m_patternWidget->slotSetItem(*item);
+}
+
+void KisControlFrame::slotSetGradient(KoIconItem *item)
+{
+ if (item)
+ m_gradientWidget->slotSetItem(*item);
+}
+
+void KisControlFrame::slotBrushChanged(KisBrush * brush)
+{
+ KisIconItem *item;
+
+ if((item = m_brushMediator->itemFor(brush)))
+ {
+ slotSetBrush(item);
+ } else {
+ slotSetBrush( new KisIconItem(brush) );
+ }
+
+}
+
+void KisControlFrame::slotPatternChanged(KisPattern * pattern)
+{
+ KisIconItem *item;
+ if (!pattern)
+ return;
+
+ if ( (item = m_patternMediator->itemFor(pattern)) )
+ slotSetPattern(item);
+ else
+ slotSetPattern( new KisIconItem(pattern) );
+}
+
+
+void KisControlFrame::slotGradientChanged(KisGradient * gradient)
+{
+ KisIconItem *item;
+ if (!gradient)
+ return;
+
+ if ( (item = m_gradientMediator->itemFor(gradient)) )
+ slotSetGradient(item);
+ else
+ slotSetGradient( new KisIconItem(gradient) );
+}
+
+void KisControlFrame::createBrushesChooser(KisView * view)
+{
+
+ m_brushChooserPopup = new KisPopupFrame(m_brushWidget, "brush_chooser_popup");
+
+ TQHBoxLayout * l = new TQHBoxLayout(m_brushChooserPopup, 2, 2, "brushpopuplayout");
+
+ TQTabWidget * m_brushesTab = new TQTabWidget(m_brushChooserPopup, "brushestab");
+ m_brushesTab->setTabShape(TQTabWidget::Triangular);
+ m_brushesTab->setFocusPolicy(TQ_NoFocus);
+ m_brushesTab->setFont(m_font);
+ m_brushesTab->setMargin(1);
+
+ l->add(m_brushesTab);
+
+ KisAutobrush * m_autobrush = new KisAutobrush(m_brushesTab, "autobrush", i18n("Autobrush"));
+ m_brushesTab->addTab( m_autobrush, i18n("Autobrush"));
+ connect(m_autobrush, TQT_SIGNAL(activatedResource(KisResource*)), m_view, TQT_SLOT(brushActivated( KisResource* )));
+
+ KisBrushChooser * m_brushChooser = new KisBrushChooser(m_brushesTab, "brush_chooser");
+ m_brushesTab->addTab( m_brushChooser, i18n("Predefined Brushes"));
+
+ KisCustomBrush* customBrushes = new KisCustomBrush(m_brushesTab, "custombrush",
+ i18n("Custom Brush"), m_view);
+ m_brushesTab->addTab( customBrushes, i18n("Custom Brush"));
+ connect(customBrushes, TQT_SIGNAL(activatedResource(KisResource*)),
+ m_view, TQT_SLOT(brushActivated(KisResource*)));
+#ifdef HAVE_TEXT_BRUSH
+ KisTextBrush* textBrushes = new KisTextBrush(m_brushesTab, "textbrush",
+ i18n("Text Brush")/*, m_view*/);
+ m_brushesTab->addTab( textBrushes, i18n("Text Brush"));
+ connect(textBrushes, TQT_SIGNAL(activatedResource(KisResource*)),
+ m_view, TQT_SLOT(brushActivated(KisResource*)));
+#endif
+
+ m_brushChooser->setFont(m_font);
+ m_brushMediator = new KisResourceMediator( m_brushChooser, this);
+ connect(m_brushMediator, TQT_SIGNAL(activatedResource(KisResource*)), m_view, TQT_SLOT(brushActivated(KisResource*)));
+
+ KisResourceServerBase* rServer;
+ rServer = KisResourceServerRegistry::instance()->get("ImagePipeBrushServer");
+ m_brushMediator->connectServer(rServer);
+ rServer = KisResourceServerRegistry::instance()->get("BrushServer");
+ m_brushMediator->connectServer(rServer);
+
+ KisControlFrame::connect(view, TQT_SIGNAL(brushChanged(KisBrush *)), this, TQT_SLOT(slotBrushChanged( KisBrush *)));
+ m_brushChooser->setCurrent( 0 );
+ m_brushMediator->setActiveItem( m_brushChooser->currentItem() );
+ customBrushes->setResourceServer(rServer);
+
+ m_autobrush->activate();
+}
+
+void KisControlFrame::createPatternsChooser(KisView * view)
+{
+ m_patternChooserPopup = new KisPopupFrame(m_patternWidget, "pattern_chooser_popup");
+
+ TQHBoxLayout * l2 = new TQHBoxLayout(m_patternChooserPopup, 2, 2, "patternpopuplayout");
+
+ TQTabWidget * m_patternsTab = new TQTabWidget(m_patternChooserPopup, "patternstab");
+ m_patternsTab->setTabShape(TQTabWidget::Triangular);
+ m_patternsTab->setFocusPolicy(TQ_NoFocus);
+ m_patternsTab->setFont(m_font);
+ m_patternsTab->setMargin(1);
+ l2->add( m_patternsTab );
+
+ KisPatternChooser * chooser = new KisPatternChooser(m_patternChooserPopup, "pattern_chooser");
+ chooser->setFont(m_font);
+ chooser->setMinimumSize(200, 150);
+ m_patternsTab->addTab(chooser, i18n("Patterns"));
+
+ KisCustomPattern* customPatterns = new KisCustomPattern(m_patternsTab, "custompatterns",
+ i18n("Custom Pattern"), m_view);
+ customPatterns->setFont(m_font);
+ m_patternsTab->addTab( customPatterns, i18n("Custom Pattern"));
+
+
+ m_patternMediator = new KisResourceMediator( chooser, TQT_TQOBJECT(view));
+ connect( m_patternMediator, TQT_SIGNAL(activatedResource(KisResource*)), view, TQT_SLOT(patternActivated(KisResource*)));
+ connect(customPatterns, TQT_SIGNAL(activatedResource(KisResource*)),
+ TQT_TQOBJECT(view), TQT_SLOT(patternActivated(KisResource*)));
+
+ KisResourceServerBase* rServer;
+ rServer = KisResourceServerRegistry::instance()->get("PatternServer");
+ m_patternMediator->connectServer(rServer);
+
+ KisControlFrame::connect(view, TQT_SIGNAL(patternChanged(KisPattern *)), this, TQT_SLOT(slotPatternChanged( KisPattern *)));
+ chooser->setCurrent( 0 );
+ m_patternMediator->setActiveItem( chooser->currentItem() );
+
+ customPatterns->setResourceServer(rServer);
+}
+
+
+void KisControlFrame::createGradientsChooser(KisView * view)
+{
+ m_gradientChooserPopup = new KisPopupFrame(m_gradientWidget, "gradient_chooser_popup");
+
+ TQHBoxLayout * l2 = new TQHBoxLayout(m_gradientChooserPopup, 2, 2, "gradientpopuplayout");
+
+ TQTabWidget * m_gradientTab = new TQTabWidget(m_gradientChooserPopup, "gradientstab");
+ m_gradientTab->setTabShape(TQTabWidget::Triangular);
+ m_gradientTab->setFocusPolicy(TQ_NoFocus);
+ m_gradientTab->setFont(m_font);
+ m_gradientTab->setMargin(1);
+
+ l2->add( m_gradientTab);
+
+ KisGradientChooser * m_gradientChooser = new KisGradientChooser(m_view, m_gradientChooserPopup, "gradient_chooser");
+ m_gradientChooser->setFont(m_font);
+ m_gradientChooser->setMinimumSize(200, 150);
+ m_gradientTab->addTab( m_gradientChooser, i18n("Gradients"));
+
+ m_gradientMediator = new KisResourceMediator( m_gradientChooser, TQT_TQOBJECT(view));
+ connect(m_gradientMediator, TQT_SIGNAL(activatedResource(KisResource*)), view, TQT_SLOT(gradientActivated(KisResource*)));
+
+ KisResourceServerBase* rServer;
+ rServer = KisResourceServerRegistry::instance()->get("GradientServer");
+ m_gradientMediator->connectServer(rServer);
+
+ connect(view, TQT_SIGNAL(gradientChanged(KisGradient *)), this, TQT_SLOT(slotGradientChanged( KisGradient *)));
+ m_gradientChooser->setCurrent( 0 );
+ m_gradientMediator->setActiveItem( m_gradientChooser->currentItem() );
+}
+
+
+#include "kis_controlframe.moc"
+
diff --git a/chalk/ui/kis_cursor.cc b/chalk/ui/kis_cursor.cc
deleted file mode 100644
index c4281eac9..000000000
--- a/chalk/ui/kis_cursor.cc
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * kis_cursor.cc - part of KImageShop
- *
- * Copyright (c) 1999 Matthias Elter <elter@kde.org>
- * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqbitmap.h>
-#include <tqcursor.h>
-#include <tqimage.h>
-#include <tqpainter.h>
-
-#include <kcursor.h>
-#include <kiconloader.h>
-#include <kstandarddirs.h>
-
-#include "kis_cursor.h"
-#include "kis_factory.h"
-
-KisCursor::KisCursor() {}
-
-/*
- * Predefined TQt cursors
- */
-TQCursor KisCursor::arrowCursor()
-{
- return TQt::arrowCursor;
-}
-
-TQCursor KisCursor::upArrowCursor()
-{
- return TQt::upArrowCursor;
-}
-
-TQCursor KisCursor::crossCursor()
-{
- return TQt::crossCursor;
-}
-
-TQCursor KisCursor::waitCursor()
-{
- return TQt::waitCursor;
-}
-
-TQCursor KisCursor::ibeamCursor()
-{
- return TQt::ibeamCursor;
-}
-
-TQCursor KisCursor::sizeVerCursor()
-{
- return TQt::sizeVerCursor;
-}
-
-TQCursor KisCursor::sizeHorCursor()
-{
- return TQt::sizeHorCursor;
-}
-
-TQCursor KisCursor::sizeBDiagCursor()
-{
- return TQt::sizeBDiagCursor;
-}
-
-TQCursor KisCursor::sizeFDiagCursor()
-{
- return TQt::sizeFDiagCursor;
-}
-
-TQCursor KisCursor::sizeAllCursor()
-{
- return TQt::sizeAllCursor;
-}
-
-TQCursor KisCursor::blankCursor()
-{
- return TQt::blankCursor;
-}
-
-TQCursor KisCursor::splitVCursor()
-{
- return TQt::splitVCursor;
-}
-
-TQCursor KisCursor::splitHCursor()
-{
- return TQt::splitHCursor;
-}
-
-TQCursor KisCursor::pointingHandCursor()
-{
- return TQt::pointingHandCursor;
-}
-
-
-/*
- * Existing custom KimageShop cursors. Use the 'load' function for all new cursors.
- */
-
-TQCursor KisCursor::pickerCursor()
-{
- static unsigned char picker_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
- 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
- 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
- 0x00, 0x72, 0x01, 0x00, 0x39, 0x00, 0x80, 0x1c, 0x00, 0x40, 0x0e, 0x00,
- 0x20, 0x07, 0x00, 0x90, 0x03, 0x00, 0xc8, 0x01, 0x00, 0xe4, 0x00, 0x00,
- 0x74, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap picker_bitmap(24, 24, picker_bits, true);
- TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
-
- return TQCursor( picker_bitmap, picker_mask, 1, 22 );
-}
-
-
-TQCursor KisCursor::pickerPlusCursor()
-{
- static unsigned char pickerplus_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
- 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
- 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
- 0x00, 0x72, 0x01, 0x00, 0x39, 0x0c, 0x80, 0x1c, 0x0c, 0x40, 0x0e, 0x0c,
- 0x20, 0x07, 0x0c, 0x90, 0x83, 0x7f, 0xc8, 0x81, 0x7f, 0xe4, 0x00, 0x0c,
- 0x74, 0x00, 0x0c, 0x32, 0x00, 0x0c, 0x0a, 0x00, 0x0c, 0x00, 0x00, 0x00};
-
- TQBitmap picker_bitmap(24, 24, pickerplus_bits, true);
- TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
-
- return TQCursor( picker_bitmap, picker_mask, 1, 22 );
-}
-
-
-TQCursor KisCursor::pickerMinusCursor()
-{
- static unsigned char pickerminus_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
- 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
- 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
- 0x00, 0x72, 0x01, 0x00, 0x39, 0x00, 0x80, 0x1c, 0x00, 0x40, 0x0e, 0x00,
- 0x20, 0x07, 0x00, 0x90, 0xc3, 0x7f, 0xc8, 0xc1, 0x7f, 0xe4, 0x00, 0x00,
- 0x74, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap picker_bitmap(24, 24, pickerminus_bits, true);
- TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
-
- return TQCursor( picker_bitmap, picker_mask, 1, 22 );
-}
-
-
-
-TQCursor KisCursor::penCursor()
-{
- static unsigned char pen_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x7d,
- 0x00, 0x80, 0x7e, 0x00, 0x40, 0x7f, 0x00, 0xa0, 0x3f, 0x00, 0xd0, 0x1f,
- 0x00, 0xe8, 0x0f, 0x00, 0xf4, 0x07, 0x00, 0xfa, 0x03, 0x00, 0xfd, 0x01,
- 0x80, 0xfe, 0x00, 0x40, 0x7f, 0x00, 0xa0, 0x3f, 0x00, 0xf0, 0x1f, 0x00,
- 0xd0, 0x0f, 0x00, 0x88, 0x07, 0x00, 0x88, 0x03, 0x00, 0xe4, 0x01, 0x00,
- 0x7c, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap pen_bitmap( 24, 24, pen_bits, true );
- TQBitmap pen_mask = pen_bitmap.createHeuristicMask( false );
-
- return TQCursor( pen_bitmap, pen_mask, 1, 22 );
-}
-
-TQCursor KisCursor::brushCursor()
-{
- static unsigned char brush_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x68, 0x00,
- 0x00, 0x00, 0xf4, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0xfd, 0x00,
- 0x00, 0x80, 0x7e, 0x00, 0x00, 0x40, 0x3f, 0x00, 0x00, 0xa0, 0x1f, 0x00,
- 0x00, 0xd0, 0x0f, 0x00, 0x00, 0xe8, 0x07, 0x00, 0x00, 0xf4, 0x03, 0x00,
- 0x00, 0xe4, 0x01, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x80, 0x41, 0x00, 0x00,
- 0x40, 0x32, 0x00, 0x00, 0xa0, 0x0f, 0x00, 0x00, 0xd0, 0x0f, 0x00, 0x00,
- 0xd0, 0x0f, 0x00, 0x00, 0xe8, 0x07, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00,
- 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap brush_bitmap( 25, 23, brush_bits, true );
- TQBitmap brush_mask = brush_bitmap.createHeuristicMask( false );
-
- return TQCursor( brush_bitmap, brush_mask, 1, 21 );
-}
-
-TQCursor KisCursor::airbrushCursor()
-{
- static unsigned char airbrush_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x68, 0x00, 0x00, 0x74,
- 0x00, 0x00, 0x7a, 0xf0, 0x00, 0x3d, 0x08, 0x81, 0x1e, 0xe8, 0x41, 0x0f,
- 0xe8, 0xa1, 0x07, 0xe8, 0xd1, 0x03, 0xe8, 0xe9, 0x01, 0xe8, 0xf5, 0x00,
- 0xe8, 0x7b, 0x00, 0xf0, 0x33, 0x00, 0xf0, 0x23, 0x1f, 0xa0, 0x9f, 0x3f,
- 0xd0, 0xff, 0x31, 0xe8, 0xf7, 0x30, 0xf4, 0x03, 0x18, 0xfc, 0x01, 0x0c,
- 0xf8, 0x00, 0x06, 0x76, 0x00, 0x03, 0x36, 0x00, 0x03, 0x00, 0x00, 0x00};
-
- TQBitmap airbrush_bitmap( 24, 24, airbrush_bits, true );
- TQBitmap airbrush_mask = airbrush_bitmap.createHeuristicMask( false );
-
- return TQCursor( airbrush_bitmap, airbrush_mask, 1, 22 );
-}
-
-TQCursor KisCursor::eraserCursor()
-{
- static unsigned char eraser_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1d, 0x00,
- 0x00, 0x80, 0x3e, 0x00, 0x00, 0x40, 0x7f, 0x00, 0x00, 0xa0, 0xff, 0x00,
- 0x00, 0xd0, 0xff, 0x00, 0x00, 0xe8, 0x7f, 0x00, 0x00, 0xf4, 0x3f, 0x00,
- 0x00, 0xfe, 0x1f, 0x00, 0x00, 0xf9, 0x0f, 0x00, 0x80, 0xf2, 0x07, 0x00,
- 0x40, 0xe7, 0x03, 0x00, 0xa0, 0xcf, 0x01, 0x00, 0xd0, 0x9f, 0x00, 0x00,
- 0xe8, 0x7f, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x00, 0xf2, 0x1f, 0x00, 0x00,
- 0xe2, 0x0f, 0x00, 0x00, 0xc4, 0x07, 0x00, 0x00, 0x88, 0x03, 0x00, 0x00,
- 0x10, 0x01, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap eraser_bitmap( 25, 24, eraser_bits, true );
- TQBitmap eraser_mask = eraser_bitmap.createHeuristicMask( false );
-
- return TQCursor( eraser_bitmap, eraser_mask, 7, 22 );
-}
-
-TQCursor KisCursor::fillerCursor()
-{
- static unsigned char filler_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x28, 0x00,
- 0x00, 0x54, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x85, 0x00, 0x80, 0x0a, 0x01,
- 0x40, 0x11, 0x01, 0xe0, 0x00, 0x02, 0x58, 0x01, 0x04, 0x2c, 0x02, 0x04,
- 0x44, 0x04, 0x08, 0x0c, 0x08, 0x18, 0x3c, 0x00, 0x14, 0x5c, 0x00, 0x0a,
- 0x9c, 0x01, 0x05, 0x1c, 0x82, 0x02, 0x18, 0x4c, 0x01, 0x18, 0xb0, 0x00,
- 0x08, 0x60, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap filler_bitmap( 22, 22, filler_bits, true );
- TQBitmap filler_mask = filler_bitmap.createHeuristicMask( false );
-
- return TQCursor( filler_bitmap, filler_mask, 3, 20 );
-}
-
-TQCursor KisCursor::colorChangerCursor()
-{
- static unsigned char colorChanger_bits[] = {
- 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x10, 0x01, 0x0e, 0x08, 0x02, 0x11,
- 0x04, 0x82, 0x20, 0x64, 0x84, 0x20, 0x92, 0x44, 0x46, 0x12, 0x49, 0x5f,
- 0x12, 0x31, 0x5f, 0x22, 0x01, 0x5f, 0xc2, 0x00, 0x4e, 0x02, 0x00, 0x40,
- 0xc2, 0x00, 0x46, 0xe2, 0x01, 0x4f, 0xe4, 0x19, 0x2f, 0xe4, 0x3d, 0x2f,
- 0xe8, 0x3d, 0x17, 0xd0, 0x3c, 0x10, 0x20, 0x38, 0x08, 0x40, 0x00, 0x06,
- 0x80, 0x81, 0x01, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap colorChanger_bitmap( 24, 23, colorChanger_bits, true );
- TQBitmap colorChanger_mask = colorChanger_bitmap.createHeuristicMask( false );
-
- return TQCursor( colorChanger_bitmap, colorChanger_mask, 12, 10 );
-}
-
-TQCursor KisCursor::zoomCursor()
-{
- static unsigned char zoom_bits[] = {
- 0x00, 0x00, 0x00, 0xc0, 0x0f, 0x00, 0xf0, 0x3f, 0x00, 0x38, 0x70, 0x00,
- 0x8c, 0xcf, 0x00, 0x0c, 0xdf, 0x00, 0x36, 0xbf, 0x01, 0xb6, 0xbf, 0x01,
- 0xf6, 0xbf, 0x01, 0xf6, 0xbf, 0x01, 0xe6, 0x9f, 0x00, 0xcc, 0xcf, 0x00,
- 0x9c, 0xe7, 0x01, 0x38, 0x70, 0x03, 0xf0, 0xbf, 0x05, 0xc0, 0xef, 0x0b,
- 0x00, 0xc0, 0x17, 0x00, 0x80, 0x2f, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x7e,
- 0x00, 0x00, 0x7c, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00};
-
- TQBitmap zoom_bitmap( 24, 23, zoom_bits, true );
- TQBitmap zoom_mask = zoom_bitmap.createHeuristicMask( false );
-
- return TQCursor( zoom_bitmap, zoom_mask, 9, 8 );
-}
-
-TQCursor KisCursor::moveCursor()
-{
- static unsigned char move_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x7e, 0x00,
- 0x00, 0xff, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00,
- 0x10, 0x18, 0x08, 0x18, 0x18, 0x18, 0x1c, 0x18, 0x38, 0xfe, 0xff, 0x7f,
- 0xfe, 0xff, 0x7f, 0x1c, 0x18, 0x38, 0x18, 0x18, 0x18, 0x10, 0x18, 0x08,
- 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0xff, 0x00,
- 0x00, 0x7e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00};
-
- TQBitmap move_bitmap( 24, 24, move_bits, true );
- TQBitmap move_mask = move_bitmap.createHeuristicMask( false );
-
- return TQCursor( move_bitmap, move_mask, 12, 11 );
-}
-
-TQCursor KisCursor::handCursor()
-{
- return KCursor::handCursor();
-}
-
-TQCursor KisCursor::selectCursor()
-{
- static unsigned char select_bits[] = {
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0xff, 0xff, 0x7f,
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
- 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00};
-
- TQBitmap select_bitmap(23, 23, select_bits, true);
- TQBitmap select_mask = select_bitmap.createHeuristicMask( false );
-
- return TQCursor( select_bitmap, select_mask, 11, 11 );
-}
-
-TQCursor KisCursor::openHandCursor()
-{
- return load("openhand_cursor.xpm");
-}
-
-TQCursor KisCursor::closedHandCursor()
-{
- return load("closedhand_cursor.xpm");
-}
-
-TQCursor KisCursor::rotateCursor()
-{
- return load("rotate_cursor.xpm");
-}
-
-TQCursor KisCursor::load(const TQString & iconName, int hotspotX, int hotspotY)
-{
- TQString filename = KisFactory::instance()->dirs()->findResource("kis_pics", iconName);
- TQImage cursorImage;
-
- cursorImage.load(filename);
- Q_ASSERT(!cursorImage.isNull());
- Q_ASSERT(cursorImage.hasAlphaBuffer());
-
- TQBitmap bitmap(cursorImage.width(), cursorImage.height());
- TQBitmap mask(cursorImage.width(), cursorImage.height());
-
- TQPainter bitmapPainter(&bitmap);
- TQPainter maskPainter(&mask);
-
- for (TQ_INT32 x = 0; x < cursorImage.width(); ++x) {
- for (TQ_INT32 y = 0; y < cursorImage.height(); ++y) {
-
- TQRgb pixel = cursorImage.pixel(x, y);
-
- if (tqAlpha(pixel) < 128) {
- bitmapPainter.setPen(TQt::color0);
- maskPainter.setPen(TQt::color0);
- } else {
- maskPainter.setPen(TQt::color1);
-
- if (tqGray(pixel) < 128) {
- bitmapPainter.setPen(TQt::color1);
- } else {
- bitmapPainter.setPen(TQt::color0);
- }
- }
-
- bitmapPainter.drawPoint(x, y);
- maskPainter.drawPoint(x, y);
- }
- }
-
- return TQCursor(bitmap, mask, hotspotX, hotspotY);
-}
-
diff --git a/chalk/ui/kis_cursor.cpp b/chalk/ui/kis_cursor.cpp
new file mode 100644
index 000000000..146dc2863
--- /dev/null
+++ b/chalk/ui/kis_cursor.cpp
@@ -0,0 +1,374 @@
+/*
+ * kis_cursor.cpp - part of KImageShop
+ *
+ * Copyright (c) 1999 Matthias Elter <elter@kde.org>
+ * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqbitmap.h>
+#include <tqcursor.h>
+#include <tqimage.h>
+#include <tqpainter.h>
+
+#include <kcursor.h>
+#include <kiconloader.h>
+#include <kstandarddirs.h>
+
+#include "kis_cursor.h"
+#include "kis_factory.h"
+
+KisCursor::KisCursor() {}
+
+/*
+ * Predefined TQt cursors
+ */
+TQCursor KisCursor::arrowCursor()
+{
+ return TQt::arrowCursor;
+}
+
+TQCursor KisCursor::upArrowCursor()
+{
+ return TQt::upArrowCursor;
+}
+
+TQCursor KisCursor::crossCursor()
+{
+ return TQt::crossCursor;
+}
+
+TQCursor KisCursor::waitCursor()
+{
+ return TQt::waitCursor;
+}
+
+TQCursor KisCursor::ibeamCursor()
+{
+ return TQt::ibeamCursor;
+}
+
+TQCursor KisCursor::sizeVerCursor()
+{
+ return TQt::sizeVerCursor;
+}
+
+TQCursor KisCursor::sizeHorCursor()
+{
+ return TQt::sizeHorCursor;
+}
+
+TQCursor KisCursor::sizeBDiagCursor()
+{
+ return TQt::sizeBDiagCursor;
+}
+
+TQCursor KisCursor::sizeFDiagCursor()
+{
+ return TQt::sizeFDiagCursor;
+}
+
+TQCursor KisCursor::sizeAllCursor()
+{
+ return TQt::sizeAllCursor;
+}
+
+TQCursor KisCursor::blankCursor()
+{
+ return TQt::blankCursor;
+}
+
+TQCursor KisCursor::splitVCursor()
+{
+ return TQt::splitVCursor;
+}
+
+TQCursor KisCursor::splitHCursor()
+{
+ return TQt::splitHCursor;
+}
+
+TQCursor KisCursor::pointingHandCursor()
+{
+ return TQt::pointingHandCursor;
+}
+
+
+/*
+ * Existing custom KimageShop cursors. Use the 'load' function for all new cursors.
+ */
+
+TQCursor KisCursor::pickerCursor()
+{
+ static unsigned char picker_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
+ 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
+ 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
+ 0x00, 0x72, 0x01, 0x00, 0x39, 0x00, 0x80, 0x1c, 0x00, 0x40, 0x0e, 0x00,
+ 0x20, 0x07, 0x00, 0x90, 0x03, 0x00, 0xc8, 0x01, 0x00, 0xe4, 0x00, 0x00,
+ 0x74, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap picker_bitmap(24, 24, picker_bits, true);
+ TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
+
+ return TQCursor( picker_bitmap, picker_mask, 1, 22 );
+}
+
+
+TQCursor KisCursor::pickerPlusCursor()
+{
+ static unsigned char pickerplus_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
+ 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
+ 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
+ 0x00, 0x72, 0x01, 0x00, 0x39, 0x0c, 0x80, 0x1c, 0x0c, 0x40, 0x0e, 0x0c,
+ 0x20, 0x07, 0x0c, 0x90, 0x83, 0x7f, 0xc8, 0x81, 0x7f, 0xe4, 0x00, 0x0c,
+ 0x74, 0x00, 0x0c, 0x32, 0x00, 0x0c, 0x0a, 0x00, 0x0c, 0x00, 0x00, 0x00};
+
+ TQBitmap picker_bitmap(24, 24, pickerplus_bits, true);
+ TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
+
+ return TQCursor( picker_bitmap, picker_mask, 1, 22 );
+}
+
+
+TQCursor KisCursor::pickerMinusCursor()
+{
+ static unsigned char pickerminus_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x34, 0x00, 0x00, 0x7a,
+ 0x00, 0x00, 0x7d, 0x00, 0x80, 0x7e, 0x00, 0x60, 0x3f, 0x00, 0xd0, 0x1f,
+ 0x00, 0xa0, 0x0f, 0x00, 0x50, 0x07, 0x00, 0xc8, 0x06, 0x00, 0xe4, 0x02,
+ 0x00, 0x72, 0x01, 0x00, 0x39, 0x00, 0x80, 0x1c, 0x00, 0x40, 0x0e, 0x00,
+ 0x20, 0x07, 0x00, 0x90, 0xc3, 0x7f, 0xc8, 0xc1, 0x7f, 0xe4, 0x00, 0x00,
+ 0x74, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap picker_bitmap(24, 24, pickerminus_bits, true);
+ TQBitmap picker_mask = picker_bitmap.createHeuristicMask( false );
+
+ return TQCursor( picker_bitmap, picker_mask, 1, 22 );
+}
+
+
+
+TQCursor KisCursor::penCursor()
+{
+ static unsigned char pen_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x7d,
+ 0x00, 0x80, 0x7e, 0x00, 0x40, 0x7f, 0x00, 0xa0, 0x3f, 0x00, 0xd0, 0x1f,
+ 0x00, 0xe8, 0x0f, 0x00, 0xf4, 0x07, 0x00, 0xfa, 0x03, 0x00, 0xfd, 0x01,
+ 0x80, 0xfe, 0x00, 0x40, 0x7f, 0x00, 0xa0, 0x3f, 0x00, 0xf0, 0x1f, 0x00,
+ 0xd0, 0x0f, 0x00, 0x88, 0x07, 0x00, 0x88, 0x03, 0x00, 0xe4, 0x01, 0x00,
+ 0x7c, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap pen_bitmap( 24, 24, pen_bits, true );
+ TQBitmap pen_mask = pen_bitmap.createHeuristicMask( false );
+
+ return TQCursor( pen_bitmap, pen_mask, 1, 22 );
+}
+
+TQCursor KisCursor::brushCursor()
+{
+ static unsigned char brush_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x68, 0x00,
+ 0x00, 0x00, 0xf4, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0xfd, 0x00,
+ 0x00, 0x80, 0x7e, 0x00, 0x00, 0x40, 0x3f, 0x00, 0x00, 0xa0, 0x1f, 0x00,
+ 0x00, 0xd0, 0x0f, 0x00, 0x00, 0xe8, 0x07, 0x00, 0x00, 0xf4, 0x03, 0x00,
+ 0x00, 0xe4, 0x01, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x80, 0x41, 0x00, 0x00,
+ 0x40, 0x32, 0x00, 0x00, 0xa0, 0x0f, 0x00, 0x00, 0xd0, 0x0f, 0x00, 0x00,
+ 0xd0, 0x0f, 0x00, 0x00, 0xe8, 0x07, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00,
+ 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap brush_bitmap( 25, 23, brush_bits, true );
+ TQBitmap brush_mask = brush_bitmap.createHeuristicMask( false );
+
+ return TQCursor( brush_bitmap, brush_mask, 1, 21 );
+}
+
+TQCursor KisCursor::airbrushCursor()
+{
+ static unsigned char airbrush_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x68, 0x00, 0x00, 0x74,
+ 0x00, 0x00, 0x7a, 0xf0, 0x00, 0x3d, 0x08, 0x81, 0x1e, 0xe8, 0x41, 0x0f,
+ 0xe8, 0xa1, 0x07, 0xe8, 0xd1, 0x03, 0xe8, 0xe9, 0x01, 0xe8, 0xf5, 0x00,
+ 0xe8, 0x7b, 0x00, 0xf0, 0x33, 0x00, 0xf0, 0x23, 0x1f, 0xa0, 0x9f, 0x3f,
+ 0xd0, 0xff, 0x31, 0xe8, 0xf7, 0x30, 0xf4, 0x03, 0x18, 0xfc, 0x01, 0x0c,
+ 0xf8, 0x00, 0x06, 0x76, 0x00, 0x03, 0x36, 0x00, 0x03, 0x00, 0x00, 0x00};
+
+ TQBitmap airbrush_bitmap( 24, 24, airbrush_bits, true );
+ TQBitmap airbrush_mask = airbrush_bitmap.createHeuristicMask( false );
+
+ return TQCursor( airbrush_bitmap, airbrush_mask, 1, 22 );
+}
+
+TQCursor KisCursor::eraserCursor()
+{
+ static unsigned char eraser_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1d, 0x00,
+ 0x00, 0x80, 0x3e, 0x00, 0x00, 0x40, 0x7f, 0x00, 0x00, 0xa0, 0xff, 0x00,
+ 0x00, 0xd0, 0xff, 0x00, 0x00, 0xe8, 0x7f, 0x00, 0x00, 0xf4, 0x3f, 0x00,
+ 0x00, 0xfe, 0x1f, 0x00, 0x00, 0xf9, 0x0f, 0x00, 0x80, 0xf2, 0x07, 0x00,
+ 0x40, 0xe7, 0x03, 0x00, 0xa0, 0xcf, 0x01, 0x00, 0xd0, 0x9f, 0x00, 0x00,
+ 0xe8, 0x7f, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x00, 0xf2, 0x1f, 0x00, 0x00,
+ 0xe2, 0x0f, 0x00, 0x00, 0xc4, 0x07, 0x00, 0x00, 0x88, 0x03, 0x00, 0x00,
+ 0x10, 0x01, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap eraser_bitmap( 25, 24, eraser_bits, true );
+ TQBitmap eraser_mask = eraser_bitmap.createHeuristicMask( false );
+
+ return TQCursor( eraser_bitmap, eraser_mask, 7, 22 );
+}
+
+TQCursor KisCursor::fillerCursor()
+{
+ static unsigned char filler_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x28, 0x00,
+ 0x00, 0x54, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x85, 0x00, 0x80, 0x0a, 0x01,
+ 0x40, 0x11, 0x01, 0xe0, 0x00, 0x02, 0x58, 0x01, 0x04, 0x2c, 0x02, 0x04,
+ 0x44, 0x04, 0x08, 0x0c, 0x08, 0x18, 0x3c, 0x00, 0x14, 0x5c, 0x00, 0x0a,
+ 0x9c, 0x01, 0x05, 0x1c, 0x82, 0x02, 0x18, 0x4c, 0x01, 0x18, 0xb0, 0x00,
+ 0x08, 0x60, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap filler_bitmap( 22, 22, filler_bits, true );
+ TQBitmap filler_mask = filler_bitmap.createHeuristicMask( false );
+
+ return TQCursor( filler_bitmap, filler_mask, 3, 20 );
+}
+
+TQCursor KisCursor::colorChangerCursor()
+{
+ static unsigned char colorChanger_bits[] = {
+ 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x10, 0x01, 0x0e, 0x08, 0x02, 0x11,
+ 0x04, 0x82, 0x20, 0x64, 0x84, 0x20, 0x92, 0x44, 0x46, 0x12, 0x49, 0x5f,
+ 0x12, 0x31, 0x5f, 0x22, 0x01, 0x5f, 0xc2, 0x00, 0x4e, 0x02, 0x00, 0x40,
+ 0xc2, 0x00, 0x46, 0xe2, 0x01, 0x4f, 0xe4, 0x19, 0x2f, 0xe4, 0x3d, 0x2f,
+ 0xe8, 0x3d, 0x17, 0xd0, 0x3c, 0x10, 0x20, 0x38, 0x08, 0x40, 0x00, 0x06,
+ 0x80, 0x81, 0x01, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap colorChanger_bitmap( 24, 23, colorChanger_bits, true );
+ TQBitmap colorChanger_mask = colorChanger_bitmap.createHeuristicMask( false );
+
+ return TQCursor( colorChanger_bitmap, colorChanger_mask, 12, 10 );
+}
+
+TQCursor KisCursor::zoomCursor()
+{
+ static unsigned char zoom_bits[] = {
+ 0x00, 0x00, 0x00, 0xc0, 0x0f, 0x00, 0xf0, 0x3f, 0x00, 0x38, 0x70, 0x00,
+ 0x8c, 0xcf, 0x00, 0x0c, 0xdf, 0x00, 0x36, 0xbf, 0x01, 0xb6, 0xbf, 0x01,
+ 0xf6, 0xbf, 0x01, 0xf6, 0xbf, 0x01, 0xe6, 0x9f, 0x00, 0xcc, 0xcf, 0x00,
+ 0x9c, 0xe7, 0x01, 0x38, 0x70, 0x03, 0xf0, 0xbf, 0x05, 0xc0, 0xef, 0x0b,
+ 0x00, 0xc0, 0x17, 0x00, 0x80, 0x2f, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x7e,
+ 0x00, 0x00, 0x7c, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00};
+
+ TQBitmap zoom_bitmap( 24, 23, zoom_bits, true );
+ TQBitmap zoom_mask = zoom_bitmap.createHeuristicMask( false );
+
+ return TQCursor( zoom_bitmap, zoom_mask, 9, 8 );
+}
+
+TQCursor KisCursor::moveCursor()
+{
+ static unsigned char move_bits[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x7e, 0x00,
+ 0x00, 0xff, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00,
+ 0x10, 0x18, 0x08, 0x18, 0x18, 0x18, 0x1c, 0x18, 0x38, 0xfe, 0xff, 0x7f,
+ 0xfe, 0xff, 0x7f, 0x1c, 0x18, 0x38, 0x18, 0x18, 0x18, 0x10, 0x18, 0x08,
+ 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0xff, 0x00,
+ 0x00, 0x7e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00};
+
+ TQBitmap move_bitmap( 24, 24, move_bits, true );
+ TQBitmap move_mask = move_bitmap.createHeuristicMask( false );
+
+ return TQCursor( move_bitmap, move_mask, 12, 11 );
+}
+
+TQCursor KisCursor::handCursor()
+{
+ return KCursor::handCursor();
+}
+
+TQCursor KisCursor::selectCursor()
+{
+ static unsigned char select_bits[] = {
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0xff, 0xff, 0x7f,
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00,
+ 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x00};
+
+ TQBitmap select_bitmap(23, 23, select_bits, true);
+ TQBitmap select_mask = select_bitmap.createHeuristicMask( false );
+
+ return TQCursor( select_bitmap, select_mask, 11, 11 );
+}
+
+TQCursor KisCursor::openHandCursor()
+{
+ return load("openhand_cursor.xpm");
+}
+
+TQCursor KisCursor::closedHandCursor()
+{
+ return load("closedhand_cursor.xpm");
+}
+
+TQCursor KisCursor::rotateCursor()
+{
+ return load("rotate_cursor.xpm");
+}
+
+TQCursor KisCursor::load(const TQString & iconName, int hotspotX, int hotspotY)
+{
+ TQString filename = KisFactory::instance()->dirs()->findResource("kis_pics", iconName);
+ TQImage cursorImage;
+
+ cursorImage.load(filename);
+ Q_ASSERT(!cursorImage.isNull());
+ Q_ASSERT(cursorImage.hasAlphaBuffer());
+
+ TQBitmap bitmap(cursorImage.width(), cursorImage.height());
+ TQBitmap mask(cursorImage.width(), cursorImage.height());
+
+ TQPainter bitmapPainter(&bitmap);
+ TQPainter maskPainter(&mask);
+
+ for (TQ_INT32 x = 0; x < cursorImage.width(); ++x) {
+ for (TQ_INT32 y = 0; y < cursorImage.height(); ++y) {
+
+ TQRgb pixel = cursorImage.pixel(x, y);
+
+ if (tqAlpha(pixel) < 128) {
+ bitmapPainter.setPen(TQt::color0);
+ maskPainter.setPen(TQt::color0);
+ } else {
+ maskPainter.setPen(TQt::color1);
+
+ if (tqGray(pixel) < 128) {
+ bitmapPainter.setPen(TQt::color1);
+ } else {
+ bitmapPainter.setPen(TQt::color0);
+ }
+ }
+
+ bitmapPainter.drawPoint(x, y);
+ maskPainter.drawPoint(x, y);
+ }
+ }
+
+ return TQCursor(bitmap, mask, hotspotX, hotspotY);
+}
+
diff --git a/chalk/ui/kis_custom_brush.cc b/chalk/ui/kis_custom_brush.cpp
index 1802e6cfd..1802e6cfd 100644
--- a/chalk/ui/kis_custom_brush.cc
+++ b/chalk/ui/kis_custom_brush.cpp
diff --git a/chalk/ui/kis_custom_image_widget.cc b/chalk/ui/kis_custom_image_widget.cpp
index 93c829778..93c829778 100644
--- a/chalk/ui/kis_custom_image_widget.cc
+++ b/chalk/ui/kis_custom_image_widget.cpp
diff --git a/chalk/ui/kis_custom_palette.cc b/chalk/ui/kis_custom_palette.cpp
index 631b9abed..631b9abed 100644
--- a/chalk/ui/kis_custom_palette.cc
+++ b/chalk/ui/kis_custom_palette.cpp
diff --git a/chalk/ui/kis_custom_pattern.cc b/chalk/ui/kis_custom_pattern.cpp
index edf92be12..edf92be12 100644
--- a/chalk/ui/kis_custom_pattern.cc
+++ b/chalk/ui/kis_custom_pattern.cpp
diff --git a/chalk/ui/kis_dlg_adj_layer_props.cc b/chalk/ui/kis_dlg_adj_layer_props.cpp
index f7d75310e..f7d75310e 100644
--- a/chalk/ui/kis_dlg_adj_layer_props.cc
+++ b/chalk/ui/kis_dlg_adj_layer_props.cpp
diff --git a/chalk/ui/kis_dlg_adjustment_layer.cc b/chalk/ui/kis_dlg_adjustment_layer.cpp
index 997887f00..997887f00 100644
--- a/chalk/ui/kis_dlg_adjustment_layer.cc
+++ b/chalk/ui/kis_dlg_adjustment_layer.cpp
diff --git a/chalk/ui/kis_dlg_apply_profile.cc b/chalk/ui/kis_dlg_apply_profile.cpp
index fcdfbd099..fcdfbd099 100644
--- a/chalk/ui/kis_dlg_apply_profile.cc
+++ b/chalk/ui/kis_dlg_apply_profile.cpp
diff --git a/chalk/ui/kis_dlg_image_properties.cc b/chalk/ui/kis_dlg_image_properties.cpp
index 00acde270..00acde270 100644
--- a/chalk/ui/kis_dlg_image_properties.cc
+++ b/chalk/ui/kis_dlg_image_properties.cpp
diff --git a/chalk/ui/kis_dlg_layer_properties.cc b/chalk/ui/kis_dlg_layer_properties.cpp
index 832102c6d..832102c6d 100644
--- a/chalk/ui/kis_dlg_layer_properties.cc
+++ b/chalk/ui/kis_dlg_layer_properties.cpp
diff --git a/chalk/ui/kis_dlg_new_layer.cc b/chalk/ui/kis_dlg_new_layer.cpp
index 91f53a751..91f53a751 100644
--- a/chalk/ui/kis_dlg_new_layer.cc
+++ b/chalk/ui/kis_dlg_new_layer.cpp
diff --git a/chalk/ui/kis_dlg_preferences.cc b/chalk/ui/kis_dlg_preferences.cc
deleted file mode 100644
index 61811d31f..000000000
--- a/chalk/ui/kis_dlg_preferences.cc
+++ /dev/null
@@ -1,821 +0,0 @@
-/*
- * preferencesdlg.cc - part of KImageShop
- *
- * Copyright (c) 1999 Michael Koch <koch@kde.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <tqbitmap.h>
-#include <tqbuttongroup.h>
-#include <tqcheckbox.h>
-#include <tqcursor.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <tqpixmap.h>
-#include <tqpushbutton.h>
-#include <tqslider.h>
-#include <tqtoolbutton.h>
-#include <tqvbox.h>
-
-#ifdef HAVE_GL
-#include <tqgl.h>
-#endif
-
-#include <KoImageResource.h>
-
-#include <kcolorbutton.h>
-#include <kcombobox.h>
-#include <tdefiledialog.h>
-#include <kiconloader.h>
-#include <klineedit.h>
-#include <tdelocale.h>
-#include <knuminput.h>
-#include <kurlrequester.h>
-
-#include "squeezedcombobox.h"
-#include "kis_cmb_idlist.h"
-#include "kis_colorspace.h"
-#include "kis_colorspace_factory_registry.h"
-#include "kis_cursor.h"
-#include "kis_config.h"
-#include "kis_dlg_preferences.h"
-#include "kis_factory.h"
-#include "kis_id.h"
-#include "kis_meta_registry.h"
-#include "kis_profile.h"
-
-#include "kis_canvas.h"
-
-#include "wdgcolorsettings.h"
-#include "wdgperformancesettings.h"
-#include "wdggeneralsettings.h"
-
-// for the performance update
-#include "tiles/kis_tilemanager.h"
-
-GeneralTab::GeneralTab( TQWidget *_parent, const char *_name )
- : WdgGeneralSettings( _parent, _name )
-{
-
- KisConfig cfg;
-
- m_cmbCursorShape->setCurrentItem(cfg.cursorStyle());
- grpDockability->setButton(cfg.dockability());
- numDockerFontSize->setValue((int)cfg.dockerFontSize());
-}
-
-void GeneralTab::setDefault()
-{
- KisConfig cfg;
-
- m_cmbCursorShape->setCurrentItem( cfg.getDefaultCursorStyle());
- grpDockability->setButton(cfg.getDefaultDockability());
- numDockerFontSize->setValue((int)(cfg.getDefaultDockerFontSize()));
-}
-
-enumCursorStyle GeneralTab::cursorStyle()
-{
- return (enumCursorStyle)m_cmbCursorShape->currentItem();
-}
-
-enumKoDockability GeneralTab::dockability()
-{
- return (enumKoDockability)grpDockability->selectedId();
-}
-
-float GeneralTab::dockerFontSize()
-{
- return (float)numDockerFontSize->value();
-}
-
-//---------------------------------------------------------------------------------------------------
-
-ColorSettingsTab::ColorSettingsTab(TQWidget *parent, const char *name )
- : TQWidget(parent, name)
-{
- // XXX: Make sure only profiles that fit the specified color model
- // are shown in the profile combos
-
- TQGridLayout * l = new TQGridLayout( this, 1, 1, KDialog::marginHint(), KDialog::spacingHint());
- l->setMargin(0);
- m_page = new WdgColorSettings(this);
- l->addWidget( m_page, 0, 0);
-
- KisConfig cfg;
-
- m_page->cmbWorkingColorSpace->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
- m_page->cmbWorkingColorSpace->setCurrentText(cfg.workingColorSpace());
-
- m_page->cmbPrintingColorSpace->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
- m_page->cmbPrintingColorSpace->setCurrentText(cfg.printerColorSpace());
-
- refillMonitorProfiles(KisID("RGBA", ""));
- refillPrintProfiles(KisID(cfg.printerColorSpace(), ""));
-
- if(m_page->cmbMonitorProfile->contains(cfg.monitorProfile()))
- m_page->cmbMonitorProfile->setCurrentText(cfg.monitorProfile());
- if(m_page->cmbPrintProfile->contains(cfg.printerProfile()))
- m_page->cmbPrintProfile->setCurrentText(cfg.printerProfile());
- m_page->chkBlackpoint->setChecked(cfg.useBlackPointCompensation());
- m_page->grpPasteBehaviour->setButton(cfg.pasteBehaviour());
- m_page->cmbMonitorIntent->setCurrentItem(cfg.renderIntent());
-
- connect(m_page->cmbPrintingColorSpace, TQT_SIGNAL(activated(const KisID &)),
- this, TQT_SLOT(refillPrintProfiles(const KisID &)));
-}
-
-void ColorSettingsTab::setDefault()
-{
- m_page->cmbWorkingColorSpace->setCurrentText("RGBA");
-
- m_page->cmbPrintingColorSpace->setCurrentText("CMYK");
- refillPrintProfiles(KisID("CMYK", ""));
-
- m_page->chkBlackpoint->setChecked(false);
- m_page->cmbMonitorIntent->setCurrentItem(INTENT_PERCEPTUAL);
- m_page->grpPasteBehaviour->setButton(2);
-}
-
-
-void ColorSettingsTab::refillMonitorProfiles(const KisID & s)
-{
- KisColorSpaceFactory * csf = KisMetaRegistry::instance()->csRegistry()->get(s);
-
- m_page->cmbMonitorProfile->clear();
-
- if ( !csf )
- return;
-
- TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor( csf );
- TQValueVector<KisProfile *> ::iterator it;
- for ( it = profileList.begin(); it != profileList.end(); ++it ) {
- if ((*it)->deviceClass() == icSigDisplayClass)
- m_page->cmbMonitorProfile->insertItem((*it)->productName());
- }
-
- m_page->cmbMonitorProfile->setCurrentText(csf->defaultProfile());
-}
-
-void ColorSettingsTab::refillPrintProfiles(const KisID & s)
-{
- KisColorSpaceFactory * csf = KisMetaRegistry::instance()->csRegistry()->get(s);
-
- m_page->cmbPrintProfile->clear();
-
- if ( !csf )
- return;
-
- TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor( csf );
- TQValueVector<KisProfile *> ::iterator it;
- for ( it = profileList.begin(); it != profileList.end(); ++it ) {
- if ((*it)->deviceClass() == icSigOutputClass)
- m_page->cmbPrintProfile->insertItem((*it)->productName());
- }
-
- m_page->cmbPrintProfile->setCurrentText(csf->defaultProfile());
-}
-
-//---------------------------------------------------------------------------------------------------
-
-PerformanceTab::PerformanceTab(TQWidget *parent, const char *name )
- : WdgPerformanceSettings(parent, name)
-{
- // XXX: Make sure only profiles that fit the specified color model
- // are shown in the profile combos
-
- KisConfig cfg;
-
- // it's scaled from 0 - 6, but the config is in 0 - 300
- m_swappiness->setValue(cfg.swappiness() / 50);
- m_maxTiles->setValue(cfg.maxTilesInMem());
-}
-
-void PerformanceTab::setDefault()
-{
- m_swappiness->setValue(3);
- m_maxTiles->setValue(500);
-}
-
-//---------------------------------------------------------------------------------------------------
-
-TabletSettingsTab::TabletSettingsTab( TQWidget *parent, const char *name)
- : WdgTabletSettings( parent, name )
-{
-#ifdef EXTENDED_X11_TABLET_SUPPORT
- initTabletDevices();
-#else
- grpTabletDevices->hide();
-#endif
-}
-
-void TabletSettingsTab::setDefault()
-{
-}
-
-void TabletSettingsTab::applySettings()
-{
-
-#ifdef EXTENDED_X11_TABLET_SUPPORT
- applyTabletDeviceSettings();
-#endif
-}
-
-#ifdef EXTENDED_X11_TABLET_SUPPORT
-TabletSettingsTab::DeviceSettings::DeviceSettings(KisCanvasWidget::X11TabletDevice *tabletDevice, bool enabled,
- TQ_INT32 xAxis, TQ_INT32 yAxis, TQ_INT32 pressureAxis,
- TQ_INT32 xTiltAxis, TQ_INT32 yTiltAxis, TQ_INT32 wheelAxis,
- TQ_INT32 toolIDAxis, TQ_INT32 serialNumberAxis)
- : m_tabletDevice(tabletDevice),
- m_enabled(enabled),
- m_xAxis(xAxis),
- m_yAxis(yAxis),
- m_pressureAxis(pressureAxis),
- m_xTiltAxis(xTiltAxis),
- m_yTiltAxis(yTiltAxis),
- m_wheelAxis(wheelAxis),
- m_toolIDAxis(toolIDAxis),
- m_serialNumberAxis(serialNumberAxis)
-{
-}
-
-TabletSettingsTab::DeviceSettings::DeviceSettings()
- : m_tabletDevice(0),
- m_enabled(false),
- m_xAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_yAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_pressureAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_xTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_yTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_wheelAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_toolIDAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
- m_serialNumberAxis(KisCanvasWidget::X11TabletDevice::NoAxis)
-{
-}
-
-void TabletSettingsTab::DeviceSettings::applySettings()
-{
- m_tabletDevice->setEnabled(enabled());
- m_tabletDevice->setXAxis(xAxis());
- m_tabletDevice->setYAxis(yAxis());
- m_tabletDevice->setPressureAxis(pressureAxis());
- m_tabletDevice->setXTiltAxis(xTiltAxis());
- m_tabletDevice->setYTiltAxis(yTiltAxis());
- m_tabletDevice->setWheelAxis(wheelAxis());
- m_tabletDevice->setToolIDAxis(toolIDAxis());
- m_tabletDevice->setSerialNumberAxis(serialNumberAxis());
- m_tabletDevice->writeSettingsToConfig();
-}
-
-void TabletSettingsTab::DeviceSettings::setEnabled(bool enabled)
-{
- m_enabled = enabled;
-}
-
-bool TabletSettingsTab::DeviceSettings::enabled() const
-{
- return m_enabled;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::numAxes() const
-{
- return m_tabletDevice->numAxes();
-}
-
-void TabletSettingsTab::DeviceSettings::setXAxis(TQ_INT32 axis)
-{
- m_xAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setYAxis(TQ_INT32 axis)
-{
- m_yAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setPressureAxis(TQ_INT32 axis)
-{
- m_pressureAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setXTiltAxis(TQ_INT32 axis)
-{
- m_xTiltAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setYTiltAxis(TQ_INT32 axis)
-{
- m_yTiltAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setWheelAxis(TQ_INT32 axis)
-{
- m_wheelAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setToolIDAxis(TQ_INT32 axis)
-{
- m_toolIDAxis = axis;
-}
-
-void TabletSettingsTab::DeviceSettings::setSerialNumberAxis(TQ_INT32 axis)
-{
- m_serialNumberAxis = axis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::xAxis() const
-{
- return m_xAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::yAxis() const
-{
- return m_yAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::pressureAxis() const
-{
- return m_pressureAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::xTiltAxis() const
-{
- return m_xTiltAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::yTiltAxis() const
-{
- return m_yTiltAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::wheelAxis() const
-{
- return m_wheelAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::toolIDAxis() const
-{
- return m_toolIDAxis;
-}
-
-TQ_INT32 TabletSettingsTab::DeviceSettings::serialNumberAxis() const
-{
- return m_serialNumberAxis;
-}
-
-TabletSettingsTab::TabletDeviceSettingsDialog::TabletDeviceSettingsDialog(const TQString& deviceName, DeviceSettings settings,
- TQWidget *parent, const char *name)
- : super(parent, name, true, "", Ok | Cancel)
-{
- setCaption(i18n("Configure %1").arg(deviceName));
-
- m_page = new WdgTabletDeviceSettings(this);
-
- setMainWidget(m_page);
- resize(m_page->sizeHint());
-
- for (TQ_INT32 axis = 0; axis < settings.numAxes(); axis++) {
- TQString axisString;
-
- axisString.setNum(axis);
-
- m_page->cbX->insertItem(axisString);
- m_page->cbY->insertItem(axisString);
- m_page->cbPressure->insertItem(axisString);
- m_page->cbXTilt->insertItem(axisString);
- m_page->cbYTilt->insertItem(axisString);
- m_page->cbWheel->insertItem(axisString);
-// m_page->cbToolID->insertItem(axisString);
-// m_page->cbSerialNumber->insertItem(axisString);
- }
-
- m_page->cbX->insertItem(i18n("None"));
- m_page->cbY->insertItem(i18n("None"));
- m_page->cbPressure->insertItem(i18n("None"));
- m_page->cbXTilt->insertItem(i18n("None"));
- m_page->cbYTilt->insertItem(i18n("None"));
- m_page->cbWheel->insertItem(i18n("None"));
-// m_page->cbToolID->insertItem(i18n("None"));
-// m_page->cbSerialNumber->insertItem(i18n("None"));
-
- if (settings.xAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbX->setCurrentItem(settings.xAxis());
- } else {
- m_page->cbX->setCurrentItem(settings.numAxes());
- }
-
- if (settings.yAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbY->setCurrentItem(settings.yAxis());
- } else {
- m_page->cbY->setCurrentItem(settings.numAxes());
- }
-
- if (settings.pressureAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbPressure->setCurrentItem(settings.pressureAxis());
- } else {
- m_page->cbPressure->setCurrentItem(settings.numAxes());
- }
-
- if (settings.xTiltAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbXTilt->setCurrentItem(settings.xTiltAxis());
- } else {
- m_page->cbXTilt->setCurrentItem(settings.numAxes());
- }
-
- if (settings.yTiltAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbYTilt->setCurrentItem(settings.yTiltAxis());
- } else {
- m_page->cbYTilt->setCurrentItem(settings.numAxes());
- }
-
- if (settings.wheelAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
- m_page->cbWheel->setCurrentItem(settings.wheelAxis());
- } else {
- m_page->cbWheel->setCurrentItem(settings.numAxes());
- }
-
-// if (settings.toolIDAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
-// m_page->cbToolID->setCurrentItem(settings.toolIDAxis());
-// } else {
-// m_page->cbToolID->setCurrentItem(settings.numAxes());
-// }
-//
-// if (settings.serialNumberAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
-// m_page->cbSerialNumber->setCurrentItem(settings.serialNumberAxis());
-// } else {
-// m_page->cbSerialNumber->setCurrentItem(settings.numAxes());
-// }
-
- m_settings = settings;
-}
-
-TabletSettingsTab::TabletDeviceSettingsDialog::~TabletDeviceSettingsDialog()
-{
- delete m_page;
-}
-
-TabletSettingsTab::DeviceSettings TabletSettingsTab::TabletDeviceSettingsDialog::settings()
-{
- const TQ_INT32 noAxis = m_settings.numAxes();
-
- if (m_page->cbX->currentItem() != noAxis ) {
- m_settings.setXAxis(m_page->cbX->currentItem());
- } else {
- m_settings.setXAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
- if (m_page->cbY->currentItem() != noAxis ) {
- m_settings.setYAxis(m_page->cbY->currentItem());
- } else {
- m_settings.setYAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
- if (m_page->cbPressure->currentItem() != noAxis ) {
- m_settings.setPressureAxis(m_page->cbPressure->currentItem());
- } else {
- m_settings.setPressureAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
- if (m_page->cbXTilt->currentItem() != noAxis ) {
- m_settings.setXTiltAxis(m_page->cbXTilt->currentItem());
- } else {
- m_settings.setXTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
- if (m_page->cbYTilt->currentItem() != noAxis ) {
- m_settings.setYTiltAxis(m_page->cbYTilt->currentItem());
- } else {
- m_settings.setYTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
- if (m_page->cbWheel->currentItem() != noAxis ) {
- m_settings.setWheelAxis(m_page->cbWheel->currentItem());
- } else {
- m_settings.setWheelAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
- }
-
-// if (m_page->cbToolID->currentItem() != noAxis ) {
-// m_settings.setToolIDAxis(m_page->cbToolID->currentItem());
-// } else {
-// m_settings.setToolIDAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
-// }
-//
-// if (m_page->cbSerialNumber->currentItem() != noAxis ) {
-// m_settings.setSerialNumberAxis(m_page->cbSerialNumber->currentItem());
-// } else {
-// m_settings.setSerialNumberAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
-// }
-
- return m_settings;
-}
-
-void TabletSettingsTab::initTabletDevices()
-{
- connect(cbTabletDevice, TQT_SIGNAL(activated(int)), TQT_SLOT(slotActivateDevice(int)));
- connect(chkEnableTabletDevice, TQT_SIGNAL(toggled(bool)), TQT_SLOT(slotSetDeviceEnabled(bool)));
- connect(btnConfigureTabletDevice, TQT_SIGNAL(clicked()), TQT_SLOT(slotConfigureDevice()));
-
- KisCanvasWidget::X11XIDTabletDeviceMap& tabletDevices = KisCanvasWidget::tabletDeviceMap();
-
- cbTabletDevice->clear();
-
- if (!tabletDevices.empty()) {
- KisCanvasWidget::X11XIDTabletDeviceMap::iterator it;
-
- for (it = tabletDevices.begin(); it != tabletDevices.end(); ++it) {
- KisCanvasWidget::X11TabletDevice& device = (*it).second;
-
- m_deviceSettings.append(DeviceSettings(&device, device.enabled(), device.xAxis(), device.yAxis(),
- device.pressureAxis(), device.xTiltAxis(), device.yTiltAxis(), device.wheelAxis(),
- device.toolIDAxis(), device.serialNumberAxis()));
- cbTabletDevice->insertItem(device.name());
- }
- slotActivateDevice(0);
- } else {
- cbTabletDevice->insertItem(i18n("No devices detected"));
- cbTabletDevice->setEnabled(false);
- chkEnableTabletDevice->setEnabled(false);
- btnConfigureTabletDevice->setEnabled(false);
- }
-}
-
-void TabletSettingsTab::slotActivateDevice(int deviceIndex)
-{
- bool deviceEnabled = m_deviceSettings[deviceIndex].enabled();
-
- chkEnableTabletDevice->setChecked(deviceEnabled);
- slotSetDeviceEnabled(deviceEnabled);
-}
-
-void TabletSettingsTab::slotSetDeviceEnabled(bool enabled)
-{
- btnConfigureTabletDevice->setEnabled(enabled);
- m_deviceSettings[cbTabletDevice->currentItem()].setEnabled(enabled);
-}
-
-void TabletSettingsTab::slotConfigureDevice()
-{
- TabletDeviceSettingsDialog dialog(cbTabletDevice->currentText(), m_deviceSettings[cbTabletDevice->currentItem()],
- this, "TabletDeviceSettings");
-
- if (dialog.exec() == TQDialog::Accepted)
- {
- m_deviceSettings[cbTabletDevice->currentItem()] = dialog.settings();
- }
-}
-
-void TabletSettingsTab::applyTabletDeviceSettings()
-{
- for (TQ_UINT32 deviceIndex = 0; deviceIndex < m_deviceSettings.count(); ++deviceIndex) {
- m_deviceSettings[deviceIndex].applySettings();
- }
-}
-
-#else // EXTENDED_X11_TABLET_SUPPORT
-
-// Fix compilation. moc seems to not see the undefined symbol needed
-// for these slots to be declared.
-void TabletSettingsTab::slotActivateDevice(int /*deviceIndex*/)
-{
-}
-
-void TabletSettingsTab::slotSetDeviceEnabled(bool /*enabled*/)
-{
-}
-
-void TabletSettingsTab::slotConfigureDevice()
-{
-}
-
-void TabletSettingsTab::applyTabletDeviceSettings()
-{
-}
-
-#endif
-
-//---------------------------------------------------------------------------------------------------
-
-DisplaySettingsTab::DisplaySettingsTab( TQWidget *parent, const char *name)
- : WdgDisplaySettings( parent, name )
-{
-#ifdef HAVE_GL
- KisConfig cfg;
-
- if (!TQGLFormat::hasOpenGL()) {
- cbUseOpenGL->setEnabled(false);
- //cbUseOpenGLShaders->setEnabled(false);
- } else {
- cbUseOpenGL->setChecked(cfg.useOpenGL());
- //cbUseOpenGLShaders->setChecked(cfg.useOpenGLShaders());
- //cbUseOpenGLShaders->setEnabled(cfg.useOpenGL());
- }
-#else
- cbUseOpenGL->setEnabled(false);
- //cbUseOpenGLShaders->setEnabled(false);
-#endif
-
- connect(cbUseOpenGL, TQT_SIGNAL(toggled(bool)), TQT_SLOT(slotUseOpenGLToggled(bool)));
-}
-
-void DisplaySettingsTab::setDefault()
-{
- cbUseOpenGL->setChecked(false);
- //cbUseOpenGLShaders->setChecked(false);
- //cbUseOpenGLShaders->setEnabled(false);
-}
-
-void DisplaySettingsTab::slotUseOpenGLToggled(bool /*isChecked*/)
-{
- //cbUseOpenGLShaders->setEnabled(isChecked);
-}
-
-//---------------------------------------------------------------------------------------------------
-GridSettingsTab::GridSettingsTab(TQWidget* parent) : WdgGridSettingsBase(parent)
-{
- KisConfig cfg;
- selectMainStyle->setCurrentItem(cfg.getGridMainStyle());
- selectSubdivisionStyle->setCurrentItem(cfg.getGridSubdivisionStyle());
-
-#if KDE_IS_VERSION(3,4,0)
- colorMain->setDefaultColor( TQColor( 99, 99, 99 ) );
- colorSubdivision->setDefaultColor( TQColor( 200, 200, 200 ) );
-#endif
- colorMain->setColor(cfg.getGridMainColor());
- colorSubdivision->setColor(cfg.getGridSubdivisionColor());
-
- intHSpacing->setValue( cfg.getGridHSpacing() );
- intVSpacing->setValue( cfg.getGridVSpacing() );
- intSubdivision->setValue( cfg.getGridSubdivisions());
- intOffsetX->setValue( cfg.getGridOffsetX());
- intOffsetY->setValue( cfg.getGridOffsetY());
-
- linkSpacingToggled(true);
- connect(bnLinkSpacing, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(linkSpacingToggled( bool )));
-
- connect(intHSpacing, TQT_SIGNAL(valueChanged(int)),this,TQT_SLOT(spinBoxHSpacingChanged(int)));
- connect(intVSpacing, TQT_SIGNAL(valueChanged(int)),this,TQT_SLOT(spinBoxVSpacingChanged(int)));
-
-
-}
-
-void GridSettingsTab::setDefault()
-{
- KisConfig cfg;
- selectMainStyle->setCurrentItem(0);
- selectSubdivisionStyle->setCurrentItem(1);
-
- colorMain->setColor(TQColor(99,99,99));
- colorSubdivision->setColor(TQColor(199,199,199));
-
- intHSpacing->setValue( 10 );
- intVSpacing->setValue( 10 );
- intSubdivision->setValue( 1 );
- intOffsetX->setValue( 0 );
- intOffsetY->setValue( 0 );
-}
-
-void GridSettingsTab::spinBoxHSpacingChanged(int v)
-{
- if(m_linkSpacing)
- {
- intVSpacing->setValue(v);
- }
-}
-
-void GridSettingsTab::spinBoxVSpacingChanged(int v )
-{
- if(m_linkSpacing)
- {
- intHSpacing->setValue(v);
- }
-}
-
-
-void GridSettingsTab::linkSpacingToggled(bool b)
-{
- m_linkSpacing = b;
-
- KoImageResource kir;
- if (b) {
- bnLinkSpacing->setPixmap(kir.chain());
- }
- else {
- bnLinkSpacing->setPixmap(kir.chainBroken());
- }
-}
-
-
-//---------------------------------------------------------------------------------------------------
-
-PreferencesDialog::PreferencesDialog( TQWidget* parent, const char* name )
- : KDialogBase( IconList, i18n("Preferences"), Ok | Cancel | Help | Default /*| Apply*/, Ok, parent, name, true, true )
-{
- TQVBox *vbox;
-
- vbox = addVBoxPage( i18n( "General"), i18n( "General"), BarIcon( "misc", TDEIcon::SizeMedium ));
- m_general = new GeneralTab( vbox );
-#ifdef HAVE_GL
- vbox = addVBoxPage ( i18n( "Display" ), i18n( "Display" ), BarIcon( "tdescreensaver", TDEIcon::SizeMedium ));
- m_displaySettings = new DisplaySettingsTab( vbox );
-#endif
- vbox = addVBoxPage( i18n( "Color Management"), i18n( "Color"), BarIcon( "colorize", TDEIcon::SizeMedium ));
- m_colorSettings = new ColorSettingsTab( vbox );
-
- vbox = addVBoxPage( i18n( "Performance"), i18n( "Performance"), BarIcon( "fork", TDEIcon::SizeMedium ));
- m_performanceSettings = new PerformanceTab ( vbox );
-
- vbox = addVBoxPage ( i18n( "Tablet" ), i18n( "Tablet" ), BarIcon( "input-tablet", TDEIcon::SizeMedium ));
- m_tabletSettings = new TabletSettingsTab( vbox );
-
- vbox = addVBoxPage ( i18n( "Grid" ), i18n( "Grid" ), BarIcon( "grid", TDEIcon::SizeMedium ));
- m_gridSettings = new GridSettingsTab( vbox );
-
-}
-
-PreferencesDialog::~PreferencesDialog()
-{
-}
-
-void PreferencesDialog::slotDefault()
-{
- m_general->setDefault();
- m_colorSettings->setDefault();
- m_tabletSettings->setDefault();
- m_performanceSettings->setDefault();
-#ifdef HAVE_GL
- m_displaySettings->setDefault();
-#endif
- m_gridSettings->setDefault();
-}
-
-bool PreferencesDialog::editPreferences()
-{
- PreferencesDialog* dialog;
-
- dialog = new PreferencesDialog();
- bool baccept = ( dialog->exec() == Accepted );
- if( baccept )
- {
- KisConfig cfg;
- cfg.setCursorStyle(dialog->m_general->cursorStyle());
- cfg.setDockability( dialog->m_general->dockability() );
- cfg.setDockerFontSize( dialog->m_general->dockerFontSize() );
-
- // Color settings
- cfg.setMonitorProfile( dialog->m_colorSettings->m_page->cmbMonitorProfile->currentText());
- cfg.setWorkingColorSpace( dialog->m_colorSettings->m_page->cmbWorkingColorSpace->currentText());
- cfg.setPrinterColorSpace( dialog->m_colorSettings->m_page->cmbPrintingColorSpace->currentText());
- cfg.setPrinterProfile( dialog->m_colorSettings->m_page->cmbPrintProfile->currentText());
-
- cfg.setUseBlackPointCompensation( dialog->m_colorSettings->m_page->chkBlackpoint->isChecked());
- cfg.setPasteBehaviour( dialog->m_colorSettings->m_page->grpPasteBehaviour->selectedId());
- cfg.setRenderIntent( dialog->m_colorSettings->m_page->cmbMonitorIntent->currentItem());
-
- // it's scaled from 0 - 6, but the config is in 0 - 300
- cfg.setSwappiness(dialog->m_performanceSettings->m_swappiness->value() * 50);
- cfg.setMaxTilesInMem(dialog->m_performanceSettings->m_maxTiles->value());
- // let the tile manager know
- KisTileManager::instance()->configChanged();
-
- dialog->m_tabletSettings->applySettings();
-
-#ifdef HAVE_GL
- cfg.setUseOpenGL(dialog->m_displaySettings->cbUseOpenGL->isChecked());
- //cfg.setUseOpenGLShaders(dialog->m_displaySettings->cbUseOpenGLShaders->isChecked());
-#endif
-
- // Grid settings
- cfg.setGridMainStyle( dialog->m_gridSettings->selectMainStyle->currentItem() );
- cfg.setGridSubdivisionStyle( dialog->m_gridSettings->selectSubdivisionStyle->currentItem() );
-
- cfg.setGridMainColor( dialog->m_gridSettings->colorMain->color() );
- cfg.setGridSubdivisionColor(dialog->m_gridSettings->colorSubdivision->color() );
-
- cfg.setGridHSpacing( dialog->m_gridSettings->intHSpacing->value( ));
- cfg.setGridVSpacing( dialog->m_gridSettings->intVSpacing->value( ));
- cfg.setGridSubdivisions( dialog->m_gridSettings->intSubdivision->value( ));
- cfg.setGridOffsetX( dialog->m_gridSettings->intOffsetX->value( ));
- cfg.setGridOffsetY( dialog->m_gridSettings->intOffsetY->value( ));
-
- }
- delete dialog;
- return baccept;
-}
-
-#include "kis_dlg_preferences.moc"
diff --git a/chalk/ui/kis_dlg_preferences.cpp b/chalk/ui/kis_dlg_preferences.cpp
new file mode 100644
index 000000000..e35477dc5
--- /dev/null
+++ b/chalk/ui/kis_dlg_preferences.cpp
@@ -0,0 +1,821 @@
+/*
+ * preferencesdlg.cpp - part of KImageShop
+ *
+ * Copyright (c) 1999 Michael Koch <koch@kde.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <tqbitmap.h>
+#include <tqbuttongroup.h>
+#include <tqcheckbox.h>
+#include <tqcursor.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <tqpixmap.h>
+#include <tqpushbutton.h>
+#include <tqslider.h>
+#include <tqtoolbutton.h>
+#include <tqvbox.h>
+
+#ifdef HAVE_GL
+#include <tqgl.h>
+#endif
+
+#include <KoImageResource.h>
+
+#include <kcolorbutton.h>
+#include <kcombobox.h>
+#include <tdefiledialog.h>
+#include <kiconloader.h>
+#include <klineedit.h>
+#include <tdelocale.h>
+#include <knuminput.h>
+#include <kurlrequester.h>
+
+#include "squeezedcombobox.h"
+#include "kis_cmb_idlist.h"
+#include "kis_colorspace.h"
+#include "kis_colorspace_factory_registry.h"
+#include "kis_cursor.h"
+#include "kis_config.h"
+#include "kis_dlg_preferences.h"
+#include "kis_factory.h"
+#include "kis_id.h"
+#include "kis_meta_registry.h"
+#include "kis_profile.h"
+
+#include "kis_canvas.h"
+
+#include "wdgcolorsettings.h"
+#include "wdgperformancesettings.h"
+#include "wdggeneralsettings.h"
+
+// for the performance update
+#include "tiles/kis_tilemanager.h"
+
+GeneralTab::GeneralTab( TQWidget *_parent, const char *_name )
+ : WdgGeneralSettings( _parent, _name )
+{
+
+ KisConfig cfg;
+
+ m_cmbCursorShape->setCurrentItem(cfg.cursorStyle());
+ grpDockability->setButton(cfg.dockability());
+ numDockerFontSize->setValue((int)cfg.dockerFontSize());
+}
+
+void GeneralTab::setDefault()
+{
+ KisConfig cfg;
+
+ m_cmbCursorShape->setCurrentItem( cfg.getDefaultCursorStyle());
+ grpDockability->setButton(cfg.getDefaultDockability());
+ numDockerFontSize->setValue((int)(cfg.getDefaultDockerFontSize()));
+}
+
+enumCursorStyle GeneralTab::cursorStyle()
+{
+ return (enumCursorStyle)m_cmbCursorShape->currentItem();
+}
+
+enumKoDockability GeneralTab::dockability()
+{
+ return (enumKoDockability)grpDockability->selectedId();
+}
+
+float GeneralTab::dockerFontSize()
+{
+ return (float)numDockerFontSize->value();
+}
+
+//---------------------------------------------------------------------------------------------------
+
+ColorSettingsTab::ColorSettingsTab(TQWidget *parent, const char *name )
+ : TQWidget(parent, name)
+{
+ // XXX: Make sure only profiles that fit the specified color model
+ // are shown in the profile combos
+
+ TQGridLayout * l = new TQGridLayout( this, 1, 1, KDialog::marginHint(), KDialog::spacingHint());
+ l->setMargin(0);
+ m_page = new WdgColorSettings(this);
+ l->addWidget( m_page, 0, 0);
+
+ KisConfig cfg;
+
+ m_page->cmbWorkingColorSpace->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
+ m_page->cmbWorkingColorSpace->setCurrentText(cfg.workingColorSpace());
+
+ m_page->cmbPrintingColorSpace->setIDList(KisMetaRegistry::instance()->csRegistry()->listKeys());
+ m_page->cmbPrintingColorSpace->setCurrentText(cfg.printerColorSpace());
+
+ refillMonitorProfiles(KisID("RGBA", ""));
+ refillPrintProfiles(KisID(cfg.printerColorSpace(), ""));
+
+ if(m_page->cmbMonitorProfile->contains(cfg.monitorProfile()))
+ m_page->cmbMonitorProfile->setCurrentText(cfg.monitorProfile());
+ if(m_page->cmbPrintProfile->contains(cfg.printerProfile()))
+ m_page->cmbPrintProfile->setCurrentText(cfg.printerProfile());
+ m_page->chkBlackpoint->setChecked(cfg.useBlackPointCompensation());
+ m_page->grpPasteBehaviour->setButton(cfg.pasteBehaviour());
+ m_page->cmbMonitorIntent->setCurrentItem(cfg.renderIntent());
+
+ connect(m_page->cmbPrintingColorSpace, TQT_SIGNAL(activated(const KisID &)),
+ this, TQT_SLOT(refillPrintProfiles(const KisID &)));
+}
+
+void ColorSettingsTab::setDefault()
+{
+ m_page->cmbWorkingColorSpace->setCurrentText("RGBA");
+
+ m_page->cmbPrintingColorSpace->setCurrentText("CMYK");
+ refillPrintProfiles(KisID("CMYK", ""));
+
+ m_page->chkBlackpoint->setChecked(false);
+ m_page->cmbMonitorIntent->setCurrentItem(INTENT_PERCEPTUAL);
+ m_page->grpPasteBehaviour->setButton(2);
+}
+
+
+void ColorSettingsTab::refillMonitorProfiles(const KisID & s)
+{
+ KisColorSpaceFactory * csf = KisMetaRegistry::instance()->csRegistry()->get(s);
+
+ m_page->cmbMonitorProfile->clear();
+
+ if ( !csf )
+ return;
+
+ TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor( csf );
+ TQValueVector<KisProfile *> ::iterator it;
+ for ( it = profileList.begin(); it != profileList.end(); ++it ) {
+ if ((*it)->deviceClass() == icSigDisplayClass)
+ m_page->cmbMonitorProfile->insertItem((*it)->productName());
+ }
+
+ m_page->cmbMonitorProfile->setCurrentText(csf->defaultProfile());
+}
+
+void ColorSettingsTab::refillPrintProfiles(const KisID & s)
+{
+ KisColorSpaceFactory * csf = KisMetaRegistry::instance()->csRegistry()->get(s);
+
+ m_page->cmbPrintProfile->clear();
+
+ if ( !csf )
+ return;
+
+ TQValueVector<KisProfile *> profileList = KisMetaRegistry::instance()->csRegistry()->profilesFor( csf );
+ TQValueVector<KisProfile *> ::iterator it;
+ for ( it = profileList.begin(); it != profileList.end(); ++it ) {
+ if ((*it)->deviceClass() == icSigOutputClass)
+ m_page->cmbPrintProfile->insertItem((*it)->productName());
+ }
+
+ m_page->cmbPrintProfile->setCurrentText(csf->defaultProfile());
+}
+
+//---------------------------------------------------------------------------------------------------
+
+PerformanceTab::PerformanceTab(TQWidget *parent, const char *name )
+ : WdgPerformanceSettings(parent, name)
+{
+ // XXX: Make sure only profiles that fit the specified color model
+ // are shown in the profile combos
+
+ KisConfig cfg;
+
+ // it's scaled from 0 - 6, but the config is in 0 - 300
+ m_swappiness->setValue(cfg.swappiness() / 50);
+ m_maxTiles->setValue(cfg.maxTilesInMem());
+}
+
+void PerformanceTab::setDefault()
+{
+ m_swappiness->setValue(3);
+ m_maxTiles->setValue(500);
+}
+
+//---------------------------------------------------------------------------------------------------
+
+TabletSettingsTab::TabletSettingsTab( TQWidget *parent, const char *name)
+ : WdgTabletSettings( parent, name )
+{
+#ifdef EXTENDED_X11_TABLET_SUPPORT
+ initTabletDevices();
+#else
+ grpTabletDevices->hide();
+#endif
+}
+
+void TabletSettingsTab::setDefault()
+{
+}
+
+void TabletSettingsTab::applySettings()
+{
+
+#ifdef EXTENDED_X11_TABLET_SUPPORT
+ applyTabletDeviceSettings();
+#endif
+}
+
+#ifdef EXTENDED_X11_TABLET_SUPPORT
+TabletSettingsTab::DeviceSettings::DeviceSettings(KisCanvasWidget::X11TabletDevice *tabletDevice, bool enabled,
+ TQ_INT32 xAxis, TQ_INT32 yAxis, TQ_INT32 pressureAxis,
+ TQ_INT32 xTiltAxis, TQ_INT32 yTiltAxis, TQ_INT32 wheelAxis,
+ TQ_INT32 toolIDAxis, TQ_INT32 serialNumberAxis)
+ : m_tabletDevice(tabletDevice),
+ m_enabled(enabled),
+ m_xAxis(xAxis),
+ m_yAxis(yAxis),
+ m_pressureAxis(pressureAxis),
+ m_xTiltAxis(xTiltAxis),
+ m_yTiltAxis(yTiltAxis),
+ m_wheelAxis(wheelAxis),
+ m_toolIDAxis(toolIDAxis),
+ m_serialNumberAxis(serialNumberAxis)
+{
+}
+
+TabletSettingsTab::DeviceSettings::DeviceSettings()
+ : m_tabletDevice(0),
+ m_enabled(false),
+ m_xAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_yAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_pressureAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_xTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_yTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_wheelAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_toolIDAxis(KisCanvasWidget::X11TabletDevice::NoAxis),
+ m_serialNumberAxis(KisCanvasWidget::X11TabletDevice::NoAxis)
+{
+}
+
+void TabletSettingsTab::DeviceSettings::applySettings()
+{
+ m_tabletDevice->setEnabled(enabled());
+ m_tabletDevice->setXAxis(xAxis());
+ m_tabletDevice->setYAxis(yAxis());
+ m_tabletDevice->setPressureAxis(pressureAxis());
+ m_tabletDevice->setXTiltAxis(xTiltAxis());
+ m_tabletDevice->setYTiltAxis(yTiltAxis());
+ m_tabletDevice->setWheelAxis(wheelAxis());
+ m_tabletDevice->setToolIDAxis(toolIDAxis());
+ m_tabletDevice->setSerialNumberAxis(serialNumberAxis());
+ m_tabletDevice->writeSettingsToConfig();
+}
+
+void TabletSettingsTab::DeviceSettings::setEnabled(bool enabled)
+{
+ m_enabled = enabled;
+}
+
+bool TabletSettingsTab::DeviceSettings::enabled() const
+{
+ return m_enabled;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::numAxes() const
+{
+ return m_tabletDevice->numAxes();
+}
+
+void TabletSettingsTab::DeviceSettings::setXAxis(TQ_INT32 axis)
+{
+ m_xAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setYAxis(TQ_INT32 axis)
+{
+ m_yAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setPressureAxis(TQ_INT32 axis)
+{
+ m_pressureAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setXTiltAxis(TQ_INT32 axis)
+{
+ m_xTiltAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setYTiltAxis(TQ_INT32 axis)
+{
+ m_yTiltAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setWheelAxis(TQ_INT32 axis)
+{
+ m_wheelAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setToolIDAxis(TQ_INT32 axis)
+{
+ m_toolIDAxis = axis;
+}
+
+void TabletSettingsTab::DeviceSettings::setSerialNumberAxis(TQ_INT32 axis)
+{
+ m_serialNumberAxis = axis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::xAxis() const
+{
+ return m_xAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::yAxis() const
+{
+ return m_yAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::pressureAxis() const
+{
+ return m_pressureAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::xTiltAxis() const
+{
+ return m_xTiltAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::yTiltAxis() const
+{
+ return m_yTiltAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::wheelAxis() const
+{
+ return m_wheelAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::toolIDAxis() const
+{
+ return m_toolIDAxis;
+}
+
+TQ_INT32 TabletSettingsTab::DeviceSettings::serialNumberAxis() const
+{
+ return m_serialNumberAxis;
+}
+
+TabletSettingsTab::TabletDeviceSettingsDialog::TabletDeviceSettingsDialog(const TQString& deviceName, DeviceSettings settings,
+ TQWidget *parent, const char *name)
+ : super(parent, name, true, "", Ok | Cancel)
+{
+ setCaption(i18n("Configure %1").arg(deviceName));
+
+ m_page = new WdgTabletDeviceSettings(this);
+
+ setMainWidget(m_page);
+ resize(m_page->sizeHint());
+
+ for (TQ_INT32 axis = 0; axis < settings.numAxes(); axis++) {
+ TQString axisString;
+
+ axisString.setNum(axis);
+
+ m_page->cbX->insertItem(axisString);
+ m_page->cbY->insertItem(axisString);
+ m_page->cbPressure->insertItem(axisString);
+ m_page->cbXTilt->insertItem(axisString);
+ m_page->cbYTilt->insertItem(axisString);
+ m_page->cbWheel->insertItem(axisString);
+// m_page->cbToolID->insertItem(axisString);
+// m_page->cbSerialNumber->insertItem(axisString);
+ }
+
+ m_page->cbX->insertItem(i18n("None"));
+ m_page->cbY->insertItem(i18n("None"));
+ m_page->cbPressure->insertItem(i18n("None"));
+ m_page->cbXTilt->insertItem(i18n("None"));
+ m_page->cbYTilt->insertItem(i18n("None"));
+ m_page->cbWheel->insertItem(i18n("None"));
+// m_page->cbToolID->insertItem(i18n("None"));
+// m_page->cbSerialNumber->insertItem(i18n("None"));
+
+ if (settings.xAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbX->setCurrentItem(settings.xAxis());
+ } else {
+ m_page->cbX->setCurrentItem(settings.numAxes());
+ }
+
+ if (settings.yAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbY->setCurrentItem(settings.yAxis());
+ } else {
+ m_page->cbY->setCurrentItem(settings.numAxes());
+ }
+
+ if (settings.pressureAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbPressure->setCurrentItem(settings.pressureAxis());
+ } else {
+ m_page->cbPressure->setCurrentItem(settings.numAxes());
+ }
+
+ if (settings.xTiltAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbXTilt->setCurrentItem(settings.xTiltAxis());
+ } else {
+ m_page->cbXTilt->setCurrentItem(settings.numAxes());
+ }
+
+ if (settings.yTiltAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbYTilt->setCurrentItem(settings.yTiltAxis());
+ } else {
+ m_page->cbYTilt->setCurrentItem(settings.numAxes());
+ }
+
+ if (settings.wheelAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+ m_page->cbWheel->setCurrentItem(settings.wheelAxis());
+ } else {
+ m_page->cbWheel->setCurrentItem(settings.numAxes());
+ }
+
+// if (settings.toolIDAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+// m_page->cbToolID->setCurrentItem(settings.toolIDAxis());
+// } else {
+// m_page->cbToolID->setCurrentItem(settings.numAxes());
+// }
+//
+// if (settings.serialNumberAxis() != KisCanvasWidget::X11TabletDevice::NoAxis) {
+// m_page->cbSerialNumber->setCurrentItem(settings.serialNumberAxis());
+// } else {
+// m_page->cbSerialNumber->setCurrentItem(settings.numAxes());
+// }
+
+ m_settings = settings;
+}
+
+TabletSettingsTab::TabletDeviceSettingsDialog::~TabletDeviceSettingsDialog()
+{
+ delete m_page;
+}
+
+TabletSettingsTab::DeviceSettings TabletSettingsTab::TabletDeviceSettingsDialog::settings()
+{
+ const TQ_INT32 noAxis = m_settings.numAxes();
+
+ if (m_page->cbX->currentItem() != noAxis ) {
+ m_settings.setXAxis(m_page->cbX->currentItem());
+ } else {
+ m_settings.setXAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+ if (m_page->cbY->currentItem() != noAxis ) {
+ m_settings.setYAxis(m_page->cbY->currentItem());
+ } else {
+ m_settings.setYAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+ if (m_page->cbPressure->currentItem() != noAxis ) {
+ m_settings.setPressureAxis(m_page->cbPressure->currentItem());
+ } else {
+ m_settings.setPressureAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+ if (m_page->cbXTilt->currentItem() != noAxis ) {
+ m_settings.setXTiltAxis(m_page->cbXTilt->currentItem());
+ } else {
+ m_settings.setXTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+ if (m_page->cbYTilt->currentItem() != noAxis ) {
+ m_settings.setYTiltAxis(m_page->cbYTilt->currentItem());
+ } else {
+ m_settings.setYTiltAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+ if (m_page->cbWheel->currentItem() != noAxis ) {
+ m_settings.setWheelAxis(m_page->cbWheel->currentItem());
+ } else {
+ m_settings.setWheelAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+ }
+
+// if (m_page->cbToolID->currentItem() != noAxis ) {
+// m_settings.setToolIDAxis(m_page->cbToolID->currentItem());
+// } else {
+// m_settings.setToolIDAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+// }
+//
+// if (m_page->cbSerialNumber->currentItem() != noAxis ) {
+// m_settings.setSerialNumberAxis(m_page->cbSerialNumber->currentItem());
+// } else {
+// m_settings.setSerialNumberAxis(KisCanvasWidget::X11TabletDevice::NoAxis);
+// }
+
+ return m_settings;
+}
+
+void TabletSettingsTab::initTabletDevices()
+{
+ connect(cbTabletDevice, TQT_SIGNAL(activated(int)), TQT_SLOT(slotActivateDevice(int)));
+ connect(chkEnableTabletDevice, TQT_SIGNAL(toggled(bool)), TQT_SLOT(slotSetDeviceEnabled(bool)));
+ connect(btnConfigureTabletDevice, TQT_SIGNAL(clicked()), TQT_SLOT(slotConfigureDevice()));
+
+ KisCanvasWidget::X11XIDTabletDeviceMap& tabletDevices = KisCanvasWidget::tabletDeviceMap();
+
+ cbTabletDevice->clear();
+
+ if (!tabletDevices.empty()) {
+ KisCanvasWidget::X11XIDTabletDeviceMap::iterator it;
+
+ for (it = tabletDevices.begin(); it != tabletDevices.end(); ++it) {
+ KisCanvasWidget::X11TabletDevice& device = (*it).second;
+
+ m_deviceSettings.append(DeviceSettings(&device, device.enabled(), device.xAxis(), device.yAxis(),
+ device.pressureAxis(), device.xTiltAxis(), device.yTiltAxis(), device.wheelAxis(),
+ device.toolIDAxis(), device.serialNumberAxis()));
+ cbTabletDevice->insertItem(device.name());
+ }
+ slotActivateDevice(0);
+ } else {
+ cbTabletDevice->insertItem(i18n("No devices detected"));
+ cbTabletDevice->setEnabled(false);
+ chkEnableTabletDevice->setEnabled(false);
+ btnConfigureTabletDevice->setEnabled(false);
+ }
+}
+
+void TabletSettingsTab::slotActivateDevice(int deviceIndex)
+{
+ bool deviceEnabled = m_deviceSettings[deviceIndex].enabled();
+
+ chkEnableTabletDevice->setChecked(deviceEnabled);
+ slotSetDeviceEnabled(deviceEnabled);
+}
+
+void TabletSettingsTab::slotSetDeviceEnabled(bool enabled)
+{
+ btnConfigureTabletDevice->setEnabled(enabled);
+ m_deviceSettings[cbTabletDevice->currentItem()].setEnabled(enabled);
+}
+
+void TabletSettingsTab::slotConfigureDevice()
+{
+ TabletDeviceSettingsDialog dialog(cbTabletDevice->currentText(), m_deviceSettings[cbTabletDevice->currentItem()],
+ this, "TabletDeviceSettings");
+
+ if (dialog.exec() == TQDialog::Accepted)
+ {
+ m_deviceSettings[cbTabletDevice->currentItem()] = dialog.settings();
+ }
+}
+
+void TabletSettingsTab::applyTabletDeviceSettings()
+{
+ for (TQ_UINT32 deviceIndex = 0; deviceIndex < m_deviceSettings.count(); ++deviceIndex) {
+ m_deviceSettings[deviceIndex].applySettings();
+ }
+}
+
+#else // EXTENDED_X11_TABLET_SUPPORT
+
+// Fix compilation. moc seems to not see the undefined symbol needed
+// for these slots to be declared.
+void TabletSettingsTab::slotActivateDevice(int /*deviceIndex*/)
+{
+}
+
+void TabletSettingsTab::slotSetDeviceEnabled(bool /*enabled*/)
+{
+}
+
+void TabletSettingsTab::slotConfigureDevice()
+{
+}
+
+void TabletSettingsTab::applyTabletDeviceSettings()
+{
+}
+
+#endif
+
+//---------------------------------------------------------------------------------------------------
+
+DisplaySettingsTab::DisplaySettingsTab( TQWidget *parent, const char *name)
+ : WdgDisplaySettings( parent, name )
+{
+#ifdef HAVE_GL
+ KisConfig cfg;
+
+ if (!TQGLFormat::hasOpenGL()) {
+ cbUseOpenGL->setEnabled(false);
+ //cbUseOpenGLShaders->setEnabled(false);
+ } else {
+ cbUseOpenGL->setChecked(cfg.useOpenGL());
+ //cbUseOpenGLShaders->setChecked(cfg.useOpenGLShaders());
+ //cbUseOpenGLShaders->setEnabled(cfg.useOpenGL());
+ }
+#else
+ cbUseOpenGL->setEnabled(false);
+ //cbUseOpenGLShaders->setEnabled(false);
+#endif
+
+ connect(cbUseOpenGL, TQT_SIGNAL(toggled(bool)), TQT_SLOT(slotUseOpenGLToggled(bool)));
+}
+
+void DisplaySettingsTab::setDefault()
+{
+ cbUseOpenGL->setChecked(false);
+ //cbUseOpenGLShaders->setChecked(false);
+ //cbUseOpenGLShaders->setEnabled(false);
+}
+
+void DisplaySettingsTab::slotUseOpenGLToggled(bool /*isChecked*/)
+{
+ //cbUseOpenGLShaders->setEnabled(isChecked);
+}
+
+//---------------------------------------------------------------------------------------------------
+GridSettingsTab::GridSettingsTab(TQWidget* parent) : WdgGridSettingsBase(parent)
+{
+ KisConfig cfg;
+ selectMainStyle->setCurrentItem(cfg.getGridMainStyle());
+ selectSubdivisionStyle->setCurrentItem(cfg.getGridSubdivisionStyle());
+
+#if KDE_IS_VERSION(3,4,0)
+ colorMain->setDefaultColor( TQColor( 99, 99, 99 ) );
+ colorSubdivision->setDefaultColor( TQColor( 200, 200, 200 ) );
+#endif
+ colorMain->setColor(cfg.getGridMainColor());
+ colorSubdivision->setColor(cfg.getGridSubdivisionColor());
+
+ intHSpacing->setValue( cfg.getGridHSpacing() );
+ intVSpacing->setValue( cfg.getGridVSpacing() );
+ intSubdivision->setValue( cfg.getGridSubdivisions());
+ intOffsetX->setValue( cfg.getGridOffsetX());
+ intOffsetY->setValue( cfg.getGridOffsetY());
+
+ linkSpacingToggled(true);
+ connect(bnLinkSpacing, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(linkSpacingToggled( bool )));
+
+ connect(intHSpacing, TQT_SIGNAL(valueChanged(int)),this,TQT_SLOT(spinBoxHSpacingChanged(int)));
+ connect(intVSpacing, TQT_SIGNAL(valueChanged(int)),this,TQT_SLOT(spinBoxVSpacingChanged(int)));
+
+
+}
+
+void GridSettingsTab::setDefault()
+{
+ KisConfig cfg;
+ selectMainStyle->setCurrentItem(0);
+ selectSubdivisionStyle->setCurrentItem(1);
+
+ colorMain->setColor(TQColor(99,99,99));
+ colorSubdivision->setColor(TQColor(199,199,199));
+
+ intHSpacing->setValue( 10 );
+ intVSpacing->setValue( 10 );
+ intSubdivision->setValue( 1 );
+ intOffsetX->setValue( 0 );
+ intOffsetY->setValue( 0 );
+}
+
+void GridSettingsTab::spinBoxHSpacingChanged(int v)
+{
+ if(m_linkSpacing)
+ {
+ intVSpacing->setValue(v);
+ }
+}
+
+void GridSettingsTab::spinBoxVSpacingChanged(int v )
+{
+ if(m_linkSpacing)
+ {
+ intHSpacing->setValue(v);
+ }
+}
+
+
+void GridSettingsTab::linkSpacingToggled(bool b)
+{
+ m_linkSpacing = b;
+
+ KoImageResource kir;
+ if (b) {
+ bnLinkSpacing->setPixmap(kir.chain());
+ }
+ else {
+ bnLinkSpacing->setPixmap(kir.chainBroken());
+ }
+}
+
+
+//---------------------------------------------------------------------------------------------------
+
+PreferencesDialog::PreferencesDialog( TQWidget* parent, const char* name )
+ : KDialogBase( IconList, i18n("Preferences"), Ok | Cancel | Help | Default /*| Apply*/, Ok, parent, name, true, true )
+{
+ TQVBox *vbox;
+
+ vbox = addVBoxPage( i18n( "General"), i18n( "General"), BarIcon( "misc", TDEIcon::SizeMedium ));
+ m_general = new GeneralTab( vbox );
+#ifdef HAVE_GL
+ vbox = addVBoxPage ( i18n( "Display" ), i18n( "Display" ), BarIcon( "tdescreensaver", TDEIcon::SizeMedium ));
+ m_displaySettings = new DisplaySettingsTab( vbox );
+#endif
+ vbox = addVBoxPage( i18n( "Color Management"), i18n( "Color"), BarIcon( "colorize", TDEIcon::SizeMedium ));
+ m_colorSettings = new ColorSettingsTab( vbox );
+
+ vbox = addVBoxPage( i18n( "Performance"), i18n( "Performance"), BarIcon( "fork", TDEIcon::SizeMedium ));
+ m_performanceSettings = new PerformanceTab ( vbox );
+
+ vbox = addVBoxPage ( i18n( "Tablet" ), i18n( "Tablet" ), BarIcon( "input-tablet", TDEIcon::SizeMedium ));
+ m_tabletSettings = new TabletSettingsTab( vbox );
+
+ vbox = addVBoxPage ( i18n( "Grid" ), i18n( "Grid" ), BarIcon( "grid", TDEIcon::SizeMedium ));
+ m_gridSettings = new GridSettingsTab( vbox );
+
+}
+
+PreferencesDialog::~PreferencesDialog()
+{
+}
+
+void PreferencesDialog::slotDefault()
+{
+ m_general->setDefault();
+ m_colorSettings->setDefault();
+ m_tabletSettings->setDefault();
+ m_performanceSettings->setDefault();
+#ifdef HAVE_GL
+ m_displaySettings->setDefault();
+#endif
+ m_gridSettings->setDefault();
+}
+
+bool PreferencesDialog::editPreferences()
+{
+ PreferencesDialog* dialog;
+
+ dialog = new PreferencesDialog();
+ bool baccept = ( dialog->exec() == Accepted );
+ if( baccept )
+ {
+ KisConfig cfg;
+ cfg.setCursorStyle(dialog->m_general->cursorStyle());
+ cfg.setDockability( dialog->m_general->dockability() );
+ cfg.setDockerFontSize( dialog->m_general->dockerFontSize() );
+
+ // Color settings
+ cfg.setMonitorProfile( dialog->m_colorSettings->m_page->cmbMonitorProfile->currentText());
+ cfg.setWorkingColorSpace( dialog->m_colorSettings->m_page->cmbWorkingColorSpace->currentText());
+ cfg.setPrinterColorSpace( dialog->m_colorSettings->m_page->cmbPrintingColorSpace->currentText());
+ cfg.setPrinterProfile( dialog->m_colorSettings->m_page->cmbPrintProfile->currentText());
+
+ cfg.setUseBlackPointCompensation( dialog->m_colorSettings->m_page->chkBlackpoint->isChecked());
+ cfg.setPasteBehaviour( dialog->m_colorSettings->m_page->grpPasteBehaviour->selectedId());
+ cfg.setRenderIntent( dialog->m_colorSettings->m_page->cmbMonitorIntent->currentItem());
+
+ // it's scaled from 0 - 6, but the config is in 0 - 300
+ cfg.setSwappiness(dialog->m_performanceSettings->m_swappiness->value() * 50);
+ cfg.setMaxTilesInMem(dialog->m_performanceSettings->m_maxTiles->value());
+ // let the tile manager know
+ KisTileManager::instance()->configChanged();
+
+ dialog->m_tabletSettings->applySettings();
+
+#ifdef HAVE_GL
+ cfg.setUseOpenGL(dialog->m_displaySettings->cbUseOpenGL->isChecked());
+ //cfg.setUseOpenGLShaders(dialog->m_displaySettings->cbUseOpenGLShaders->isChecked());
+#endif
+
+ // Grid settings
+ cfg.setGridMainStyle( dialog->m_gridSettings->selectMainStyle->currentItem() );
+ cfg.setGridSubdivisionStyle( dialog->m_gridSettings->selectSubdivisionStyle->currentItem() );
+
+ cfg.setGridMainColor( dialog->m_gridSettings->colorMain->color() );
+ cfg.setGridSubdivisionColor(dialog->m_gridSettings->colorSubdivision->color() );
+
+ cfg.setGridHSpacing( dialog->m_gridSettings->intHSpacing->value( ));
+ cfg.setGridVSpacing( dialog->m_gridSettings->intVSpacing->value( ));
+ cfg.setGridSubdivisions( dialog->m_gridSettings->intSubdivision->value( ));
+ cfg.setGridOffsetX( dialog->m_gridSettings->intOffsetX->value( ));
+ cfg.setGridOffsetY( dialog->m_gridSettings->intOffsetY->value( ));
+
+ }
+ delete dialog;
+ return baccept;
+}
+
+#include "kis_dlg_preferences.moc"
diff --git a/chalk/ui/kis_doc.cc b/chalk/ui/kis_doc.cpp
index 60dbbfdda..60dbbfdda 100644
--- a/chalk/ui/kis_doc.cc
+++ b/chalk/ui/kis_doc.cpp
diff --git a/chalk/ui/kis_doc_iface.cc b/chalk/ui/kis_doc_iface.cpp
index ae5a4a581..ae5a4a581 100644
--- a/chalk/ui/kis_doc_iface.cc
+++ b/chalk/ui/kis_doc_iface.cpp
diff --git a/chalk/ui/kis_double_widget.cc b/chalk/ui/kis_double_widget.cc
deleted file mode 100644
index a966691dd..000000000
--- a/chalk/ui/kis_double_widget.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * kis_double_widget.cc - part of Chalk
- *
- * Copyright (c) 1999 Carsten Pfeiffer <pfeiffer@kde.org>
- * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqhbox.h>
-#include <tqlayout.h>
-#include <tqslider.h>
-
-#include <knuminput.h>
-
-#include "kis_double_widget.h"
-
-KisDoubleWidget::KisDoubleWidget(TQWidget* parent, const char* name)
- : super(parent, name)
-{
- init(0, 1);
-}
-
-KisDoubleWidget::KisDoubleWidget(double min, double max, TQWidget* parent, const char* name)
- : super(parent, name)
-{
- init(min, max);
-}
-
-KisDoubleWidget::~KisDoubleWidget()
-{
-}
-
-void KisDoubleWidget::init(double min, double max)
-{
- m_spinBox = new KDoubleSpinBox(min, max, 0.05, 0, 2, this, "spinbox");
- connect(m_spinBox, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(setSliderValue(double)));
-
- m_slider = new TQSlider(static_cast<int>(min * 100 + 0.5), static_cast<int>(max * 100 + 0.5), 1, 0, Qt::Horizontal, this, "sld");
- connect(m_slider, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(sliderValueChanged(int)));
- connect(m_slider, TQT_SIGNAL(sliderPressed()), TQT_SIGNAL(sliderPressed()));
- connect(m_slider, TQT_SIGNAL(sliderReleased()), TQT_SIGNAL(sliderReleased()));
-
- m_layout = new TQHBoxLayout(this, 0, -1, "hbox layout");
-
- m_layout->addWidget(m_slider);
- m_layout->addSpacing(5);
- m_layout->addWidget(m_spinBox);
- m_layout->addItem(new TQSpacerItem(5,1,TQSizePolicy::Expanding, TQSizePolicy::Minimum));
-}
-
-double KisDoubleWidget::value() const
-{
- return m_spinBox->value();
-}
-
-void KisDoubleWidget::setValue(double value)
-{
- int intValue;
-
- if (value < 0) {
- intValue = static_cast<int>(value * 100 - 0.5);
- } else {
- intValue = static_cast<int>(value * 100 + 0.5);
- }
- m_slider->setValue(intValue);
-}
-
-void KisDoubleWidget::setRange(double min, double max)
-{
- m_spinBox->setRange(min, max);
- m_slider->setRange(static_cast<int>(min * 100 + 0.5), static_cast<int>(max * 100 + 0.5));
-}
-
-void KisDoubleWidget::setTickmarks(TQSlider::TickSetting tickSetting)
-{
- m_slider->setTickmarks(tickSetting);
-}
-
-void KisDoubleWidget::setTickInterval(double value)
-{
- m_slider->setTickInterval(static_cast<int>(value * 100 + 0.5));
-}
-
-double KisDoubleWidget::tickInterval() const
-{
- return m_slider->tickInterval() / 100.0;
-}
-
-void KisDoubleWidget::setSliderValue(double value)
-{
- int intValue;
-
- if (value < 0) {
- intValue = static_cast<int>(value * 100 - 0.5);
- } else {
- intValue = static_cast<int>(value * 100 + 0.5);
- }
- m_slider->setValue(intValue);
- emit valueChanged(value);
-}
-
-void KisDoubleWidget::sliderValueChanged(int value)
-{
- m_spinBox->setValue(value / 100.0);
-}
-
-void KisDoubleWidget::setPrecision(int precision)
-{
- m_spinBox->setPrecision(precision);
-}
-
-void KisDoubleWidget::setLineStep(double step)
-{
- m_spinBox->setLineStep(step);
- m_slider->setLineStep(static_cast<int>(step * 100));
-}
-
-void KisDoubleWidget::setPageStep(double step)
-{
- m_slider->setPageStep(static_cast<int>(step * 100));
-}
-
-void KisDoubleWidget::setTracking(bool tracking)
-{
- m_slider->setTracking(tracking);
-}
-
-bool KisDoubleWidget::tracking() const
-{
- return m_slider->tracking();
-}
-
-#include "kis_double_widget.moc"
-
diff --git a/chalk/ui/kis_double_widget.cpp b/chalk/ui/kis_double_widget.cpp
new file mode 100644
index 000000000..3325f07bb
--- /dev/null
+++ b/chalk/ui/kis_double_widget.cpp
@@ -0,0 +1,147 @@
+/*
+ * kis_double_widget.cpp - part of Chalk
+ *
+ * Copyright (c) 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+ * Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqhbox.h>
+#include <tqlayout.h>
+#include <tqslider.h>
+
+#include <knuminput.h>
+
+#include "kis_double_widget.h"
+
+KisDoubleWidget::KisDoubleWidget(TQWidget* parent, const char* name)
+ : super(parent, name)
+{
+ init(0, 1);
+}
+
+KisDoubleWidget::KisDoubleWidget(double min, double max, TQWidget* parent, const char* name)
+ : super(parent, name)
+{
+ init(min, max);
+}
+
+KisDoubleWidget::~KisDoubleWidget()
+{
+}
+
+void KisDoubleWidget::init(double min, double max)
+{
+ m_spinBox = new KDoubleSpinBox(min, max, 0.05, 0, 2, this, "spinbox");
+ connect(m_spinBox, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(setSliderValue(double)));
+
+ m_slider = new TQSlider(static_cast<int>(min * 100 + 0.5), static_cast<int>(max * 100 + 0.5), 1, 0, Qt::Horizontal, this, "sld");
+ connect(m_slider, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(sliderValueChanged(int)));
+ connect(m_slider, TQT_SIGNAL(sliderPressed()), TQT_SIGNAL(sliderPressed()));
+ connect(m_slider, TQT_SIGNAL(sliderReleased()), TQT_SIGNAL(sliderReleased()));
+
+ m_layout = new TQHBoxLayout(this, 0, -1, "hbox layout");
+
+ m_layout->addWidget(m_slider);
+ m_layout->addSpacing(5);
+ m_layout->addWidget(m_spinBox);
+ m_layout->addItem(new TQSpacerItem(5,1,TQSizePolicy::Expanding, TQSizePolicy::Minimum));
+}
+
+double KisDoubleWidget::value() const
+{
+ return m_spinBox->value();
+}
+
+void KisDoubleWidget::setValue(double value)
+{
+ int intValue;
+
+ if (value < 0) {
+ intValue = static_cast<int>(value * 100 - 0.5);
+ } else {
+ intValue = static_cast<int>(value * 100 + 0.5);
+ }
+ m_slider->setValue(intValue);
+}
+
+void KisDoubleWidget::setRange(double min, double max)
+{
+ m_spinBox->setRange(min, max);
+ m_slider->setRange(static_cast<int>(min * 100 + 0.5), static_cast<int>(max * 100 + 0.5));
+}
+
+void KisDoubleWidget::setTickmarks(TQSlider::TickSetting tickSetting)
+{
+ m_slider->setTickmarks(tickSetting);
+}
+
+void KisDoubleWidget::setTickInterval(double value)
+{
+ m_slider->setTickInterval(static_cast<int>(value * 100 + 0.5));
+}
+
+double KisDoubleWidget::tickInterval() const
+{
+ return m_slider->tickInterval() / 100.0;
+}
+
+void KisDoubleWidget::setSliderValue(double value)
+{
+ int intValue;
+
+ if (value < 0) {
+ intValue = static_cast<int>(value * 100 - 0.5);
+ } else {
+ intValue = static_cast<int>(value * 100 + 0.5);
+ }
+ m_slider->setValue(intValue);
+ emit valueChanged(value);
+}
+
+void KisDoubleWidget::sliderValueChanged(int value)
+{
+ m_spinBox->setValue(value / 100.0);
+}
+
+void KisDoubleWidget::setPrecision(int precision)
+{
+ m_spinBox->setPrecision(precision);
+}
+
+void KisDoubleWidget::setLineStep(double step)
+{
+ m_spinBox->setLineStep(step);
+ m_slider->setLineStep(static_cast<int>(step * 100));
+}
+
+void KisDoubleWidget::setPageStep(double step)
+{
+ m_slider->setPageStep(static_cast<int>(step * 100));
+}
+
+void KisDoubleWidget::setTracking(bool tracking)
+{
+ m_slider->setTracking(tracking);
+}
+
+bool KisDoubleWidget::tracking() const
+{
+ return m_slider->tracking();
+}
+
+#include "kis_double_widget.moc"
+
diff --git a/chalk/ui/kis_factory.cc b/chalk/ui/kis_factory.cc
deleted file mode 100644
index 154213b49..000000000
--- a/chalk/ui/kis_factory.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * kis_factory.cc - part of Krayon
- *
- * Copyright (c) 1999 Matthias Elter <elter@kde.org>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <config.h>
-#include LCMS_HEADER
-
-#include <tqstringlist.h>
-#include <tqdir.h>
-
-#include <kdebug.h>
-#include <kinstance.h>
-#include <tdeglobal.h>
-#include <tdelocale.h>
-#include <kstandarddirs.h>
-#include <kiconloader.h>
-
-#include "kis_aboutdata.h"
-#include "kis_resourceserver.h"
-#include "kis_paintop_registry.h"
-#include "kis_filter_registry.h"
-#include "kis_tool_registry.h"
-#include "kis_doc.h"
-#include "kis_brush.h"
-#include "kis_imagepipe_brush.h"
-#include "kis_gradient.h"
-#include "kis_pattern.h"
-#include "kis_palette.h"
-#include <kogradientmanager.h>
-
-#include "kis_factory.h"
-
-TDEAboutData* KisFactory::s_aboutData = 0;
-TDEInstance* KisFactory::s_instance = 0;
-
-
-
-KisFactory::KisFactory( TQObject* parent, const char* name )
- : KoFactory( parent, name )
-{
- s_aboutData = newChalkAboutData();
-
- (void)instance();
-
- // Load extension modules and plugins
- KisToolRegistry::instance();
- KisPaintOpRegistry::instance();
- KisFilterRegistry::instance();
- KisResourceServerRegistry::instance();
-
-
-
-}
-
-KisFactory::~KisFactory()
-{
- delete s_aboutData;
- s_aboutData = 0L;
- delete s_instance;
- s_instance = 0L;
-}
-
-/**
- * Create the document
- */
-KParts::Part* KisFactory::createPartObject( TQWidget *parentWidget,
- const char *widgetName, TQObject* parent,
- const char* name, const char* classname, const TQStringList & )
-{
- bool bWantKoDocument = ( strcmp( classname, "KoDocument" ) == 0 );
-
- KisDoc *doc = new KisDoc( parentWidget,
- widgetName, parent, name, !bWantKoDocument );
- TQ_CHECK_PTR(doc);
-
- if ( !bWantKoDocument )
- doc->setReadWrite( false );
-
- return doc;
-}
-
-
-TDEAboutData* KisFactory::aboutData()
-{
- return s_aboutData;
-}
-
-TDEInstance* KisFactory::instance()
-{
- TQString homedir = getenv("HOME");
-
- if ( !s_instance )
- {
- s_instance = new TDEInstance(s_aboutData);
- TQ_CHECK_PTR(s_instance);
-
- s_instance->dirs()->addResourceType("chalk_template", TDEStandardDirs::kde_default("data") + "chalk/templates");
-
- // XXX: Are these obsolete?
- s_instance->dirs()->addResourceType("kis", TDEStandardDirs::kde_default("data") + "chalk/");
-
- s_instance->dirs()->addResourceType("kis_pics", TDEStandardDirs::kde_default("data") + "chalk/pics/");
-
- s_instance->dirs()->addResourceType("kis_images", TDEStandardDirs::kde_default("data") + "chalk/images/");
-
- s_instance->dirs()->addResourceType("toolbars", TDEStandardDirs::kde_default("data") + "koffice/toolbar/");
-
- // Create spec
-
- s_instance->dirs()->addResourceType("kis_brushes", TDEStandardDirs::kde_default("data") + "chalk/brushes/");
- s_instance->dirs()->addResourceDir("kis_brushes", "/usr/share/create/brushes/gimp");
- s_instance->dirs()->addResourceDir("kis_brushes", TQDir::homeDirPath() + TQString("/.create/brushes/gimp"));
-
- s_instance->dirs()->addResourceType("kis_patterns", TDEStandardDirs::kde_default("data") + "chalk/patterns/");
- s_instance->dirs()->addResourceDir("kis_patterns", "/usr/share/create/patterns/gimp");
- s_instance->dirs()->addResourceDir("kis_patterns", TQDir::homeDirPath() + TQString("/.create/patterns/gimp"));
-
- s_instance->dirs()->addResourceType("kis_gradients", TDEStandardDirs::kde_default("data") + "chalk/gradients/");
- s_instance->dirs()->addResourceDir("kis_gradients", "/usr/share/create/gradients/gimp");
- s_instance->dirs()->addResourceDir("kis_gradients", TQDir::homeDirPath() + TQString("/.create/gradients/gimp"));
-
- s_instance->dirs()->addResourceType("kis_profiles", TDEStandardDirs::kde_default("data") + "chalk/profiles/");
- s_instance->dirs()->addResourceDir("kis_profiles", "/usr/share/color/icc");
- s_instance->dirs()->addResourceDir("kis_profiles", TQDir::homeDirPath() + TQString("/.icc"));
- s_instance->dirs()->addResourceDir("kis_profiles", TQDir::homeDirPath() + TQString("/.color/icc"));
-
- s_instance->dirs()->addResourceType("kis_palettes", TDEStandardDirs::kde_default("data") + "chalk/palettes/");
- s_instance->dirs()->addResourceDir("kis_palettes", "/usr/share/create/swatches");
- s_instance->dirs()->addResourceDir("kis_palettes", TQDir::homeDirPath() + TQString("/.create/swatches"));
-
- // Tell the iconloader about share/apps/koffice/icons
- s_instance->iconLoader()->addAppDir("koffice");
- }
-
- return s_instance;
-}
-
-#include "kis_factory.moc"
diff --git a/chalk/ui/kis_factory.cpp b/chalk/ui/kis_factory.cpp
new file mode 100644
index 000000000..e9e51e487
--- /dev/null
+++ b/chalk/ui/kis_factory.cpp
@@ -0,0 +1,153 @@
+/*
+ * kis_factory.cpp - part of Krayon
+ *
+ * Copyright (c) 1999 Matthias Elter <elter@kde.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <config.h>
+#include LCMS_HEADER
+
+#include <tqstringlist.h>
+#include <tqdir.h>
+
+#include <kdebug.h>
+#include <kinstance.h>
+#include <tdeglobal.h>
+#include <tdelocale.h>
+#include <kstandarddirs.h>
+#include <kiconloader.h>
+
+#include "kis_aboutdata.h"
+#include "kis_resourceserver.h"
+#include "kis_paintop_registry.h"
+#include "kis_filter_registry.h"
+#include "kis_tool_registry.h"
+#include "kis_doc.h"
+#include "kis_brush.h"
+#include "kis_imagepipe_brush.h"
+#include "kis_gradient.h"
+#include "kis_pattern.h"
+#include "kis_palette.h"
+#include <kogradientmanager.h>
+
+#include "kis_factory.h"
+
+TDEAboutData* KisFactory::s_aboutData = 0;
+TDEInstance* KisFactory::s_instance = 0;
+
+
+
+KisFactory::KisFactory( TQObject* parent, const char* name )
+ : KoFactory( parent, name )
+{
+ s_aboutData = newChalkAboutData();
+
+ (void)instance();
+
+ // Load extension modules and plugins
+ KisToolRegistry::instance();
+ KisPaintOpRegistry::instance();
+ KisFilterRegistry::instance();
+ KisResourceServerRegistry::instance();
+
+
+
+}
+
+KisFactory::~KisFactory()
+{
+ delete s_aboutData;
+ s_aboutData = 0L;
+ delete s_instance;
+ s_instance = 0L;
+}
+
+/**
+ * Create the document
+ */
+KParts::Part* KisFactory::createPartObject( TQWidget *parentWidget,
+ const char *widgetName, TQObject* parent,
+ const char* name, const char* classname, const TQStringList & )
+{
+ bool bWantKoDocument = ( strcmp( classname, "KoDocument" ) == 0 );
+
+ KisDoc *doc = new KisDoc( parentWidget,
+ widgetName, parent, name, !bWantKoDocument );
+ TQ_CHECK_PTR(doc);
+
+ if ( !bWantKoDocument )
+ doc->setReadWrite( false );
+
+ return doc;
+}
+
+
+TDEAboutData* KisFactory::aboutData()
+{
+ return s_aboutData;
+}
+
+TDEInstance* KisFactory::instance()
+{
+ TQString homedir = getenv("HOME");
+
+ if ( !s_instance )
+ {
+ s_instance = new TDEInstance(s_aboutData);
+ TQ_CHECK_PTR(s_instance);
+
+ s_instance->dirs()->addResourceType("chalk_template", TDEStandardDirs::kde_default("data") + "chalk/templates");
+
+ // XXX: Are these obsolete?
+ s_instance->dirs()->addResourceType("kis", TDEStandardDirs::kde_default("data") + "chalk/");
+
+ s_instance->dirs()->addResourceType("kis_pics", TDEStandardDirs::kde_default("data") + "chalk/pics/");
+
+ s_instance->dirs()->addResourceType("kis_images", TDEStandardDirs::kde_default("data") + "chalk/images/");
+
+ s_instance->dirs()->addResourceType("toolbars", TDEStandardDirs::kde_default("data") + "koffice/toolbar/");
+
+ // Create spec
+
+ s_instance->dirs()->addResourceType("kis_brushes", TDEStandardDirs::kde_default("data") + "chalk/brushes/");
+ s_instance->dirs()->addResourceDir("kis_brushes", "/usr/share/create/brushes/gimp");
+ s_instance->dirs()->addResourceDir("kis_brushes", TQDir::homeDirPath() + TQString("/.create/brushes/gimp"));
+
+ s_instance->dirs()->addResourceType("kis_patterns", TDEStandardDirs::kde_default("data") + "chalk/patterns/");
+ s_instance->dirs()->addResourceDir("kis_patterns", "/usr/share/create/patterns/gimp");
+ s_instance->dirs()->addResourceDir("kis_patterns", TQDir::homeDirPath() + TQString("/.create/patterns/gimp"));
+
+ s_instance->dirs()->addResourceType("kis_gradients", TDEStandardDirs::kde_default("data") + "chalk/gradients/");
+ s_instance->dirs()->addResourceDir("kis_gradients", "/usr/share/create/gradients/gimp");
+ s_instance->dirs()->addResourceDir("kis_gradients", TQDir::homeDirPath() + TQString("/.create/gradients/gimp"));
+
+ s_instance->dirs()->addResourceType("kis_profiles", TDEStandardDirs::kde_default("data") + "chalk/profiles/");
+ s_instance->dirs()->addResourceDir("kis_profiles", "/usr/share/color/icc");
+ s_instance->dirs()->addResourceDir("kis_profiles", TQDir::homeDirPath() + TQString("/.icc"));
+ s_instance->dirs()->addResourceDir("kis_profiles", TQDir::homeDirPath() + TQString("/.color/icc"));
+
+ s_instance->dirs()->addResourceType("kis_palettes", TDEStandardDirs::kde_default("data") + "chalk/palettes/");
+ s_instance->dirs()->addResourceDir("kis_palettes", "/usr/share/create/swatches");
+ s_instance->dirs()->addResourceDir("kis_palettes", TQDir::homeDirPath() + TQString("/.create/swatches"));
+
+ // Tell the iconloader about share/apps/koffice/icons
+ s_instance->iconLoader()->addAppDir("koffice");
+ }
+
+ return s_instance;
+}
+
+#include "kis_factory.moc"
diff --git a/chalk/ui/kis_filter_manager.cc b/chalk/ui/kis_filter_manager.cpp
index 848f99b73..848f99b73 100644
--- a/chalk/ui/kis_filter_manager.cc
+++ b/chalk/ui/kis_filter_manager.cpp
diff --git a/chalk/ui/kis_filters_listview.cc b/chalk/ui/kis_filters_listview.cpp
index e3674fc89..e3674fc89 100644
--- a/chalk/ui/kis_filters_listview.cc
+++ b/chalk/ui/kis_filters_listview.cpp
diff --git a/chalk/ui/kis_gradient_chooser.cc b/chalk/ui/kis_gradient_chooser.cpp
index 5022a28b9..5022a28b9 100644
--- a/chalk/ui/kis_gradient_chooser.cc
+++ b/chalk/ui/kis_gradient_chooser.cpp
diff --git a/chalk/ui/kis_gradient_slider_widget.cc b/chalk/ui/kis_gradient_slider_widget.cpp
index 255d3847a..255d3847a 100644
--- a/chalk/ui/kis_gradient_slider_widget.cc
+++ b/chalk/ui/kis_gradient_slider_widget.cpp
diff --git a/chalk/ui/kis_histogram_view.cc b/chalk/ui/kis_histogram_view.cpp
index 3b94db619..3b94db619 100644
--- a/chalk/ui/kis_histogram_view.cc
+++ b/chalk/ui/kis_histogram_view.cpp
diff --git a/chalk/ui/kis_icon_item.cc b/chalk/ui/kis_icon_item.cpp
index 339017fc3..339017fc3 100644
--- a/chalk/ui/kis_icon_item.cc
+++ b/chalk/ui/kis_icon_item.cpp
diff --git a/chalk/ui/kis_iconwidget.cc b/chalk/ui/kis_iconwidget.cpp
index 0109f7ebd..0109f7ebd 100644
--- a/chalk/ui/kis_iconwidget.cc
+++ b/chalk/ui/kis_iconwidget.cpp
diff --git a/chalk/ui/kis_import_catcher.cc b/chalk/ui/kis_import_catcher.cpp
index 26040309b..26040309b 100644
--- a/chalk/ui/kis_import_catcher.cc
+++ b/chalk/ui/kis_import_catcher.cpp
diff --git a/chalk/ui/kis_input_device.cc b/chalk/ui/kis_input_device.cpp
index 0923c7274..0923c7274 100644
--- a/chalk/ui/kis_input_device.cc
+++ b/chalk/ui/kis_input_device.cpp
diff --git a/chalk/ui/kis_int_spinbox.cc b/chalk/ui/kis_int_spinbox.cpp
index cb1b69384..cb1b69384 100644
--- a/chalk/ui/kis_int_spinbox.cc
+++ b/chalk/ui/kis_int_spinbox.cpp
diff --git a/chalk/ui/kis_itemchooser.cc b/chalk/ui/kis_itemchooser.cpp
index d33c38738..d33c38738 100644
--- a/chalk/ui/kis_itemchooser.cc
+++ b/chalk/ui/kis_itemchooser.cpp
diff --git a/chalk/ui/kis_label_cursor_pos.cc b/chalk/ui/kis_label_cursor_pos.cpp
index d28f1a83b..d28f1a83b 100644
--- a/chalk/ui/kis_label_cursor_pos.cc
+++ b/chalk/ui/kis_label_cursor_pos.cpp
diff --git a/chalk/ui/kis_label_progress.cc b/chalk/ui/kis_label_progress.cpp
index 0caadcbba..0caadcbba 100644
--- a/chalk/ui/kis_label_progress.cc
+++ b/chalk/ui/kis_label_progress.cpp
diff --git a/chalk/ui/kis_label_zoom.cc b/chalk/ui/kis_label_zoom.cpp
index cd8620d68..cd8620d68 100644
--- a/chalk/ui/kis_label_zoom.cc
+++ b/chalk/ui/kis_label_zoom.cpp
diff --git a/chalk/ui/kis_layerbox.cc b/chalk/ui/kis_layerbox.cc
deleted file mode 100644
index 058eb2f96..000000000
--- a/chalk/ui/kis_layerbox.cc
+++ /dev/null
@@ -1,675 +0,0 @@
-/*
- * kis_layerbox.cc - part of Chalk aka Krayon aka KimageShop
- *
- * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
- * Copyright (C) 2006 Gábor Lehel <illissius@gmail.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqbutton.h>
-#include <tqtoolbutton.h>
-#include <tqbrush.h>
-#include <tqfont.h>
-#include <tqfontmetrics.h>
-#include <tqhbox.h>
-#include <tqlayout.h>
-#include <tqpainter.h>
-#include <tqpoint.h>
-#include <tqrect.h>
-#include <tqstring.h>
-#include <tqstyle.h>
-#include <tqtooltip.h>
-#include <tqwidget.h>
-#include <tqcombobox.h>
-#include <tqcheckbox.h>
-
-#include <kdebug.h>
-#include <tdeglobal.h>
-#include <tdepopupmenu.h>
-#include <tdemessagebox.h>
-#include <kpushbutton.h>
-#include <kiconloader.h>
-#include <kicontheme.h>
-#include <tdelocale.h>
-
-#include <KoPartSelectAction.h>
-
-#include "kis_layerlist.h"
-#include "kis_cmb_composite.h"
-#include "kis_int_spinbox.h"
-#include "wdglayerbox.h"
-#include "kis_colorspace.h"
-#include "kis_paint_device.h"
-#include "kis_layer.h"
-#include "kis_group_layer.h"
-#include "kis_image.h"
-
-#include "kis_populate_visitor.h"
-
-#include "kis_layerbox.h"
-
-KisLayerBox::KisLayerBox(KisCanvasSubject *subject, TQWidget *parent, const char *name)
- : super(parent, name), m_image(0)
-{
- TQVBoxLayout *vbox = new TQVBoxLayout(this);
- vbox->setAutoAdd(true);
-
- m_lst = new WdgLayerBox(this);
- setMinimumSize(m_lst->minimumSizeHint());
-
- TQToolTip::add(m_lst->bnAdd, i18n("Create new layer"));
-
- TQToolTip::add(m_lst->bnDelete, i18n("Remove current layer"));
-
- TQToolTip::add(m_lst->bnRaise, i18n("Raise current layer"));
- m_lst->bnRaise->setEnabled(false);
-
- m_lst->bnLower->setEnabled(false);
- TQToolTip::add(m_lst->bnLower, i18n("Lower current layer"));
-
- TQToolTip::add(m_lst->bnProperties, i18n("Properties for layer"));
-
- TDEIconLoader il( "chalk" );
-
- list()->setPreviewsShown(true);
-
- list()->setFoldersCanBeActive(true);
-
- list()->addProperty("visible", i18n("Visible"), loadPixmap("visible.png", il, TDEIcon::SizeSmallMedium),
- loadPixmap("novisible.png", il, TDEIcon::SizeSmallMedium), true);
-
- list()->addProperty("locked", i18n("Locked"), loadPixmap("locked.png", il, TDEIcon::SizeSmallMedium),
- loadPixmap("unlocked.png", il, TDEIcon::SizeSmallMedium));
-
-
- connect(list()->contextMenu(), TQT_SIGNAL(aboutToShow()), TQT_SLOT(slotAboutToShow()));
- connect(list(), TQT_SIGNAL(activated(LayerItem*)),
- TQT_SLOT(slotLayerActivated(LayerItem*)));
- connect(list(), TQT_SIGNAL(displayNameChanged(LayerItem*, const TQString&)),
- TQT_SLOT(slotLayerDisplayNameChanged(LayerItem*, const TQString&)));
- connect(list(), TQT_SIGNAL(propertyChanged(LayerItem*, const TQString&, bool)),
- TQT_SLOT(slotLayerPropertyChanged(LayerItem*, const TQString&, bool)));
- connect(list(), TQT_SIGNAL(layerMoved(LayerItem*, LayerItem*, LayerItem*)),
- TQT_SLOT(slotLayerMoved(LayerItem*, LayerItem*, LayerItem*)));
- connect(list(), TQT_SIGNAL(requestNewLayer(LayerItem*, LayerItem*)),
- TQT_SLOT(slotRequestNewLayer(LayerItem*, LayerItem*)));
- connect(list(), TQT_SIGNAL(requestNewFolder(LayerItem*, LayerItem*)),
- TQT_SLOT(slotRequestNewFolder(LayerItem*, LayerItem*)));
- connect(list(), TQT_SIGNAL(requestNewAdjustmentLayer(LayerItem*, LayerItem*)),
- TQT_SLOT(slotRequestNewAdjustmentLayer(LayerItem*, LayerItem*)));
- connect(list(), TQT_SIGNAL(requestNewObjectLayer(LayerItem*, LayerItem*, const KoDocumentEntry&)),
- TQT_SLOT(slotRequestNewObjectLayer(LayerItem*, LayerItem*, const KoDocumentEntry&)));
- connect(list(), TQT_SIGNAL(requestRemoveLayer(LayerItem*)),
- TQT_SLOT(slotRequestRemoveLayer(LayerItem*)));
- connect(list(), TQT_SIGNAL(requestLayerProperties(LayerItem*)),
- TQT_SLOT(slotRequestLayerProperties(LayerItem*)));
-
- m_newLayerMenu = new TDEPopupMenu(this);
- m_lst->bnAdd->setPopup(m_newLayerMenu);
- m_lst->bnAdd->setPopupDelay(1);
- m_newLayerMenu->insertItem( SmallIconSet( "document-new" ), i18n( "&New Layer..." ), PAINT_LAYER );
- m_newLayerMenu->insertItem( SmallIconSet( "folder" ), i18n( "New &Group Layer..." ), GROUP_LAYER );
- m_newLayerMenu->insertItem( SmallIconSet( "tool_filter" ), i18n( "New &Adjustment Layer..." ), ADJUSTMENT_LAYER );
- m_partLayerAction = new KoPartSelectAction( i18n( "New &Object Layer" ), "gear", TQT_TQOBJECT(this) );
- m_partLayerAction->plug( m_newLayerMenu );
- connect(m_partLayerAction, TQT_SIGNAL(activated()), this, TQT_SLOT(slotAddMenuActivated()));
- connect(m_newLayerMenu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotAddMenuActivated(int)));
-
-
- connect(m_lst->bnDelete, TQT_SIGNAL(clicked()), TQT_SLOT(slotRmClicked()));
- connect(m_lst->bnRaise, TQT_SIGNAL(clicked()), TQT_SLOT(slotRaiseClicked()));
- connect(m_lst->bnLower, TQT_SIGNAL(clicked()), TQT_SLOT(slotLowerClicked()));
- connect(m_lst->bnProperties, TQT_SIGNAL(clicked()), TQT_SLOT(slotPropertiesClicked()));
- connect(m_lst->intOpacity, TQT_SIGNAL(valueChanged(int, bool)), TQT_SIGNAL(sigOpacityChanged(int, bool)));
- connect(m_lst->intOpacity, TQT_SIGNAL(finishedChanging(int, int)), TQT_SIGNAL(sigOpacityFinishedChanging(int, int)));
- connect(m_lst->cmbComposite, TQT_SIGNAL(activated(const KisCompositeOp&)), TQT_SIGNAL(sigItemComposite(const KisCompositeOp&)));
-
- Q_ASSERT(subject->document() != 0);
-
- if (subject->document()) {
- connect(subject->document(), TQT_SIGNAL(sigCommandExecuted()), TQT_SLOT(updateThumbnails()));
- }
-}
-
-KisLayerBox::~KisLayerBox()
-{
-}
-
-KisLayerList* KisLayerBox::list() const
-{
- return m_lst->listLayers;
-}
-
-void KisLayerBox::setImage(KisImageSP img)
-{
- if (m_image == img)
- return;
-
- if (m_image)
- m_image->disconnect(this);
-
- m_image = img;
-
- if (img)
- {
- connect(img, TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
- connect(img, TQT_SIGNAL(sigLayerAdded(KisLayerSP)), this, TQT_SLOT(slotLayerAdded(KisLayerSP)));
- connect(img, TQT_SIGNAL(sigLayerRemoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)),
- this, TQT_SLOT(slotLayerRemoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)));
- connect(img, TQT_SIGNAL(sigLayerPropertiesChanged(KisLayerSP)),
- this, TQT_SLOT(slotLayerPropertiesChanged(KisLayerSP)));
- connect(img, TQT_SIGNAL(sigLayerMoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)),
- this, TQT_SLOT(slotLayerMoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)));
- connect(img, TQT_SIGNAL(sigLayersChanged(KisGroupLayerSP)), this, TQT_SLOT(slotLayersChanged(KisGroupLayerSP)));
- connect(img, TQT_SIGNAL(sigLayerUpdated(KisLayerSP, TQRect)), this, TQT_SLOT(slotLayerUpdated(KisLayerSP, TQRect)));
- slotLayersChanged(img->rootLayer());
- updateThumbnails();
- }
- else
- {
- clear();
- }
-}
-
-void KisLayerBox::slotLayerActivated(KisLayerSP layer)
-{
- if (layer)
- list()->setActiveLayer(layer->id());
- else
- list()->setActiveLayer(-1);
- updateUI();
-}
-
-void KisLayerBox::slotLayerAdded(KisLayerSP layer)
-{
- if (layer.data() == m_image->rootLayer().data() || list()->layer(layer->id()))
- return;
-
- vKisLayerSP layersAdded;
-
- if (layer->parent() == m_image->rootLayer())
- {
- KisPopulateVisitor visitor(list());
- layer->accept(visitor);
- layersAdded = visitor.layersAdded();
- }
- else
- {
- KisPopulateVisitor visitor(static_cast<KisLayerItem*>(list()->layer(layer->parent()->id())));
- layer->accept(visitor);
- layersAdded = visitor.layersAdded();
- }
-
- for (vKisLayerSP::iterator it = layersAdded.begin(); it != layersAdded.end(); ++it) {
- markModified(*it);
- }
- updateUI();
-}
-
-void KisLayerBox::slotLayerRemoved(KisLayerSP layer, KisGroupLayerSP wasParent, KisLayerSP)
-{
- list()->removeLayer(layer->id());
- m_modified.remove(layer->id());
- markModified(wasParent);
- updateUI();
-}
-
-void KisLayerBox::slotLayerMoved(KisLayerSP layer, KisGroupLayerSP wasParent, KisLayerSP)
-{
- int parentID = layer->parent()->id();
- if (layer->parent() == m_image->rootLayer())
- parentID = -1;
-
- int siblingID = -1;
- if (layer->prevSibling())
- siblingID = layer->prevSibling()->id();
-
- list()->moveLayer(layer->id(), parentID, siblingID);
-
- markModified(layer->parent());
- markModified(wasParent);
- updateUI();
-}
-
-void KisLayerBox::slotLayerPropertiesChanged(KisLayerSP layer)
-{
- if (KisLayerItem* item = dynamic_cast<KisLayerItem*>(list()->layer(layer->id())))
- {
- Q_ASSERT(item->layer() == layer.data());
- item->sync();
- updateUI();
- markModified(layer);
- }
-}
-
-void KisLayerBox::slotLayersChanged(KisGroupLayerSP rootLayer)
-{
- list()->clear();
- KisPopulateVisitor visitor(list());
- for (KisLayerSP layer = rootLayer->firstChild(); layer; layer = layer->nextSibling())
- layer->accept(visitor);
- m_modified.clear();
- for (TQListViewItemIterator it(list()->lastItem()); *it; --it)
- m_modified.append(static_cast<LayerItem*>(*it)->id());
- updateUI();
-}
-
-void KisLayerBox::slotLayerUpdated(KisLayerSP layer, TQRect)
-{
- markModified(layer);
-}
-
-void KisLayerBox::slotLayerActivated(LayerItem* item)
-{
- if (item)
- m_image->activate(m_image->findLayer(item->id()));
- else
- m_image->activate(0);
- updateUI();
-}
-
-void KisLayerBox::slotLayerDisplayNameChanged(LayerItem* item, const TQString& displayName)
-{
- if(KisLayerSP layer = m_image->findLayer(item->id()))
- layer->setName(displayName);
- updateUI();
-}
-
-void KisLayerBox::slotLayerPropertyChanged(LayerItem* item, const TQString& name, bool on)
-{
- if (KisLayerSP layer = m_image->findLayer(item->id()))
- {
- if (name == "visible")
- layer->setVisible(on);
- else if (name == "locked")
- layer->setLocked(on);
- }
-}
-
-void KisLayerBox::slotLayerMoved(LayerItem* item, LayerItem*, LayerItem*)
-{
- KisLayerSP layer = m_image->findLayer(item->id());
- KisGroupLayerSP parent;
- if( item->parent() )
- parent = dynamic_cast<KisGroupLayer*>(m_image->findLayer(item->parent()->id()).data());
- if( !parent )
- parent = m_image->rootLayer();
- KisLayerSP above = 0;
- if (item->nextSibling())
- above = m_image->findLayer(item->nextSibling()->id());
- if (layer)
- m_image->moveLayer(layer, parent.data(), above);
- updateUI();
-}
-
-void KisLayerBox::slotRequestNewLayer(LayerItem* p, LayerItem* after)
-{
- KisLayer* l = m_image->rootLayer().data();
- if (p)
- l = m_image->findLayer(p->id()).data();
- KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
-
- KisLayerSP above = 0;
- if (after && after->nextSibling())
- above = m_image->findLayer(after->nextSibling()->id());
- else if (after)
- above = 0;
- else if (p && p->firstChild())
- above = parent->firstChild();
- else if (!p && m_image->rootLayer()->childCount())
- above = m_image->rootLayer()->firstChild();
- emit sigRequestLayer(parent, above);
-}
-
-void KisLayerBox::slotRequestNewFolder(LayerItem* p, LayerItem* after)
-{
- KisLayer* l = m_image->rootLayer().data(); //FIXME I hate copy-pasting like this.
- if (p)
- l = m_image->findLayer(p->id()).data();
- KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
-
- KisLayerSP above = 0;
- if (after && after->nextSibling())
- above = m_image->findLayer(after->nextSibling()->id());
- else if (after)
- above = 0;
- else if (p && p->firstChild())
- above = parent->firstChild();
- else if (!p && m_image->rootLayer()->childCount())
- above = m_image->rootLayer()->firstChild();
- emit sigRequestGroupLayer(parent, above);
-}
-
-void KisLayerBox::slotRequestNewAdjustmentLayer(LayerItem* p, LayerItem* after)
-{
- KisLayer* l = m_image->rootLayer().data(); //FIXME here too.
- if (p)
- l = m_image->findLayer(p->id()).data();
- KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
-
- KisLayerSP above = 0;
- if (after && after->nextSibling())
- above = m_image->findLayer(after->nextSibling()->id());
- else if (after)
- above = 0;
- else if (p && p->firstChild())
- above = parent->firstChild();
- else if (!p && m_image->rootLayer()->childCount())
- above = m_image->rootLayer()->firstChild();
- emit sigRequestAdjustmentLayer(parent, above);
-}
-
-void KisLayerBox::slotRequestNewObjectLayer(LayerItem* p, LayerItem* after, const KoDocumentEntry& entry)
-{
- KisLayer* l = m_image->rootLayer().data(); //FIXME and here.
- if (p)
- l = m_image->findLayer(p->id()).data();
- KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
-
- KisLayerSP above = 0;
- if (after && after->nextSibling())
- above = m_image->findLayer(after->nextSibling()->id());
- else if (after)
- above = 0;
- else if (p && p->firstChild())
- above = parent->firstChild();
- else if (!p && m_image->rootLayer()->childCount())
- above = m_image->rootLayer()->firstChild();
- emit sigRequestPartLayer(parent, above, entry);
-}
-
-void KisLayerBox::slotRequestRemoveLayer(LayerItem* item)
-{
- if (KisLayerSP layer = m_image->findLayer(item->id())) {
- m_image->removeLayer(layer);
- }
- updateUI();
-}
-
-void KisLayerBox::slotRequestLayerProperties(LayerItem* item)
-{
- if (KisLayerSP layer = m_image->findLayer(item->id()))
- {
- emit sigRequestLayerProperties(layer);
- }
-}
-
-void KisLayerBox::updateUI()
-{
- m_lst->bnDelete->setEnabled(list()->activeLayer());
- m_lst->bnRaise->setEnabled(list()->activeLayer() && (list()->activeLayer()->prevSibling() || list()->activeLayer()->parent()));
- m_lst->bnLower->setEnabled(list()->activeLayer() && list()->activeLayer()->nextSibling());
- m_lst->intOpacity->setEnabled(list()->activeLayer());
- m_lst->cmbComposite->setEnabled(list()->activeLayer());
- if (m_image)
- if (KisLayerSP active = m_image->activeLayer())
- {
- if (m_image->activeDevice())
- slotSetColorSpace(m_image->activeDevice()->colorSpace());
- else
- slotSetColorSpace(m_image->colorSpace());
- slotSetOpacity(int(float(active->opacity() * 100) / 255 + 0.5));
- slotSetCompositeOp(active->compositeOp());
- }
-}
-
-void KisLayerBox::slotAboutToShow()
-{
-}
-
-void KisLayerBox::slotSetCompositeOp(const KisCompositeOp& compositeOp)
-{
- m_lst->cmbComposite->blockSignals(true);
- m_lst->cmbComposite->setCurrentItem(compositeOp);
- m_lst->cmbComposite->blockSignals(false);
-}
-
-void KisLayerBox::slotSetColorSpace(const KisColorSpace * colorSpace)
-{
- m_lst->cmbComposite->blockSignals(true);
- m_lst->cmbComposite->setCompositeOpList(colorSpace->userVisiblecompositeOps());
- m_lst->cmbComposite->blockSignals(false);
-}
-
-// range: 0-100
-void KisLayerBox::slotSetOpacity(int opacity)
-{
- m_lst->intOpacity->blockSignals(true);
- m_lst->intOpacity->setValue(opacity);
- m_lst->intOpacity->blockSignals(false);
-}
-
-void KisLayerBox::clear()
-{
- list()->clear();
- updateUI();
-}
-
-void KisLayerBox::slotAddMenuActivated(int type)
-{
- if(type == -1)
- return;
-
- KisGroupLayerSP root = m_image->rootLayer();
- KisGroupLayerSP parent;
- KisLayerSP above;
- if (KisLayerSP active = m_image->activeLayer())
- {
- parent = root;
- above = active;
- if (active->parent())
- parent = active->parent();
- }
- else
- {
- parent = root;
- above = m_image->rootLayer()->firstChild();
- }
-
- switch (type)
- {
- case PAINT_LAYER:
- emit sigRequestLayer(parent, above);
- break;
- case GROUP_LAYER:
- emit sigRequestGroupLayer(parent, above);
- break;
- case ADJUSTMENT_LAYER:
- emit sigRequestAdjustmentLayer(parent, above);
- break;
- case OBJECT_LAYER:
- default: //TQt doesn't emit activated for default-assigned IDs, so this does nothing
- emit sigRequestPartLayer(parent, above, m_partLayerAction->documentEntry());
- }
-}
-
-void KisLayerBox::slotRmClicked()
-{
- TQValueList<int> l = list()->selectedLayerIDs();
- if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()->id()))
- {
- l.clear();
- l.append(list()->activeLayer()->id());
- }
-
- for (int i = 0, n = l.count(); i < n; ++i)
- {
- m_modified.remove(l[i]);
- m_image->removeLayer(m_image->findLayer(l[i]));
- }
-}
-
-void KisLayerBox::slotRaiseClicked()
-{
- TQValueList<int> l = list()->selectedLayerIDs();
- if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()->id()))
- {
- l.clear();
- l.append(list()->activeLayer()->id());
- }
-
- KisLayerSP layer = m_image->findLayer(l.first());
- if( l.count() == 1 && layer == layer->parent()->firstChild() && layer->parent() != m_image->rootLayer())
- {
- if (KisGroupLayerSP grandparent = layer->parent()->parent())
- m_image->moveLayer(layer, grandparent, layer->parent().data());
- }
- else
- {
- for (int i = 0, n = l.count(); i < n; ++i)
- if (KisLayerSP li = m_image->findLayer(l[i]))
- if (li->prevSibling())
- m_image->moveLayer(li, li->parent(), li->prevSibling());
- }
-
- if( !l.isEmpty() )
- list()->ensureItemVisible( list()->layer( l.first() ) );
-}
-
-void KisLayerBox::slotLowerClicked()
-{
- TQValueList<LayerItem*> l = list()->selectedLayers();
- if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()))
- {
- l.clear();
- l.append(list()->activeLayer());
- }
-
- for (int i = l.count() - 1; i >= 0; --i)
- if (LayerItem *layer = l[i])
- if (layer->nextSibling())
- list()->moveLayer(layer, layer->parent(), layer->nextSibling());
-
- if( !l.isEmpty() )
- list()->ensureItemVisible( l.last() );
-}
-
-void KisLayerBox::slotPropertiesClicked()
-{
- if (KisLayerSP active = m_image->activeLayer())
- emit sigRequestLayerProperties(active);
-}
-
-void KisLayerBox::updateThumbnails()
-{
- bool again = true;
- while (m_modified.count() && again)
- {
- //again = false;
- KisLayerItem* item = static_cast<KisLayerItem*>(list()->layer(m_modified.last()));
- m_modified.pop_back();
- if (!item || !item->updatePreview())
- again = true;
- }
-}
-
-void KisLayerBox::setUpdatesAndSignalsEnabled(bool enable)
-{
- setUpdatesEnabled(enable);
- m_lst->intOpacity->setUpdatesEnabled(enable);
- m_lst->cmbComposite->setUpdatesEnabled(enable);
-
- list()->blockSignals(!enable);
- m_lst->intOpacity->blockSignals(!enable);
- m_lst->cmbComposite->blockSignals(!enable);
-}
-
-
-TQPixmap KisLayerBox::loadPixmap(const TQString& filename, const TDEIconLoader&
- il, int size)
-{
- TQPixmap pixmap = il.loadIcon(filename, TDEIcon::NoGroup, size);
-
- if (pixmap.isNull())
- KMessageBox::error(0, i18n("Cannot find %1").arg(filename),
- i18n("Canvas"));
-
- return pixmap;
-}
-
-void KisLayerBox::markModified(KisLayer* layer)
-{
- if( !layer )
- return;
-
- TQValueList<int> v;
- while (layer && layer != m_image->rootLayer().data())
- {
- v.append(layer->id());
- layer = layer->parent();
- }
- for (int i = v.count() - 1; i >= 0; --i)
- if (!m_modified.contains(v[i]))
- m_modified.append(v[i]);
-}
-
-void KisLayerBox::printChalkLayers() const
-{
- static int indent = 0;
- static KisLayer *root = 0;
- if( !root )
- root = m_image->rootLayer();
- if( !root )
- return;
- TQString s = root->name();
- if( dynamic_cast<KisGroupLayer*>( root ) )
- s = TQString("[%1]").arg( s );
- if( m_image->activeLayer().data() == root )
- s.prepend("*");
- kdDebug() << (TQString().fill(' ', indent) + s) << endl;
- for (KisLayer* layer = root->firstChild(); layer; layer = layer->nextSibling())
- {
- indent += 2;
- root = layer;
- printChalkLayers();
- indent -= 2;
- root = layer->parent();
- }
-}
-
-void KisLayerBox::printLayerboxLayers() const
-{
- static int indent = 0;
- static LayerItem *root = 0;
- if( !root )
- {
- for (LayerItem* layer = list()->firstChild(); layer; layer = layer->nextSibling())
- {
- indent += 2;
- root = layer;
- printLayerboxLayers();
- indent -= 2;
- root = layer->parent();
- }
- return;
- }
- TQString s = root->displayName();
- if( root->isFolder() )
- s = TQString("[%1]").arg( s );
- if( list()->activeLayer() == root )
- s.prepend("*");
- kdDebug() << (TQString().fill(' ', indent) + s) << endl;
- for (LayerItem* layer = root->firstChild(); layer; layer = layer->nextSibling())
- {
- indent += 2;
- root = layer;
- printLayerboxLayers();
- indent -= 2;
- root = layer->parent();
- }
-}
-
-#include "kis_layerbox.moc"
diff --git a/chalk/ui/kis_layerbox.cpp b/chalk/ui/kis_layerbox.cpp
new file mode 100644
index 000000000..1d769fb42
--- /dev/null
+++ b/chalk/ui/kis_layerbox.cpp
@@ -0,0 +1,675 @@
+/*
+ * kis_layerbox.cpp - part of Chalk aka Krayon aka KimageShop
+ *
+ * Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
+ * Copyright (C) 2006 Gábor Lehel <illissius@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqbutton.h>
+#include <tqtoolbutton.h>
+#include <tqbrush.h>
+#include <tqfont.h>
+#include <tqfontmetrics.h>
+#include <tqhbox.h>
+#include <tqlayout.h>
+#include <tqpainter.h>
+#include <tqpoint.h>
+#include <tqrect.h>
+#include <tqstring.h>
+#include <tqstyle.h>
+#include <tqtooltip.h>
+#include <tqwidget.h>
+#include <tqcombobox.h>
+#include <tqcheckbox.h>
+
+#include <kdebug.h>
+#include <tdeglobal.h>
+#include <tdepopupmenu.h>
+#include <tdemessagebox.h>
+#include <kpushbutton.h>
+#include <kiconloader.h>
+#include <kicontheme.h>
+#include <tdelocale.h>
+
+#include <KoPartSelectAction.h>
+
+#include "kis_layerlist.h"
+#include "kis_cmb_composite.h"
+#include "kis_int_spinbox.h"
+#include "wdglayerbox.h"
+#include "kis_colorspace.h"
+#include "kis_paint_device.h"
+#include "kis_layer.h"
+#include "kis_group_layer.h"
+#include "kis_image.h"
+
+#include "kis_populate_visitor.h"
+
+#include "kis_layerbox.h"
+
+KisLayerBox::KisLayerBox(KisCanvasSubject *subject, TQWidget *parent, const char *name)
+ : super(parent, name), m_image(0)
+{
+ TQVBoxLayout *vbox = new TQVBoxLayout(this);
+ vbox->setAutoAdd(true);
+
+ m_lst = new WdgLayerBox(this);
+ setMinimumSize(m_lst->minimumSizeHint());
+
+ TQToolTip::add(m_lst->bnAdd, i18n("Create new layer"));
+
+ TQToolTip::add(m_lst->bnDelete, i18n("Remove current layer"));
+
+ TQToolTip::add(m_lst->bnRaise, i18n("Raise current layer"));
+ m_lst->bnRaise->setEnabled(false);
+
+ m_lst->bnLower->setEnabled(false);
+ TQToolTip::add(m_lst->bnLower, i18n("Lower current layer"));
+
+ TQToolTip::add(m_lst->bnProperties, i18n("Properties for layer"));
+
+ TDEIconLoader il( "chalk" );
+
+ list()->setPreviewsShown(true);
+
+ list()->setFoldersCanBeActive(true);
+
+ list()->addProperty("visible", i18n("Visible"), loadPixmap("visible.png", il, TDEIcon::SizeSmallMedium),
+ loadPixmap("novisible.png", il, TDEIcon::SizeSmallMedium), true);
+
+ list()->addProperty("locked", i18n("Locked"), loadPixmap("locked.png", il, TDEIcon::SizeSmallMedium),
+ loadPixmap("unlocked.png", il, TDEIcon::SizeSmallMedium));
+
+
+ connect(list()->contextMenu(), TQT_SIGNAL(aboutToShow()), TQT_SLOT(slotAboutToShow()));
+ connect(list(), TQT_SIGNAL(activated(LayerItem*)),
+ TQT_SLOT(slotLayerActivated(LayerItem*)));
+ connect(list(), TQT_SIGNAL(displayNameChanged(LayerItem*, const TQString&)),
+ TQT_SLOT(slotLayerDisplayNameChanged(LayerItem*, const TQString&)));
+ connect(list(), TQT_SIGNAL(propertyChanged(LayerItem*, const TQString&, bool)),
+ TQT_SLOT(slotLayerPropertyChanged(LayerItem*, const TQString&, bool)));
+ connect(list(), TQT_SIGNAL(layerMoved(LayerItem*, LayerItem*, LayerItem*)),
+ TQT_SLOT(slotLayerMoved(LayerItem*, LayerItem*, LayerItem*)));
+ connect(list(), TQT_SIGNAL(requestNewLayer(LayerItem*, LayerItem*)),
+ TQT_SLOT(slotRequestNewLayer(LayerItem*, LayerItem*)));
+ connect(list(), TQT_SIGNAL(requestNewFolder(LayerItem*, LayerItem*)),
+ TQT_SLOT(slotRequestNewFolder(LayerItem*, LayerItem*)));
+ connect(list(), TQT_SIGNAL(requestNewAdjustmentLayer(LayerItem*, LayerItem*)),
+ TQT_SLOT(slotRequestNewAdjustmentLayer(LayerItem*, LayerItem*)));
+ connect(list(), TQT_SIGNAL(requestNewObjectLayer(LayerItem*, LayerItem*, const KoDocumentEntry&)),
+ TQT_SLOT(slotRequestNewObjectLayer(LayerItem*, LayerItem*, const KoDocumentEntry&)));
+ connect(list(), TQT_SIGNAL(requestRemoveLayer(LayerItem*)),
+ TQT_SLOT(slotRequestRemoveLayer(LayerItem*)));
+ connect(list(), TQT_SIGNAL(requestLayerProperties(LayerItem*)),
+ TQT_SLOT(slotRequestLayerProperties(LayerItem*)));
+
+ m_newLayerMenu = new TDEPopupMenu(this);
+ m_lst->bnAdd->setPopup(m_newLayerMenu);
+ m_lst->bnAdd->setPopupDelay(1);
+ m_newLayerMenu->insertItem( SmallIconSet( "document-new" ), i18n( "&New Layer..." ), PAINT_LAYER );
+ m_newLayerMenu->insertItem( SmallIconSet( "folder" ), i18n( "New &Group Layer..." ), GROUP_LAYER );
+ m_newLayerMenu->insertItem( SmallIconSet( "tool_filter" ), i18n( "New &Adjustment Layer..." ), ADJUSTMENT_LAYER );
+ m_partLayerAction = new KoPartSelectAction( i18n( "New &Object Layer" ), "gear", TQT_TQOBJECT(this) );
+ m_partLayerAction->plug( m_newLayerMenu );
+ connect(m_partLayerAction, TQT_SIGNAL(activated()), this, TQT_SLOT(slotAddMenuActivated()));
+ connect(m_newLayerMenu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotAddMenuActivated(int)));
+
+
+ connect(m_lst->bnDelete, TQT_SIGNAL(clicked()), TQT_SLOT(slotRmClicked()));
+ connect(m_lst->bnRaise, TQT_SIGNAL(clicked()), TQT_SLOT(slotRaiseClicked()));
+ connect(m_lst->bnLower, TQT_SIGNAL(clicked()), TQT_SLOT(slotLowerClicked()));
+ connect(m_lst->bnProperties, TQT_SIGNAL(clicked()), TQT_SLOT(slotPropertiesClicked()));
+ connect(m_lst->intOpacity, TQT_SIGNAL(valueChanged(int, bool)), TQT_SIGNAL(sigOpacityChanged(int, bool)));
+ connect(m_lst->intOpacity, TQT_SIGNAL(finishedChanging(int, int)), TQT_SIGNAL(sigOpacityFinishedChanging(int, int)));
+ connect(m_lst->cmbComposite, TQT_SIGNAL(activated(const KisCompositeOp&)), TQT_SIGNAL(sigItemComposite(const KisCompositeOp&)));
+
+ Q_ASSERT(subject->document() != 0);
+
+ if (subject->document()) {
+ connect(subject->document(), TQT_SIGNAL(sigCommandExecuted()), TQT_SLOT(updateThumbnails()));
+ }
+}
+
+KisLayerBox::~KisLayerBox()
+{
+}
+
+KisLayerList* KisLayerBox::list() const
+{
+ return m_lst->listLayers;
+}
+
+void KisLayerBox::setImage(KisImageSP img)
+{
+ if (m_image == img)
+ return;
+
+ if (m_image)
+ m_image->disconnect(this);
+
+ m_image = img;
+
+ if (img)
+ {
+ connect(img, TQT_SIGNAL(sigLayerActivated(KisLayerSP)), this, TQT_SLOT(slotLayerActivated(KisLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayerAdded(KisLayerSP)), this, TQT_SLOT(slotLayerAdded(KisLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayerRemoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)),
+ this, TQT_SLOT(slotLayerRemoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayerPropertiesChanged(KisLayerSP)),
+ this, TQT_SLOT(slotLayerPropertiesChanged(KisLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayerMoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)),
+ this, TQT_SLOT(slotLayerMoved(KisLayerSP, KisGroupLayerSP, KisLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayersChanged(KisGroupLayerSP)), this, TQT_SLOT(slotLayersChanged(KisGroupLayerSP)));
+ connect(img, TQT_SIGNAL(sigLayerUpdated(KisLayerSP, TQRect)), this, TQT_SLOT(slotLayerUpdated(KisLayerSP, TQRect)));
+ slotLayersChanged(img->rootLayer());
+ updateThumbnails();
+ }
+ else
+ {
+ clear();
+ }
+}
+
+void KisLayerBox::slotLayerActivated(KisLayerSP layer)
+{
+ if (layer)
+ list()->setActiveLayer(layer->id());
+ else
+ list()->setActiveLayer(-1);
+ updateUI();
+}
+
+void KisLayerBox::slotLayerAdded(KisLayerSP layer)
+{
+ if (layer.data() == m_image->rootLayer().data() || list()->layer(layer->id()))
+ return;
+
+ vKisLayerSP layersAdded;
+
+ if (layer->parent() == m_image->rootLayer())
+ {
+ KisPopulateVisitor visitor(list());
+ layer->accept(visitor);
+ layersAdded = visitor.layersAdded();
+ }
+ else
+ {
+ KisPopulateVisitor visitor(static_cast<KisLayerItem*>(list()->layer(layer->parent()->id())));
+ layer->accept(visitor);
+ layersAdded = visitor.layersAdded();
+ }
+
+ for (vKisLayerSP::iterator it = layersAdded.begin(); it != layersAdded.end(); ++it) {
+ markModified(*it);
+ }
+ updateUI();
+}
+
+void KisLayerBox::slotLayerRemoved(KisLayerSP layer, KisGroupLayerSP wasParent, KisLayerSP)
+{
+ list()->removeLayer(layer->id());
+ m_modified.remove(layer->id());
+ markModified(wasParent);
+ updateUI();
+}
+
+void KisLayerBox::slotLayerMoved(KisLayerSP layer, KisGroupLayerSP wasParent, KisLayerSP)
+{
+ int parentID = layer->parent()->id();
+ if (layer->parent() == m_image->rootLayer())
+ parentID = -1;
+
+ int siblingID = -1;
+ if (layer->prevSibling())
+ siblingID = layer->prevSibling()->id();
+
+ list()->moveLayer(layer->id(), parentID, siblingID);
+
+ markModified(layer->parent());
+ markModified(wasParent);
+ updateUI();
+}
+
+void KisLayerBox::slotLayerPropertiesChanged(KisLayerSP layer)
+{
+ if (KisLayerItem* item = dynamic_cast<KisLayerItem*>(list()->layer(layer->id())))
+ {
+ Q_ASSERT(item->layer() == layer.data());
+ item->sync();
+ updateUI();
+ markModified(layer);
+ }
+}
+
+void KisLayerBox::slotLayersChanged(KisGroupLayerSP rootLayer)
+{
+ list()->clear();
+ KisPopulateVisitor visitor(list());
+ for (KisLayerSP layer = rootLayer->firstChild(); layer; layer = layer->nextSibling())
+ layer->accept(visitor);
+ m_modified.clear();
+ for (TQListViewItemIterator it(list()->lastItem()); *it; --it)
+ m_modified.append(static_cast<LayerItem*>(*it)->id());
+ updateUI();
+}
+
+void KisLayerBox::slotLayerUpdated(KisLayerSP layer, TQRect)
+{
+ markModified(layer);
+}
+
+void KisLayerBox::slotLayerActivated(LayerItem* item)
+{
+ if (item)
+ m_image->activate(m_image->findLayer(item->id()));
+ else
+ m_image->activate(0);
+ updateUI();
+}
+
+void KisLayerBox::slotLayerDisplayNameChanged(LayerItem* item, const TQString& displayName)
+{
+ if(KisLayerSP layer = m_image->findLayer(item->id()))
+ layer->setName(displayName);
+ updateUI();
+}
+
+void KisLayerBox::slotLayerPropertyChanged(LayerItem* item, const TQString& name, bool on)
+{
+ if (KisLayerSP layer = m_image->findLayer(item->id()))
+ {
+ if (name == "visible")
+ layer->setVisible(on);
+ else if (name == "locked")
+ layer->setLocked(on);
+ }
+}
+
+void KisLayerBox::slotLayerMoved(LayerItem* item, LayerItem*, LayerItem*)
+{
+ KisLayerSP layer = m_image->findLayer(item->id());
+ KisGroupLayerSP parent;
+ if( item->parent() )
+ parent = dynamic_cast<KisGroupLayer*>(m_image->findLayer(item->parent()->id()).data());
+ if( !parent )
+ parent = m_image->rootLayer();
+ KisLayerSP above = 0;
+ if (item->nextSibling())
+ above = m_image->findLayer(item->nextSibling()->id());
+ if (layer)
+ m_image->moveLayer(layer, parent.data(), above);
+ updateUI();
+}
+
+void KisLayerBox::slotRequestNewLayer(LayerItem* p, LayerItem* after)
+{
+ KisLayer* l = m_image->rootLayer().data();
+ if (p)
+ l = m_image->findLayer(p->id()).data();
+ KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
+
+ KisLayerSP above = 0;
+ if (after && after->nextSibling())
+ above = m_image->findLayer(after->nextSibling()->id());
+ else if (after)
+ above = 0;
+ else if (p && p->firstChild())
+ above = parent->firstChild();
+ else if (!p && m_image->rootLayer()->childCount())
+ above = m_image->rootLayer()->firstChild();
+ emit sigRequestLayer(parent, above);
+}
+
+void KisLayerBox::slotRequestNewFolder(LayerItem* p, LayerItem* after)
+{
+ KisLayer* l = m_image->rootLayer().data(); //FIXME I hate copy-pasting like this.
+ if (p)
+ l = m_image->findLayer(p->id()).data();
+ KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
+
+ KisLayerSP above = 0;
+ if (after && after->nextSibling())
+ above = m_image->findLayer(after->nextSibling()->id());
+ else if (after)
+ above = 0;
+ else if (p && p->firstChild())
+ above = parent->firstChild();
+ else if (!p && m_image->rootLayer()->childCount())
+ above = m_image->rootLayer()->firstChild();
+ emit sigRequestGroupLayer(parent, above);
+}
+
+void KisLayerBox::slotRequestNewAdjustmentLayer(LayerItem* p, LayerItem* after)
+{
+ KisLayer* l = m_image->rootLayer().data(); //FIXME here too.
+ if (p)
+ l = m_image->findLayer(p->id()).data();
+ KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
+
+ KisLayerSP above = 0;
+ if (after && after->nextSibling())
+ above = m_image->findLayer(after->nextSibling()->id());
+ else if (after)
+ above = 0;
+ else if (p && p->firstChild())
+ above = parent->firstChild();
+ else if (!p && m_image->rootLayer()->childCount())
+ above = m_image->rootLayer()->firstChild();
+ emit sigRequestAdjustmentLayer(parent, above);
+}
+
+void KisLayerBox::slotRequestNewObjectLayer(LayerItem* p, LayerItem* after, const KoDocumentEntry& entry)
+{
+ KisLayer* l = m_image->rootLayer().data(); //FIXME and here.
+ if (p)
+ l = m_image->findLayer(p->id()).data();
+ KisGroupLayerSP parent = dynamic_cast<KisGroupLayer*>(l);
+
+ KisLayerSP above = 0;
+ if (after && after->nextSibling())
+ above = m_image->findLayer(after->nextSibling()->id());
+ else if (after)
+ above = 0;
+ else if (p && p->firstChild())
+ above = parent->firstChild();
+ else if (!p && m_image->rootLayer()->childCount())
+ above = m_image->rootLayer()->firstChild();
+ emit sigRequestPartLayer(parent, above, entry);
+}
+
+void KisLayerBox::slotRequestRemoveLayer(LayerItem* item)
+{
+ if (KisLayerSP layer = m_image->findLayer(item->id())) {
+ m_image->removeLayer(layer);
+ }
+ updateUI();
+}
+
+void KisLayerBox::slotRequestLayerProperties(LayerItem* item)
+{
+ if (KisLayerSP layer = m_image->findLayer(item->id()))
+ {
+ emit sigRequestLayerProperties(layer);
+ }
+}
+
+void KisLayerBox::updateUI()
+{
+ m_lst->bnDelete->setEnabled(list()->activeLayer());
+ m_lst->bnRaise->setEnabled(list()->activeLayer() && (list()->activeLayer()->prevSibling() || list()->activeLayer()->parent()));
+ m_lst->bnLower->setEnabled(list()->activeLayer() && list()->activeLayer()->nextSibling());
+ m_lst->intOpacity->setEnabled(list()->activeLayer());
+ m_lst->cmbComposite->setEnabled(list()->activeLayer());
+ if (m_image)
+ if (KisLayerSP active = m_image->activeLayer())
+ {
+ if (m_image->activeDevice())
+ slotSetColorSpace(m_image->activeDevice()->colorSpace());
+ else
+ slotSetColorSpace(m_image->colorSpace());
+ slotSetOpacity(int(float(active->opacity() * 100) / 255 + 0.5));
+ slotSetCompositeOp(active->compositeOp());
+ }
+}
+
+void KisLayerBox::slotAboutToShow()
+{
+}
+
+void KisLayerBox::slotSetCompositeOp(const KisCompositeOp& compositeOp)
+{
+ m_lst->cmbComposite->blockSignals(true);
+ m_lst->cmbComposite->setCurrentItem(compositeOp);
+ m_lst->cmbComposite->blockSignals(false);
+}
+
+void KisLayerBox::slotSetColorSpace(const KisColorSpace * colorSpace)
+{
+ m_lst->cmbComposite->blockSignals(true);
+ m_lst->cmbComposite->setCompositeOpList(colorSpace->userVisiblecompositeOps());
+ m_lst->cmbComposite->blockSignals(false);
+}
+
+// range: 0-100
+void KisLayerBox::slotSetOpacity(int opacity)
+{
+ m_lst->intOpacity->blockSignals(true);
+ m_lst->intOpacity->setValue(opacity);
+ m_lst->intOpacity->blockSignals(false);
+}
+
+void KisLayerBox::clear()
+{
+ list()->clear();
+ updateUI();
+}
+
+void KisLayerBox::slotAddMenuActivated(int type)
+{
+ if(type == -1)
+ return;
+
+ KisGroupLayerSP root = m_image->rootLayer();
+ KisGroupLayerSP parent;
+ KisLayerSP above;
+ if (KisLayerSP active = m_image->activeLayer())
+ {
+ parent = root;
+ above = active;
+ if (active->parent())
+ parent = active->parent();
+ }
+ else
+ {
+ parent = root;
+ above = m_image->rootLayer()->firstChild();
+ }
+
+ switch (type)
+ {
+ case PAINT_LAYER:
+ emit sigRequestLayer(parent, above);
+ break;
+ case GROUP_LAYER:
+ emit sigRequestGroupLayer(parent, above);
+ break;
+ case ADJUSTMENT_LAYER:
+ emit sigRequestAdjustmentLayer(parent, above);
+ break;
+ case OBJECT_LAYER:
+ default: //TQt doesn't emit activated for default-assigned IDs, so this does nothing
+ emit sigRequestPartLayer(parent, above, m_partLayerAction->documentEntry());
+ }
+}
+
+void KisLayerBox::slotRmClicked()
+{
+ TQValueList<int> l = list()->selectedLayerIDs();
+ if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()->id()))
+ {
+ l.clear();
+ l.append(list()->activeLayer()->id());
+ }
+
+ for (int i = 0, n = l.count(); i < n; ++i)
+ {
+ m_modified.remove(l[i]);
+ m_image->removeLayer(m_image->findLayer(l[i]));
+ }
+}
+
+void KisLayerBox::slotRaiseClicked()
+{
+ TQValueList<int> l = list()->selectedLayerIDs();
+ if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()->id()))
+ {
+ l.clear();
+ l.append(list()->activeLayer()->id());
+ }
+
+ KisLayerSP layer = m_image->findLayer(l.first());
+ if( l.count() == 1 && layer == layer->parent()->firstChild() && layer->parent() != m_image->rootLayer())
+ {
+ if (KisGroupLayerSP grandparent = layer->parent()->parent())
+ m_image->moveLayer(layer, grandparent, layer->parent().data());
+ }
+ else
+ {
+ for (int i = 0, n = l.count(); i < n; ++i)
+ if (KisLayerSP li = m_image->findLayer(l[i]))
+ if (li->prevSibling())
+ m_image->moveLayer(li, li->parent(), li->prevSibling());
+ }
+
+ if( !l.isEmpty() )
+ list()->ensureItemVisible( list()->layer( l.first() ) );
+}
+
+void KisLayerBox::slotLowerClicked()
+{
+ TQValueList<LayerItem*> l = list()->selectedLayers();
+ if (l.count() < 2 && list()->activeLayer() && !l.contains(list()->activeLayer()))
+ {
+ l.clear();
+ l.append(list()->activeLayer());
+ }
+
+ for (int i = l.count() - 1; i >= 0; --i)
+ if (LayerItem *layer = l[i])
+ if (layer->nextSibling())
+ list()->moveLayer(layer, layer->parent(), layer->nextSibling());
+
+ if( !l.isEmpty() )
+ list()->ensureItemVisible( l.last() );
+}
+
+void KisLayerBox::slotPropertiesClicked()
+{
+ if (KisLayerSP active = m_image->activeLayer())
+ emit sigRequestLayerProperties(active);
+}
+
+void KisLayerBox::updateThumbnails()
+{
+ bool again = true;
+ while (m_modified.count() && again)
+ {
+ //again = false;
+ KisLayerItem* item = static_cast<KisLayerItem*>(list()->layer(m_modified.last()));
+ m_modified.pop_back();
+ if (!item || !item->updatePreview())
+ again = true;
+ }
+}
+
+void KisLayerBox::setUpdatesAndSignalsEnabled(bool enable)
+{
+ setUpdatesEnabled(enable);
+ m_lst->intOpacity->setUpdatesEnabled(enable);
+ m_lst->cmbComposite->setUpdatesEnabled(enable);
+
+ list()->blockSignals(!enable);
+ m_lst->intOpacity->blockSignals(!enable);
+ m_lst->cmbComposite->blockSignals(!enable);
+}
+
+
+TQPixmap KisLayerBox::loadPixmap(const TQString& filename, const TDEIconLoader&
+ il, int size)
+{
+ TQPixmap pixmap = il.loadIcon(filename, TDEIcon::NoGroup, size);
+
+ if (pixmap.isNull())
+ KMessageBox::error(0, i18n("Cannot find %1").arg(filename),
+ i18n("Canvas"));
+
+ return pixmap;
+}
+
+void KisLayerBox::markModified(KisLayer* layer)
+{
+ if( !layer )
+ return;
+
+ TQValueList<int> v;
+ while (layer && layer != m_image->rootLayer().data())
+ {
+ v.append(layer->id());
+ layer = layer->parent();
+ }
+ for (int i = v.count() - 1; i >= 0; --i)
+ if (!m_modified.contains(v[i]))
+ m_modified.append(v[i]);
+}
+
+void KisLayerBox::printChalkLayers() const
+{
+ static int indent = 0;
+ static KisLayer *root = 0;
+ if( !root )
+ root = m_image->rootLayer();
+ if( !root )
+ return;
+ TQString s = root->name();
+ if( dynamic_cast<KisGroupLayer*>( root ) )
+ s = TQString("[%1]").arg( s );
+ if( m_image->activeLayer().data() == root )
+ s.prepend("*");
+ kdDebug() << (TQString().fill(' ', indent) + s) << endl;
+ for (KisLayer* layer = root->firstChild(); layer; layer = layer->nextSibling())
+ {
+ indent += 2;
+ root = layer;
+ printChalkLayers();
+ indent -= 2;
+ root = layer->parent();
+ }
+}
+
+void KisLayerBox::printLayerboxLayers() const
+{
+ static int indent = 0;
+ static LayerItem *root = 0;
+ if( !root )
+ {
+ for (LayerItem* layer = list()->firstChild(); layer; layer = layer->nextSibling())
+ {
+ indent += 2;
+ root = layer;
+ printLayerboxLayers();
+ indent -= 2;
+ root = layer->parent();
+ }
+ return;
+ }
+ TQString s = root->displayName();
+ if( root->isFolder() )
+ s = TQString("[%1]").arg( s );
+ if( list()->activeLayer() == root )
+ s.prepend("*");
+ kdDebug() << (TQString().fill(' ', indent) + s) << endl;
+ for (LayerItem* layer = root->firstChild(); layer; layer = layer->nextSibling())
+ {
+ indent += 2;
+ root = layer;
+ printLayerboxLayers();
+ indent -= 2;
+ root = layer->parent();
+ }
+}
+
+#include "kis_layerbox.moc"
diff --git a/chalk/ui/kis_layerlist.cc b/chalk/ui/kis_layerlist.cpp
index bfae82825..bfae82825 100644
--- a/chalk/ui/kis_layerlist.cc
+++ b/chalk/ui/kis_layerlist.cpp
diff --git a/chalk/ui/kis_multi_bool_filter_widget.cc b/chalk/ui/kis_multi_bool_filter_widget.cpp
index e02695049..e02695049 100644
--- a/chalk/ui/kis_multi_bool_filter_widget.cc
+++ b/chalk/ui/kis_multi_bool_filter_widget.cpp
diff --git a/chalk/ui/kis_multi_double_filter_widget.cc b/chalk/ui/kis_multi_double_filter_widget.cpp
index 9491f2218..9491f2218 100644
--- a/chalk/ui/kis_multi_double_filter_widget.cc
+++ b/chalk/ui/kis_multi_double_filter_widget.cpp
diff --git a/chalk/ui/kis_multi_integer_filter_widget.cc b/chalk/ui/kis_multi_integer_filter_widget.cpp
index aef29d2cb..aef29d2cb 100644
--- a/chalk/ui/kis_multi_integer_filter_widget.cc
+++ b/chalk/ui/kis_multi_integer_filter_widget.cpp
diff --git a/chalk/ui/kis_opengl_canvas.cc b/chalk/ui/kis_opengl_canvas.cpp
index 82363a0b8..82363a0b8 100644
--- a/chalk/ui/kis_opengl_canvas.cc
+++ b/chalk/ui/kis_opengl_canvas.cpp
diff --git a/chalk/ui/kis_opengl_canvas_painter.cc b/chalk/ui/kis_opengl_canvas_painter.cpp
index e6551f816..e6551f816 100644
--- a/chalk/ui/kis_opengl_canvas_painter.cc
+++ b/chalk/ui/kis_opengl_canvas_painter.cpp
diff --git a/chalk/ui/kis_opengl_image_context.cc b/chalk/ui/kis_opengl_image_context.cpp
index 6a302192b..6a302192b 100644
--- a/chalk/ui/kis_opengl_image_context.cc
+++ b/chalk/ui/kis_opengl_image_context.cpp
diff --git a/chalk/ui/kis_paintop_box.cc b/chalk/ui/kis_paintop_box.cc
deleted file mode 100644
index 6036ef74c..000000000
--- a/chalk/ui/kis_paintop_box.cc
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * kis_paintop_box.cc - part of KImageShop/Krayon/Chalk
- *
- * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqwidget.h>
-#include <tqstring.h>
-#include <tqvaluelist.h>
-#include <tqpixmap.h>
-#include <tqlayout.h>
-#include <tqtooltip.h>
-
-#include <tdelocale.h>
-#include <tdeactioncollection.h>
-#include <kdebug.h>
-#include <tdeglobal.h>
-#include <tdelocale.h>
-#include <tdeglobalsettings.h>
-#include <tdeaccelmanager.h>
-#include <tdeconfig.h>
-#include <kstandarddirs.h>
-
-#include <kis_paintop_registry.h>
-#include <kis_view.h>
-#include <kis_painter.h>
-#include <kis_paintop.h>
-#include <kis_layer.h>
-#include <kis_factory.h>
-
-#include "kis_paintop_box.h"
-
-KisPaintopBox::KisPaintopBox (KisView * view, TQWidget *parent, const char * name)
- : super (parent, name),
- m_canvasController(view->getCanvasController())
-{
-#if TDE_VERSION >= TDE_MAKE_VERSION(3,3,90)
- TDEAcceleratorManager::setNoAccel(this);
-#endif
-
- Q_ASSERT(m_canvasController != 0);
-
- setCaption(i18n("Painter's Toolchest"));
- m_optionWidget = 0;
- m_paintops = new TQValueList<KisID>();
- m_displayedOps = new TQValueList<KisID>();
-
- m_cmbPaintops = new TQComboBox(this, "KisPaintopBox::m_cmbPaintops");
- m_cmbPaintops->setMinimumWidth(150);
- TQToolTip::add(m_cmbPaintops, i18n("Styles of painting for the painting tools"));
- m_layout = new TQHBoxLayout(this, 1, 1);
- m_layout->addWidget(m_cmbPaintops);
-
- connect(this, TQT_SIGNAL(selected(const KisID &, const KisPaintOpSettings *)), view, TQT_SLOT(paintopActivated(const KisID &, const KisPaintOpSettings *)));
- connect(m_cmbPaintops, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotItemSelected(int)));
-
- // XXX: Let's see... Are all paintops loaded and ready?
- KisIDList keys = KisPaintOpRegistry::instance()->listKeys();
- for ( KisIDList::Iterator it = keys.begin(); it != keys.end(); ++it ) {
- // add all paintops, and show/hide them afterwards
- addItem(*it);
- }
-
- connect(view, TQT_SIGNAL(currentColorSpaceChanged(KisColorSpace*)),
- this, TQT_SLOT(colorSpaceChanged(KisColorSpace*)));
- connect(view, TQT_SIGNAL(sigInputDeviceChanged(const KisInputDevice&)),
- this, TQT_SLOT(slotInputDeviceChanged(const KisInputDevice&)));
-
- setCurrentPaintop(defaultPaintop(m_canvasController->currentInputDevice()));
-}
-
-KisPaintopBox::~KisPaintopBox()
-{
- delete m_paintops;
- delete m_displayedOps;
-}
-
-void KisPaintopBox::addItem(const KisID & paintop, const TQString & /*category*/)
-{
- m_paintops->append(paintop);
-}
-
-void KisPaintopBox::slotItemSelected(int index)
-{
- if ((uint)index > m_displayedOps->count()) {
- return;
- }
-
- KisID paintop = *m_displayedOps->at(index);
-
- setCurrentPaintop(paintop);
-}
-
-void KisPaintopBox::colorSpaceChanged(KisColorSpace *cs)
-{
- TQValueList<KisID>::iterator it = m_paintops->begin();
- TQValueList<KisID>::iterator end = m_paintops->end();
- m_displayedOps->clear();
- m_cmbPaintops->clear();
-
- for ( ; it != end; ++it ) {
- if (KisPaintOpRegistry::instance()->userVisible(*it, cs)) {
- TQPixmap pm = paintopPixmap(*it);
- if (pm.isNull()) {
- TQPixmap p = TQPixmap( 16, 16 );
- p.fill();
- m_cmbPaintops->insertItem(p, (*it).name());
- }
- else {
- m_cmbPaintops->insertItem(pm, (*it).name());
- }
- m_displayedOps->append(*it);
- }
- }
-
- int index = m_displayedOps->findIndex(currentPaintop());
-
- if (index == -1) {
- // Must change the paintop as the current one is not supported
- // by the new colourspace.
- index = 0;
- }
-
- m_cmbPaintops->setCurrentItem( index );
- slotItemSelected( index );
-}
-
-TQPixmap KisPaintopBox::paintopPixmap(const KisID & paintop)
-{
- TQString pixmapName = KisPaintOpRegistry::instance()->pixmap(paintop);
-
- if (pixmapName.isEmpty()) {
- return TQPixmap();
- }
-
- TQString fname = KisFactory::instance()->dirs()->findResource("kis_images", pixmapName);
-
- return TQPixmap(fname);
-}
-
-void KisPaintopBox::slotInputDeviceChanged(const KisInputDevice & inputDevice)
-{
- KisID paintop;
- InputDevicePaintopMap::iterator it = m_currentID.find(inputDevice);
-
- if (it == m_currentID.end()) {
- paintop = defaultPaintop(inputDevice);
- } else {
- paintop = (*it).second;
- }
-
- int index = m_displayedOps->findIndex(paintop);
-
- if (index == -1) {
- // Must change the paintop as the current one is not supported
- // by the new colourspace.
- index = 0;
- paintop = *m_displayedOps->at(index);
- }
-
- m_cmbPaintops->setCurrentItem(index);
- setCurrentPaintop(paintop);
-}
-
-void KisPaintopBox::updateOptionWidget()
-{
- if (m_optionWidget != 0) {
- m_layout->remove(m_optionWidget);
- m_optionWidget->hide();
- m_layout->invalidate();
- }
-
- const KisPaintOpSettings *settings = paintopSettings(currentPaintop(), m_canvasController->currentInputDevice());
-
- if (settings != 0) {
- m_optionWidget = settings->widget();
- Q_ASSERT(m_optionWidget != 0);
-
- m_layout->addWidget(m_optionWidget);
- updateGeometry();
- m_optionWidget->show();
- }
-}
-
-const KisID& KisPaintopBox::currentPaintop()
-{
- return m_currentID[m_canvasController->currentInputDevice()];
-}
-
-void KisPaintopBox::setCurrentPaintop(const KisID & paintop)
-{
- m_currentID[m_canvasController->currentInputDevice()] = paintop;
-
- updateOptionWidget();
-
- emit selected(paintop, paintopSettings(paintop, m_canvasController->currentInputDevice()));
-}
-
-KisID KisPaintopBox::defaultPaintop(const KisInputDevice& inputDevice)
-{
- if (inputDevice == KisInputDevice::eraser()) {
- return KisID("eraser","");
- } else {
- return KisID("paintbrush","");
- }
-}
-
-const KisPaintOpSettings *KisPaintopBox::paintopSettings(const KisID & paintop, const KisInputDevice & inputDevice)
-{
- TQValueVector<KisPaintOpSettings *> settingsArray;
- InputDevicePaintopSettingsMap::iterator it = m_inputDevicePaintopSettings.find(inputDevice);
-
- if (it == m_inputDevicePaintopSettings.end()) {
- // Create settings for each paintop.
-
- for (TQValueList<KisID>::const_iterator pit = m_paintops->begin(); pit != m_paintops->end(); ++pit) {
- KisPaintOpSettings *settings = KisPaintOpRegistry::instance()->settings(*pit, this, inputDevice);
- settingsArray.append(settings);
- if (settings && settings->widget()) {
- settings->widget()->hide();
- }
- }
- m_inputDevicePaintopSettings[inputDevice] = settingsArray;
- } else {
- settingsArray = (*it).second;
- }
-
- const int index = m_paintops->findIndex(paintop);
- if (index >= 0 && index < (int)settingsArray.count())
- return settingsArray[index];
- else
- return 0;
-}
-
-#include "kis_paintop_box.moc"
-
diff --git a/chalk/ui/kis_paintop_box.cpp b/chalk/ui/kis_paintop_box.cpp
new file mode 100644
index 000000000..57ed7a736
--- /dev/null
+++ b/chalk/ui/kis_paintop_box.cpp
@@ -0,0 +1,249 @@
+/*
+ * kis_paintop_box.cpp - part of KImageShop/Krayon/Chalk
+ *
+ * Copyright (c) 2004 Boudewijn Rempt (boud@valdyas.org)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqwidget.h>
+#include <tqstring.h>
+#include <tqvaluelist.h>
+#include <tqpixmap.h>
+#include <tqlayout.h>
+#include <tqtooltip.h>
+
+#include <tdelocale.h>
+#include <tdeactioncollection.h>
+#include <kdebug.h>
+#include <tdeglobal.h>
+#include <tdelocale.h>
+#include <tdeglobalsettings.h>
+#include <tdeaccelmanager.h>
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+
+#include <kis_paintop_registry.h>
+#include <kis_view.h>
+#include <kis_painter.h>
+#include <kis_paintop.h>
+#include <kis_layer.h>
+#include <kis_factory.h>
+
+#include "kis_paintop_box.h"
+
+KisPaintopBox::KisPaintopBox (KisView * view, TQWidget *parent, const char * name)
+ : super (parent, name),
+ m_canvasController(view->getCanvasController())
+{
+#if TDE_VERSION >= TDE_MAKE_VERSION(3,3,90)
+ TDEAcceleratorManager::setNoAccel(this);
+#endif
+
+ Q_ASSERT(m_canvasController != 0);
+
+ setCaption(i18n("Painter's Toolchest"));
+ m_optionWidget = 0;
+ m_paintops = new TQValueList<KisID>();
+ m_displayedOps = new TQValueList<KisID>();
+
+ m_cmbPaintops = new TQComboBox(this, "KisPaintopBox::m_cmbPaintops");
+ m_cmbPaintops->setMinimumWidth(150);
+ TQToolTip::add(m_cmbPaintops, i18n("Styles of painting for the painting tools"));
+ m_layout = new TQHBoxLayout(this, 1, 1);
+ m_layout->addWidget(m_cmbPaintops);
+
+ connect(this, TQT_SIGNAL(selected(const KisID &, const KisPaintOpSettings *)), view, TQT_SLOT(paintopActivated(const KisID &, const KisPaintOpSettings *)));
+ connect(m_cmbPaintops, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotItemSelected(int)));
+
+ // XXX: Let's see... Are all paintops loaded and ready?
+ KisIDList keys = KisPaintOpRegistry::instance()->listKeys();
+ for ( KisIDList::Iterator it = keys.begin(); it != keys.end(); ++it ) {
+ // add all paintops, and show/hide them afterwards
+ addItem(*it);
+ }
+
+ connect(view, TQT_SIGNAL(currentColorSpaceChanged(KisColorSpace*)),
+ this, TQT_SLOT(colorSpaceChanged(KisColorSpace*)));
+ connect(view, TQT_SIGNAL(sigInputDeviceChanged(const KisInputDevice&)),
+ this, TQT_SLOT(slotInputDeviceChanged(const KisInputDevice&)));
+
+ setCurrentPaintop(defaultPaintop(m_canvasController->currentInputDevice()));
+}
+
+KisPaintopBox::~KisPaintopBox()
+{
+ delete m_paintops;
+ delete m_displayedOps;
+}
+
+void KisPaintopBox::addItem(const KisID & paintop, const TQString & /*category*/)
+{
+ m_paintops->append(paintop);
+}
+
+void KisPaintopBox::slotItemSelected(int index)
+{
+ if ((uint)index > m_displayedOps->count()) {
+ return;
+ }
+
+ KisID paintop = *m_displayedOps->at(index);
+
+ setCurrentPaintop(paintop);
+}
+
+void KisPaintopBox::colorSpaceChanged(KisColorSpace *cs)
+{
+ TQValueList<KisID>::iterator it = m_paintops->begin();
+ TQValueList<KisID>::iterator end = m_paintops->end();
+ m_displayedOps->clear();
+ m_cmbPaintops->clear();
+
+ for ( ; it != end; ++it ) {
+ if (KisPaintOpRegistry::instance()->userVisible(*it, cs)) {
+ TQPixmap pm = paintopPixmap(*it);
+ if (pm.isNull()) {
+ TQPixmap p = TQPixmap( 16, 16 );
+ p.fill();
+ m_cmbPaintops->insertItem(p, (*it).name());
+ }
+ else {
+ m_cmbPaintops->insertItem(pm, (*it).name());
+ }
+ m_displayedOps->append(*it);
+ }
+ }
+
+ int index = m_displayedOps->findIndex(currentPaintop());
+
+ if (index == -1) {
+ // Must change the paintop as the current one is not supported
+ // by the new colourspace.
+ index = 0;
+ }
+
+ m_cmbPaintops->setCurrentItem( index );
+ slotItemSelected( index );
+}
+
+TQPixmap KisPaintopBox::paintopPixmap(const KisID & paintop)
+{
+ TQString pixmapName = KisPaintOpRegistry::instance()->pixmap(paintop);
+
+ if (pixmapName.isEmpty()) {
+ return TQPixmap();
+ }
+
+ TQString fname = KisFactory::instance()->dirs()->findResource("kis_images", pixmapName);
+
+ return TQPixmap(fname);
+}
+
+void KisPaintopBox::slotInputDeviceChanged(const KisInputDevice & inputDevice)
+{
+ KisID paintop;
+ InputDevicePaintopMap::iterator it = m_currentID.find(inputDevice);
+
+ if (it == m_currentID.end()) {
+ paintop = defaultPaintop(inputDevice);
+ } else {
+ paintop = (*it).second;
+ }
+
+ int index = m_displayedOps->findIndex(paintop);
+
+ if (index == -1) {
+ // Must change the paintop as the current one is not supported
+ // by the new colourspace.
+ index = 0;
+ paintop = *m_displayedOps->at(index);
+ }
+
+ m_cmbPaintops->setCurrentItem(index);
+ setCurrentPaintop(paintop);
+}
+
+void KisPaintopBox::updateOptionWidget()
+{
+ if (m_optionWidget != 0) {
+ m_layout->remove(m_optionWidget);
+ m_optionWidget->hide();
+ m_layout->invalidate();
+ }
+
+ const KisPaintOpSettings *settings = paintopSettings(currentPaintop(), m_canvasController->currentInputDevice());
+
+ if (settings != 0) {
+ m_optionWidget = settings->widget();
+ Q_ASSERT(m_optionWidget != 0);
+
+ m_layout->addWidget(m_optionWidget);
+ updateGeometry();
+ m_optionWidget->show();
+ }
+}
+
+const KisID& KisPaintopBox::currentPaintop()
+{
+ return m_currentID[m_canvasController->currentInputDevice()];
+}
+
+void KisPaintopBox::setCurrentPaintop(const KisID & paintop)
+{
+ m_currentID[m_canvasController->currentInputDevice()] = paintop;
+
+ updateOptionWidget();
+
+ emit selected(paintop, paintopSettings(paintop, m_canvasController->currentInputDevice()));
+}
+
+KisID KisPaintopBox::defaultPaintop(const KisInputDevice& inputDevice)
+{
+ if (inputDevice == KisInputDevice::eraser()) {
+ return KisID("eraser","");
+ } else {
+ return KisID("paintbrush","");
+ }
+}
+
+const KisPaintOpSettings *KisPaintopBox::paintopSettings(const KisID & paintop, const KisInputDevice & inputDevice)
+{
+ TQValueVector<KisPaintOpSettings *> settingsArray;
+ InputDevicePaintopSettingsMap::iterator it = m_inputDevicePaintopSettings.find(inputDevice);
+
+ if (it == m_inputDevicePaintopSettings.end()) {
+ // Create settings for each paintop.
+
+ for (TQValueList<KisID>::const_iterator pit = m_paintops->begin(); pit != m_paintops->end(); ++pit) {
+ KisPaintOpSettings *settings = KisPaintOpRegistry::instance()->settings(*pit, this, inputDevice);
+ settingsArray.append(settings);
+ if (settings && settings->widget()) {
+ settings->widget()->hide();
+ }
+ }
+ m_inputDevicePaintopSettings[inputDevice] = settingsArray;
+ } else {
+ settingsArray = (*it).second;
+ }
+
+ const int index = m_paintops->findIndex(paintop);
+ if (index >= 0 && index < (int)settingsArray.count())
+ return settingsArray[index];
+ else
+ return 0;
+}
+
+#include "kis_paintop_box.moc"
+
diff --git a/chalk/ui/kis_palette_view.cc b/chalk/ui/kis_palette_view.cpp
index 2e17f651a..2e17f651a 100644
--- a/chalk/ui/kis_palette_view.cc
+++ b/chalk/ui/kis_palette_view.cpp
diff --git a/chalk/ui/kis_palette_widget.cc b/chalk/ui/kis_palette_widget.cpp
index e04b04942..e04b04942 100644
--- a/chalk/ui/kis_palette_widget.cc
+++ b/chalk/ui/kis_palette_widget.cpp
diff --git a/chalk/ui/kis_part_layer.cc b/chalk/ui/kis_part_layer.cpp
index 4c05360eb..4c05360eb 100644
--- a/chalk/ui/kis_part_layer.cc
+++ b/chalk/ui/kis_part_layer.cpp
diff --git a/chalk/ui/kis_part_layer_handler.cc b/chalk/ui/kis_part_layer_handler.cpp
index d44f928a8..d44f928a8 100644
--- a/chalk/ui/kis_part_layer_handler.cc
+++ b/chalk/ui/kis_part_layer_handler.cpp
diff --git a/chalk/ui/kis_pattern_chooser.cc b/chalk/ui/kis_pattern_chooser.cpp
index 741cba653..741cba653 100644
--- a/chalk/ui/kis_pattern_chooser.cc
+++ b/chalk/ui/kis_pattern_chooser.cpp
diff --git a/chalk/ui/kis_previewdialog.cc b/chalk/ui/kis_previewdialog.cc
deleted file mode 100644
index d67d5e58b..000000000
--- a/chalk/ui/kis_previewdialog.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * kis_previewdialog.cc - part of Chalk
- *
- * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqframe.h>
-#include <tqhbox.h>
-#include <tqgroupbox.h>
-#include <tqlayout.h>
-
-#include "kis_previewwidget.h"
-#include "kis_previewdialog.h"
-
-KisPreviewDialog::KisPreviewDialog( TQWidget * parent, const char * name, bool modal, const TQString &caption)
- : super (parent, name, modal, caption, Ok | Cancel, Ok)
-{
- TQHBox* layout = new TQHBox(this);
- layout->setSpacing( 6 );
-
- m_containerFrame = new TQFrame( layout, "container" );
-
- m_preview = new KisPreviewWidget( layout, "previewWidget" );
-
- setMainWidget(layout);
-}
-
-KisPreviewDialog::~KisPreviewDialog()
-{
-
-}
-
-#include "kis_previewdialog.moc"
diff --git a/chalk/ui/kis_previewdialog.cpp b/chalk/ui/kis_previewdialog.cpp
new file mode 100644
index 000000000..cfbe05b23
--- /dev/null
+++ b/chalk/ui/kis_previewdialog.cpp
@@ -0,0 +1,46 @@
+/*
+ * kis_previewdialog.cpp - part of Chalk
+ *
+ * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqframe.h>
+#include <tqhbox.h>
+#include <tqgroupbox.h>
+#include <tqlayout.h>
+
+#include "kis_previewwidget.h"
+#include "kis_previewdialog.h"
+
+KisPreviewDialog::KisPreviewDialog( TQWidget * parent, const char * name, bool modal, const TQString &caption)
+ : super (parent, name, modal, caption, Ok | Cancel, Ok)
+{
+ TQHBox* layout = new TQHBox(this);
+ layout->setSpacing( 6 );
+
+ m_containerFrame = new TQFrame( layout, "container" );
+
+ m_preview = new KisPreviewWidget( layout, "previewWidget" );
+
+ setMainWidget(layout);
+}
+
+KisPreviewDialog::~KisPreviewDialog()
+{
+
+}
+
+#include "kis_previewdialog.moc"
diff --git a/chalk/ui/kis_previewwidget.cc b/chalk/ui/kis_previewwidget.cc
deleted file mode 100644
index 29a91fbdb..000000000
--- a/chalk/ui/kis_previewwidget.cc
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- * kis_previewwidget.cc - part of Chalk
- *
- * Copyright (c) 2001 John Califf <jwcaliff@compuzone.net>
- * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
- * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
- * Copyright (c) 2007 Ben Schleimer <bensch128@yahoo.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include <tqcheckbox.h>
-#include <tqradiobutton.h>
-#include <tqpainter.h>
-#include <tqpoint.h>
-#include <tqpushbutton.h>
-#include <tqlayout.h>
-#include <tqlabel.h>
-#include <tqapplication.h>
-#include <tqcolor.h>
-#include <tqgroupbox.h>
-#include <tqcursor.h>
-#include <tqtimer.h>
-
-#include <kdebug.h>
-#include <kiconloader.h>
-#include <kpushbutton.h>
-
-#include <kis_cursor.h>
-#include <kis_colorspace.h>
-#include <kis_colorspace_factory_registry.h>
-#include <kis_config.h>
-#include <kis_filter_strategy.h>
-#include <kis_global.h>
-#include <kis_image.h>
-#include <kis_layer.h>
-#include <kis_paint_layer.h>
-#include <kis_group_layer.h>
-#include <kis_meta_registry.h>
-#include <kis_painter.h>
-#include <kis_profile.h>
-#include <kis_types.h>
-#include <kis_undo_adapter.h>
-#include <kis_label_progress.h>
-#include <kis_selection.h>
-#include <kis_transform_worker.h>
-
-#include "kis_previewwidgetbase.h"
-#include "kis_previewwidget.h"
-#include "imageviewer.h"
-
-static const int ZOOM_PAUSE = 100;
-static const int FILTER_PAUSE = 500;
-static const double ZOOM_FACTOR = 1.1;
-
-KisPreviewWidget::KisPreviewWidget( TQWidget* parent, const char* name )
- : PreviewWidgetBase( parent, name )
- , m_autoupdate(true)
- , m_previewIsDisplayed(true)
- , m_scaledOriginal()
- , m_dirtyOriginal(true)
- , m_origDevice(new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getRGB8(), "temp"))
- , m_scaledPreview()
- , m_dirtyPreview(true)
- , m_previewDevice(new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getRGB8(), "temp"))
- , m_scaledImage(NULL)
- , m_filterZoom(1.0)
- , m_zoom(-1.0)
- , m_profile(NULL)
- , m_progress( 0 )
- , m_zoomTimer(new TQTimer(this))
- , m_filterTimer(new TQTimer(this))
- , m_firstFilter(true)
- , m_firstZoom(true)
-{
- btnZoomIn->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-in", TDEIcon::MainToolbar, 16 ));
- connect(btnZoomIn, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomIn()));
- btnZoomOut->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-out", TDEIcon::MainToolbar, 16 ));
- connect(btnZoomOut, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomOut()));
- btnUpdate->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "reload", TDEIcon::MainToolbar, 16 ));
- connect(btnUpdate, TQT_SIGNAL(clicked()), this, TQT_SLOT(forceUpdate()));
-
- connect(radioBtnPreview, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(setPreviewDisplayed(bool)));
-
- connect(checkBoxAutoUpdate, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetAutoUpdate(bool)));
- btnZoomOneToOne->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-original", TDEIcon::MainToolbar, 16 ));
- connect(btnZoomOneToOne, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomOneToOne()));
-
- m_progress = new KisLabelProgress(frmProgress);
- m_progress->setMaximumHeight(fontMetrics().height() );
- TQVBoxLayout *vbox = new TQVBoxLayout( frmProgress );
- vbox->addWidget(m_progress);
- m_progress->hide();
-
- connect(m_zoomTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(updateZoom()));
- connect(m_filterTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(runFilterHelper()));
-
-/* kToolBar1->insertLineSeparator();
- kToolBar1->insertButton("reload",2, true, i18n("Update"));
- connect(kToolBar1->getButton(2),TQT_SIGNAL(clicked()),this,TQT_SLOT(forceUpdate()));
-
- kToolBar1->insertButton("",3, true, i18n("Auto Update"));
- connect(kToolBar1->getButton(3),TQT_SIGNAL(clicked()),this,TQT_SLOT(toggleAutoUpdate()));
-
- kToolBar1->insertButton("",4, true, i18n("Switch"));
- connect(kToolBar1->getButton(4),TQT_SIGNAL(clicked()),this,TQT_SLOT(toggleImageDisplayed()));*/
-// these currently don't yet work, reenable when they do work :) (TZ-12-2005)
-// TODO reenable these
-// kToolBar1->insertButton("",5, true, i18n("Popup Original and Preview"));
-}
-
-KisPreviewWidget::~KisPreviewWidget() { }
-
-void KisPreviewWidget::forceUpdate()
-{
- if(m_previewIsDisplayed)
- {
- m_groupBox->setTitle(m_origDevice->name());
- emit updated();
- }
-}
-
-void KisPreviewWidget::slotSetDevice(KisPaintDeviceSP dev)
-{
- Q_ASSERT( dev );
-
- if (!dev) return;
-
- m_origDevice = dev;
- m_previewDevice = dev;
- m_filterZoom = 1.0;
-
- KisConfig cfg;
- TQString monitorProfileName = cfg.monitorProfile();
- m_profile = KisMetaRegistry::instance()->csRegistry()->getProfileByName(monitorProfileName);
-
- TQRect r = dev->exactBounds();
-
- m_groupBox->setTitle(i18n("Preview: ") + dev->name());
- m_previewIsDisplayed = true;
-
- m_zoom = -1.0;
- zoomChanged(double(m_preview->width()) / double(r.width()) );
-}
-
-void KisPreviewWidget::updateZoom()
-{
- TQApplication::setOverrideCursor(KisCursor::waitCursor());
-
- if(m_previewIsDisplayed)
- {
- if(m_dirtyPreview)
- {
- TQSize r = m_previewDevice->extent().size();
- int w = r.width(), h = r.height();
- int sw = int(ceil(m_zoom * w / m_filterZoom));
- int sh = int(ceil(m_zoom * h / m_filterZoom));
- m_dirtyPreview = false;
- m_scaledPreview = m_previewDevice->convertToTQImage(m_profile, 0, 0, w, h);
- m_scaledPreview = m_scaledPreview.scale(sw,sh, TQ_ScaleMax); // Use scale instead of smoothScale for speed up
- }
- m_preview->setImage(m_scaledPreview);
- } else
- {
- if(m_dirtyOriginal)
- {
- TQSize r = m_origDevice->extent().size();
- int w = r.width(), h = r.height();
- int sw = int(ceil(m_zoom * w));
- int sh = int(ceil(m_zoom * h));
- m_dirtyOriginal = false;
- m_scaledOriginal = m_origDevice->convertToTQImage(m_profile, 0, 0, w, h);
- m_scaledOriginal = m_scaledOriginal.scale(sw,sh, TQ_ScaleMax); // Use scale instead of smoothScale for speed up
- }
- m_preview->setImage(m_scaledOriginal);
- }
-
- TQApplication::restoreOverrideCursor();
-}
-
-void KisPreviewWidget::slotSetAutoUpdate(bool set) {
- m_autoupdate = set;
-}
-
-void KisPreviewWidget::wheelEvent(TQWheelEvent * e)
-{
- if (e->delta() > 0) {
- zoomIn();
- } else {
- zoomOut();
- }
- e->accept();
-}
-
-void KisPreviewWidget::setPreviewDisplayed(bool v)
-{
- if(v != m_previewIsDisplayed)
- {
- m_previewIsDisplayed = v;
- if(m_previewIsDisplayed) {
- m_groupBox->setTitle(i18n("Preview: ") + m_origDevice->name());
- } else {
- m_groupBox->setTitle(i18n("Original: ") + m_origDevice->name());
- }
- // Call directly without any pause because there is no scaling
- updateZoom();
- }
-}
-
-void KisPreviewWidget::needUpdate()
-{
- if(m_previewIsDisplayed)
- m_groupBox->setTitle(i18n("Preview (needs update)"));
-}
-
-bool KisPreviewWidget::getAutoUpdate() const {
- return m_autoupdate;
-}
-
-void KisPreviewWidget::zoomChanged(const double zoom)
-{
- // constrain the zoom
- double tZoom = zoom;
- if(zoom <= 1./8.) { tZoom = 1./8.; }
- if(zoom > 8.) { tZoom = 8.; }
-
- if(tZoom != m_zoom)
- {
- m_zoom = tZoom;
- m_dirtyOriginal = true;
- m_dirtyPreview = true;
-
- if(m_firstZoom) {
- m_firstZoom = false;
- updateZoom();
- } else {
- m_zoomTimer->start(ZOOM_PAUSE, true);
- }
- }
-}
-
-void KisPreviewWidget::zoomIn() {
- zoomChanged(m_zoom * ZOOM_FACTOR);
-}
-
-void KisPreviewWidget::zoomOut() {
- zoomChanged(m_zoom / ZOOM_FACTOR);
-}
-
-void KisPreviewWidget::zoomOneToOne() {
- zoomChanged(1.0);
-}
-
-static inline void cropDevice(KisPaintDevice * device, const double & zoom) {
- TQRect r = device->exactBounds();
- r.setX(int(zoom * r.x()) );
- r.setY(int(zoom * r.y()) );
- r.setWidth(int(zoom * r.width()) );
- r.setHeight(int(zoom * r.height()) );
- device->crop(r);
-}
-
-class MyCropVisitor : public KisLayerVisitor {
- const double m_zoom;
-
-public:
- MyCropVisitor(const double & z) : m_zoom(z) { }
- virtual ~MyCropVisitor() { }
-
- virtual bool visit(KisPaintLayer *layer) {
- KisPaintDeviceSP device = layer->paintDevice();
- ::cropDevice(device.data(), m_zoom);
- // Make sure we have a tight fit for the selection
- if(device->hasSelection()) {
- ::cropDevice(device->selection().data(), m_zoom);
- }
-
- return true;
- }
- virtual bool visit(KisGroupLayer *layer) {
- for(KisLayerSP l = layer->firstChild(); l; l = l->nextSibling()) {
- l->accept(*this);
- }
- return true;
- }
- virtual bool visit(KisPartLayer *) { return true; }
- virtual bool visit(KisAdjustmentLayer *) { return true; }
-};
-
-void KisPreviewWidget::runFilter(KisFilter * filter, KisFilterConfiguration * config) {
- if(!filter) return;
- if(!config) return;
-
- m_filter = filter;
- m_config = config;
-
- if(m_firstFilter) {
- m_firstFilter = false;
- runFilterHelper();
- } else {
- m_filterTimer->start(FILTER_PAUSE, true);
- }
-}
-
-/**
- * XXX: Fix the situations which m_origDevice is NOT associated with a image.
- * If it comes from a adjustment layer or projection or thumbnail. Currently, nothing happens
- */
-void KisPreviewWidget::runFilterHelper() {
-
- m_filterZoom = m_zoom;
- // Dont scale more then 1.0 so we don't waste time in preview widget for large scaling.
- if(m_filterZoom > 1.0) {
- m_filterZoom = 1.0;
- }
-
- KisPaintDeviceSP scaledDevice;
- KisHermiteFilterStrategy strategy;
-
- // Copy the image and scale
- if (m_origDevice->image())
- {
- m_scaledImage = new KisImage(*m_origDevice->image());
- if(!m_origDevice->parentLayer()) return;
- TQString layerName = m_origDevice->parentLayer()->name();
- KisPaintLayerSP pl = ::tqqt_cast<KisPaintLayer*>(m_scaledImage->findLayer(layerName));
- if(!pl) return;
- scaledDevice = pl->paintDevice();
-
- KisSelectionSP select;
- if(scaledDevice->hasSelection())
- {
- select = new KisSelection(*scaledDevice->selection());
- scaledDevice->deselect();
- }
- // Scale
- m_scaledImage->setUndoAdapter(NULL);
- m_scaledImage->scale(m_filterZoom, m_filterZoom, NULL, &strategy);
- // Scale the selection
- if(select)
- {
- KisPaintDeviceSP t = select.data();
- KisTransformWorker tw(t, m_filterZoom, m_filterZoom,
- 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
- tw.run();
- scaledDevice->setSelection(select);
- select->setParentLayer(scaledDevice->parentLayer());
- }
-
- // Crop by the zoom value instead of cropping by rectangle. It gives better results
- MyCropVisitor v(m_filterZoom);
- m_scaledImage->rootLayer()->accept(v);
- } else
- {
- scaledDevice = new KisPaintDevice(*m_origDevice);
- KisSelectionSP select;
- if(scaledDevice->hasSelection())
- {
- select = new KisSelection(*scaledDevice->selection());
- scaledDevice->deselect();
- }
- KisTransformWorker tw(scaledDevice, m_filterZoom, m_filterZoom,
- 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
- tw.run();
- // Scale the selection
- if(select)
- {
- KisPaintDeviceSP t = select.data();
- KisTransformWorker tw(t, m_filterZoom, m_filterZoom,
- 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
- tw.run();
- scaledDevice->setSelection(select);
- ::cropDevice(select.data(), m_filterZoom);
- }
- ::cropDevice(scaledDevice.data(), m_filterZoom);
- }
-
- m_previewDevice = new KisPaintDevice(*scaledDevice);
-
- // Setup the progress display
- m_filter->enableProgress();
- m_progress->setSubject(m_filter, true, true);
- m_filter->setProgressDisplay(m_progress);
- m_filter->process(scaledDevice, m_previewDevice, m_config, scaledDevice->exactBounds());
- m_filter->disableProgress();
-
- m_dirtyPreview = true;
-
- if(m_firstZoom) {
- m_firstZoom = false;
- updateZoom();
- } else {
- m_zoomTimer->start(ZOOM_PAUSE, true);
- }
-}
-
-#include "kis_previewwidget.moc"
diff --git a/chalk/ui/kis_previewwidget.cpp b/chalk/ui/kis_previewwidget.cpp
new file mode 100644
index 000000000..f60755a14
--- /dev/null
+++ b/chalk/ui/kis_previewwidget.cpp
@@ -0,0 +1,409 @@
+/*
+ * kis_previewwidget.cpp - part of Chalk
+ *
+ * Copyright (c) 2001 John Califf <jwcaliff@compuzone.net>
+ * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2007 Ben Schleimer <bensch128@yahoo.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include <tqcheckbox.h>
+#include <tqradiobutton.h>
+#include <tqpainter.h>
+#include <tqpoint.h>
+#include <tqpushbutton.h>
+#include <tqlayout.h>
+#include <tqlabel.h>
+#include <tqapplication.h>
+#include <tqcolor.h>
+#include <tqgroupbox.h>
+#include <tqcursor.h>
+#include <tqtimer.h>
+
+#include <kdebug.h>
+#include <kiconloader.h>
+#include <kpushbutton.h>
+
+#include <kis_cursor.h>
+#include <kis_colorspace.h>
+#include <kis_colorspace_factory_registry.h>
+#include <kis_config.h>
+#include <kis_filter_strategy.h>
+#include <kis_global.h>
+#include <kis_image.h>
+#include <kis_layer.h>
+#include <kis_paint_layer.h>
+#include <kis_group_layer.h>
+#include <kis_meta_registry.h>
+#include <kis_painter.h>
+#include <kis_profile.h>
+#include <kis_types.h>
+#include <kis_undo_adapter.h>
+#include <kis_label_progress.h>
+#include <kis_selection.h>
+#include <kis_transform_worker.h>
+
+#include "kis_previewwidgetbase.h"
+#include "kis_previewwidget.h"
+#include "imageviewer.h"
+
+static const int ZOOM_PAUSE = 100;
+static const int FILTER_PAUSE = 500;
+static const double ZOOM_FACTOR = 1.1;
+
+KisPreviewWidget::KisPreviewWidget( TQWidget* parent, const char* name )
+ : PreviewWidgetBase( parent, name )
+ , m_autoupdate(true)
+ , m_previewIsDisplayed(true)
+ , m_scaledOriginal()
+ , m_dirtyOriginal(true)
+ , m_origDevice(new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getRGB8(), "temp"))
+ , m_scaledPreview()
+ , m_dirtyPreview(true)
+ , m_previewDevice(new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getRGB8(), "temp"))
+ , m_scaledImage(NULL)
+ , m_filterZoom(1.0)
+ , m_zoom(-1.0)
+ , m_profile(NULL)
+ , m_progress( 0 )
+ , m_zoomTimer(new TQTimer(this))
+ , m_filterTimer(new TQTimer(this))
+ , m_firstFilter(true)
+ , m_firstZoom(true)
+{
+ btnZoomIn->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-in", TDEIcon::MainToolbar, 16 ));
+ connect(btnZoomIn, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomIn()));
+ btnZoomOut->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-out", TDEIcon::MainToolbar, 16 ));
+ connect(btnZoomOut, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomOut()));
+ btnUpdate->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "reload", TDEIcon::MainToolbar, 16 ));
+ connect(btnUpdate, TQT_SIGNAL(clicked()), this, TQT_SLOT(forceUpdate()));
+
+ connect(radioBtnPreview, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(setPreviewDisplayed(bool)));
+
+ connect(checkBoxAutoUpdate, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotSetAutoUpdate(bool)));
+ btnZoomOneToOne->setIconSet(TDEGlobal::instance()->iconLoader()->loadIconSet( "zoom-original", TDEIcon::MainToolbar, 16 ));
+ connect(btnZoomOneToOne, TQT_SIGNAL(clicked()), this, TQT_SLOT(zoomOneToOne()));
+
+ m_progress = new KisLabelProgress(frmProgress);
+ m_progress->setMaximumHeight(fontMetrics().height() );
+ TQVBoxLayout *vbox = new TQVBoxLayout( frmProgress );
+ vbox->addWidget(m_progress);
+ m_progress->hide();
+
+ connect(m_zoomTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(updateZoom()));
+ connect(m_filterTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(runFilterHelper()));
+
+/* kToolBar1->insertLineSeparator();
+ kToolBar1->insertButton("reload",2, true, i18n("Update"));
+ connect(kToolBar1->getButton(2),TQT_SIGNAL(clicked()),this,TQT_SLOT(forceUpdate()));
+
+ kToolBar1->insertButton("",3, true, i18n("Auto Update"));
+ connect(kToolBar1->getButton(3),TQT_SIGNAL(clicked()),this,TQT_SLOT(toggleAutoUpdate()));
+
+ kToolBar1->insertButton("",4, true, i18n("Switch"));
+ connect(kToolBar1->getButton(4),TQT_SIGNAL(clicked()),this,TQT_SLOT(toggleImageDisplayed()));*/
+// these currently don't yet work, reenable when they do work :) (TZ-12-2005)
+// TODO reenable these
+// kToolBar1->insertButton("",5, true, i18n("Popup Original and Preview"));
+}
+
+KisPreviewWidget::~KisPreviewWidget() { }
+
+void KisPreviewWidget::forceUpdate()
+{
+ if(m_previewIsDisplayed)
+ {
+ m_groupBox->setTitle(m_origDevice->name());
+ emit updated();
+ }
+}
+
+void KisPreviewWidget::slotSetDevice(KisPaintDeviceSP dev)
+{
+ Q_ASSERT( dev );
+
+ if (!dev) return;
+
+ m_origDevice = dev;
+ m_previewDevice = dev;
+ m_filterZoom = 1.0;
+
+ KisConfig cfg;
+ TQString monitorProfileName = cfg.monitorProfile();
+ m_profile = KisMetaRegistry::instance()->csRegistry()->getProfileByName(monitorProfileName);
+
+ TQRect r = dev->exactBounds();
+
+ m_groupBox->setTitle(i18n("Preview: ") + dev->name());
+ m_previewIsDisplayed = true;
+
+ m_zoom = -1.0;
+ zoomChanged(double(m_preview->width()) / double(r.width()) );
+}
+
+void KisPreviewWidget::updateZoom()
+{
+ TQApplication::setOverrideCursor(KisCursor::waitCursor());
+
+ if(m_previewIsDisplayed)
+ {
+ if(m_dirtyPreview)
+ {
+ TQSize r = m_previewDevice->extent().size();
+ int w = r.width(), h = r.height();
+ int sw = int(ceil(m_zoom * w / m_filterZoom));
+ int sh = int(ceil(m_zoom * h / m_filterZoom));
+ m_dirtyPreview = false;
+ m_scaledPreview = m_previewDevice->convertToTQImage(m_profile, 0, 0, w, h);
+ m_scaledPreview = m_scaledPreview.scale(sw,sh, TQ_ScaleMax); // Use scale instead of smoothScale for speed up
+ }
+ m_preview->setImage(m_scaledPreview);
+ } else
+ {
+ if(m_dirtyOriginal)
+ {
+ TQSize r = m_origDevice->extent().size();
+ int w = r.width(), h = r.height();
+ int sw = int(ceil(m_zoom * w));
+ int sh = int(ceil(m_zoom * h));
+ m_dirtyOriginal = false;
+ m_scaledOriginal = m_origDevice->convertToTQImage(m_profile, 0, 0, w, h);
+ m_scaledOriginal = m_scaledOriginal.scale(sw,sh, TQ_ScaleMax); // Use scale instead of smoothScale for speed up
+ }
+ m_preview->setImage(m_scaledOriginal);
+ }
+
+ TQApplication::restoreOverrideCursor();
+}
+
+void KisPreviewWidget::slotSetAutoUpdate(bool set) {
+ m_autoupdate = set;
+}
+
+void KisPreviewWidget::wheelEvent(TQWheelEvent * e)
+{
+ if (e->delta() > 0) {
+ zoomIn();
+ } else {
+ zoomOut();
+ }
+ e->accept();
+}
+
+void KisPreviewWidget::setPreviewDisplayed(bool v)
+{
+ if(v != m_previewIsDisplayed)
+ {
+ m_previewIsDisplayed = v;
+ if(m_previewIsDisplayed) {
+ m_groupBox->setTitle(i18n("Preview: ") + m_origDevice->name());
+ } else {
+ m_groupBox->setTitle(i18n("Original: ") + m_origDevice->name());
+ }
+ // Call directly without any pause because there is no scaling
+ updateZoom();
+ }
+}
+
+void KisPreviewWidget::needUpdate()
+{
+ if(m_previewIsDisplayed)
+ m_groupBox->setTitle(i18n("Preview (needs update)"));
+}
+
+bool KisPreviewWidget::getAutoUpdate() const {
+ return m_autoupdate;
+}
+
+void KisPreviewWidget::zoomChanged(const double zoom)
+{
+ // constrain the zoom
+ double tZoom = zoom;
+ if(zoom <= 1./8.) { tZoom = 1./8.; }
+ if(zoom > 8.) { tZoom = 8.; }
+
+ if(tZoom != m_zoom)
+ {
+ m_zoom = tZoom;
+ m_dirtyOriginal = true;
+ m_dirtyPreview = true;
+
+ if(m_firstZoom) {
+ m_firstZoom = false;
+ updateZoom();
+ } else {
+ m_zoomTimer->start(ZOOM_PAUSE, true);
+ }
+ }
+}
+
+void KisPreviewWidget::zoomIn() {
+ zoomChanged(m_zoom * ZOOM_FACTOR);
+}
+
+void KisPreviewWidget::zoomOut() {
+ zoomChanged(m_zoom / ZOOM_FACTOR);
+}
+
+void KisPreviewWidget::zoomOneToOne() {
+ zoomChanged(1.0);
+}
+
+static inline void cropDevice(KisPaintDevice * device, const double & zoom) {
+ TQRect r = device->exactBounds();
+ r.setX(int(zoom * r.x()) );
+ r.setY(int(zoom * r.y()) );
+ r.setWidth(int(zoom * r.width()) );
+ r.setHeight(int(zoom * r.height()) );
+ device->crop(r);
+}
+
+class MyCropVisitor : public KisLayerVisitor {
+ const double m_zoom;
+
+public:
+ MyCropVisitor(const double & z) : m_zoom(z) { }
+ virtual ~MyCropVisitor() { }
+
+ virtual bool visit(KisPaintLayer *layer) {
+ KisPaintDeviceSP device = layer->paintDevice();
+ ::cropDevice(device.data(), m_zoom);
+ // Make sure we have a tight fit for the selection
+ if(device->hasSelection()) {
+ ::cropDevice(device->selection().data(), m_zoom);
+ }
+
+ return true;
+ }
+ virtual bool visit(KisGroupLayer *layer) {
+ for(KisLayerSP l = layer->firstChild(); l; l = l->nextSibling()) {
+ l->accept(*this);
+ }
+ return true;
+ }
+ virtual bool visit(KisPartLayer *) { return true; }
+ virtual bool visit(KisAdjustmentLayer *) { return true; }
+};
+
+void KisPreviewWidget::runFilter(KisFilter * filter, KisFilterConfiguration * config) {
+ if(!filter) return;
+ if(!config) return;
+
+ m_filter = filter;
+ m_config = config;
+
+ if(m_firstFilter) {
+ m_firstFilter = false;
+ runFilterHelper();
+ } else {
+ m_filterTimer->start(FILTER_PAUSE, true);
+ }
+}
+
+/**
+ * XXX: Fix the situations which m_origDevice is NOT associated with a image.
+ * If it comes from a adjustment layer or projection or thumbnail. Currently, nothing happens
+ */
+void KisPreviewWidget::runFilterHelper() {
+
+ m_filterZoom = m_zoom;
+ // Dont scale more then 1.0 so we don't waste time in preview widget for large scaling.
+ if(m_filterZoom > 1.0) {
+ m_filterZoom = 1.0;
+ }
+
+ KisPaintDeviceSP scaledDevice;
+ KisHermiteFilterStrategy strategy;
+
+ // Copy the image and scale
+ if (m_origDevice->image())
+ {
+ m_scaledImage = new KisImage(*m_origDevice->image());
+ if(!m_origDevice->parentLayer()) return;
+ TQString layerName = m_origDevice->parentLayer()->name();
+ KisPaintLayerSP pl = ::tqqt_cast<KisPaintLayer*>(m_scaledImage->findLayer(layerName));
+ if(!pl) return;
+ scaledDevice = pl->paintDevice();
+
+ KisSelectionSP select;
+ if(scaledDevice->hasSelection())
+ {
+ select = new KisSelection(*scaledDevice->selection());
+ scaledDevice->deselect();
+ }
+ // Scale
+ m_scaledImage->setUndoAdapter(NULL);
+ m_scaledImage->scale(m_filterZoom, m_filterZoom, NULL, &strategy);
+ // Scale the selection
+ if(select)
+ {
+ KisPaintDeviceSP t = select.data();
+ KisTransformWorker tw(t, m_filterZoom, m_filterZoom,
+ 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
+ tw.run();
+ scaledDevice->setSelection(select);
+ select->setParentLayer(scaledDevice->parentLayer());
+ }
+
+ // Crop by the zoom value instead of cropping by rectangle. It gives better results
+ MyCropVisitor v(m_filterZoom);
+ m_scaledImage->rootLayer()->accept(v);
+ } else
+ {
+ scaledDevice = new KisPaintDevice(*m_origDevice);
+ KisSelectionSP select;
+ if(scaledDevice->hasSelection())
+ {
+ select = new KisSelection(*scaledDevice->selection());
+ scaledDevice->deselect();
+ }
+ KisTransformWorker tw(scaledDevice, m_filterZoom, m_filterZoom,
+ 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
+ tw.run();
+ // Scale the selection
+ if(select)
+ {
+ KisPaintDeviceSP t = select.data();
+ KisTransformWorker tw(t, m_filterZoom, m_filterZoom,
+ 0.0, 0.0, 0.0, 0, 0, NULL, &strategy);
+ tw.run();
+ scaledDevice->setSelection(select);
+ ::cropDevice(select.data(), m_filterZoom);
+ }
+ ::cropDevice(scaledDevice.data(), m_filterZoom);
+ }
+
+ m_previewDevice = new KisPaintDevice(*scaledDevice);
+
+ // Setup the progress display
+ m_filter->enableProgress();
+ m_progress->setSubject(m_filter, true, true);
+ m_filter->setProgressDisplay(m_progress);
+ m_filter->process(scaledDevice, m_previewDevice, m_config, scaledDevice->exactBounds());
+ m_filter->disableProgress();
+
+ m_dirtyPreview = true;
+
+ if(m_firstZoom) {
+ m_firstZoom = false;
+ updateZoom();
+ } else {
+ m_zoomTimer->start(ZOOM_PAUSE, true);
+ }
+}
+
+#include "kis_previewwidget.moc"
diff --git a/chalk/ui/kis_qpaintdevice_canvas.cc b/chalk/ui/kis_qpaintdevice_canvas.cpp
index e3824f555..e3824f555 100644
--- a/chalk/ui/kis_qpaintdevice_canvas.cc
+++ b/chalk/ui/kis_qpaintdevice_canvas.cpp
diff --git a/chalk/ui/kis_qpaintdevice_canvas_painter.cc b/chalk/ui/kis_qpaintdevice_canvas_painter.cpp
index 07f78eb9a..07f78eb9a 100644
--- a/chalk/ui/kis_qpaintdevice_canvas_painter.cc
+++ b/chalk/ui/kis_qpaintdevice_canvas_painter.cpp
diff --git a/chalk/ui/kis_resource_mediator.cc b/chalk/ui/kis_resource_mediator.cpp
index ddecf85a6..ddecf85a6 100644
--- a/chalk/ui/kis_resource_mediator.cc
+++ b/chalk/ui/kis_resource_mediator.cpp
diff --git a/chalk/ui/kis_resourceserver.cc b/chalk/ui/kis_resourceserver.cc
deleted file mode 100644
index 3076bc00d..000000000
--- a/chalk/ui/kis_resourceserver.cc
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * kis_resourceserver.cc - part of KImageShop
- *
- * Copyright (c) 1999 Matthias Elter <elter@kde.org>
- * Copyright (c) 2003 Patrick Julien <freak@codepimps.org>
- * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqfileinfo.h>
-#include <tqstringlist.h>
-#include <tqthread.h>
-#include <tqdir.h>
-
-#include <kdebug.h>
-#include <tdeglobal.h>
-#include <kstandarddirs.h>
-#include <kinstance.h>
-
-#include "kis_resource.h"
-#include "kis_factory.h"
-#include "kis_generic_registry.h"
-#include "kis_resourceserver.h"
-#include "kis_brush.h"
-#include "kis_imagepipe_brush.h"
-#include "kis_gradient.h"
-#include "kis_pattern.h"
-#include "kis_palette.h"
-#include <kogradientmanager.h>
-
-KisResourceServerBase::KisResourceServerBase(TQString type)
- : m_type(type), m_loaded(false)
-{
-}
-
-KisResourceServerBase::~KisResourceServerBase()
-{
-}
-
-void KisResourceServerBase::loadResources(TQStringList filenames)
-{
- TQStringList uniqueFiles;
-
- while( !filenames.empty() )
- {
-
- TQString front = *filenames.begin();
- filenames.pop_front();
-
- TQString fname = TQFileInfo(front).fileName();
- //ebug() << "Loading " << fname << "\n";
- // XXX: Don't load resources with the same filename. Actually, we should look inside
- // the resource to find out whether they are really the same, but for now this
- // will prevent the same brush etc. showing up twice.
- if (uniqueFiles.empty() || uniqueFiles.find(fname) == uniqueFiles.end()) {
- uniqueFiles.append(fname);
- KisResource *resource;
- resource = createResource(front);
- if(resource->load() && resource->valid())
- {
- m_resources.append(resource);
- TQ_CHECK_PTR(resource);
- emit resourceAdded(resource);
- }
- else {
- delete resource;
- }
- }
- }
- m_loaded = true;
-}
-
-TQValueList<KisResource*> KisResourceServerBase::resources()
-{
- if(!m_loaded) {
- return TQValueList<KisResource*>();
- }
-
- return m_resources;
-}
-
-void KisResourceServerBase::addResource(KisResource* resource)
-{
- if (!resource->valid()) {
- kdWarning(41001) << "Tried to add an invalid resource!" << endl;
- return;
- }
-
- m_resources.append(resource);
- emit resourceAdded(resource);
-}
-
-
-class ResourceLoaderThread : public TQThread {
-
-public:
-
- ResourceLoaderThread(KisResourceServerBase * server, TQStringList files)
- : TQThread()
- , m_server(server)
- , m_fileNames( files )
- {
- }
-
-
- void run()
- {
- m_server->loadResources(m_fileNames);
- }
-
-private:
-
- KisResourceServerBase * m_server;
- TQStringList m_fileNames;
-
-};
-
-TQStringList getFileNames( TQString extensions, TQString type )
-{
- TQStringList extensionList = TQStringList::split(":", extensions);
- TQStringList fileNames;
-
- TQStringList::Iterator it;
- for ( it = extensionList.begin(); it != extensionList.end(); ++it ) {
- TQString s = (*it);
- fileNames += KisFactory::instance()->dirs()->findAllResources(type.ascii(), (*it));
- }
- return fileNames;
-}
-
-
-KisResourceServerRegistry *KisResourceServerRegistry::m_singleton = 0;
-
-KisResourceServerRegistry::KisResourceServerRegistry()
-{
-
- KisResourceServer<KisBrush>* brushServer = new KisResourceServer<KisBrush>("kis_brushes");
- ResourceLoaderThread t1 (brushServer, getFileNames( "*.gbr","kis_brushes" ));
- t1.start();
-
- KisResourceServer<KisImagePipeBrush>* imagePipeBrushServer = new KisResourceServer<KisImagePipeBrush>("kis_brushes");
- ResourceLoaderThread t2 (imagePipeBrushServer, getFileNames( "*.gih", "kis_brushes"));
- t2.start();
-
- KisResourceServer<KisPattern>* patternServer = new KisResourceServer<KisPattern>("kis_patterns");
- ResourceLoaderThread t3 (patternServer, getFileNames("*.pat", "kis_patterns"));
- t3.start();
-
- KisResourceServer<KisGradient>* gradientServer = new KisResourceServer<KisGradient>("kis_gradients");
- ResourceLoaderThread t4 (gradientServer, getFileNames(KoGradientManager::filters().join( ":" ), "kis_gradients"));
- t4.start();
-
-
- KisResourceServer<KisPalette>* paletteServer = new KisResourceServer<KisPalette>("kis_palettes");
- ResourceLoaderThread t5 (paletteServer, getFileNames("*.gpl:*.pal:*.act", "kis_palettes") );
- t5.start();
-
- t1.wait();
- t2.wait();
- t3.wait();
- t4.wait();
- t5.wait();
-
- add( KisID( "BrushServer", ""), brushServer );
- add( KisID( "ImagePipeBrushServer", ""), imagePipeBrushServer );
- add( KisID( "PatternServer", ""), patternServer );
- add( KisID( "GradientServer", ""), gradientServer );
- add( KisID( "PaletteServer", ""), paletteServer );
-
-}
-
-KisResourceServerRegistry::~KisResourceServerRegistry()
-{
-}
-
-KisResourceServerRegistry* KisResourceServerRegistry::instance()
-{
- if(KisResourceServerRegistry::m_singleton == 0)
- {
- KisResourceServerRegistry::m_singleton = new KisResourceServerRegistry();
- }
- return KisResourceServerRegistry::m_singleton;
-}
-
-
-#include "kis_resourceserver.moc"
-
diff --git a/chalk/ui/kis_resourceserver.cpp b/chalk/ui/kis_resourceserver.cpp
new file mode 100644
index 000000000..333bccd1d
--- /dev/null
+++ b/chalk/ui/kis_resourceserver.cpp
@@ -0,0 +1,199 @@
+/*
+ * kis_resourceserver.cpp - part of KImageShop
+ *
+ * Copyright (c) 1999 Matthias Elter <elter@kde.org>
+ * Copyright (c) 2003 Patrick Julien <freak@codepimps.org>
+ * Copyright (c) 2005 Sven Langkamp <longamp@reallygood.de>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqfileinfo.h>
+#include <tqstringlist.h>
+#include <tqthread.h>
+#include <tqdir.h>
+
+#include <kdebug.h>
+#include <tdeglobal.h>
+#include <kstandarddirs.h>
+#include <kinstance.h>
+
+#include "kis_resource.h"
+#include "kis_factory.h"
+#include "kis_generic_registry.h"
+#include "kis_resourceserver.h"
+#include "kis_brush.h"
+#include "kis_imagepipe_brush.h"
+#include "kis_gradient.h"
+#include "kis_pattern.h"
+#include "kis_palette.h"
+#include <kogradientmanager.h>
+
+KisResourceServerBase::KisResourceServerBase(TQString type)
+ : m_type(type), m_loaded(false)
+{
+}
+
+KisResourceServerBase::~KisResourceServerBase()
+{
+}
+
+void KisResourceServerBase::loadResources(TQStringList filenames)
+{
+ TQStringList uniqueFiles;
+
+ while( !filenames.empty() )
+ {
+
+ TQString front = *filenames.begin();
+ filenames.pop_front();
+
+ TQString fname = TQFileInfo(front).fileName();
+ //ebug() << "Loading " << fname << "\n";
+ // XXX: Don't load resources with the same filename. Actually, we should look inside
+ // the resource to find out whether they are really the same, but for now this
+ // will prevent the same brush etc. showing up twice.
+ if (uniqueFiles.empty() || uniqueFiles.find(fname) == uniqueFiles.end()) {
+ uniqueFiles.append(fname);
+ KisResource *resource;
+ resource = createResource(front);
+ if(resource->load() && resource->valid())
+ {
+ m_resources.append(resource);
+ TQ_CHECK_PTR(resource);
+ emit resourceAdded(resource);
+ }
+ else {
+ delete resource;
+ }
+ }
+ }
+ m_loaded = true;
+}
+
+TQValueList<KisResource*> KisResourceServerBase::resources()
+{
+ if(!m_loaded) {
+ return TQValueList<KisResource*>();
+ }
+
+ return m_resources;
+}
+
+void KisResourceServerBase::addResource(KisResource* resource)
+{
+ if (!resource->valid()) {
+ kdWarning(41001) << "Tried to add an invalid resource!" << endl;
+ return;
+ }
+
+ m_resources.append(resource);
+ emit resourceAdded(resource);
+}
+
+
+class ResourceLoaderThread : public TQThread {
+
+public:
+
+ ResourceLoaderThread(KisResourceServerBase * server, TQStringList files)
+ : TQThread()
+ , m_server(server)
+ , m_fileNames( files )
+ {
+ }
+
+
+ void run()
+ {
+ m_server->loadResources(m_fileNames);
+ }
+
+private:
+
+ KisResourceServerBase * m_server;
+ TQStringList m_fileNames;
+
+};
+
+TQStringList getFileNames( TQString extensions, TQString type )
+{
+ TQStringList extensionList = TQStringList::split(":", extensions);
+ TQStringList fileNames;
+
+ TQStringList::Iterator it;
+ for ( it = extensionList.begin(); it != extensionList.end(); ++it ) {
+ TQString s = (*it);
+ fileNames += KisFactory::instance()->dirs()->findAllResources(type.ascii(), (*it));
+ }
+ return fileNames;
+}
+
+
+KisResourceServerRegistry *KisResourceServerRegistry::m_singleton = 0;
+
+KisResourceServerRegistry::KisResourceServerRegistry()
+{
+
+ KisResourceServer<KisBrush>* brushServer = new KisResourceServer<KisBrush>("kis_brushes");
+ ResourceLoaderThread t1 (brushServer, getFileNames( "*.gbr","kis_brushes" ));
+ t1.start();
+
+ KisResourceServer<KisImagePipeBrush>* imagePipeBrushServer = new KisResourceServer<KisImagePipeBrush>("kis_brushes");
+ ResourceLoaderThread t2 (imagePipeBrushServer, getFileNames( "*.gih", "kis_brushes"));
+ t2.start();
+
+ KisResourceServer<KisPattern>* patternServer = new KisResourceServer<KisPattern>("kis_patterns");
+ ResourceLoaderThread t3 (patternServer, getFileNames("*.pat", "kis_patterns"));
+ t3.start();
+
+ KisResourceServer<KisGradient>* gradientServer = new KisResourceServer<KisGradient>("kis_gradients");
+ ResourceLoaderThread t4 (gradientServer, getFileNames(KoGradientManager::filters().join( ":" ), "kis_gradients"));
+ t4.start();
+
+
+ KisResourceServer<KisPalette>* paletteServer = new KisResourceServer<KisPalette>("kis_palettes");
+ ResourceLoaderThread t5 (paletteServer, getFileNames("*.gpl:*.pal:*.act", "kis_palettes") );
+ t5.start();
+
+ t1.wait();
+ t2.wait();
+ t3.wait();
+ t4.wait();
+ t5.wait();
+
+ add( KisID( "BrushServer", ""), brushServer );
+ add( KisID( "ImagePipeBrushServer", ""), imagePipeBrushServer );
+ add( KisID( "PatternServer", ""), patternServer );
+ add( KisID( "GradientServer", ""), gradientServer );
+ add( KisID( "PaletteServer", ""), paletteServer );
+
+}
+
+KisResourceServerRegistry::~KisResourceServerRegistry()
+{
+}
+
+KisResourceServerRegistry* KisResourceServerRegistry::instance()
+{
+ if(KisResourceServerRegistry::m_singleton == 0)
+ {
+ KisResourceServerRegistry::m_singleton = new KisResourceServerRegistry();
+ }
+ return KisResourceServerRegistry::m_singleton;
+}
+
+
+#include "kis_resourceserver.moc"
+
diff --git a/chalk/ui/kis_ruler.cc b/chalk/ui/kis_ruler.cpp
index 234269227..234269227 100644
--- a/chalk/ui/kis_ruler.cc
+++ b/chalk/ui/kis_ruler.cpp
diff --git a/chalk/ui/kis_selection_manager.cc b/chalk/ui/kis_selection_manager.cpp
index 7d001586a..7d001586a 100644
--- a/chalk/ui/kis_selection_manager.cc
+++ b/chalk/ui/kis_selection_manager.cpp
diff --git a/chalk/ui/kis_selection_options.cc b/chalk/ui/kis_selection_options.cpp
index 8593d22ae..8593d22ae 100644
--- a/chalk/ui/kis_selection_options.cc
+++ b/chalk/ui/kis_selection_options.cpp
diff --git a/chalk/ui/kis_text_brush.cc b/chalk/ui/kis_text_brush.cpp
index 8666f1a19..8666f1a19 100644
--- a/chalk/ui/kis_text_brush.cc
+++ b/chalk/ui/kis_text_brush.cpp
diff --git a/chalk/ui/kis_tool.cc b/chalk/ui/kis_tool.cpp
index 026747417..026747417 100644
--- a/chalk/ui/kis_tool.cc
+++ b/chalk/ui/kis_tool.cpp
diff --git a/chalk/ui/kis_tool_dummy.cc b/chalk/ui/kis_tool_dummy.cpp
index 759136f44..759136f44 100644
--- a/chalk/ui/kis_tool_dummy.cc
+++ b/chalk/ui/kis_tool_dummy.cpp
diff --git a/chalk/ui/kis_tool_freehand.cc b/chalk/ui/kis_tool_freehand.cc
deleted file mode 100644
index 787afee47..000000000
--- a/chalk/ui/kis_tool_freehand.cc
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * kis_tool_brush.cc - part of Chalk
- *
- * Copyright (c) 2003-2004 Boudewijn Rempt <boud@valdyas.org>
- * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include <tqevent.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqwidget.h>
-#include <tqrect.h>
-
-#include <kdebug.h>
-#include <tdeaction.h>
-#include <kcommand.h>
-#include <tdelocale.h>
-
-#include "kis_canvas_subject.h"
-#include "kis_undo_adapter.h"
-#include "kis_selection.h"
-#include "kis_painter.h"
-#include "kis_fill_painter.h"
-#include "kis_tool_freehand.h"
-#include "kis_cursor.h"
-#include "kis_button_press_event.h"
-#include "kis_button_release_event.h"
-#include "kis_move_event.h"
-#include "kis_layer.h"
-#include "kis_group_layer.h"
-#include "kis_paint_layer.h"
-#include "kis_canvas.h"
-#include "kis_canvas_painter.h"
-#include "kis_boundary_painter.h"
-#include "kis_brush.h"
-
-KisToolFreehand::KisToolFreehand(TQString transactionText)
- : super(transactionText),
- m_dragDist ( 0 ),
- m_transactionText(transactionText),
- m_mode( HOVER )
-{
- m_painter = 0;
- m_currentImage = 0;
- m_tempLayer = 0;
- m_paintIncremental = true;
- m_paintOnSelection = false;
- m_paintedOutline = false;
-}
-
-KisToolFreehand::~KisToolFreehand()
-{
-}
-
-void KisToolFreehand::update(KisCanvasSubject *subject)
-{
- super::update(subject);
- m_currentImage = m_subject->currentImg();
-}
-
-void KisToolFreehand::buttonPress(KisButtonPressEvent *e)
-{
- if (!m_subject) return;
-
- if (!m_subject->currentBrush()) return;
-
- if (!m_currentImage || !m_currentImage->activeDevice()) return;
-
- if (e->button() == Qt::LeftButton) {
-
- m_currentImage->activeDevice()->lock( true );
- kdDebug() << ">>>>>>>>>>>>>>>>>>>Locking paint device\n";
-
- // People complain that they can't start brush strokes outside of the image boundaries.
- // This makes sense, especially when combined with BUG:132759, so commenting out the
- // next line makes sense.
- //if (!m_currentImage->bounds().contains(e->pos().floorTQPoint())) return;
-
- initPaint(e);
- paintAt(e->pos(), e->pressure(), e->xTilt(), e->yTilt());
-
- m_prevPos = e->pos();
- m_prevPressure = e->pressure();
- m_prevXTilt = e->xTilt();
- m_prevYTilt = e->yTilt();
-
- TQRect r = m_painter->dirtyRect();
- if ( r.isValid() ) {
- m_dirtyRect = r;
-
- r = TQRect(r.left()-1, r.top()-1, r.width()+2, r.height()+2); //needed to update selectionvisualization
- if (!m_paintOnSelection) {
- m_currentImage->activeLayer()->setDirty(r);
- }
- else {
- m_target->setDirty(r);
- // Just update the canvas. XXX: After 1.5, find a better way to make sure tools don't set dirty what they didn't touch.
- m_subject->canvasController()->updateCanvas( r );
- }
- }
- }
-}
-
-void KisToolFreehand::buttonRelease(KisButtonReleaseEvent* e)
-{
- if (e->button() == Qt::LeftButton && m_mode == PAINT) {
- endPaint();
- m_currentImage->activeDevice()->lock( false );
- kdDebug() << ">>>>>>>>>>>>>>>>>>>UNLocking paint device\n";
-
- }
- KisToolPaint::buttonRelease(e);
-}
-
-void KisToolFreehand::move(KisMoveEvent *e)
-{
- if (m_mode == PAINT) {
-
- paintLine(m_prevPos, m_prevPressure, m_prevXTilt, m_prevYTilt, e->pos(), e->pressure(), e->xTilt(), e->yTilt());
-
- m_prevPos = e->pos();
- m_prevPressure = e->pressure();
- m_prevXTilt = e->xTilt();
- m_prevYTilt = e->yTilt();
-
- TQRect r = m_painter->dirtyRect();
-
- if (r.isValid()) {
- m_dirtyRect |= r;
-
- if (!m_paintOnSelection) {
- m_currentImage->activeLayer()->setDirty(r);
- }
- else {
- // Just update the canvas
- r = TQRect(r.left()-1, r.top()-1, r.width()+2, r.height()+2); //needed to update selectionvisualization
- m_target->setDirty(r);
- m_subject->canvasController()->updateCanvas( r );
- }
- }
- }
-}
-
-void KisToolFreehand::initPaint(KisEvent *)
-{
- if (!m_currentImage || !m_currentImage->activeDevice()) return;
-
- m_mode = PAINT;
- m_dragDist = 0;
-
- // Create painter
- KisPaintDeviceSP device;
- if (m_currentImage && (device = m_currentImage->activeDevice())) {
-
- if (m_painter)
- delete m_painter;
-
- if (!m_paintIncremental) {
- if (m_currentImage->undo())
- m_currentImage->undoAdapter()->beginMacro(m_transactionText);
-
- KisLayerSupportsIndirectPainting* layer;
- if ((layer = dynamic_cast<KisLayerSupportsIndirectPainting*>(
- m_currentImage->activeLayer().data()))) {
-
- // Hack for the painting of single-layered layers using indirect painting,
- // because the group layer would not have a correctly synched cache (
- // because of an optimization that would happen, having this layer as
- // projection).
- KisLayer* l = layer->layer();
- KisPaintLayer* pl = dynamic_cast<KisPaintLayer*>(l);
- if (l->parent() && (l->parent()->parent() == 0)
- && (l->parent()->childCount() == 1)
- && l->parent()->paintLayerInducesProjectionOptimization(pl)) {
- // If there's a mask, device could've been the mask. The induce function
- // should catch this, but better safe than sorry
- l->parent()->resetProjection(pl->paintDevice());
- }
-
- m_target = new KisPaintDevice(m_currentImage->activeLayer(),
- device->colorSpace());
- layer->setTemporaryTarget(m_target);
- layer->setTemporaryCompositeOp(m_compositeOp);
- layer->setTemporaryOpacity(m_opacity);
-
- if (device->hasSelection())
- m_target->setSelection(device->selection());
- }
- } else {
- m_target = device;
- }
- if(m_target->hasSelection()) m_target->selection()->startCachingExactRect();
- m_painter = new KisPainter( m_target );
- TQ_CHECK_PTR(m_painter);
- m_source = device;
- if (currentImage()->undo()) m_painter->beginTransaction(m_transactionText);
- }
-
- m_painter->setPaintColor(m_subject->fgColor());
- m_painter->setBackgroundColor(m_subject->bgColor());
- m_painter->setBrush(m_subject->currentBrush());
-
-
- // if you're drawing on a temporary layer, the layer already sets this
- if (m_paintIncremental) {
- m_painter->setCompositeOp(m_compositeOp);
- m_painter->setOpacity(m_opacity);
- } else {
- m_painter->setCompositeOp(COMPOSITE_ALPHA_DARKEN);
- m_painter->setOpacity( OPACITY_OPAQUE );
-
- }
-
-/* kdDebug() << "target: " << m_target << "( " << m_target->name() << " )"
- << " source: " << m_source << "( " << m_source->name() << " )"
- << ", incremental " << m_paintIncremental
- << ", paint on selection: " << m_paintOnSelection
- << ", active device has selection: " << device->hasSelection()
- << ", target has selection: " << m_target->hasSelection()
- << endl;
-*/
-}
-
-void KisToolFreehand::endPaint()
-{
- m_mode = HOVER;
- if (m_currentImage) {
-
- if (m_painter) {
- // If painting in mouse release, make sure painter
- // is destructed or end()ed
- if (!m_paintIncremental) {
- if (m_currentImage->undo())
- m_painter->endTransaction();
- KisPainter painter( m_source );
- painter.setCompositeOp(m_compositeOp);
- if (m_currentImage->undo())
- painter.beginTransaction(m_transactionText);
- painter.bitBlt(m_dirtyRect.x(), m_dirtyRect.y(), m_compositeOp, m_target,
- m_opacity,
- m_dirtyRect.x(), m_dirtyRect.y(),
- m_dirtyRect.width(), m_dirtyRect.height());
-
- KisLayerSupportsIndirectPainting* layer =
- dynamic_cast<KisLayerSupportsIndirectPainting*>(m_source->parentLayer());
- layer->setTemporaryTarget(0);
- m_source->parentLayer()->setDirty(m_dirtyRect);
-
- if (m_currentImage->undo()) {
- m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
- m_currentImage->undoAdapter()->endMacro();
- }
- } else {
- if (m_currentImage->undo())
- m_currentImage->undoAdapter()->addCommand(m_painter->endTransaction());
- }
- }
- delete m_painter;
- m_painter = 0;
- notifyModified();
- if(m_target->hasSelection()) m_target->selection()->stopCachingExactRect();
- }
-}
-
-void KisToolFreehand::paintAt(const KisPoint &pos,
- const double pressure,
- const double xTilt,
- const double yTilt)
-{
- painter()->paintAt(pos, pressure, xTilt, yTilt);
-}
-
-void KisToolFreehand::paintLine(const KisPoint & pos1,
- const double pressure1,
- const double xtilt1,
- const double ytilt1,
- const KisPoint & pos2,
- const double pressure2,
- const double xtilt2,
- const double ytilt2)
-{
- m_dragDist = painter()->paintLine(pos1, pressure1, xtilt1, ytilt1, pos2, pressure2, xtilt2, ytilt2, m_dragDist);
-}
-
-
-KisImageSP KisToolFreehand::currentImage()
-{
- return m_currentImage;
-}
-
-
-void KisToolFreehand::paintOutline(const KisPoint& point) {
- if (!m_subject) {
- return;
- }
-
- KisCanvasController *controller = m_subject->canvasController();
-
- if (currentImage() && !currentImage()->bounds().contains(point.floorTQPoint())) {
- if (m_paintedOutline) {
- controller->kiscanvas()->update();
- m_paintedOutline = false;
- }
- return;
- }
-
- KisCanvas *canvas = controller->kiscanvas();
- canvas->repaint();
-
- KisBrush *brush = m_subject->currentBrush();
- // There may not be a brush present, and we shouldn't crash in that case
- if (brush) {
- KisCanvasPainter gc(canvas);
- TQPen pen(TQt::SolidLine);
-
- KisPoint hotSpot = brush->hotSpot();
-
- gc.setRasterOp(TQt::NotROP);
- gc.setPen(pen);
- gc.setViewport(0, 0, static_cast<TQ_INT32>(canvas->width() * m_subject->zoomFactor()),
- static_cast<TQ_INT32>(canvas->height() * m_subject->zoomFactor()));
- gc.translate((- controller->horzValue()) / m_subject->zoomFactor(),
- (- controller->vertValue()) / m_subject->zoomFactor());
-
- KisPoint topLeft = point - hotSpot;
-
- if (m_subject->currentPaintop().id() == "pen") {
- // Pen paints on whole pixels only.
- topLeft = topLeft.roundTQPoint();
- }
-
- gc.translate(topLeft.x(), topLeft.y());
-
- KisBoundaryPainter::paint(brush->boundary(), gc);
- m_paintedOutline = true;
- }
-}
-
-
-#include "kis_tool_freehand.moc"
-
diff --git a/chalk/ui/kis_tool_freehand.cpp b/chalk/ui/kis_tool_freehand.cpp
new file mode 100644
index 000000000..74eec4066
--- /dev/null
+++ b/chalk/ui/kis_tool_freehand.cpp
@@ -0,0 +1,354 @@
+/*
+ * kis_tool_brush.cpp - part of Chalk
+ *
+ * Copyright (c) 2003-2004 Boudewijn Rempt <boud@valdyas.org>
+ * Copyright (c) 2004 Bart Coppens <kde@bartcoppens.be>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include <tqevent.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqwidget.h>
+#include <tqrect.h>
+
+#include <kdebug.h>
+#include <tdeaction.h>
+#include <kcommand.h>
+#include <tdelocale.h>
+
+#include "kis_canvas_subject.h"
+#include "kis_undo_adapter.h"
+#include "kis_selection.h"
+#include "kis_painter.h"
+#include "kis_fill_painter.h"
+#include "kis_tool_freehand.h"
+#include "kis_cursor.h"
+#include "kis_button_press_event.h"
+#include "kis_button_release_event.h"
+#include "kis_move_event.h"
+#include "kis_layer.h"
+#include "kis_group_layer.h"
+#include "kis_paint_layer.h"
+#include "kis_canvas.h"
+#include "kis_canvas_painter.h"
+#include "kis_boundary_painter.h"
+#include "kis_brush.h"
+
+KisToolFreehand::KisToolFreehand(TQString transactionText)
+ : super(transactionText),
+ m_dragDist ( 0 ),
+ m_transactionText(transactionText),
+ m_mode( HOVER )
+{
+ m_painter = 0;
+ m_currentImage = 0;
+ m_tempLayer = 0;
+ m_paintIncremental = true;
+ m_paintOnSelection = false;
+ m_paintedOutline = false;
+}
+
+KisToolFreehand::~KisToolFreehand()
+{
+}
+
+void KisToolFreehand::update(KisCanvasSubject *subject)
+{
+ super::update(subject);
+ m_currentImage = m_subject->currentImg();
+}
+
+void KisToolFreehand::buttonPress(KisButtonPressEvent *e)
+{
+ if (!m_subject) return;
+
+ if (!m_subject->currentBrush()) return;
+
+ if (!m_currentImage || !m_currentImage->activeDevice()) return;
+
+ if (e->button() == Qt::LeftButton) {
+
+ m_currentImage->activeDevice()->lock( true );
+ kdDebug() << ">>>>>>>>>>>>>>>>>>>Locking paint device\n";
+
+ // People complain that they can't start brush strokes outside of the image boundaries.
+ // This makes sense, especially when combined with BUG:132759, so commenting out the
+ // next line makes sense.
+ //if (!m_currentImage->bounds().contains(e->pos().floorTQPoint())) return;
+
+ initPaint(e);
+ paintAt(e->pos(), e->pressure(), e->xTilt(), e->yTilt());
+
+ m_prevPos = e->pos();
+ m_prevPressure = e->pressure();
+ m_prevXTilt = e->xTilt();
+ m_prevYTilt = e->yTilt();
+
+ TQRect r = m_painter->dirtyRect();
+ if ( r.isValid() ) {
+ m_dirtyRect = r;
+
+ r = TQRect(r.left()-1, r.top()-1, r.width()+2, r.height()+2); //needed to update selectionvisualization
+ if (!m_paintOnSelection) {
+ m_currentImage->activeLayer()->setDirty(r);
+ }
+ else {
+ m_target->setDirty(r);
+ // Just update the canvas. XXX: After 1.5, find a better way to make sure tools don't set dirty what they didn't touch.
+ m_subject->canvasController()->updateCanvas( r );
+ }
+ }
+ }
+}
+
+void KisToolFreehand::buttonRelease(KisButtonReleaseEvent* e)
+{
+ if (e->button() == Qt::LeftButton && m_mode == PAINT) {
+ endPaint();
+ m_currentImage->activeDevice()->lock( false );
+ kdDebug() << ">>>>>>>>>>>>>>>>>>>UNLocking paint device\n";
+
+ }
+ KisToolPaint::buttonRelease(e);
+}
+
+void KisToolFreehand::move(KisMoveEvent *e)
+{
+ if (m_mode == PAINT) {
+
+ paintLine(m_prevPos, m_prevPressure, m_prevXTilt, m_prevYTilt, e->pos(), e->pressure(), e->xTilt(), e->yTilt());
+
+ m_prevPos = e->pos();
+ m_prevPressure = e->pressure();
+ m_prevXTilt = e->xTilt();
+ m_prevYTilt = e->yTilt();
+
+ TQRect r = m_painter->dirtyRect();
+
+ if (r.isValid()) {
+ m_dirtyRect |= r;
+
+ if (!m_paintOnSelection) {
+ m_currentImage->activeLayer()->setDirty(r);
+ }
+ else {
+ // Just update the canvas
+ r = TQRect(r.left()-1, r.top()-1, r.width()+2, r.height()+2); //needed to update selectionvisualization
+ m_target->setDirty(r);
+ m_subject->canvasController()->updateCanvas( r );
+ }
+ }
+ }
+}
+
+void KisToolFreehand::initPaint(KisEvent *)
+{
+ if (!m_currentImage || !m_currentImage->activeDevice()) return;
+
+ m_mode = PAINT;
+ m_dragDist = 0;
+
+ // Create painter
+ KisPaintDeviceSP device;
+ if (m_currentImage && (device = m_currentImage->activeDevice())) {
+
+ if (m_painter)
+ delete m_painter;
+
+ if (!m_paintIncremental) {
+ if (m_currentImage->undo())
+ m_currentImage->undoAdapter()->beginMacro(m_transactionText);
+
+ KisLayerSupportsIndirectPainting* layer;
+ if ((layer = dynamic_cast<KisLayerSupportsIndirectPainting*>(
+ m_currentImage->activeLayer().data()))) {
+
+ // Hack for the painting of single-layered layers using indirect painting,
+ // because the group layer would not have a correctly synched cache (
+ // because of an optimization that would happen, having this layer as
+ // projection).
+ KisLayer* l = layer->layer();
+ KisPaintLayer* pl = dynamic_cast<KisPaintLayer*>(l);
+ if (l->parent() && (l->parent()->parent() == 0)
+ && (l->parent()->childCount() == 1)
+ && l->parent()->paintLayerInducesProjectionOptimization(pl)) {
+ // If there's a mask, device could've been the mask. The induce function
+ // should catch this, but better safe than sorry
+ l->parent()->resetProjection(pl->paintDevice());
+ }
+
+ m_target = new KisPaintDevice(m_currentImage->activeLayer(),
+ device->colorSpace());
+ layer->setTemporaryTarget(m_target);
+ layer->setTemporaryCompositeOp(m_compositeOp);
+ layer->setTemporaryOpacity(m_opacity);
+
+ if (device->hasSelection())
+ m_target->setSelection(device->selection());
+ }
+ } else {
+ m_target = device;
+ }
+ if(m_target->hasSelection()) m_target->selection()->startCachingExactRect();
+ m_painter = new KisPainter( m_target );
+ TQ_CHECK_PTR(m_painter);
+ m_source = device;
+ if (currentImage()->undo()) m_painter->beginTransaction(m_transactionText);
+ }
+
+ m_painter->setPaintColor(m_subject->fgColor());
+ m_painter->setBackgroundColor(m_subject->bgColor());
+ m_painter->setBrush(m_subject->currentBrush());
+
+
+ // if you're drawing on a temporary layer, the layer already sets this
+ if (m_paintIncremental) {
+ m_painter->setCompositeOp(m_compositeOp);
+ m_painter->setOpacity(m_opacity);
+ } else {
+ m_painter->setCompositeOp(COMPOSITE_ALPHA_DARKEN);
+ m_painter->setOpacity( OPACITY_OPAQUE );
+
+ }
+
+/* kdDebug() << "target: " << m_target << "( " << m_target->name() << " )"
+ << " source: " << m_source << "( " << m_source->name() << " )"
+ << ", incremental " << m_paintIncremental
+ << ", paint on selection: " << m_paintOnSelection
+ << ", active device has selection: " << device->hasSelection()
+ << ", target has selection: " << m_target->hasSelection()
+ << endl;
+*/
+}
+
+void KisToolFreehand::endPaint()
+{
+ m_mode = HOVER;
+ if (m_currentImage) {
+
+ if (m_painter) {
+ // If painting in mouse release, make sure painter
+ // is destructed or end()ed
+ if (!m_paintIncremental) {
+ if (m_currentImage->undo())
+ m_painter->endTransaction();
+ KisPainter painter( m_source );
+ painter.setCompositeOp(m_compositeOp);
+ if (m_currentImage->undo())
+ painter.beginTransaction(m_transactionText);
+ painter.bitBlt(m_dirtyRect.x(), m_dirtyRect.y(), m_compositeOp, m_target,
+ m_opacity,
+ m_dirtyRect.x(), m_dirtyRect.y(),
+ m_dirtyRect.width(), m_dirtyRect.height());
+
+ KisLayerSupportsIndirectPainting* layer =
+ dynamic_cast<KisLayerSupportsIndirectPainting*>(m_source->parentLayer());
+ layer->setTemporaryTarget(0);
+ m_source->parentLayer()->setDirty(m_dirtyRect);
+
+ if (m_currentImage->undo()) {
+ m_currentImage->undoAdapter()->addCommand(painter.endTransaction());
+ m_currentImage->undoAdapter()->endMacro();
+ }
+ } else {
+ if (m_currentImage->undo())
+ m_currentImage->undoAdapter()->addCommand(m_painter->endTransaction());
+ }
+ }
+ delete m_painter;
+ m_painter = 0;
+ notifyModified();
+ if(m_target->hasSelection()) m_target->selection()->stopCachingExactRect();
+ }
+}
+
+void KisToolFreehand::paintAt(const KisPoint &pos,
+ const double pressure,
+ const double xTilt,
+ const double yTilt)
+{
+ painter()->paintAt(pos, pressure, xTilt, yTilt);
+}
+
+void KisToolFreehand::paintLine(const KisPoint & pos1,
+ const double pressure1,
+ const double xtilt1,
+ const double ytilt1,
+ const KisPoint & pos2,
+ const double pressure2,
+ const double xtilt2,
+ const double ytilt2)
+{
+ m_dragDist = painter()->paintLine(pos1, pressure1, xtilt1, ytilt1, pos2, pressure2, xtilt2, ytilt2, m_dragDist);
+}
+
+
+KisImageSP KisToolFreehand::currentImage()
+{
+ return m_currentImage;
+}
+
+
+void KisToolFreehand::paintOutline(const KisPoint& point) {
+ if (!m_subject) {
+ return;
+ }
+
+ KisCanvasController *controller = m_subject->canvasController();
+
+ if (currentImage() && !currentImage()->bounds().contains(point.floorTQPoint())) {
+ if (m_paintedOutline) {
+ controller->kiscanvas()->update();
+ m_paintedOutline = false;
+ }
+ return;
+ }
+
+ KisCanvas *canvas = controller->kiscanvas();
+ canvas->repaint();
+
+ KisBrush *brush = m_subject->currentBrush();
+ // There may not be a brush present, and we shouldn't crash in that case
+ if (brush) {
+ KisCanvasPainter gc(canvas);
+ TQPen pen(TQt::SolidLine);
+
+ KisPoint hotSpot = brush->hotSpot();
+
+ gc.setRasterOp(TQt::NotROP);
+ gc.setPen(pen);
+ gc.setViewport(0, 0, static_cast<TQ_INT32>(canvas->width() * m_subject->zoomFactor()),
+ static_cast<TQ_INT32>(canvas->height() * m_subject->zoomFactor()));
+ gc.translate((- controller->horzValue()) / m_subject->zoomFactor(),
+ (- controller->vertValue()) / m_subject->zoomFactor());
+
+ KisPoint topLeft = point - hotSpot;
+
+ if (m_subject->currentPaintop().id() == "pen") {
+ // Pen paints on whole pixels only.
+ topLeft = topLeft.roundTQPoint();
+ }
+
+ gc.translate(topLeft.x(), topLeft.y());
+
+ KisBoundaryPainter::paint(brush->boundary(), gc);
+ m_paintedOutline = true;
+ }
+}
+
+
+#include "kis_tool_freehand.moc"
+
diff --git a/chalk/ui/kis_tool_manager.cc b/chalk/ui/kis_tool_manager.cpp
index 043880586..043880586 100644
--- a/chalk/ui/kis_tool_manager.cc
+++ b/chalk/ui/kis_tool_manager.cpp
diff --git a/chalk/ui/kis_tool_non_paint.cc b/chalk/ui/kis_tool_non_paint.cpp
index 4adccc602..4adccc602 100644
--- a/chalk/ui/kis_tool_non_paint.cc
+++ b/chalk/ui/kis_tool_non_paint.cpp
diff --git a/chalk/ui/kis_tool_paint.cc b/chalk/ui/kis_tool_paint.cpp
index 143bd6754..143bd6754 100644
--- a/chalk/ui/kis_tool_paint.cc
+++ b/chalk/ui/kis_tool_paint.cpp
diff --git a/chalk/ui/kis_tool_registry.cc b/chalk/ui/kis_tool_registry.cpp
index 036e538fc..036e538fc 100644
--- a/chalk/ui/kis_tool_registry.cc
+++ b/chalk/ui/kis_tool_registry.cpp
diff --git a/chalk/ui/kis_tool_shape.cc b/chalk/ui/kis_tool_shape.cpp
index 68ce4c69e..68ce4c69e 100644
--- a/chalk/ui/kis_tool_shape.cc
+++ b/chalk/ui/kis_tool_shape.cpp
diff --git a/chalk/ui/kis_view.cc b/chalk/ui/kis_view.cpp
index 59da51890..59da51890 100644
--- a/chalk/ui/kis_view.cc
+++ b/chalk/ui/kis_view.cpp
diff --git a/chalk/ui/kis_view_iface.cc b/chalk/ui/kis_view_iface.cpp
index 7de36c483..7de36c483 100644
--- a/chalk/ui/kis_view_iface.cc
+++ b/chalk/ui/kis_view_iface.cpp
diff --git a/doc/chalk/developers-plugins.docbook b/doc/chalk/developers-plugins.docbook
index 029af8d7e..bf5fab62f 100644
--- a/doc/chalk/developers-plugins.docbook
+++ b/doc/chalk/developers-plugins.docbook
@@ -195,7 +195,7 @@ kde_services_DATA = chalkLIBRARYNAME.desktop
INCLUDES = $(all_includes)
-chalkLIBRARYNAME_la_SOURCES = sourcefile1.cc sourcefile2.cc
+chalkLIBRARYNAME_la_SOURCES = sourcefile1.cpp sourcefile2.cpp
kde_module_LTLIBRARIES = chalkLIBRARYNAME.la
noinst_HEADERS = header1.h header2.h
@@ -878,14 +878,14 @@ A good example of a tool is the star tool:
</para>
<screen>
-kis_tool_star.cc Makefile.am tool_star_cursor.png wdg_tool_star.ui
+kis_tool_star.cpp Makefile.am tool_star_cursor.png wdg_tool_star.ui
kis_tool_star.h Makefile.in tool_star.h
-chalktoolstar.desktop tool_star.cc tool_star.png
+chalktoolstar.desktop tool_star.cpp tool_star.png
</screen>
<para>
As you see, you need two images: one for the cursor and one for the toolbox.
-<filename>tool_star.cc</filename> is just the plugin loader, similar to what
+<filename>tool_star.cpp</filename> is just the plugin loader, similar to what
we have seen above. The real meat is in the implementation:
</para>
diff --git a/example/Makefile.am b/example/Makefile.am
index 96799ae0a..0bcdf91bb 100644
--- a/example/Makefile.am
+++ b/example/Makefile.am
@@ -3,8 +3,8 @@ INCLUDES = $(KOFFICE_INCLUDES) $(all_includes)
## The part
kde_module_LTLIBRARIES = libexamplepart.la
-libexamplepart_la_SOURCES = example_part.cc \
- example_view.cc example_factory.cc
+libexamplepart_la_SOURCES = example_part.cpp \
+ example_view.cpp example_factory.cpp
libexamplepart_la_LDFLAGS = $(KDE_PLUGIN)
libexamplepart_la_LIBADD = $(LIB_KOFFICEUI)
@@ -12,7 +12,7 @@ libexamplepart_la_LIBADD = $(LIB_KOFFICEUI)
tdeinit_LTLIBRARIES = example.la
lib_LTLIBRARIES =
bin_PROGRAMS =
-example_la_SOURCES = main.cc
+example_la_SOURCES = main.cpp
example_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
example_la_LIBADD = $(LIB_KOFFICEUI)
@@ -32,7 +32,7 @@ rc_DATA = example.rc example_readonly.rc
rcdir = $(kde_datadir)/example
messages: rc.cpp
- $(XGETTEXT) rc.cpp *.cc example_aboutdata.h -o $(podir)/example.pot
+ $(XGETTEXT) rc.cpp *.cpp example_aboutdata.h -o $(podir)/example.pot
kde_services_DATA = examplepart.desktop
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/example/example_factory.cc b/example/example_factory.cpp
index 9564e5fae..9564e5fae 100644
--- a/example/example_factory.cc
+++ b/example/example_factory.cpp
diff --git a/example/example_part.cc b/example/example_part.cpp
index 4afc46b0e..4afc46b0e 100644
--- a/example/example_part.cc
+++ b/example/example_part.cpp
diff --git a/example/example_view.cc b/example/example_view.cpp
index 1a8e07e19..1a8e07e19 100644
--- a/example/example_view.cc
+++ b/example/example_view.cpp
diff --git a/example/main.cc b/example/main.cpp
index ecffb3736..ecffb3736 100644
--- a/example/main.cc
+++ b/example/main.cpp
diff --git a/filters/Makefile.am b/filters/Makefile.am
index e8473741e..83ea4f863 100644
--- a/filters/Makefile.am
+++ b/filters/Makefile.am
@@ -43,6 +43,6 @@ SUBDIRS = generic_wrapper libdialogfilter liboofilter $(KSPREADDIR) $(KCHARTDIR)
messages:
$(EXTRACTRC) `find . -name \*.ui` > rc.cpp
- $(XGETTEXT) `find . -name \*.cpp -o -name \*.cc` -o $(podir)/kofficefilters.pot
+ $(XGETTEXT) `find . -name \*.cpp` -o $(podir)/kofficefilters.pot
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/filters/chalk/gmagick/Makefile.am b/filters/chalk/gmagick/Makefile.am
index 410c95ea2..431704334 100644
--- a/filters/chalk/gmagick/Makefile.am
+++ b/filters/chalk/gmagick/Makefile.am
@@ -39,8 +39,8 @@ servicedir = $(kde_servicesdir)
kdelnk_DATA = chalk_magick.desktop
kdelnkdir = $(kde_appsdir)/.hidden
-libchalkgmagickimport_la_SOURCES = magickimport.cpp kis_image_magick_converter.cc
-libchalkgmagickexport_la_SOURCES = magickexport.cpp kis_image_magick_converter.cc
+libchalkgmagickimport_la_SOURCES = magickimport.cpp kis_image_magick_converter.cpp
+libchalkgmagickexport_la_SOURCES = magickexport.cpp kis_image_magick_converter.cpp
METASOURCES = AUTO
diff --git a/filters/chalk/gmagick/kis_image_magick_converter.cc b/filters/chalk/gmagick/kis_image_magick_converter.cpp
index f25449ec4..f25449ec4 100644
--- a/filters/chalk/gmagick/kis_image_magick_converter.cc
+++ b/filters/chalk/gmagick/kis_image_magick_converter.cpp
diff --git a/filters/chalk/jpeg/Makefile.am b/filters/chalk/jpeg/Makefile.am
index 9e84cfa15..d12b57ed5 100644
--- a/filters/chalk/jpeg/Makefile.am
+++ b/filters/chalk/jpeg/Makefile.am
@@ -3,7 +3,7 @@ kde_module_LTLIBRARIES = libchalkjpegimport.la libchalkjpegexport.la
libchalkconverter_la_LDFLAGS = $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts \
-llcms
-libchalkconverter_la_SOURCES = kis_jpeg_converter.cc iccjpeg.c
+libchalkconverter_la_SOURCES = kis_jpeg_converter.cpp iccjpeg.c
libchalkconverter_la_LIBADD = $(KOFFICE_LIBS) $(top_builddir)/filters/chalk/libkisexif/libkisexif.la \
../../../chalk/core/libchalkimage.la \
../../../chalk/ui/libchalkui.la \
@@ -49,8 +49,8 @@ servicedir = $(kde_servicesdir)
kdelnk_DATA = chalk_jpeg.desktop
kdelnkdir = $(kde_appsdir)/.hidden
-libchalkjpegimport_la_SOURCES = kis_jpeg_import.cc
-libchalkjpegexport_la_SOURCES = kis_wdg_options_jpeg.ui kis_jpeg_export.cc
+libchalkjpegimport_la_SOURCES = kis_jpeg_import.cpp
+libchalkjpegexport_la_SOURCES = kis_wdg_options_jpeg.ui kis_jpeg_export.cpp
METASOURCES = AUTO
diff --git a/filters/chalk/jpeg/kis_jpeg_converter.cc b/filters/chalk/jpeg/kis_jpeg_converter.cpp
index fd0630ecf..fd0630ecf 100644
--- a/filters/chalk/jpeg/kis_jpeg_converter.cc
+++ b/filters/chalk/jpeg/kis_jpeg_converter.cpp
diff --git a/filters/chalk/jpeg/kis_jpeg_export.cc b/filters/chalk/jpeg/kis_jpeg_export.cpp
index 042a3c8ef..042a3c8ef 100644
--- a/filters/chalk/jpeg/kis_jpeg_export.cc
+++ b/filters/chalk/jpeg/kis_jpeg_export.cpp
diff --git a/filters/chalk/jpeg/kis_jpeg_import.cc b/filters/chalk/jpeg/kis_jpeg_import.cpp
index bacec6794..bacec6794 100644
--- a/filters/chalk/jpeg/kis_jpeg_import.cc
+++ b/filters/chalk/jpeg/kis_jpeg_import.cpp
diff --git a/filters/chalk/magick/Makefile.am b/filters/chalk/magick/Makefile.am
index e6bfcf29a..b41d09585 100644
--- a/filters/chalk/magick/Makefile.am
+++ b/filters/chalk/magick/Makefile.am
@@ -39,8 +39,8 @@ servicedir = $(kde_servicesdir)
kdelnk_DATA = chalk_magick.desktop
kdelnkdir = $(kde_appsdir)/Office
-libchalkmagickimport_la_SOURCES = magickimport.cpp kis_image_magick_converter.cc
-libchalkmagickexport_la_SOURCES = magickexport.cpp kis_image_magick_converter.cc
+libchalkmagickimport_la_SOURCES = magickimport.cpp kis_image_magick_converter.cpp
+libchalkmagickexport_la_SOURCES = magickexport.cpp kis_image_magick_converter.cpp
METASOURCES = AUTO
diff --git a/filters/chalk/magick/kis_image_magick_converter.cc b/filters/chalk/magick/kis_image_magick_converter.cpp
index 5f8bafa3a..5f8bafa3a 100644
--- a/filters/chalk/magick/kis_image_magick_converter.cc
+++ b/filters/chalk/magick/kis_image_magick_converter.cpp
diff --git a/filters/chalk/png/Makefile.am b/filters/chalk/png/Makefile.am
index d314e65a3..93822d1fc 100644
--- a/filters/chalk/png/Makefile.am
+++ b/filters/chalk/png/Makefile.am
@@ -39,8 +39,8 @@ servicedir = $(kde_servicesdir)
kdelnk_DATA = chalk_png.desktop
kdelnkdir = $(kde_appsdir)/.hidden
-libchalkpngimport_la_SOURCES = kis_png_import.cc kis_png_converter.cc
-libchalkpngexport_la_SOURCES = kis_wdg_options_png.ui kis_png_export.cc kis_png_converter.cc
+libchalkpngimport_la_SOURCES = kis_png_import.cpp kis_png_converter.cpp
+libchalkpngexport_la_SOURCES = kis_wdg_options_png.ui kis_png_export.cpp kis_png_converter.cpp
METASOURCES = AUTO
diff --git a/filters/chalk/png/kis_png_converter.cc b/filters/chalk/png/kis_png_converter.cpp
index 3956b640b..3956b640b 100644
--- a/filters/chalk/png/kis_png_converter.cc
+++ b/filters/chalk/png/kis_png_converter.cpp
diff --git a/filters/chalk/png/kis_png_export.cc b/filters/chalk/png/kis_png_export.cpp
index bb071ff2e..bb071ff2e 100644
--- a/filters/chalk/png/kis_png_export.cc
+++ b/filters/chalk/png/kis_png_export.cpp
diff --git a/filters/chalk/png/kis_png_import.cc b/filters/chalk/png/kis_png_import.cpp
index dc2a63256..dc2a63256 100644
--- a/filters/chalk/png/kis_png_import.cc
+++ b/filters/chalk/png/kis_png_import.cpp
diff --git a/filters/chalk/tiff/Makefile.am b/filters/chalk/tiff/Makefile.am
index b07e3eee7..f53432aba 100644
--- a/filters/chalk/tiff/Makefile.am
+++ b/filters/chalk/tiff/Makefile.am
@@ -46,8 +46,8 @@ METASOURCES = AUTO
KDE_CXXFLAGS = $(USE_EXCEPTIONS)
-libchalktiffimport_la_SOURCES = kis_tiff_import.cc
-libchalktiffexport_la_SOURCES = kis_tiff_export.cc kis_wdg_options_tiff.ui \
+libchalktiffimport_la_SOURCES = kis_tiff_import.cpp
+libchalktiffexport_la_SOURCES = kis_tiff_export.cpp kis_wdg_options_tiff.ui \
kis_dlg_options_tiff.cpp
service_DATA = chalk_tiff_export.desktop chalk_tiff_import.desktop
kdelnk_DATA = chalk_tiff.desktop
@@ -60,5 +60,5 @@ libchalktiffconverter_la_LIBADD = $(KOFFICE_LIBS) \
../../../chalk/ui/libchalkui.la \
../../../chalk/chalkcolor/libchalkcolor.la
noinst_LTLIBRARIES = libchalktiffconverter.la
-libchalktiffconverter_la_SOURCES = kis_tiff_converter.cc kis_tiff_stream.cc \
- kis_tiff_writer_visitor.cpp kis_tiff_reader.cc kis_tiff_ycbcr_reader.cc
+libchalktiffconverter_la_SOURCES = kis_tiff_converter.cpp kis_tiff_stream.cpp \
+ kis_tiff_writer_visitor.cpp kis_tiff_reader.cpp kis_tiff_ycbcr_reader.cpp
diff --git a/filters/chalk/tiff/kis_tiff_converter.cc b/filters/chalk/tiff/kis_tiff_converter.cpp
index ea39dec28..ea39dec28 100644
--- a/filters/chalk/tiff/kis_tiff_converter.cc
+++ b/filters/chalk/tiff/kis_tiff_converter.cpp
diff --git a/filters/chalk/tiff/kis_tiff_export.cc b/filters/chalk/tiff/kis_tiff_export.cpp
index 41f38fc80..41f38fc80 100644
--- a/filters/chalk/tiff/kis_tiff_export.cc
+++ b/filters/chalk/tiff/kis_tiff_export.cpp
diff --git a/filters/chalk/tiff/kis_tiff_import.cc b/filters/chalk/tiff/kis_tiff_import.cpp
index 8c785ffec..8c785ffec 100644
--- a/filters/chalk/tiff/kis_tiff_import.cc
+++ b/filters/chalk/tiff/kis_tiff_import.cpp
diff --git a/filters/chalk/tiff/kis_tiff_reader.cc b/filters/chalk/tiff/kis_tiff_reader.cpp
index f2eabd878..f2eabd878 100644
--- a/filters/chalk/tiff/kis_tiff_reader.cc
+++ b/filters/chalk/tiff/kis_tiff_reader.cpp
diff --git a/filters/chalk/tiff/kis_tiff_stream.cc b/filters/chalk/tiff/kis_tiff_stream.cpp
index 4c80fefcd..4c80fefcd 100644
--- a/filters/chalk/tiff/kis_tiff_stream.cc
+++ b/filters/chalk/tiff/kis_tiff_stream.cpp
diff --git a/filters/chalk/tiff/kis_tiff_ycbcr_reader.cc b/filters/chalk/tiff/kis_tiff_ycbcr_reader.cpp
index ce5e4ae95..ce5e4ae95 100644
--- a/filters/chalk/tiff/kis_tiff_ycbcr_reader.cc
+++ b/filters/chalk/tiff/kis_tiff_ycbcr_reader.cpp
diff --git a/filters/chalk/xcf/xcf/xcf-load.cc b/filters/chalk/xcf/xcf/xcf-load.cpp
index 3209e1811..3209e1811 100644
--- a/filters/chalk/xcf/xcf/xcf-load.cc
+++ b/filters/chalk/xcf/xcf/xcf-load.cpp
diff --git a/filters/chalk/xcf/xcf/xcf-read.cc b/filters/chalk/xcf/xcf/xcf-read.cpp
index 314daa900..314daa900 100644
--- a/filters/chalk/xcf/xcf/xcf-read.cc
+++ b/filters/chalk/xcf/xcf/xcf-read.cpp
diff --git a/filters/chalk/xcf/xcf/xcf-save.cc b/filters/chalk/xcf/xcf/xcf-save.cpp
index a0dbb9b5a..a0dbb9b5a 100644
--- a/filters/chalk/xcf/xcf/xcf-save.cc
+++ b/filters/chalk/xcf/xcf/xcf-save.cpp
diff --git a/filters/chalk/xcf/xcf/xcf-seek.cc b/filters/chalk/xcf/xcf/xcf-seek.cpp
index a24271f5e..a24271f5e 100644
--- a/filters/chalk/xcf/xcf/xcf-seek.cc
+++ b/filters/chalk/xcf/xcf/xcf-seek.cpp
diff --git a/filters/chalk/xcf/xcf/xcf-write.cc b/filters/chalk/xcf/xcf/xcf-write.cpp
index 4010ab18f..4010ab18f 100644
--- a/filters/chalk/xcf/xcf/xcf-write.cc
+++ b/filters/chalk/xcf/xcf/xcf-write.cpp
diff --git a/filters/generic_wrapper/Makefile.am b/filters/generic_wrapper/Makefile.am
index 8d1cb7a05..66d95473f 100644
--- a/filters/generic_wrapper/Makefile.am
+++ b/filters/generic_wrapper/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libgenerickofilter.la
-libgenerickofilter_la_SOURCES = generic_filter.cc
+libgenerickofilter_la_SOURCES = generic_filter.cpp
libgenerickofilter_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libgenerickofilter_la_LIBADD = $(KOFFICE_LIBS) $(LIB_TDEIO)
diff --git a/filters/generic_wrapper/generic_filter.cc b/filters/generic_wrapper/generic_filter.cpp
index 112c29d1c..112c29d1c 100644
--- a/filters/generic_wrapper/generic_filter.cc
+++ b/filters/generic_wrapper/generic_filter.cpp
diff --git a/filters/karbon/ai/Makefile.am b/filters/karbon/ai/Makefile.am
index 761feaffd..2bbc124df 100644
--- a/filters/karbon/ai/Makefile.am
+++ b/filters/karbon/ai/Makefile.am
@@ -30,14 +30,14 @@ noinst_HEADERS = \
karbonaiparserbase.h
libkarbonaiimport_la_SOURCES = \
- aicolor.cc \
- aielement.cc \
- aiimport.cc \
- ailexer.cc \
- aiparserbase.cc \
- ai88handler.cc \
- ai3handler.cc \
- karbonaiparserbase.cc
+ aicolor.cpp \
+ aielement.cpp \
+ aiimport.cpp \
+ ailexer.cpp \
+ aiparserbase.cpp \
+ ai88handler.cpp \
+ ai3handler.cpp \
+ karbonaiparserbase.cpp
libkarbonaiimport_la_METASOURCES = \
AUTO
diff --git a/filters/karbon/ai/ai3handler.cc b/filters/karbon/ai/ai3handler.cpp
index c014d9306..c014d9306 100644
--- a/filters/karbon/ai/ai3handler.cc
+++ b/filters/karbon/ai/ai3handler.cpp
diff --git a/filters/karbon/ai/ai88handler.cc b/filters/karbon/ai/ai88handler.cpp
index 87a937ae9..87a937ae9 100644
--- a/filters/karbon/ai/ai88handler.cc
+++ b/filters/karbon/ai/ai88handler.cpp
diff --git a/filters/karbon/ai/aicolor.cc b/filters/karbon/ai/aicolor.cpp
index cabc932fb..cabc932fb 100644
--- a/filters/karbon/ai/aicolor.cc
+++ b/filters/karbon/ai/aicolor.cpp
diff --git a/filters/karbon/ai/aielement.cc b/filters/karbon/ai/aielement.cpp
index 2f514d06c..2f514d06c 100644
--- a/filters/karbon/ai/aielement.cc
+++ b/filters/karbon/ai/aielement.cpp
diff --git a/filters/karbon/ai/aiimport.cc b/filters/karbon/ai/aiimport.cpp
index 0af2cc939..0af2cc939 100644
--- a/filters/karbon/ai/aiimport.cc
+++ b/filters/karbon/ai/aiimport.cpp
diff --git a/filters/karbon/ai/ailexer.cc b/filters/karbon/ai/ailexer.cpp
index 352b8f48a..352b8f48a 100644
--- a/filters/karbon/ai/ailexer.cc
+++ b/filters/karbon/ai/ailexer.cpp
diff --git a/filters/karbon/ai/aiparserbase.cc b/filters/karbon/ai/aiparserbase.cpp
index 24f9920e7..24f9920e7 100644
--- a/filters/karbon/ai/aiparserbase.cc
+++ b/filters/karbon/ai/aiparserbase.cpp
diff --git a/filters/karbon/ai/karbonaiparserbase.cc b/filters/karbon/ai/karbonaiparserbase.cpp
index c4321252d..c4321252d 100644
--- a/filters/karbon/ai/karbonaiparserbase.cc
+++ b/filters/karbon/ai/karbonaiparserbase.cpp
diff --git a/filters/karbon/applixgraphics/Makefile.am b/filters/karbon/applixgraphics/Makefile.am
index b3c03f384..83fefb227 100644
--- a/filters/karbon/applixgraphics/Makefile.am
+++ b/filters/karbon/applixgraphics/Makefile.am
@@ -7,7 +7,7 @@ libapplixgraphicimport_la_LDFLAGS = -module -avoid-version -no-undefined $(all_l
kde_module_LTLIBRARIES = libapplixgraphicimport.la
-libapplixgraphicimport_la_SOURCES = applixgraphicimport.cc
+libapplixgraphicimport_la_SOURCES = applixgraphicimport.cpp
libapplixgraphicimport_la_LIBADD = $(KOFFICE_LIBS)
noinst_HEADERS = applixgraphicimport.h
@@ -17,4 +17,4 @@ service_DATA = kontour_applixgraphic_import.desktop
servicedir = $(kde_servicesdir)
messages: rc.cpp
- $(XGETTEXT) *.cc *.cpp -o $(podir)/kontourapplixgraphicsfilter.pot
+ $(XGETTEXT) *.cpp -o $(podir)/kontourapplixgraphicsfilter.pot
diff --git a/filters/karbon/applixgraphics/applixgraphicimport.cc b/filters/karbon/applixgraphics/applixgraphicimport.cpp
index fd81b108c..fd81b108c 100644
--- a/filters/karbon/applixgraphics/applixgraphicimport.cc
+++ b/filters/karbon/applixgraphics/applixgraphicimport.cpp
diff --git a/filters/karbon/eps/Makefile.am b/filters/karbon/eps/Makefile.am
index 035a188e0..ccf3503eb 100644
--- a/filters/karbon/eps/Makefile.am
+++ b/filters/karbon/eps/Makefile.am
@@ -3,13 +3,13 @@ kde_module_LTLIBRARIES = \
libkarbonepsimport.la
libkarbonepsexport_la_SOURCES = \
- epsexport.cc \
- epsexportdlg.cc
+ epsexport.cpp \
+ epsexportdlg.cpp
libkarbonepsexport_la_LDFLAGS = $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkarbonepsexport_la_LIBADD = $(KOFFICE_LIBS) ../../../karbon/libkarboncommon.la
-libkarbonepsimport_la_SOURCES = epsimport.cc pscommentlexer.cc
+libkarbonepsimport_la_SOURCES = epsimport.cpp pscommentlexer.cpp
libkarbonepsimport_la_LDFLAGS = $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkarbonepsimport_la_LIBADD = $(KOFFICE_LIBS)
diff --git a/filters/karbon/eps/epsexport.cc b/filters/karbon/eps/epsexport.cpp
index 023074daa..023074daa 100644
--- a/filters/karbon/eps/epsexport.cc
+++ b/filters/karbon/eps/epsexport.cpp
diff --git a/filters/karbon/eps/epsexportdlg.cc b/filters/karbon/eps/epsexportdlg.cpp
index 4bf4aec7e..4bf4aec7e 100644
--- a/filters/karbon/eps/epsexportdlg.cc
+++ b/filters/karbon/eps/epsexportdlg.cpp
diff --git a/filters/karbon/eps/epsimport.cc b/filters/karbon/eps/epsimport.cpp
index 72bb1334d..72bb1334d 100644
--- a/filters/karbon/eps/epsimport.cc
+++ b/filters/karbon/eps/epsimport.cpp
diff --git a/filters/karbon/eps/pscommentlexer.cc b/filters/karbon/eps/pscommentlexer.cpp
index e15dcc59e..e15dcc59e 100644
--- a/filters/karbon/eps/pscommentlexer.cc
+++ b/filters/karbon/eps/pscommentlexer.cpp
diff --git a/filters/karbon/kontour/Makefile.am b/filters/karbon/kontour/Makefile.am
index be0b835ff..d955dbef0 100644
--- a/filters/karbon/kontour/Makefile.am
+++ b/filters/karbon/kontour/Makefile.am
@@ -5,7 +5,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(KOPAINTER_INCLUDES) -I$(top_srcdir)/
####### Files
# Obviously you have to change "foo" (and maybe "import") to
# reflect the name of your filter. If you have more files
-# than just fooimport.cc please add them to the _SOURCES line.
+# than just fooimport.cpp please add them to the _SOURCES line.
kde_module_LTLIBRARIES = libkarbonkontourimport.la
diff --git a/filters/karbon/msod/Makefile.am b/filters/karbon/msod/Makefile.am
index f7191cd11..a555234a4 100644
--- a/filters/karbon/msod/Makefile.am
+++ b/filters/karbon/msod/Makefile.am
@@ -8,7 +8,7 @@ libkarbonmsodimport_la_LIBADD = $(KOFFICE_LIBS) $(LIBZ)
kde_module_LTLIBRARIES = libkarbonmsodimport.la
-libkarbonmsodimport_la_SOURCES = msodimport.cc msod.cc
+libkarbonmsodimport_la_SOURCES = msodimport.cpp msod.cpp
noinst_HEADERS = msodimport.h msod.h
diff --git a/filters/karbon/msod/msod.cc b/filters/karbon/msod/msod.cpp
index 35445e18f..35445e18f 100644
--- a/filters/karbon/msod/msod.cc
+++ b/filters/karbon/msod/msod.cpp
diff --git a/filters/karbon/msod/msodimport.cc b/filters/karbon/msod/msodimport.cpp
index bd272271e..bd272271e 100644
--- a/filters/karbon/msod/msodimport.cc
+++ b/filters/karbon/msod/msodimport.cpp
diff --git a/filters/karbon/oodraw/Makefile.am b/filters/karbon/oodraw/Makefile.am
index 4cca1e325..3ace9839b 100644
--- a/filters/karbon/oodraw/Makefile.am
+++ b/filters/karbon/oodraw/Makefile.am
@@ -11,7 +11,7 @@ INCLUDES= -I$(srcdir)/../../liboofilter \
kde_module_LTLIBRARIES = liboodrawimport.la
-liboodrawimport_la_SOURCES = oodrawimport.cc
+liboodrawimport_la_SOURCES = oodrawimport.cpp
liboodrawimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
liboodrawimport_la_LIBADD = ../../liboofilter/liboofilter.la \
../../../karbon/libkarboncommon.la \
diff --git a/filters/karbon/oodraw/oodrawimport.cc b/filters/karbon/oodraw/oodrawimport.cpp
index fba488671..fba488671 100644
--- a/filters/karbon/oodraw/oodrawimport.cc
+++ b/filters/karbon/oodraw/oodrawimport.cpp
diff --git a/filters/karbon/png/Makefile.am b/filters/karbon/png/Makefile.am
index 86d7e4114..2a12d23b6 100644
--- a/filters/karbon/png/Makefile.am
+++ b/filters/karbon/png/Makefile.am
@@ -20,7 +20,7 @@ noinst_HEADERS = \
pngexport.h
libkarbonpngexport_la_SOURCES = \
- pngexport.cc
+ pngexport.cpp
libkarbonpngexport_la_METASOURCES = \
AUTO
diff --git a/filters/karbon/png/pngexport.cc b/filters/karbon/png/pngexport.cpp
index 89b43d03f..89b43d03f 100644
--- a/filters/karbon/png/pngexport.cc
+++ b/filters/karbon/png/pngexport.cpp
diff --git a/filters/karbon/svg/Makefile.am b/filters/karbon/svg/Makefile.am
index b8e08060f..289f689a7 100644
--- a/filters/karbon/svg/Makefile.am
+++ b/filters/karbon/svg/Makefile.am
@@ -25,10 +25,10 @@ noinst_HEADERS = \
svgexport.h
libkarbonsvgexport_la_SOURCES = \
- svgexport.cc
+ svgexport.cpp
METASOURCES = AUTO
libkarbonsvgimport_la_SOURCES = \
- svgimport.cc
+ svgimport.cpp
diff --git a/filters/karbon/svg/svgexport.cc b/filters/karbon/svg/svgexport.cpp
index 41fd6a542..41fd6a542 100644
--- a/filters/karbon/svg/svgexport.cc
+++ b/filters/karbon/svg/svgexport.cpp
diff --git a/filters/karbon/svg/svgimport.cc b/filters/karbon/svg/svgimport.cpp
index 9d323d3da..9d323d3da 100644
--- a/filters/karbon/svg/svgimport.cc
+++ b/filters/karbon/svg/svgimport.cpp
diff --git a/filters/karbon/wmf/Makefile.am b/filters/karbon/wmf/Makefile.am
index 54bae415f..976888ac1 100644
--- a/filters/karbon/wmf/Makefile.am
+++ b/filters/karbon/wmf/Makefile.am
@@ -13,11 +13,11 @@ kde_module_LTLIBRARIES = libwmfimport.la libwmfexport.la
libwmfimport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libwmfimport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KOWMF) ../../../karbon/libkarboncommon.la
-libwmfimport_la_SOURCES = wmfimport.cc wmfimportparser.cc
+libwmfimport_la_SOURCES = wmfimport.cpp wmfimportparser.cpp
libwmfexport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libwmfexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KOWMF) ../../../karbon/libkarboncommon.la
-libwmfexport_la_SOURCES = wmfexport.cc
+libwmfexport_la_SOURCES = wmfexport.cpp
noinst_HEADERS = wmfimport.h wmfimportparser.h wmfexport.h
diff --git a/filters/karbon/wmf/wmfexport.cc b/filters/karbon/wmf/wmfexport.cpp
index de929ca88..de929ca88 100644
--- a/filters/karbon/wmf/wmfexport.cc
+++ b/filters/karbon/wmf/wmfexport.cpp
diff --git a/filters/karbon/wmf/wmfimport.cc b/filters/karbon/wmf/wmfimport.cpp
index f7dcdcf3d..f7dcdcf3d 100644
--- a/filters/karbon/wmf/wmfimport.cc
+++ b/filters/karbon/wmf/wmfimport.cpp
diff --git a/filters/karbon/wmf/wmfimportparser.cc b/filters/karbon/wmf/wmfimportparser.cpp
index 275490fef..275490fef 100644
--- a/filters/karbon/wmf/wmfimportparser.cc
+++ b/filters/karbon/wmf/wmfimportparser.cpp
diff --git a/filters/karbon/xaml/Makefile.am b/filters/karbon/xaml/Makefile.am
index f7036adac..9bf1e0686 100644
--- a/filters/karbon/xaml/Makefile.am
+++ b/filters/karbon/xaml/Makefile.am
@@ -26,10 +26,10 @@ noinst_HEADERS = \
xamlimport.h
libkarbonxamlexport_la_SOURCES = \
- xamlexport.cc
+ xamlexport.cpp
libkarbonxamlimport_la_SOURCES = \
- xamlimport.cc
+ xamlimport.cpp
METASOURCES = AUTO
diff --git a/filters/karbon/xaml/xamlexport.cc b/filters/karbon/xaml/xamlexport.cpp
index e1599a8cf..e1599a8cf 100644
--- a/filters/karbon/xaml/xamlexport.cc
+++ b/filters/karbon/xaml/xamlexport.cpp
diff --git a/filters/karbon/xaml/xamlimport.cc b/filters/karbon/xaml/xamlimport.cpp
index 002001e27..002001e27 100644
--- a/filters/karbon/xaml/xamlimport.cc
+++ b/filters/karbon/xaml/xamlimport.cpp
diff --git a/filters/karbon/xcf/Makefile.am b/filters/karbon/xcf/Makefile.am
index f3a1b3ac2..bc16ca76d 100644
--- a/filters/karbon/xcf/Makefile.am
+++ b/filters/karbon/xcf/Makefile.am
@@ -20,7 +20,7 @@ noinst_HEADERS = \
xcfexport.h
libkarbonxcfexport_la_SOURCES = \
- xcfexport.cc
+ xcfexport.cpp
libkarbonxcfexport_la_METASOURCES = \
AUTO
diff --git a/filters/karbon/xcf/xcfexport.cc b/filters/karbon/xcf/xcfexport.cpp
index 215c4f018..215c4f018 100644
--- a/filters/karbon/xcf/xcfexport.cc
+++ b/filters/karbon/xcf/xcfexport.cpp
diff --git a/filters/karbon/xfig/xfigimport.cc b/filters/karbon/xfig/xfigimport.cpp
index c3d6ab6a9..c3d6ab6a9 100644
--- a/filters/karbon/xfig/xfigimport.cc
+++ b/filters/karbon/xfig/xfigimport.cpp
diff --git a/filters/karbon/xfig/xfigimport_factory.cc b/filters/karbon/xfig/xfigimport_factory.cpp
index 1e2311997..1e2311997 100644
--- a/filters/karbon/xfig/xfigimport_factory.cc
+++ b/filters/karbon/xfig/xfigimport_factory.cpp
diff --git a/filters/kchart/svg/Makefile.am b/filters/kchart/svg/Makefile.am
index 6c440ed1b..864653e33 100644
--- a/filters/kchart/svg/Makefile.am
+++ b/filters/kchart/svg/Makefile.am
@@ -9,7 +9,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) \
####### Files
kde_module_LTLIBRARIES = libkchartsvgexport.la
-libkchartsvgexport_la_SOURCES = svgexport.cc
+libkchartsvgexport_la_SOURCES = svgexport.cpp
libkchartsvgexport_la_LDFLAGS = -module $(KDE_PLUGIN) -no-undefined $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkchartsvgexport_la_LIBADD = ../../../kchart/libkchartcommon.la $(KOFFICE_LIBS)
noinst_HEADERS = \
diff --git a/filters/kchart/svg/svgexport.cc b/filters/kchart/svg/svgexport.cpp
index 062ccd9b0..062ccd9b0 100644
--- a/filters/kchart/svg/svgexport.cc
+++ b/filters/kchart/svg/svgexport.cpp
diff --git a/filters/kformula/latex/Makefile.am b/filters/kformula/latex/Makefile.am
index 95bee7d58..25bf902f8 100644
--- a/filters/kformula/latex/Makefile.am
+++ b/filters/kformula/latex/Makefile.am
@@ -8,13 +8,13 @@ libkfolatexexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA)
kde_module_LTLIBRARIES = libkfolatexexport.la
-libkfolatexexport_la_SOURCES = latexexport.cc
+libkfolatexexport_la_SOURCES = latexexport.cpp
noinst_HEADERS = latexexport.h
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kformula/latex/latexexport.cc b/filters/kformula/latex/latexexport.cpp
index d47e36bd3..d47e36bd3 100644
--- a/filters/kformula/latex/latexexport.cc
+++ b/filters/kformula/latex/latexexport.cpp
diff --git a/filters/kformula/mathml/Makefile.am b/filters/kformula/mathml/Makefile.am
index cdd07955a..0d2a9c386 100644
--- a/filters/kformula/mathml/Makefile.am
+++ b/filters/kformula/mathml/Makefile.am
@@ -10,9 +10,9 @@ libkfomathmlimport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA)
kde_module_LTLIBRARIES = libkfomathmlexport.la libkfomathmlimport.la
-libkfomathmlexport_la_SOURCES = mathmlexport.cc
+libkfomathmlexport_la_SOURCES = mathmlexport.cpp
-libkfomathmlimport_la_SOURCES = mathmlimport.cc
+libkfomathmlimport_la_SOURCES = mathmlimport.cpp
noinst_HEADERS = mathmlexport.h mathmlimport.h
diff --git a/filters/kformula/mathml/mathmlexport.cc b/filters/kformula/mathml/mathmlexport.cpp
index 37951d2de..37951d2de 100644
--- a/filters/kformula/mathml/mathmlexport.cc
+++ b/filters/kformula/mathml/mathmlexport.cpp
diff --git a/filters/kformula/mathml/mathmlimport.cc b/filters/kformula/mathml/mathmlimport.cpp
index b8fa07ed4..b8fa07ed4 100644
--- a/filters/kformula/mathml/mathmlimport.cc
+++ b/filters/kformula/mathml/mathmlimport.cpp
diff --git a/filters/kformula/png/Makefile.am b/filters/kformula/png/Makefile.am
index 277f063d2..43b599bf2 100644
--- a/filters/kformula/png/Makefile.am
+++ b/filters/kformula/png/Makefile.am
@@ -8,13 +8,13 @@ libkfopngexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA)
kde_module_LTLIBRARIES = libkfopngexport.la
-libkfopngexport_la_SOURCES = pngexport.cc pngexportdia.cc
+libkfopngexport_la_SOURCES = pngexport.cpp pngexportdia.cpp
noinst_HEADERS = pngexport.h pngexportdia.h
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kformula/png/pngexport.cc b/filters/kformula/png/pngexport.cpp
index 47b0d316f..47b0d316f 100644
--- a/filters/kformula/png/pngexport.cc
+++ b/filters/kformula/png/pngexport.cpp
diff --git a/filters/kformula/png/pngexportdia.cc b/filters/kformula/png/pngexportdia.cpp
index 938fed782..938fed782 100644
--- a/filters/kformula/png/pngexportdia.cc
+++ b/filters/kformula/png/pngexportdia.cpp
diff --git a/filters/kformula/svg/Makefile.am b/filters/kformula/svg/Makefile.am
index 144cfbb2a..9ef58a21a 100644
--- a/filters/kformula/svg/Makefile.am
+++ b/filters/kformula/svg/Makefile.am
@@ -8,13 +8,13 @@ libkfosvgexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA)
kde_module_LTLIBRARIES = libkfosvgexport.la
-libkfosvgexport_la_SOURCES = svgexport.cc
+libkfosvgexport_la_SOURCES = svgexport.cpp
noinst_HEADERS = svgexport.h
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kformula/svg/svgexport.cc b/filters/kformula/svg/svgexport.cpp
index 35896ac1b..35896ac1b 100644
--- a/filters/kformula/svg/svgexport.cc
+++ b/filters/kformula/svg/svgexport.cpp
diff --git a/filters/kpresenter/kword/Makefile.am b/filters/kpresenter/kword/Makefile.am
index 0e579f5cb..829aa93c9 100644
--- a/filters/kpresenter/kword/Makefile.am
+++ b/filters/kpresenter/kword/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libkprkword.la
-libkprkword_la_SOURCES = kprkword.cc
+libkprkword_la_SOURCES = kprkword.cpp
libkprkword_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libkprkword_la_LIBADD = $(KOFFICE_LIBS)
diff --git a/filters/kpresenter/kword/kprkword.cc b/filters/kpresenter/kword/kprkword.cpp
index fc0f50cd0..fc0f50cd0 100644
--- a/filters/kpresenter/kword/kprkword.cc
+++ b/filters/kpresenter/kword/kprkword.cpp
diff --git a/filters/kpresenter/ooimpress/Makefile.am b/filters/kpresenter/ooimpress/Makefile.am
index b69dc04cf..f17330405 100644
--- a/filters/kpresenter/ooimpress/Makefile.am
+++ b/filters/kpresenter/ooimpress/Makefile.am
@@ -6,11 +6,11 @@ INCLUDES= -I$(srcdir)/../../liboofilter $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libooimpressimport.la libooimpressexport.la
-libooimpressimport_la_SOURCES = ooimpressimport.cc
+libooimpressimport_la_SOURCES = ooimpressimport.cpp
libooimpressimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libooimpressimport_la_LIBADD = ../../liboofilter/liboofilter.la $(KOFFICE_LIBS)
-libooimpressexport_la_SOURCES = ooimpressexport.cc stylefactory.cc
+libooimpressexport_la_SOURCES = ooimpressexport.cpp stylefactory.cpp
libooimpressexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libooimpressexport_la_LIBADD = ../../liboofilter/liboofilter.la $(KOFFICE_LIBS)
diff --git a/filters/kpresenter/ooimpress/ooimpressexport.cc b/filters/kpresenter/ooimpress/ooimpressexport.cpp
index 507ba84e3..507ba84e3 100644
--- a/filters/kpresenter/ooimpress/ooimpressexport.cc
+++ b/filters/kpresenter/ooimpress/ooimpressexport.cpp
diff --git a/filters/kpresenter/ooimpress/ooimpressimport.cc b/filters/kpresenter/ooimpress/ooimpressimport.cpp
index 5d6c9da4a..5d6c9da4a 100644
--- a/filters/kpresenter/ooimpress/ooimpressimport.cc
+++ b/filters/kpresenter/ooimpress/ooimpressimport.cpp
diff --git a/filters/kpresenter/ooimpress/stylefactory.cc b/filters/kpresenter/ooimpress/stylefactory.cpp
index e50b652e2..e50b652e2 100644
--- a/filters/kpresenter/ooimpress/stylefactory.cc
+++ b/filters/kpresenter/ooimpress/stylefactory.cpp
diff --git a/filters/kpresenter/powerpoint/import/Makefile.am b/filters/kpresenter/powerpoint/import/Makefile.am
index 91f27887b..0034dfbb5 100644
--- a/filters/kpresenter/powerpoint/import/Makefile.am
+++ b/filters/kpresenter/powerpoint/import/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = -I$(srcdir) -I$(srcdir)/../libppt $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libpowerpointimport.la
-libpowerpointimport_la_SOURCES = powerpointimport.cc
+libpowerpointimport_la_SOURCES = powerpointimport.cpp
libpowerpointimport_la_LIBADD = $(KOFFICE_LIBS) ../libppt/libppt.la
libpowerpointimport_la_LDFLAGS = -module $(KDE_PLUGIN)
noinst_HEADERS = powerpointimport.h
diff --git a/filters/kpresenter/powerpoint/import/powerpointimport.cc b/filters/kpresenter/powerpoint/import/powerpointimport.cpp
index 4291c0a4e..4291c0a4e 100644
--- a/filters/kpresenter/powerpoint/import/powerpointimport.cc
+++ b/filters/kpresenter/powerpoint/import/powerpointimport.cpp
diff --git a/filters/kpresenter/svg/Makefile.am b/filters/kpresenter/svg/Makefile.am
index dcfa91f28..c1024e311 100644
--- a/filters/kpresenter/svg/Makefile.am
+++ b/filters/kpresenter/svg/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) \
####### Files
kde_module_LTLIBRARIES = libkpresentersvgexport.la
-libkpresentersvgexport_la_SOURCES = svgexport.cc
+libkpresentersvgexport_la_SOURCES = svgexport.cpp
libkpresentersvgexport_la_LDFLAGS = -module $(KDE_PLUGIN) -no-undefined $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkpresentersvgexport_la_LIBADD = ../../../kpresenter/libkpresenterprivate.la $(KOFFICE_LIBS)
noinst_HEADERS = \
diff --git a/filters/kpresenter/svg/svgexport.cc b/filters/kpresenter/svg/svgexport.cc
deleted file mode 100644
index 5b6ed8928..000000000
--- a/filters/kpresenter/svg/svgexport.cc
+++ /dev/null
@@ -1,100 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2005 Laurent Montel <montel@kde.org>
- code based on svgexport.cc from Inge Wallin <inge@lysator.liu.se>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301 USA.
-*/
-
-#include <tqpicture.h>
-#include <tqpainter.h>
-
-#include <tdemessagebox.h>
-
-#include <KoFilterChain.h>
-#include <KoStore.h>
-//#include <KoStoreDevice.h>
-#include <kgenericfactory.h>
-
-#include "KPrDocument.h"
-#include "KPrView.h"
-#include "KPrCanvas.h"
-
-#include "svgexport.h"
-
-
-typedef KGenericFactory<SvgExport, KoFilter> SvgExportFactory;
-K_EXPORT_COMPONENT_FACTORY( libkpresentersvgexport, SvgExportFactory( "svgexport" ) )
-
-SvgExport::SvgExport(KoFilter *, const char *, const TQStringList&)
- : KoFilter()
-{
-}
-
-SvgExport::~SvgExport()
-{
-}
-
-
-KoFilter::ConversionStatus
-SvgExport::convert(const TQCString& from, const TQCString& to)
-{
- KoDocument * document = m_chain->inputDocument();
-
- if ( !document )
- return KoFilter::StupidError;
-
- if ( strcmp(document->className(), "KPrDocument") != 0)
- {
- kdWarning() << "document isn't a KPrDocument but a "
- << document->className() << endl;
- return KoFilter::NotImplemented;
- }
-
- // Check for proper conversion.
- if ( from != "application/x-kpresenter" || to != "image/svg+xml" )
- {
- kdWarning() << "Invalid mimetypes " << to << " " << from << endl;
- return KoFilter::NotImplemented;
- }
- KPrDocument * kpresenterdoc = const_cast<KPrDocument *>(static_cast<const KPrDocument *>(document));
-
- if ( kpresenterdoc->mimeType() != "application/x-kpresenter" )
- {
- kdWarning() << "Invalid document mimetype " << kpresenterdoc->mimeType() << endl;
- return KoFilter::NotImplemented;
- }
- KoPageLayout layoutPage= kpresenterdoc->pageLayout();
- int width = int( layoutPage.ptWidth );
- int height = int( layoutPage.ptHeight );
-
- TQPicture picture;
- TQPainter painter(&picture);
- TQRect rect(TQPoint(0, 0), TQPoint(width, height));
- kpresenterdoc->paintContent(painter, rect, false);
- painter.end();
-
- if ( !picture.save( m_chain->outputFile(), "SVG" ) ) {
- KMessageBox::error( 0, i18n( "Failed to write file." ),
- i18n( "SVG Export Error" ) );
- }
-
- return KoFilter::OK;
-}
-
-
-#include "svgexport.moc"
-
-
diff --git a/filters/kpresenter/svg/svgexport.cpp b/filters/kpresenter/svg/svgexport.cpp
new file mode 100644
index 000000000..711864df4
--- /dev/null
+++ b/filters/kpresenter/svg/svgexport.cpp
@@ -0,0 +1,100 @@
+/* This file is part of the KDE project
+ Copyright (C) 2005 Laurent Montel <montel@kde.org>
+ code based on svgexport.cpp from Inge Wallin <inge@lysator.liu.se>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301 USA.
+*/
+
+#include <tqpicture.h>
+#include <tqpainter.h>
+
+#include <tdemessagebox.h>
+
+#include <KoFilterChain.h>
+#include <KoStore.h>
+//#include <KoStoreDevice.h>
+#include <kgenericfactory.h>
+
+#include "KPrDocument.h"
+#include "KPrView.h"
+#include "KPrCanvas.h"
+
+#include "svgexport.h"
+
+
+typedef KGenericFactory<SvgExport, KoFilter> SvgExportFactory;
+K_EXPORT_COMPONENT_FACTORY( libkpresentersvgexport, SvgExportFactory( "svgexport" ) )
+
+SvgExport::SvgExport(KoFilter *, const char *, const TQStringList&)
+ : KoFilter()
+{
+}
+
+SvgExport::~SvgExport()
+{
+}
+
+
+KoFilter::ConversionStatus
+SvgExport::convert(const TQCString& from, const TQCString& to)
+{
+ KoDocument * document = m_chain->inputDocument();
+
+ if ( !document )
+ return KoFilter::StupidError;
+
+ if ( strcmp(document->className(), "KPrDocument") != 0)
+ {
+ kdWarning() << "document isn't a KPrDocument but a "
+ << document->className() << endl;
+ return KoFilter::NotImplemented;
+ }
+
+ // Check for proper conversion.
+ if ( from != "application/x-kpresenter" || to != "image/svg+xml" )
+ {
+ kdWarning() << "Invalid mimetypes " << to << " " << from << endl;
+ return KoFilter::NotImplemented;
+ }
+ KPrDocument * kpresenterdoc = const_cast<KPrDocument *>(static_cast<const KPrDocument *>(document));
+
+ if ( kpresenterdoc->mimeType() != "application/x-kpresenter" )
+ {
+ kdWarning() << "Invalid document mimetype " << kpresenterdoc->mimeType() << endl;
+ return KoFilter::NotImplemented;
+ }
+ KoPageLayout layoutPage= kpresenterdoc->pageLayout();
+ int width = int( layoutPage.ptWidth );
+ int height = int( layoutPage.ptHeight );
+
+ TQPicture picture;
+ TQPainter painter(&picture);
+ TQRect rect(TQPoint(0, 0), TQPoint(width, height));
+ kpresenterdoc->paintContent(painter, rect, false);
+ painter.end();
+
+ if ( !picture.save( m_chain->outputFile(), "SVG" ) ) {
+ KMessageBox::error( 0, i18n( "Failed to write file." ),
+ i18n( "SVG Export Error" ) );
+ }
+
+ return KoFilter::OK;
+}
+
+
+#include "svgexport.moc"
+
+
diff --git a/filters/kpresenter/svg/svgexport.h b/filters/kpresenter/svg/svgexport.h
index d46ba5faa..e08171ec5 100644
--- a/filters/kpresenter/svg/svgexport.h
+++ b/filters/kpresenter/svg/svgexport.h
@@ -1,6 +1,6 @@
/* This file is part of the KDE project
Copyright (C) 2005 Laurent Montel <montel@kde.org>
- code based on svgexport.cc from Inge Wallin <inge@lysator.liu.se>
+ code based on svgexport.cpp from Inge Wallin <inge@lysator.liu.se>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
diff --git a/filters/kspread/applixspread/Makefile.am b/filters/kspread/applixspread/Makefile.am
index 5d2d42e4e..667c76494 100644
--- a/filters/kspread/applixspread/Makefile.am
+++ b/filters/kspread/applixspread/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libapplixspreadimport.la
-libapplixspreadimport_la_SOURCES = applixspreadimport.cc
+libapplixspreadimport_la_SOURCES = applixspreadimport.cpp
libapplixspreadimport_la_LIBADD = $(KOFFICE_LIBS)
libapplixspreadimport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
noinst_HEADERS = applixspreadimport.h
diff --git a/filters/kspread/applixspread/applixspreadimport.cc b/filters/kspread/applixspread/applixspreadimport.cpp
index cb60c83ae..cb60c83ae 100644
--- a/filters/kspread/applixspread/applixspreadimport.cc
+++ b/filters/kspread/applixspread/applixspreadimport.cpp
diff --git a/filters/kspread/applixspread/status.html b/filters/kspread/applixspread/status.html
index c944ef5c0..859f8b155 100644
--- a/filters/kspread/applixspread/status.html
+++ b/filters/kspread/applixspread/status.html
@@ -236,7 +236,7 @@
<spacer size="20">If the value of r, g or b if less then 0 you must set it to 0 .<BR>
<BR>
<spacer size="20">For examples inside koffice look a this files too<br>
- <spacer size="20"><I>koffice/kimageshop/core/kis_color.cc and kis_color.h</I><BR>
+ <spacer size="20"><I>koffice/kimageshop/core/kis_color.cpp and kis_color.h</I><BR>
<BR><BR>
<spacer size="10"><U>2.3. Colormap end:</U><BR>
diff --git a/filters/kspread/csv/DESIGN b/filters/kspread/csv/DESIGN
index 9c6c4c909..5f9a3ed13 100644
--- a/filters/kspread/csv/DESIGN
+++ b/filters/kspread/csv/DESIGN
@@ -32,6 +32,6 @@ EOL : End Of Line.
Ugly isn't it ? :) One can't be good in drawings AND in hacking :)
-That's all. For the rest, see csvfilter.cc
+That's all. For the rest, see csvfilter.cpp
David Faure <faure@kde.org>, 1999
diff --git a/filters/kspread/csv/Makefile.am b/filters/kspread/csv/Makefile.am
index 32c8408a5..c46b0302a 100644
--- a/filters/kspread/csv/Makefile.am
+++ b/filters/kspread/csv/Makefile.am
@@ -7,11 +7,11 @@ INCLUDES= -I$(srcdir) -I$(top_srcdir)/kspread $(KOFFICE_INCLUDES) \
kde_module_LTLIBRARIES = libcsvimport.la libcsvexport.la
-libcsvimport_la_SOURCES = csvimport.cc xmltree.cc csvdialog.cpp dialogui.ui
+libcsvimport_la_SOURCES = csvimport.cpp xmltree.cpp csvdialog.cpp dialogui.ui
libcsvimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libcsvimport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la
-libcsvexport_la_SOURCES = csvexport.cc csvexportdialog.cpp exportdialogui.ui
+libcsvexport_la_SOURCES = csvexport.cpp csvexportdialog.cpp exportdialogui.ui
libcsvexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libcsvexport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la
diff --git a/filters/kspread/csv/csvexport.cc b/filters/kspread/csv/csvexport.cpp
index ceeb8b5ec..ceeb8b5ec 100644
--- a/filters/kspread/csv/csvexport.cc
+++ b/filters/kspread/csv/csvexport.cpp
diff --git a/filters/kspread/csv/csvimport.cc b/filters/kspread/csv/csvimport.cpp
index 72cadfa2b..72cadfa2b 100644
--- a/filters/kspread/csv/csvimport.cc
+++ b/filters/kspread/csv/csvimport.cpp
diff --git a/filters/kspread/csv/status.html b/filters/kspread/csv/status.html
index c4379ade8..e31c27613 100644
--- a/filters/kspread/csv/status.html
+++ b/filters/kspread/csv/status.html
@@ -117,7 +117,7 @@ EOL : End Of Line.
Ugly isn't it ? :) One can't be good in drawings AND in hacking :)
-That's all. For the rest, see csvfilter.cc
+That's all. For the rest, see csvfilter.cpp
David Faure &lt;faure@kde.org&gt;, 1999
</PRE>
diff --git a/filters/kspread/csv/xmltree.cc b/filters/kspread/csv/xmltree.cpp
index f5c56373a..f5c56373a 100644
--- a/filters/kspread/csv/xmltree.cc
+++ b/filters/kspread/csv/xmltree.cpp
diff --git a/filters/kspread/dbase/Makefile.am b/filters/kspread/dbase/Makefile.am
index ea7713283..5802ff7ea 100644
--- a/filters/kspread/dbase/Makefile.am
+++ b/filters/kspread/dbase/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libdbaseimport.la
-libdbaseimport_la_SOURCES = dbaseimport.cc dbase.cpp
+libdbaseimport_la_SOURCES = dbaseimport.cpp dbase.cpp
libdbaseimport_la_LIBADD = $(KOFFICE_LIBS)
libdbaseimport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
noinst_HEADERS = dbaseimport.h dbase.h
diff --git a/filters/kspread/dbase/dbaseimport.cc b/filters/kspread/dbase/dbaseimport.cpp
index 001b35a20..001b35a20 100644
--- a/filters/kspread/dbase/dbaseimport.cc
+++ b/filters/kspread/dbase/dbaseimport.cpp
diff --git a/filters/kspread/excel/Makefile.am b/filters/kspread/excel/Makefile.am
index 73d5db56a..329f247c4 100644
--- a/filters/kspread/excel/Makefile.am
+++ b/filters/kspread/excel/Makefile.am
@@ -12,4 +12,4 @@ METASOURCES = AUTO
servicedir = $(kde_servicesdir)
messages: rc.cpp
- $(XGETTEXT) *.cc *.cpp -o $(podir)/kspreadexcelfilter.pot
+ $(XGETTEXT) *.cpp *.cpp -o $(podir)/kspreadexcelfilter.pot
diff --git a/filters/kspread/excel/excelexport.cc b/filters/kspread/excel/excelexport.cpp
index 0ecf41f7b..0ecf41f7b 100644
--- a/filters/kspread/excel/excelexport.cc
+++ b/filters/kspread/excel/excelexport.cpp
diff --git a/filters/kspread/excel/import/Makefile.am b/filters/kspread/excel/import/Makefile.am
index 9f371d22d..1f966ef73 100644
--- a/filters/kspread/excel/import/Makefile.am
+++ b/filters/kspread/excel/import/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) -I$(srcdir)/../sidewinder $(KOFFICE_INCLUDES) $(all_includ
kde_module_LTLIBRARIES = libexcelimport.la
-libexcelimport_la_SOURCES = excelimport.cc
+libexcelimport_la_SOURCES = excelimport.cpp
libexcelimport_la_LIBADD = $(KOFFICE_LIBS) ../sidewinder/libsidewinder.la
libexcelimport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
noinst_HEADERS = excelimport.h
diff --git a/filters/kspread/excel/import/excelimport.cc b/filters/kspread/excel/import/excelimport.cpp
index 19f5888bf..19f5888bf 100644
--- a/filters/kspread/excel/import/excelimport.cc
+++ b/filters/kspread/excel/import/excelimport.cpp
diff --git a/filters/kspread/gnumeric/Makefile.am b/filters/kspread/gnumeric/Makefile.am
index 6bb9608ed..a16f0024e 100644
--- a/filters/kspread/gnumeric/Makefile.am
+++ b/filters/kspread/gnumeric/Makefile.am
@@ -6,11 +6,11 @@ INCLUDES= -I$(srcdir) -I$(top_srcdir)/kspread $(KOFFICE_INCLUDES) \
####### Files
kde_module_LTLIBRARIES = libgnumericexport.la libgnumericimport.la
-libgnumericexport_la_SOURCES = gnumericexport.cc
+libgnumericexport_la_SOURCES = gnumericexport.cpp
libgnumericexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libgnumericexport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la
-libgnumericimport_la_SOURCES = gnumericimport.cc
+libgnumericimport_la_SOURCES = gnumericimport.cpp
libgnumericimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libgnumericimport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la
diff --git a/filters/kspread/gnumeric/gnumericexport.cc b/filters/kspread/gnumeric/gnumericexport.cpp
index 28f5453e9..28f5453e9 100644
--- a/filters/kspread/gnumeric/gnumericexport.cc
+++ b/filters/kspread/gnumeric/gnumericexport.cpp
diff --git a/filters/kspread/gnumeric/gnumericimport.cc b/filters/kspread/gnumeric/gnumericimport.cpp
index f437aad00..f437aad00 100644
--- a/filters/kspread/gnumeric/gnumericimport.cc
+++ b/filters/kspread/gnumeric/gnumericimport.cpp
diff --git a/filters/kspread/html/Makefile.am b/filters/kspread/html/Makefile.am
index 87018febd..b170396fd 100644
--- a/filters/kspread/html/Makefile.am
+++ b/filters/kspread/html/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES= -I$(srcdir) -I$(top_srcdir)/kspread $(KOFFICE_INCLUDES) \
kde_module_LTLIBRARIES = libkspreadhtmlexport.la
-libkspreadhtmlexport_la_SOURCES = htmlexport.cc exportdialog.cc exportwidget.ui
+libkspreadhtmlexport_la_SOURCES = htmlexport.cpp exportdialog.cpp exportwidget.ui
libkspreadhtmlexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libkspreadhtmlexport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la
diff --git a/filters/kspread/html/exportdialog.cc b/filters/kspread/html/exportdialog.cpp
index 8df7e0ce2..8df7e0ce2 100644
--- a/filters/kspread/html/exportdialog.cc
+++ b/filters/kspread/html/exportdialog.cpp
diff --git a/filters/kspread/html/htmlexport.cc b/filters/kspread/html/htmlexport.cpp
index f680207e4..f680207e4 100644
--- a/filters/kspread/html/htmlexport.cc
+++ b/filters/kspread/html/htmlexport.cpp
diff --git a/filters/kspread/kexi/Makefile.am b/filters/kspread/kexi/Makefile.am
index 6f76a2969..acfedf973 100644
--- a/filters/kspread/kexi/Makefile.am
+++ b/filters/kspread/kexi/Makefile.am
@@ -7,9 +7,9 @@ INCLUDES= -I$(srcdir) -I$(top_srcdir)/kspread -I$(top_srcdir)/kexi $(KOFFICE_INC
kde_module_LTLIBRARIES = libkspreadkexiimport.la
-libkspreadkexiimport_la_SOURCES = kspread_kexiimport.cc \
+libkspreadkexiimport_la_SOURCES = kspread_kexiimport.cpp \
kspread_kexiimportdialogbase.ui \
- kspread_kexiimportdialog.cc
+ kspread_kexiimportdialog.cpp
libkspreadkexiimport_la_LDFLAGS = -avoid-version -module -no-undefined \
$(all_libraries)
libkspreadkexiimport_la_LIBADD = ../../../kexi/kexidb/libkexidb.la \
diff --git a/filters/kspread/kexi/kspread_kexiimport.cc b/filters/kspread/kexi/kspread_kexiimport.cpp
index 6100dabe3..6100dabe3 100644
--- a/filters/kspread/kexi/kspread_kexiimport.cc
+++ b/filters/kspread/kexi/kspread_kexiimport.cpp
diff --git a/filters/kspread/kexi/kspread_kexiimportdialog.cc b/filters/kspread/kexi/kspread_kexiimportdialog.cpp
index 0e15acbe7..0e15acbe7 100644
--- a/filters/kspread/kexi/kspread_kexiimportdialog.cc
+++ b/filters/kspread/kexi/kspread_kexiimportdialog.cpp
diff --git a/filters/kspread/latex/export/Makefile.am b/filters/kspread/latex/export/Makefile.am
index 053dd4323..0460b4be6 100644
--- a/filters/kspread/latex/export/Makefile.am
+++ b/filters/kspread/latex/export/Makefile.am
@@ -8,11 +8,11 @@ libkspreadlatexexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA)
kde_module_LTLIBRARIES = libkspreadlatexexport.la
-libkspreadlatexexport_la_SOURCES = cell.cc column.cc config.cc document.cc fileheader.cc \
- format.cc latexexportdia.ui kspreadlatexexportdiaImpl.cc \
- latexexport.cc latexexportIface.cc latexexportIface.skel \
- map.cc pen.cc row.cc spreadsheet.cc table.cc \
- xmlparser.cc
+libkspreadlatexexport_la_SOURCES = cell.cpp column.cpp config.cpp document.cpp fileheader.cpp \
+ format.cpp latexexportdia.ui kspreadlatexexportdiaImpl.cpp \
+ latexexport.cpp latexexportIface.cpp latexexportIface.skel \
+ map.cpp pen.cpp row.cpp spreadsheet.cpp table.cpp \
+ xmlparser.cpp
noinst_HEADERS = cell.h column.h config.h document.h fileheader.h format.h \
kspreadlatexexportdiaImpl.h latexexport.h latexexportIface.h \
@@ -20,7 +20,7 @@ noinst_HEADERS = cell.h column.h config.h document.h fileheader.h format.h \
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kspread/latex/export/cell.cc b/filters/kspread/latex/export/cell.cpp
index 74eb95bb6..74eb95bb6 100644
--- a/filters/kspread/latex/export/cell.cc
+++ b/filters/kspread/latex/export/cell.cpp
diff --git a/filters/kspread/latex/export/column.cc b/filters/kspread/latex/export/column.cpp
index fece8cb8c..fece8cb8c 100644
--- a/filters/kspread/latex/export/column.cc
+++ b/filters/kspread/latex/export/column.cpp
diff --git a/filters/kspread/latex/export/config.cc b/filters/kspread/latex/export/config.cpp
index 8460aae41..8460aae41 100644
--- a/filters/kspread/latex/export/config.cc
+++ b/filters/kspread/latex/export/config.cpp
diff --git a/filters/kspread/latex/export/document.cc b/filters/kspread/latex/export/document.cpp
index 45cdbb734..45cdbb734 100644
--- a/filters/kspread/latex/export/document.cc
+++ b/filters/kspread/latex/export/document.cpp
diff --git a/filters/kspread/latex/export/fileheader.cc b/filters/kspread/latex/export/fileheader.cpp
index 07b1fbe4e..07b1fbe4e 100644
--- a/filters/kspread/latex/export/fileheader.cc
+++ b/filters/kspread/latex/export/fileheader.cpp
diff --git a/filters/kspread/latex/export/format.cc b/filters/kspread/latex/export/format.cpp
index 96f2ad089..96f2ad089 100644
--- a/filters/kspread/latex/export/format.cc
+++ b/filters/kspread/latex/export/format.cpp
diff --git a/filters/kspread/latex/export/formula.cc b/filters/kspread/latex/export/formula.cpp
index 1d805a2a3..1d805a2a3 100644
--- a/filters/kspread/latex/export/formula.cc
+++ b/filters/kspread/latex/export/formula.cpp
diff --git a/filters/kspread/latex/export/kspreadlatexexportdiaImpl.cc b/filters/kspread/latex/export/kspreadlatexexportdiaImpl.cpp
index b088afe14..b088afe14 100644
--- a/filters/kspread/latex/export/kspreadlatexexportdiaImpl.cc
+++ b/filters/kspread/latex/export/kspreadlatexexportdiaImpl.cpp
diff --git a/filters/kspread/latex/export/latexexport.cc b/filters/kspread/latex/export/latexexport.cpp
index d9ebd7946..d9ebd7946 100644
--- a/filters/kspread/latex/export/latexexport.cc
+++ b/filters/kspread/latex/export/latexexport.cpp
diff --git a/filters/kspread/latex/export/latexexportIface.cc b/filters/kspread/latex/export/latexexportIface.cpp
index f99e6745b..f99e6745b 100644
--- a/filters/kspread/latex/export/latexexportIface.cc
+++ b/filters/kspread/latex/export/latexexportIface.cpp
diff --git a/filters/kspread/latex/export/map.cc b/filters/kspread/latex/export/map.cpp
index 886f6c115..886f6c115 100644
--- a/filters/kspread/latex/export/map.cc
+++ b/filters/kspread/latex/export/map.cpp
diff --git a/filters/kspread/latex/export/pen.cc b/filters/kspread/latex/export/pen.cpp
index 03a87bd80..03a87bd80 100644
--- a/filters/kspread/latex/export/pen.cc
+++ b/filters/kspread/latex/export/pen.cpp
diff --git a/filters/kspread/latex/export/row.cc b/filters/kspread/latex/export/row.cpp
index 3aaaaaba7..3aaaaaba7 100644
--- a/filters/kspread/latex/export/row.cc
+++ b/filters/kspread/latex/export/row.cpp
diff --git a/filters/kspread/latex/export/spreadsheet.cc b/filters/kspread/latex/export/spreadsheet.cpp
index afb02cad6..afb02cad6 100644
--- a/filters/kspread/latex/export/spreadsheet.cc
+++ b/filters/kspread/latex/export/spreadsheet.cpp
diff --git a/filters/kspread/latex/export/table.cc b/filters/kspread/latex/export/table.cpp
index 0f300356f..0f300356f 100644
--- a/filters/kspread/latex/export/table.cc
+++ b/filters/kspread/latex/export/table.cpp
diff --git a/filters/kspread/latex/export/xmlparser.cc b/filters/kspread/latex/export/xmlparser.cpp
index fb2c8e1f2..fb2c8e1f2 100644
--- a/filters/kspread/latex/export/xmlparser.cc
+++ b/filters/kspread/latex/export/xmlparser.cpp
diff --git a/filters/kspread/libkspreadexport/KSpreadBaseWorker.cc b/filters/kspread/libkspreadexport/KSpreadBaseWorker.cpp
index cc7b2b462..cc7b2b462 100644
--- a/filters/kspread/libkspreadexport/KSpreadBaseWorker.cc
+++ b/filters/kspread/libkspreadexport/KSpreadBaseWorker.cpp
diff --git a/filters/kspread/libkspreadexport/KSpreadLeader.cc b/filters/kspread/libkspreadexport/KSpreadLeader.cpp
index 8e300c7d1..8e300c7d1 100644
--- a/filters/kspread/libkspreadexport/KSpreadLeader.cc
+++ b/filters/kspread/libkspreadexport/KSpreadLeader.cpp
diff --git a/filters/kspread/libkspreadexport/Makefile.am b/filters/kspread/libkspreadexport/Makefile.am
index a36b3ad92..4411804a5 100644
--- a/filters/kspread/libkspreadexport/Makefile.am
+++ b/filters/kspread/libkspreadexport/Makefile.am
@@ -11,7 +11,7 @@ libkspreadexport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.l
lib_LTLIBRARIES = libkspreadexport.la
-libkspreadexport_la_SOURCES = KSpreadLeader.cc KSpreadBaseWorker.cc
+libkspreadexport_la_SOURCES = KSpreadLeader.cpp KSpreadBaseWorker.cpp
noinst_HEADERS = KSpreadLeader.h KSpreadBaseWorker.h
diff --git a/filters/kspread/opencalc/Makefile.am b/filters/kspread/opencalc/Makefile.am
index 65741b1d7..1312119fa 100644
--- a/filters/kspread/opencalc/Makefile.am
+++ b/filters/kspread/opencalc/Makefile.am
@@ -6,11 +6,11 @@ INCLUDES= -I$(srcdir)/../../liboofilter -I$(srcdir) -I$(top_srcdir)/kspread $(KO
####### Files
kde_module_LTLIBRARIES = libopencalcimport.la libopencalcexport.la
-libopencalcexport_la_SOURCES = opencalcexport.cc opencalcstyleexport.cc
+libopencalcexport_la_SOURCES = opencalcexport.cpp opencalcstyleexport.cpp
libopencalcexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libopencalcexport_la_LIBADD = ../../../kspread/libkspreadcommon.la ../../liboofilter/liboofilter.la $(KOFFICE_LIBS)
-libopencalcimport_la_SOURCES = opencalcimport.cc
+libopencalcimport_la_SOURCES = opencalcimport.cpp
libopencalcimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libopencalcimport_la_LIBADD = ../../../kspread/libkspreadcommon.la ../../liboofilter/liboofilter.la $(KOFFICE_LIBS)
diff --git a/filters/kspread/opencalc/opencalcexport.cc b/filters/kspread/opencalc/opencalcexport.cpp
index 2db60420f..2db60420f 100644
--- a/filters/kspread/opencalc/opencalcexport.cc
+++ b/filters/kspread/opencalc/opencalcexport.cpp
diff --git a/filters/kspread/opencalc/opencalcimport.cc b/filters/kspread/opencalc/opencalcimport.cpp
index 6dc3216ed..6dc3216ed 100644
--- a/filters/kspread/opencalc/opencalcimport.cc
+++ b/filters/kspread/opencalc/opencalcimport.cpp
diff --git a/filters/kspread/opencalc/opencalcstyleexport.cc b/filters/kspread/opencalc/opencalcstyleexport.cpp
index 9585ae139..9585ae139 100644
--- a/filters/kspread/opencalc/opencalcstyleexport.cc
+++ b/filters/kspread/opencalc/opencalcstyleexport.cpp
diff --git a/filters/kspread/qpro/Makefile.am b/filters/kspread/qpro/Makefile.am
index 9f34af473..95ecdb8aa 100644
--- a/filters/kspread/qpro/Makefile.am
+++ b/filters/kspread/qpro/Makefile.am
@@ -10,7 +10,7 @@ SUBDIRS = libqpro
kde_module_LTLIBRARIES = libqproimport.la
-libqproimport_la_SOURCES = qproimport.cc qproformula.cc
+libqproimport_la_SOURCES = qproimport.cpp qproformula.cpp
libqproimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libqproimport_la_LIBADD = $(KOFFICE_LIBS) ../../../kspread/libkspreadcommon.la \
diff --git a/filters/kspread/qpro/libqpro/ChangeLog b/filters/kspread/qpro/libqpro/ChangeLog
index 35dbf4c2f..18a733a2e 100644
--- a/filters/kspread/qpro/libqpro/ChangeLog
+++ b/filters/kspread/qpro/libqpro/ChangeLog
@@ -6,16 +6,16 @@
* /cvsroot/libqpro/libqpro/Makefile.in: Update version number to 0.2
- * /cvsroot/libqpro/libqpro/src/record.cc, /cvsroot/libqpro/libqpro/src/record_factory.cc, /cvsroot/libqpro/libqpro/src/stream.cc, /cvsroot/libqpro/libqpro/src/tablenames.cc:
+ * /cvsroot/libqpro/libqpro/src/record.cpp, /cvsroot/libqpro/libqpro/src/record_factory.cpp, /cvsroot/libqpro/libqpro/src/stream.cpp, /cvsroot/libqpro/libqpro/src/tablenames.cpp:
libqpro library. C++ libray for reading & writing Quattro Pro spreadsheet files.
- * /cvsroot/libqpro/libqpro/src/record.cc, /cvsroot/libqpro/libqpro/src/record_factory.cc, /cvsroot/libqpro/libqpro/src/stream.cc, /cvsroot/libqpro/libqpro/src/tablenames.cc:
+ * /cvsroot/libqpro/libqpro/src/record.cpp, /cvsroot/libqpro/libqpro/src/record_factory.cpp, /cvsroot/libqpro/libqpro/src/stream.cpp, /cvsroot/libqpro/libqpro/src/tablenames.cpp:
New file.
- * /cvsroot/libqpro/libqpro/src/formula.cc:
+ * /cvsroot/libqpro/libqpro/src/formula.cpp:
libqpro library. C++ libray for reading & writing Quattro Pro spreadsheet files.
- * /cvsroot/libqpro/libqpro/src/formula.cc: New file.
+ * /cvsroot/libqpro/libqpro/src/formula.cpp: New file.
* /cvsroot/libqpro/libqpro/src/Makefile.am, /cvsroot/libqpro/libqpro/src/Makefile.in:
libqpro library. C++ libray for reading & writing Quattro Pro spreadsheet files.
diff --git a/filters/kspread/qpro/libqpro/src/Makefile.am b/filters/kspread/qpro/libqpro/src/Makefile.am
index 9eac256cd..1a6393bbd 100644
--- a/filters/kspread/qpro/libqpro/src/Makefile.am
+++ b/filters/kspread/qpro/libqpro/src/Makefile.am
@@ -1,5 +1,5 @@
INCLUDES= -I$(srcdir) -I$(srcdir)/.. $(all_includes)
noinst_LTLIBRARIES = libqpro.la
-libqpro_la_SOURCES = formula.cc record.cc record_factory.cc stream.cc tablenames.cc
+libqpro_la_SOURCES = formula.cpp record.cpp record_factory.cpp stream.cpp tablenames.cpp
diff --git a/filters/kspread/qpro/libqpro/src/formula.cc b/filters/kspread/qpro/libqpro/src/formula.cpp
index aab0bb8d4..aab0bb8d4 100644
--- a/filters/kspread/qpro/libqpro/src/formula.cc
+++ b/filters/kspread/qpro/libqpro/src/formula.cpp
diff --git a/filters/kspread/qpro/libqpro/src/record.cc b/filters/kspread/qpro/libqpro/src/record.cpp
index 461b65d34..461b65d34 100644
--- a/filters/kspread/qpro/libqpro/src/record.cc
+++ b/filters/kspread/qpro/libqpro/src/record.cpp
diff --git a/filters/kspread/qpro/libqpro/src/record_factory.cc b/filters/kspread/qpro/libqpro/src/record_factory.cpp
index ed6e86174..ed6e86174 100644
--- a/filters/kspread/qpro/libqpro/src/record_factory.cc
+++ b/filters/kspread/qpro/libqpro/src/record_factory.cpp
diff --git a/filters/kspread/qpro/libqpro/src/stream.cc b/filters/kspread/qpro/libqpro/src/stream.cpp
index 390fc3703..390fc3703 100644
--- a/filters/kspread/qpro/libqpro/src/stream.cc
+++ b/filters/kspread/qpro/libqpro/src/stream.cpp
diff --git a/filters/kspread/qpro/libqpro/src/tablenames.cc b/filters/kspread/qpro/libqpro/src/tablenames.cpp
index 4b9b7248c..4b9b7248c 100644
--- a/filters/kspread/qpro/libqpro/src/tablenames.cc
+++ b/filters/kspread/qpro/libqpro/src/tablenames.cpp
diff --git a/filters/kspread/qpro/qproformula.cc b/filters/kspread/qpro/qproformula.cpp
index 4f437cb16..4f437cb16 100644
--- a/filters/kspread/qpro/qproformula.cc
+++ b/filters/kspread/qpro/qproformula.cpp
diff --git a/filters/kspread/qpro/qproimport.cc b/filters/kspread/qpro/qproimport.cpp
index e282a7698..e282a7698 100644
--- a/filters/kspread/qpro/qproimport.cc
+++ b/filters/kspread/qpro/qproimport.cpp
diff --git a/filters/kword/abiword/ImportField.cc b/filters/kword/abiword/ImportField.cpp
index e9474364f..e9474364f 100644
--- a/filters/kword/abiword/ImportField.cc
+++ b/filters/kword/abiword/ImportField.cpp
diff --git a/filters/kword/abiword/ImportFormatting.cc b/filters/kword/abiword/ImportFormatting.cpp
index 7c45f07a0..7c45f07a0 100644
--- a/filters/kword/abiword/ImportFormatting.cc
+++ b/filters/kword/abiword/ImportFormatting.cpp
diff --git a/filters/kword/abiword/ImportHelpers.cc b/filters/kword/abiword/ImportHelpers.cpp
index c3cad308a..c3cad308a 100644
--- a/filters/kword/abiword/ImportHelpers.cc
+++ b/filters/kword/abiword/ImportHelpers.cpp
diff --git a/filters/kword/abiword/ImportStyle.cc b/filters/kword/abiword/ImportStyle.cpp
index 1a023c8e5..1a023c8e5 100644
--- a/filters/kword/abiword/ImportStyle.cc
+++ b/filters/kword/abiword/ImportStyle.cpp
diff --git a/filters/kword/abiword/Makefile.am b/filters/kword/abiword/Makefile.am
index 0a0f1f824..098266e96 100644
--- a/filters/kword/abiword/Makefile.am
+++ b/filters/kword/abiword/Makefile.am
@@ -12,10 +12,10 @@ libabiwordexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.
kde_module_LTLIBRARIES = libabiwordimport.la libabiwordexport.la
-libabiwordimport_la_SOURCES = abiwordimport.cc ImportHelpers.cc\
-ImportFormatting.cc ImportStyle.cc ImportField.cc
+libabiwordimport_la_SOURCES = abiwordimport.cpp ImportHelpers.cpp\
+ImportFormatting.cpp ImportStyle.cpp ImportField.cpp
-libabiwordexport_la_SOURCES = abiwordexport.cc
+libabiwordexport_la_SOURCES = abiwordexport.cpp
noinst_HEADERS = abiwordimport.h ImportHelpers.h ImportFormatting.h\
ImportStyle.h ImportField.h abiwordexport.h
diff --git a/filters/kword/abiword/abiwordexport.cc b/filters/kword/abiword/abiwordexport.cc
deleted file mode 100644
index 11f5d2dd7..000000000
--- a/filters/kword/abiword/abiwordexport.cc
+++ /dev/null
@@ -1,1261 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <tqmap.h>
-#include <tqiodevice.h>
-#include <tqtextstream.h>
-#include <tqdom.h>
-
-#include <kdebug.h>
-#include <kmdcodec.h>
-#include <kfilterdev.h>
-#include <kgenericfactory.h>
-#include <kimageio.h>
-
-#include <KoPageLayout.h>
-#include <KoFilterChain.h>
-#include <KoPictureKey.h>
-
-#include <KWEFStructures.h>
-#include <KWEFUtil.h>
-#include <KWEFBaseWorker.h>
-#include <KWEFKWordLeader.h>
-
-#include <abiwordexport.h>
-#include <abiwordexport.moc>
-
-class ABIWORDExportFactory : KGenericFactory<ABIWORDExport, KoFilter>
-{
-public:
- ABIWORDExportFactory(void) : KGenericFactory<ABIWORDExport, KoFilter> ("kwordabiwordexport")
- {}
-protected:
- virtual void setupTranslations( void )
- {
- TDEGlobal::locale()->insertCatalogue( "kofficefilters" );
- }
-};
-
-K_EXPORT_COMPONENT_FACTORY( libabiwordexport, ABIWORDExportFactory() )
-
-class StyleMap : public TQMap<TQString,LayoutData>
-{
-public:
- StyleMap(void) {}
- ~StyleMap(void) {}
-};
-
-class AbiWordWorker : public KWEFBaseWorker
-{
-public:
- AbiWordWorker(void);
- virtual ~AbiWordWorker(void) { delete m_streamOut; delete m_ioDevice; }
-public:
- virtual bool doOpenFile(const TQString& filenameOut, const TQString& to);
- virtual bool doCloseFile(void); // Close file in normal conditions
- virtual bool doOpenDocument(void);
- virtual bool doCloseDocument(void);
- virtual bool doFullParagraph(const TQString& paraText, const LayoutData& layout,
- const ValueListFormatData& paraFormatDataList);
- virtual bool doOpenTextFrameSet(void); // AbiWord's <section>
- virtual bool doCloseTextFrameSet(void); // AbiWord's </section>
- virtual bool doFullPaperFormat(const int format,
- const double width, const double height, const int orientation); // Calc AbiWord's <papersize>
- virtual bool doFullPaperBorders (const double top, const double left,
- const double bottom, const double right); // Like KWord's <PAPERBORDERS>
- virtual bool doCloseHead(void); // Write <papersize>
- virtual bool doOpenStyles(void); // AbiWord's <styles>
- virtual bool doCloseStyles(void); // AbiWord's </styles>
- virtual bool doFullDefineStyle(LayoutData& layout); // AbiWord's <s></s>
- virtual bool doOpenSpellCheckIgnoreList (void); // AbiWord's <ignorewords>
- virtual bool doCloseSpellCheckIgnoreList (void); // AbiWord's </ignorewords>
- virtual bool doFullSpellCheckIgnoreWord (const TQString& ignoreword); // AbiWord's <iw>
- virtual bool doFullDocumentInfo(const KWEFDocumentInfo& docInfo); // AbiWord's <metadata>
-private:
- void processParagraphData (const TQString& paraText,
- const TextFormatting& formatLayout,
- const ValueListFormatData& paraFormatDataList);
- void processNormalText ( const TQString& paraText,
- const TextFormatting& formatLayout,
- const FormatData& formatData);
- void processVariable ( const TQString& paraText,
- const TextFormatting& formatLayout,
- const FormatData& formatData);
- void processAnchor ( const TQString& paraText,
- const TextFormatting& formatLayout,
- const FormatData& formatData);
- TQString textFormatToAbiProps(const TextFormatting& formatOrigin,
- const TextFormatting& formatData, const bool force) const;
- TQString layoutToCss(const LayoutData& layoutOrigin,
- const LayoutData& layout, const bool force) const;
- TQString escapeAbiWordText(const TQString& strText) const;
- bool makeTable(const FrameAnchor& anchor);
- bool makePicture(const FrameAnchor& anchor);
- void writeAbiProps(const TextFormatting& formatLayout, const TextFormatting& format);
- void writePictureData(const TQString& koStoreName, const TQString& keyName);
- TQString transformToTextDate(const TQDateTime& dt);
-private:
- TQIODevice* m_ioDevice;
- TQTextStream* m_streamOut;
- TQString m_pagesize; // Buffer for the <pagesize> tag
- TQMap<TQString,KoPictureKey> m_mapPictureData;
- StyleMap m_styleMap;
- double m_paperBorderTop,m_paperBorderLeft,m_paperBorderBottom,m_paperBorderRight;
- bool m_inIgnoreWords; // true if <ignorewords> has been written
- KWEFDocumentInfo m_docInfo; // document information
-};
-
-AbiWordWorker::AbiWordWorker(void) : m_ioDevice(NULL), m_streamOut(NULL),
- m_paperBorderTop(0.0),m_paperBorderLeft(0.0),
- m_paperBorderBottom(0.0),m_paperBorderRight(0.0)
-{
-}
-
-TQString AbiWordWorker::escapeAbiWordText(const TQString& strText) const
-{
- // Escape quotes (needed in attributes)
- // Escape apostrophs (allowed by XML)
- return KWEFUtil::EscapeSgmlText(NULL,strText,true,true);
-}
-
-bool AbiWordWorker::doOpenFile(const TQString& filenameOut, const TQString& )
-{
- kdDebug(30506) << "Opening file: " << filenameOut
- << " (in AbiWordWorker::doOpenFile)" << endl;
- //Find the last extension
- TQString strExt;
- const int result=filenameOut.findRev('.');
- if (result>=0)
- {
- strExt=filenameOut.mid(result);
- }
-
- TQString strMimeType; // Mime type of the compressor
-
- if ((strExt==".gz")||(strExt==".GZ") //in case of .abw.gz (logical extension)
- ||(strExt==".zabw")||(strExt==".ZABW")) //in case of .zabw (extension used prioritary with AbiWord)
- {
- // Compressed with gzip
- strMimeType="application/x-gzip";
- }
- else if ((strExt==".bz2")||(strExt==".BZ2") //in case of .abw.bz2 (logical extension)
- ||(strExt==".bzabw")||(strExt==".BZABW")) //in case of .bzabw (extension used prioritary with AbiWord)
- {
- // Compressed with bzip2
- strMimeType="application/x-bzip2";
- }
- else
- {
- // No compression
- strMimeType="text/plain";
- }
-
- kdDebug(30506) << "Compression: " << strMimeType << endl;
-
- m_ioDevice = KFilterDev::deviceForFile(filenameOut,strMimeType);
-
- if (!m_ioDevice)
- {
- kdError(30506) << "No output file! Aborting!" << endl;
- return false;
- }
-
- if ( !m_ioDevice->open (IO_WriteOnly) )
- {
- kdError(30506) << "Unable to open output file! Aborting!" << endl;
- return false;
- }
-
- m_streamOut=new TQTextStream(m_ioDevice);
-
- // We only export in UTF-8 (are there AbiWord ports that cannot read UTF-8? Be careful SVG uses UTF-8 too!)
- m_streamOut->setEncoding( TQTextStream::UnicodeUTF8 );
- return true;
-}
-
-bool AbiWordWorker::doCloseFile(void)
-{
- delete m_streamOut;
- m_streamOut=NULL;
- if (m_ioDevice)
- m_ioDevice->close();
- return (m_ioDevice);
-}
-
-bool AbiWordWorker::doOpenDocument(void)
-{
- kdDebug(30506)<< "AbiWordWorker::doOpenDocument" << endl;
- // Make the file header
-
- // First the XML header in UTF-8 version
- // (AbiWord and QT handle UTF-8 well, so we stay with this encoding!)
- *m_streamOut << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
-
- // NOTE: AbiWord CVS 2002-02-?? has a new DOCTYPE
- *m_streamOut << "<!DOCTYPE abiword PUBLIC \"-//ABISOURCE//DTD AWML 1.0 Strict//EN\"";
- *m_streamOut << " \"http://www.abisource.com/awml.dtd\">\n";
-
- // First magic: "<abiword"
- *m_streamOut << "<abiword";
- // AbiWord CVS 2002-02-23 defines a default namespace.
- *m_streamOut << " xmlns=\"http://www.abisource.com/awml.dtd\"";
- // As we do not use xmlns:awml, do we need to define it?
- // *m_streamOut << " xmlns:awml=\"http://www.abisource.com/awml.dtd\"";
- *m_streamOut << " xmlns:xlink=\"http://www.w3.org/1999/xlink\"";
- // AbiWord CVS 2002-02-22 defines other namespaces, which we are not using.
- // AbiWord CVS 2002-12-23 has no fileformat attribute anymore
- // ### TODO: add document language and document direction of writing.
- *m_streamOut << " xml:space=\"preserve\" version=\"1.1.2\" template=\"false\" styles=\"unlocked\">\n";
- // Second magic: "<!-- This file is an AbiWord document."
- // TODO/FIXME: write as much spaces as AbiWord does for the following line.
- *m_streamOut << "<!-- This file is an AbiWord document. -->\n";
- // We have chosen NOT to have the full comment header that AbiWord files normally have.
- // ### TODO: perhaps we should add the comment: do not edit the file
- *m_streamOut << "\n";
-
-
- return true;
-}
-
-void AbiWordWorker::writePictureData(const TQString& koStoreName, const TQString& keyName)
-{
- kdDebug(30506) << "AbiWordWorker::writeImageData" << endl;
-
- TQByteArray image;
-
- TQString strExtension(koStoreName.lower());
- const int result=koStoreName.findRev(".");
- if (result>=0)
- {
- strExtension=koStoreName.mid(result+1);
- }
-
- bool isImageLoaded=false;
-
- if (strExtension=="png")
- {
- isImageLoaded=loadSubFile(koStoreName,image);
- }
- else
- {
- // All other picture types must be converted to PNG
- // (yes, even JPEG, SVG or WMF!)
- isImageLoaded=loadAndConvertToImage(koStoreName,strExtension,"PNG",image);
- }
-
- if (isImageLoaded)
- {
- *m_streamOut << "<d name=\"" << keyName << "\""
- << " base64=\"yes\""
- << " mime=\"image/png\">\n";
-
- TQCString base64=KCodecs::base64Encode(image,true);
-
- *m_streamOut << base64 << "\n"; // TQCString is taken as Latin1 by TQTextStream
-
- *m_streamOut << "</d>\n";
- }
- else
- {
- kdWarning(30506) << "Unable to load picture: " << koStoreName << endl;
- }
-}
-
-bool AbiWordWorker::doCloseDocument(void)
-{
- // Before writing the <data> element,
- // we must be sure that we have data and that we can retrieve it.
-
- if (m_kwordLeader && !m_mapPictureData.isEmpty())
- {
- *m_streamOut << "<data>\n";
-
- TQMap<TQString,KoPictureKey>::ConstIterator it;
- TQMap<TQString,KoPictureKey>::ConstIterator end(m_mapPictureData.end());
- // all images first
- for (it=m_mapPictureData.begin(); it!=end; ++it)
- {
- // Warning: do not mix up KWord's key and the iterator's key!
- writePictureData(it.key(),it.data().filename());
- }
-
- *m_streamOut << "</data>\n";
- }
-
- *m_streamOut << "</abiword>\n"; //Close the file for XML
- return true;
-}
-
-bool AbiWordWorker::doOpenTextFrameSet(void)
-{
- *m_streamOut << "<section props=\"";
- *m_streamOut << "page-margin-top: ";
- *m_streamOut << m_paperBorderTop;
- *m_streamOut << "pt; ";
- *m_streamOut << "page-margin-left: ";
- *m_streamOut << m_paperBorderLeft;
- *m_streamOut << "pt; ";
- *m_streamOut << "page-margin-bottom: ";
- *m_streamOut << m_paperBorderBottom;
- *m_streamOut << "pt; ";
- *m_streamOut << "page-margin-right: ";
- *m_streamOut << m_paperBorderRight;
- *m_streamOut << "pt"; // Last one, so no semi-comma
- *m_streamOut << "\">\n";
- return true;
-}
-
-bool AbiWordWorker::doCloseTextFrameSet(void)
-{
- *m_streamOut << "</section>\n";
- return true;
-}
-
-bool AbiWordWorker::doOpenStyles(void)
-{
- *m_streamOut << "<styles>\n";
- return true;
-}
-
-bool AbiWordWorker::doCloseStyles(void)
-{
- *m_streamOut << "</styles>\n";
- return true;
-}
-
-TQString AbiWordWorker::textFormatToAbiProps(const TextFormatting& formatOrigin,
- const TextFormatting& formatData, const bool force) const
-{
- // TODO: rename variable formatData
- TQString strElement; // TODO: rename this variable
-
- // Font name
- TQString fontName = formatData.fontName;
- if ( !fontName.isEmpty()
- && (force || (formatOrigin.fontName!=formatData.fontName)))
- {
- strElement+="font-family: ";
- strElement+= escapeAbiWordText(fontName); // TODO: add alternative font names
- strElement+="; ";
- }
-
- if (force || (formatOrigin.italic!=formatData.italic))
- {
- // Font style
- strElement+="font-style: ";
- if ( formatData.italic )
- {
- strElement+="italic";
- }
- else
- {
- strElement+="normal";
- }
- strElement+="; ";
- }
-
- if (force || ((formatOrigin.weight>=75)!=(formatData.weight>=75)))
- {
- strElement+="font-weight: ";
- if ( formatData.weight >= 75 )
- {
- strElement+="bold";
- }
- else
- {
- strElement+="normal";
- }
- strElement+="; ";
- }
-
- if (force || (formatOrigin.fontSize!=formatData.fontSize))
- {
- const int size=formatData.fontSize;
- if (size>0)
- {
- // We use absolute font sizes.
- strElement+="font-size: ";
- strElement+=TQString::number(size,10);
- strElement+="pt; ";
- }
- }
-
- if (force || (formatOrigin.fgColor!=formatData.fgColor))
- {
- if ( formatData.fgColor.isValid() )
- {
- // Give colour
- strElement+="color: ";
-
- // No leading # (unlike CSS2)
- // We must have two hex digits for each colour channel!
- const int red=formatData.fgColor.red();
- strElement += TQString::number((red&0xf0)>>4,16);
- strElement += TQString::number(red&0x0f,16);
-
- const int green=formatData.fgColor.green();
- strElement += TQString::number((green&0xf0)>>4,16);
- strElement += TQString::number(green&0x0f,16);
-
- const int blue=formatData.fgColor.blue();
- strElement += TQString::number((blue&0xf0)>>4,16);
- strElement += TQString::number(blue&0x0f,16);
-
- strElement+="; ";
- }
- }
-
- if (force || (formatOrigin.bgColor!=formatData.bgColor))
- {
- if ( formatData.bgColor.isValid() )
- {
- // Give background colour
- strElement+="bgcolor: ";
-
- // No leading # (unlike CSS2)
- // We must have two hex digits for each colour channel!
- const int red=formatData.bgColor.red();
- strElement += TQString::number((red&0xf0)>>4,16);
- strElement += TQString::number(red&0x0f,16);
-
- const int green=formatData.bgColor.green();
- strElement += TQString::number((green&0xf0)>>4,16);
- strElement += TQString::number(green&0x0f,16);
-
- const int blue=formatData.bgColor.blue();
- strElement += TQString::number((blue&0xf0)>>4,16);
- strElement += TQString::number(blue&0x0f,16);
-
- strElement+="; ";
- }
- }
-
- if (force || (formatOrigin.underline!=formatData.underline)
- || (formatOrigin.strikeout!=formatData.strikeout))
- {
- strElement+="text-decoration: ";
- if ( formatData.underline )
- {
- strElement+="underline";
- }
- else if ( formatData.strikeout )
- {
- strElement+="line-through";
- }
- else
- {
- strElement+="none";
- }
- strElement+="; ";
- }
-
- return strElement;
-}
-
-bool AbiWordWorker::makeTable(const FrameAnchor& anchor)
-{
-#if 0
- *m_streamOut << "</p>\n"; // Close previous paragraph ### TODO: do it correctly like for HTML
- *m_streamOut << "<table>\n";
-#endif
-
- TQValueList<TableCell>::ConstIterator itCell;
- for (itCell=anchor.table.cellList.begin();
- itCell!=anchor.table.cellList.end(); itCell++)
- {
-#if 0
- // ### TODO: rowspan, colspan
-
- // AbiWord seems to work by attaching to the cell borders
- *m_streamOut << "<cell props=\"";
- *m_streamOut << "left-attach:" << (*itCell).col << "; ";
- *m_streamOut << "right-attach:" << (*itCell).col + 1 << "; ";
- *m_streamOut << "top-attach:" << (*itCell).row << "; ";
- *m_streamOut << "bot-attach:" << (*itCell).row + 1;
- *m_streamOut << "\">\n";
-#endif
- if (!doFullAllParagraphs(*(*itCell).paraList))
- {
- return false;
- }
-#if 0
- *m_streamOut << "</cell>\n";
-#endif
- }
-#if 0
- *m_streamOut << "</table>\n";
- *m_streamOut << "<p>\n"; // Re-open the "previous" paragraph ### TODO: do it correctly like for HTML
-#endif
- return true;
-}
-
-bool AbiWordWorker::makePicture(const FrameAnchor& anchor)
-{
- kdDebug(30506) << "New image/clipart: " << anchor.picture.koStoreName
- << " , " << anchor.picture.key.toString() << endl;
-
- const double height=anchor.frame.bottom - anchor.frame.top;
- const double width =anchor.frame.right - anchor.frame.left;
-
- // TODO: we are only using the filename, not the rest of the key
- // TODO: (bad if there are two images of the same name, but of a different key)
- *m_streamOut << "<image dataid=\"" << anchor.picture.key.filename() << "\"";
- *m_streamOut << " props= \"height:" << height << "pt;width:" << width << "pt\"";
- *m_streamOut << "/>"; // NO end of line!
- // TODO: other props for image
-
- m_mapPictureData[anchor.picture.koStoreName]=anchor.picture.key;
-
- return true;
-}
-
-void AbiWordWorker::writeAbiProps (const TextFormatting& formatLayout, const TextFormatting& format)
-{
- TQString abiprops=textFormatToAbiProps(formatLayout,format,false);
-
- // Erase the last semi-comma (as in CSS2, semi-commas only separate instructions and do not terminate them)
- const int result=abiprops.findRev(";");
-
- if (result>=0)
- {
- // Remove the last semi-comma and the space thereafter
- abiprops.remove(result,2);
- }
-
- if (!abiprops.isEmpty())
- {
- *m_streamOut << " props=\"" << abiprops << "\"";
- }
-}
-
-void AbiWordWorker::processNormalText ( const TQString &paraText,
- const TextFormatting& formatLayout,
- const FormatData& formatData)
-{
- // Retrieve text and escape it
- TQString partialText=escapeAbiWordText(paraText.mid(formatData.pos,formatData.len));
-
- // Replace line feeds by line breaks
- int pos;
- while ((pos=partialText.find(TQChar(10)))>-1)
- {
- partialText.replace(pos,1,"<br/>");
- }
-
- if (formatData.text.missing)
- {
- // It's just normal text, so we do not need a <c> element!
- *m_streamOut << partialText;
- }
- else
- { // Text with properties, so use a <c> element!
- *m_streamOut << "<c";
- writeAbiProps(formatLayout,formatData.text);
- *m_streamOut << ">" << partialText << "</c>";
- }
-}
-
-void AbiWordWorker::processVariable ( const TQString&,
- const TextFormatting& formatLayout,
- const FormatData& formatData)
-{
- if (0==formatData.variable.m_type)
- {
- // As AbiWord's field is inflexible, we cannot make the date custom
- *m_streamOut << "<field type=\"date_ntdfl\"";
- writeAbiProps(formatLayout,formatData.text);
- *m_streamOut << "/>";
- }
- else if (2==formatData.variable.m_type)
- {
- // As AbiWord's field is inflexible, we cannot make the time custom
- *m_streamOut << "<field type=\"time\"";
- writeAbiProps(formatLayout,formatData.text);
- *m_streamOut << "/>";
- }
- else if (4==formatData.variable.m_type)
- {
- // As AbiWord's field is inflexible, we cannot make the time custom
- TQString strFieldType;
- if (formatData.variable.isPageNumber())
- {
- strFieldType="page_number";
- }
- else if (formatData.variable.isPageCount())
- {
- strFieldType="page_count";
- }
- if (strFieldType.isEmpty())
- {
- // Unknown subtype, therefore write out the result
- *m_streamOut << formatData.variable.m_text;
- }
- else
- {
- *m_streamOut << "<field type=\"" << strFieldType <<"\"";
- writeAbiProps(formatLayout,formatData.text);
- *m_streamOut << "/>";
- }
- }
- else if (9==formatData.variable.m_type)
- {
- // A link
- *m_streamOut << "<a xlink:href=\""
- << escapeAbiWordText(formatData.variable.getHrefName())
- << "\"><c"; // In AbiWord, an anchor <a> has always a <c> child
- writeAbiProps(formatLayout,formatData.text);
- *m_streamOut << ">"
- << escapeAbiWordText(formatData.variable.getLinkName())
- << "</c></a>";
- }
-#if 0
- else if (11==(*paraFormatDataIt).variable.m_type)
- {
- // Footnote
- TQString value = (*paraFormatDataIt).variable.getFootnoteValue();
- bool automatic = (*paraFormatDataIt).variable.getFootnoteAuto();
- TQValueList<ParaData> *paraList = (*paraFormatDataIt).variable.getFootnotePara();
- if( paraList )
- {
- TQString fstr;
- TQValueList<ParaData>::ConstIterator it;
- for (it=paraList->begin();it!=paraList->end();it++)
- fstr += ProcessParagraphData( (*it).text, (*it).layout,(*it).formattingList);
- str += "{\\super ";
- str += automatic ? "\\chftn " : value;
- str += "{\\footnote ";
- str += "{\\super ";
- str += automatic ? "\\chftn " : value;
- str += fstr;
- str += " }";
- str += " }";
- str += " }";
- }
- }
-#endif
- else
- {
- // Generic variable
- *m_streamOut << formatData.variable.m_text;
- }
-}
-
-void AbiWordWorker::processAnchor ( const TQString&,
- const TextFormatting& /*formatLayout*/, //TODO
- const FormatData& formatData)
-{
- // We have an image or a table
- if ( (2==formatData.frameAnchor.type) // <IMAGE> or <PICTURE>
- || (5==formatData.frameAnchor.type) ) // <CLIPART>
- {
- makePicture(formatData.frameAnchor);
- }
- else if (6==formatData.frameAnchor.type)
- {
- makeTable(formatData.frameAnchor);
- }
- else
- {
- kdWarning(30506) << "Unsupported anchor type: "
- << formatData.frameAnchor.type << endl;
- }
-}
-
-void AbiWordWorker::processParagraphData ( const TQString &paraText,
- const TextFormatting& formatLayout,
- const ValueListFormatData &paraFormatDataList)
-{
- if ( paraText.length () > 0 )
- {
- ValueListFormatData::ConstIterator paraFormatDataIt;
-
- for ( paraFormatDataIt = paraFormatDataList.begin ();
- paraFormatDataIt != paraFormatDataList.end ();
- paraFormatDataIt++ )
- {
- if (1==(*paraFormatDataIt).id)
- {
- processNormalText(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if (4==(*paraFormatDataIt).id)
- {
- processVariable(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if (6==(*paraFormatDataIt).id)
- {
- processAnchor(paraText, formatLayout, (*paraFormatDataIt));
- }
- }
- }
-}
-
-TQString AbiWordWorker::layoutToCss(const LayoutData& layoutOrigin,
- const LayoutData& layout, const bool force) const
-{
- TQString props;
-
- if (force || (layoutOrigin.alignment!=layout.alignment))
- {
- // Check if the current alignment is a valid one for AbiWord.
- if ((layout.alignment == "left") || (layout.alignment == "right")
- || (layout.alignment == "center") || (layout.alignment == "justify"))
- {
- props += "text-align:";
- props += layout.alignment;
- props += "; ";
- }
- else if (layout.alignment == "auto")
- {
- // We assume a left alignment as AbiWord is not really bi-di (and this filter even less.)
- props += "text-align:left; ";
- }
- else
- {
- kdWarning(30506) << "Unknown alignment: " << layout.alignment << endl;
- }
- }
-
- // TODO/FIXME: what if all tabulators must be erased?
-#if 0
- // DEPRECATED!
- if (!layout.tabulator.isEmpty()
- && (force || (layoutOrigin.tabulator!=layout.tabulator)))
- {
- props += "tabstops:";
- props += layout.tabulator;
- props += "; ";
- }
-#endif
- if (!layout.tabulatorList.isEmpty()
- && (force || (layoutOrigin.tabulatorList!=layout.tabulatorList) ))
- {
- props += "tabstops:";
- bool first=true;
- TabulatorList::ConstIterator it;
- TabulatorList::ConstIterator end(layout.tabulatorList.end());
- for (it=layout.tabulatorList.begin();it!=end;++it)
- {
- if (first)
- {
- first=false;
- }
- else
- {
- props += ",";
- }
- props += TQString::number((*it).m_ptpos);
- props += "pt";
-
- switch ((*it).m_type)
- {
- case 0: props += "/L"; break;
- case 1: props += "/C"; break;
- case 2: props += "/R"; break;
- case 3: props += "/D"; break;
- default: props += "/L";
- }
-
- props += "0"; // No filling
- }
- props += "; ";
- }
-
- if ((layout.indentLeft>=0.0)
- && (force || (layoutOrigin.indentLeft!=layout.indentLeft)))
- {
- props += TQString("margin-left:%1pt; ").arg(layout.indentLeft);
- }
-
- if ((layout.indentRight>=0.0)
- && (force || (layoutOrigin.indentRight!=layout.indentRight)))
- {
- props += TQString("margin-right:%1pt; ").arg(layout.indentRight);
- }
-
- if (force || (layoutOrigin.indentLeft!=layout.indentLeft))
- {
- props += "text-indent: ";
- props += TQString::number(layout.indentFirst);
- props += "pt; ";
- }
-
- if ((layout.marginBottom>=0.0)
- && ( force || ( layoutOrigin.marginBottom != layout.marginBottom ) ) )
- {
- props += TQString("margin-bottom:%1pt; ").arg(layout.marginBottom);
- }
-
- if ((layout.marginTop>=0.0)
- && ( force || ( layoutOrigin.marginTop != layout.marginTop ) ) )
- {
- props += TQString("margin-top:%1pt; ").arg(layout.marginTop);
- }
-
- if (force
- || ( layoutOrigin.lineSpacingType != layout.lineSpacingType )
- || ( layoutOrigin.lineSpacing != layout.lineSpacing ) )
- {
- switch ( layout.lineSpacingType )
- {
- case LayoutData::LS_CUSTOM:
- {
- // We have a custom line spacing (in points). However AbiWord cannot do it, so transform in "at-least"
- props += "line-height=:";
- props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
- props += "pt+; ";
- break;
- }
- case LayoutData::LS_SINGLE:
- {
- props += "line-height:1.0; "; // One
- break;
- }
- case LayoutData::LS_ONEANDHALF:
- {
- props += "line-height:1.5; "; // One-and-half
- break;
- }
- case LayoutData::LS_DOUBLE:
- {
- props += "line-height:2.0; "; // Two
- break;
- }
- case LayoutData::LS_MULTIPLE:
- {
- props += "line-height:";
- props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
- props += "; ";
- break;
- }
- case LayoutData::LS_FIXED:
- {
- // We have a fixed line height (in points)
- props += "line-height:";
- props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
- props += "pt; ";
- break;
- }
- case LayoutData::LS_ATLEAST:
- {
- // We have an "at-least" line height (in points)
- props += "line-height=:";
- props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
- props += "pt+; "; // The + makes the difference
- break;
- }
- default:
- {
- kdWarning(30506) << "Unsupported lineSpacingType: " << layout.lineSpacingType << " (Ignoring!)" << endl;
- break;
- }
- }
- }
-
- // Add all AbiWord properties collected in the <FORMAT> element
- props += textFormatToAbiProps(layoutOrigin.formatData.text,layout.formatData.text,force);
-
- return props;
-}
-
-bool AbiWordWorker::doFullParagraph(const TQString& paraText, const LayoutData& layout,
- const ValueListFormatData& paraFormatDataList)
-{
- TQString style=layout.styleName;
-
- const LayoutData& styleLayout=m_styleMap[style];
-
- TQString props=layoutToCss(styleLayout,layout,false);
-
- *m_streamOut << "<p";
- if (!style.isEmpty())
- {
- *m_streamOut << " style=\"" << EscapeXmlText(style,true,true) << "\"";
- }
- if (!props.isEmpty())
- {
- // Find the last semi-comma
- // Note: as in CSS2, semi-commas only separates instructions (like in PASCAL) and do not terminate them (like in C)
- const int result=props.findRev(";");
- if (result>=0)
- {
- // Remove the last semi-comma and the space thereafter
- props.remove(result,2);
- }
-
- *m_streamOut << " props=\"" << props << "\"";
- }
- *m_streamOut << ">"; //Warning: No trailing white space or else it's in the text!!!
-
- // Before processing the text, test if we have a page break
- if (layout.pageBreakBefore)
- {
- // We have a page break before the paragraph
- *m_streamOut << "<pbr/>";
- }
-
- processParagraphData(paraText, layout.formatData.text, paraFormatDataList);
-
- // Before closing the paragraph, test if we have a page break
- if (layout.pageBreakAfter)
- {
- // We have a page break after the paragraph
- *m_streamOut << "<pbr/>";
- }
-
- *m_streamOut << "</p>\n";
- return true;
-}
-
-bool AbiWordWorker::doFullDefineStyle(LayoutData& layout)
-{
- //Register style in the style map
- m_styleMap[layout.styleName]=layout;
-
- *m_streamOut << "<s";
-
- // TODO: cook the style name to the standard style names in AbiWord
- *m_streamOut << " name=\"" << EscapeXmlText(layout.styleName,true,true) << "\"";
- *m_streamOut << " followedby=\"" << EscapeXmlText(layout.styleFollowing,true,true) << "\"";
-
- if ( (layout.counter.numbering == CounterData::NUM_CHAPTER)
- && (layout.counter.depth<10) )
- {
- *m_streamOut << " level=\"";
- *m_streamOut << TQString::number(layout.counter.depth+1,10);
- *m_streamOut << "\"";
- }
-
- TQString abiprops=layoutToCss(layout,layout,true);
-
- const int result=abiprops.findRev(";");
- if (result>=0)
- {
- // Remove the last semi-comma and the space thereafter
- abiprops.remove(result,2);
- }
-
- *m_streamOut << " props=\"" << abiprops << "\"";
-
- *m_streamOut << "/>\n";
-
- return true;
-}
-
-bool AbiWordWorker::doFullPaperFormat(const int format,
- const double width, const double height, const int orientation)
-{
- TQString outputText = "<pagesize ";
-
- switch (format)
- {
- // ISO A formats
- case PG_DIN_A0: // ISO A0
- case PG_DIN_A1: // ISO A1
- case PG_DIN_A2: // ISO A2
- case PG_DIN_A3: // ISO A3
- case PG_DIN_A4: // ISO A4
- case PG_DIN_A5: // ISO A5
- case PG_DIN_A6: // ISO A6
- // ISO B formats
- case PG_DIN_B0: // ISO B0
- case PG_DIN_B1: // ISO B1
- case PG_DIN_B2: // ISO B2
- case PG_DIN_B3: // ISO B3
- case PG_DIN_B4: // ISO B4
- case PG_DIN_B5: // ISO B5
- case PG_DIN_B6: // ISO B6
- // American formats
- case PG_US_LETTER: // US Letter
- case PG_US_LEGAL: // US Legal
- {
- TQString pagetype=KoPageFormat::formatString(KoFormat(format));
- outputText+="pagetype=\"";
- outputText+=pagetype;
-
- TQString strWidth, strHeight, strUnits;
- KWEFUtil::GetNativePaperFormat(format, strWidth, strHeight, strUnits);
- outputText+="\" width=\"";
- outputText+=strWidth;
- outputText+="\" height=\"";
- outputText+=strHeight;
- outputText+="\" units=\"";
- outputText+=strUnits;
- outputText+="\" ";
- break;
- }
- case PG_US_EXECUTIVE: // US Executive (does not exists in AbiWord!)
- {
- // FIXME/TODO: AbiWord (CVS 2001-04-25) seems not to like custom formats, so avoid them for now!
-#if 0
- outputText += "pagetype=\"Custom\" width=\"7.5\" height=\"10.0\" units=\"inch\" ";
-#else
- // As replacement, use the slightly bigger "letter" format.
- outputText += "pagetype=\"Letter\" width=\"8.5\" height=\"11.0\" units=\"inch\" ";
-#endif
- break;
- }
- // Other format not supported yet by AbiWord CVS 2001-04-25)
- case PG_DIN_A7: // ISO A7
- case PG_DIN_A8: // ISO A8
- case PG_DIN_A9: // ISO A9
- case PG_DIN_B10: // ISO B10
- // Other formats
- case PG_SCREEN: // Screen
- case PG_CUSTOM: // Custom
- default:
- {
- // FIXME/TODO: AbiWord (CVS 2001-04-25) seems not to like custom formats, so avoid them for now!
- if ((width<=1.0) || (height<=1.0) || true)
- {
- // Height or width is ridiculous, so assume A4 format
- outputText += "pagetype=\"A4\" width=\"21.0\" height=\"29.7\" units=\"cm\" ";
- }
- else
- { // We prefer to use inches, as to limit rounding errors (page size is in points!)
- outputText += TQString("pagetype=\"Custom\" width=\"%1\" height=\"%2\" units=\"inch\" ").arg(width/72.0).arg(height/72.0);
- }
- break;
- }
- }
-
- outputText += "orientation=\"";
- if (1==orientation)
- {
- outputText += "landscape";
- }
- else
- {
- outputText += "portrait";
- }
- outputText += "\" ";
-
- outputText += "page-scale=\"1.0\"/>\n"; // KWord has no page scale, so assume 100%
-
- m_pagesize=outputText;
- return true;
-}
-
-bool AbiWordWorker::doFullPaperBorders (const double top, const double left,
- const double bottom, const double right)
-{
- m_paperBorderTop=top;
- m_paperBorderLeft=left;
- m_paperBorderBottom=bottom;
- m_paperBorderRight=right;
- return true;
-}
-
-bool AbiWordWorker::doCloseHead(void)
-{
- if (!m_pagesize.isEmpty())
- {
- *m_streamOut << m_pagesize;
- }
- return true;
-}
-
-bool AbiWordWorker::doOpenSpellCheckIgnoreList (void)
-{
- kdDebug(30506) << "AbiWordWorker::doOpenSpellCheckIgnoreList" << endl;
- m_inIgnoreWords=false; // reset
- return true;
-}
-
-bool AbiWordWorker::doCloseSpellCheckIgnoreList (void)
-{
- kdDebug(30506) << "AbiWordWorker::doCloseSpellCheckIgnoreList" << endl;
- if (m_inIgnoreWords)
- *m_streamOut << "</ignorewords>\n";
- return true;
-}
-
-bool AbiWordWorker::doFullSpellCheckIgnoreWord (const TQString& ignoreword)
-{
- kdDebug(30506) << "AbiWordWorker::doFullSpellCheckIgnoreWord: " << ignoreword << endl;
- if (!m_inIgnoreWords)
- {
- *m_streamOut << "<ignorewords>\n";
- m_inIgnoreWords=true;
- }
- *m_streamOut << " <iw>" << ignoreword << "</iw>\n";
- return true;
-}
-
-// Similar to TQDateTime::toString, but guaranteed *not* to be translated
-TQString AbiWordWorker::transformToTextDate(const TQDateTime& dt)
-{
- if (dt.isValid())
- {
- TQString result;
-
- const TQDate date(dt.date());
-
- const char* dayName[7] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
- const int dow = date.dayOfWeek() - 1;
- if ((dow<0) || (dow>6))
- result += "Mon"; // Unknown day, rename it Monday.
- else
- result += dayName[dow];
- result += ' ';
-
- const char* monthName[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
- const int month = date.month() - 1;
- if ((month<0) || (month>11))
- result += "Jan"; // Unknown month, rename it January
- else
- result += monthName[month];
- result += ' ';
-
- TQString temp;
-
- temp = "00";
- temp += TQString::number(date.day(), 10);
- result += temp.right(2);
- result += ' ';
-
- const TQTime time(dt.time());
-
- temp = "00";
- temp += TQString::number(time.hour(), 10);
- result += temp.right(2);
- result += ':';
-
- temp = "00";
- temp += TQString::number(time.minute(), 10);
- result += temp.right(2);
- result += ':';
-
- temp = "00";
- temp += TQString::number(time.second(), 10);
- result += temp.right(2);
- result += ' ';
-
- temp = "0000";
- temp += TQString::number(date.year(), 10);
- result += temp.right(4);
-
- return result;
- }
- else
- {
- // Invalid, so give back 1970-01-01
- return "Thu Jan 01 00:00:00 1970";
- }
-}
-
-bool AbiWordWorker::doFullDocumentInfo(const KWEFDocumentInfo& docInfo)
-{
- m_docInfo=docInfo;
-
- *m_streamOut << "<metadata>\n";
-
- // First all Dublin Core data
- *m_streamOut << "<m key=\"dc.format\">application/x-abiword</m>\n";
- if (!m_docInfo.title.isEmpty())
- {
- *m_streamOut << "<m key=\"dc.title\">" << escapeAbiWordText(m_docInfo.title) << "</m>\n";
- }
- if (!m_docInfo.abstract.isEmpty())
- {
- *m_streamOut << "<m key=\"dc.description\">" << escapeAbiWordText(m_docInfo.abstract) << "</m>\n";
- }
-
- if ( !m_docInfo.keywords.isEmpty() )
- {
- *m_streamOut << "<m key=\"abiword.keywords\">" << escapeAbiWordText(m_docInfo.keywords) << "</m>\n";
- }
- if ( !m_docInfo.subject.isEmpty() )
- {
- *m_streamOut << "<m key=\"dc.subject\">" << escapeAbiWordText(m_docInfo.subject) << "</m>\n";
- }
-
- // Say who we are (with the CVS revision number) in case we have a bug in our filter output!
- *m_streamOut << "<m key=\"abiword.generator\">KWord Export Filter";
-
- TQString strVersion("$Revision: 508787 $");
- // Remove the dollar signs
- // (We don't want that the version number changes if the AbiWord file is itself put in a CVS storage.)
- *m_streamOut << strVersion.mid(10).remove('$');
-
- *m_streamOut << "</m>\n";
-
- TQDateTime now (TQDateTime::currentDateTime(Qt::UTC)); // current time in UTC
- *m_streamOut << "<m key=\"abiword.date_last_changed\">"
- << escapeAbiWordText(transformToTextDate(now))
- << "</m>\n";
-
- *m_streamOut << "</metadata>\n";
-
- return true;
-}
-
-
-// ==========================================================================================
-
-ABIWORDExport::ABIWORDExport(KoFilter */*parent*/, const char */*name*/, const TQStringList &) :
- KoFilter() {
-}
-
-KoFilter::ConversionStatus ABIWORDExport::convert( const TQCString& from, const TQCString& to )
-{
- if ( to != "application/x-abiword" || from != "application/x-kword" )
- {
- return KoFilter::NotImplemented;
- }
-
- // We need KimageIO's help in AbiWordWorker::convertUnknownImage
- KImageIO::registerFormats();
-
- AbiWordWorker* worker=new AbiWordWorker();
-
- if (!worker)
- {
- kdError(30506) << "Cannot create Worker! Aborting!" << endl;
- return KoFilter::StupidError;
- }
-
- KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
-
- if (!leader)
- {
- kdError(30506) << "Cannot create Worker! Aborting!" << endl;
- delete worker;
- return KoFilter::StupidError;
- }
-
- KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
-
- delete leader;
- delete worker;
-
- return result;
-}
diff --git a/filters/kword/abiword/abiwordexport.cpp b/filters/kword/abiword/abiwordexport.cpp
new file mode 100644
index 000000000..d1b5a98a2
--- /dev/null
+++ b/filters/kword/abiword/abiwordexport.cpp
@@ -0,0 +1,1261 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <tqmap.h>
+#include <tqiodevice.h>
+#include <tqtextstream.h>
+#include <tqdom.h>
+
+#include <kdebug.h>
+#include <kmdcodec.h>
+#include <kfilterdev.h>
+#include <kgenericfactory.h>
+#include <kimageio.h>
+
+#include <KoPageLayout.h>
+#include <KoFilterChain.h>
+#include <KoPictureKey.h>
+
+#include <KWEFStructures.h>
+#include <KWEFUtil.h>
+#include <KWEFBaseWorker.h>
+#include <KWEFKWordLeader.h>
+
+#include <abiwordexport.h>
+#include <abiwordexport.moc>
+
+class ABIWORDExportFactory : KGenericFactory<ABIWORDExport, KoFilter>
+{
+public:
+ ABIWORDExportFactory(void) : KGenericFactory<ABIWORDExport, KoFilter> ("kwordabiwordexport")
+ {}
+protected:
+ virtual void setupTranslations( void )
+ {
+ TDEGlobal::locale()->insertCatalogue( "kofficefilters" );
+ }
+};
+
+K_EXPORT_COMPONENT_FACTORY( libabiwordexport, ABIWORDExportFactory() )
+
+class StyleMap : public TQMap<TQString,LayoutData>
+{
+public:
+ StyleMap(void) {}
+ ~StyleMap(void) {}
+};
+
+class AbiWordWorker : public KWEFBaseWorker
+{
+public:
+ AbiWordWorker(void);
+ virtual ~AbiWordWorker(void) { delete m_streamOut; delete m_ioDevice; }
+public:
+ virtual bool doOpenFile(const TQString& filenameOut, const TQString& to);
+ virtual bool doCloseFile(void); // Close file in normal conditions
+ virtual bool doOpenDocument(void);
+ virtual bool doCloseDocument(void);
+ virtual bool doFullParagraph(const TQString& paraText, const LayoutData& layout,
+ const ValueListFormatData& paraFormatDataList);
+ virtual bool doOpenTextFrameSet(void); // AbiWord's <section>
+ virtual bool doCloseTextFrameSet(void); // AbiWord's </section>
+ virtual bool doFullPaperFormat(const int format,
+ const double width, const double height, const int orientation); // Calc AbiWord's <papersize>
+ virtual bool doFullPaperBorders (const double top, const double left,
+ const double bottom, const double right); // Like KWord's <PAPERBORDERS>
+ virtual bool doCloseHead(void); // Write <papersize>
+ virtual bool doOpenStyles(void); // AbiWord's <styles>
+ virtual bool doCloseStyles(void); // AbiWord's </styles>
+ virtual bool doFullDefineStyle(LayoutData& layout); // AbiWord's <s></s>
+ virtual bool doOpenSpellCheckIgnoreList (void); // AbiWord's <ignorewords>
+ virtual bool doCloseSpellCheckIgnoreList (void); // AbiWord's </ignorewords>
+ virtual bool doFullSpellCheckIgnoreWord (const TQString& ignoreword); // AbiWord's <iw>
+ virtual bool doFullDocumentInfo(const KWEFDocumentInfo& docInfo); // AbiWord's <metadata>
+private:
+ void processParagraphData (const TQString& paraText,
+ const TextFormatting& formatLayout,
+ const ValueListFormatData& paraFormatDataList);
+ void processNormalText ( const TQString& paraText,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData);
+ void processVariable ( const TQString& paraText,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData);
+ void processAnchor ( const TQString& paraText,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData);
+ TQString textFormatToAbiProps(const TextFormatting& formatOrigin,
+ const TextFormatting& formatData, const bool force) const;
+ TQString layoutToCss(const LayoutData& layoutOrigin,
+ const LayoutData& layout, const bool force) const;
+ TQString escapeAbiWordText(const TQString& strText) const;
+ bool makeTable(const FrameAnchor& anchor);
+ bool makePicture(const FrameAnchor& anchor);
+ void writeAbiProps(const TextFormatting& formatLayout, const TextFormatting& format);
+ void writePictureData(const TQString& koStoreName, const TQString& keyName);
+ TQString transformToTextDate(const TQDateTime& dt);
+private:
+ TQIODevice* m_ioDevice;
+ TQTextStream* m_streamOut;
+ TQString m_pagesize; // Buffer for the <pagesize> tag
+ TQMap<TQString,KoPictureKey> m_mapPictureData;
+ StyleMap m_styleMap;
+ double m_paperBorderTop,m_paperBorderLeft,m_paperBorderBottom,m_paperBorderRight;
+ bool m_inIgnoreWords; // true if <ignorewords> has been written
+ KWEFDocumentInfo m_docInfo; // document information
+};
+
+AbiWordWorker::AbiWordWorker(void) : m_ioDevice(NULL), m_streamOut(NULL),
+ m_paperBorderTop(0.0),m_paperBorderLeft(0.0),
+ m_paperBorderBottom(0.0),m_paperBorderRight(0.0)
+{
+}
+
+TQString AbiWordWorker::escapeAbiWordText(const TQString& strText) const
+{
+ // Escape quotes (needed in attributes)
+ // Escape apostrophs (allowed by XML)
+ return KWEFUtil::EscapeSgmlText(NULL,strText,true,true);
+}
+
+bool AbiWordWorker::doOpenFile(const TQString& filenameOut, const TQString& )
+{
+ kdDebug(30506) << "Opening file: " << filenameOut
+ << " (in AbiWordWorker::doOpenFile)" << endl;
+ //Find the last extension
+ TQString strExt;
+ const int result=filenameOut.findRev('.');
+ if (result>=0)
+ {
+ strExt=filenameOut.mid(result);
+ }
+
+ TQString strMimeType; // Mime type of the compressor
+
+ if ((strExt==".gz")||(strExt==".GZ") //in case of .abw.gz (logical extension)
+ ||(strExt==".zabw")||(strExt==".ZABW")) //in case of .zabw (extension used prioritary with AbiWord)
+ {
+ // Compressed with gzip
+ strMimeType="application/x-gzip";
+ }
+ else if ((strExt==".bz2")||(strExt==".BZ2") //in case of .abw.bz2 (logical extension)
+ ||(strExt==".bzabw")||(strExt==".BZABW")) //in case of .bzabw (extension used prioritary with AbiWord)
+ {
+ // Compressed with bzip2
+ strMimeType="application/x-bzip2";
+ }
+ else
+ {
+ // No compression
+ strMimeType="text/plain";
+ }
+
+ kdDebug(30506) << "Compression: " << strMimeType << endl;
+
+ m_ioDevice = KFilterDev::deviceForFile(filenameOut,strMimeType);
+
+ if (!m_ioDevice)
+ {
+ kdError(30506) << "No output file! Aborting!" << endl;
+ return false;
+ }
+
+ if ( !m_ioDevice->open (IO_WriteOnly) )
+ {
+ kdError(30506) << "Unable to open output file! Aborting!" << endl;
+ return false;
+ }
+
+ m_streamOut=new TQTextStream(m_ioDevice);
+
+ // We only export in UTF-8 (are there AbiWord ports that cannot read UTF-8? Be careful SVG uses UTF-8 too!)
+ m_streamOut->setEncoding( TQTextStream::UnicodeUTF8 );
+ return true;
+}
+
+bool AbiWordWorker::doCloseFile(void)
+{
+ delete m_streamOut;
+ m_streamOut=NULL;
+ if (m_ioDevice)
+ m_ioDevice->close();
+ return (m_ioDevice);
+}
+
+bool AbiWordWorker::doOpenDocument(void)
+{
+ kdDebug(30506)<< "AbiWordWorker::doOpenDocument" << endl;
+ // Make the file header
+
+ // First the XML header in UTF-8 version
+ // (AbiWord and QT handle UTF-8 well, so we stay with this encoding!)
+ *m_streamOut << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
+
+ // NOTE: AbiWord CVS 2002-02-?? has a new DOCTYPE
+ *m_streamOut << "<!DOCTYPE abiword PUBLIC \"-//ABISOURCE//DTD AWML 1.0 Strict//EN\"";
+ *m_streamOut << " \"http://www.abisource.com/awml.dtd\">\n";
+
+ // First magic: "<abiword"
+ *m_streamOut << "<abiword";
+ // AbiWord CVS 2002-02-23 defines a default namespace.
+ *m_streamOut << " xmlns=\"http://www.abisource.com/awml.dtd\"";
+ // As we do not use xmlns:awml, do we need to define it?
+ // *m_streamOut << " xmlns:awml=\"http://www.abisource.com/awml.dtd\"";
+ *m_streamOut << " xmlns:xlink=\"http://www.w3.org/1999/xlink\"";
+ // AbiWord CVS 2002-02-22 defines other namespaces, which we are not using.
+ // AbiWord CVS 2002-12-23 has no fileformat attribute anymore
+ // ### TODO: add document language and document direction of writing.
+ *m_streamOut << " xml:space=\"preserve\" version=\"1.1.2\" template=\"false\" styles=\"unlocked\">\n";
+ // Second magic: "<!-- This file is an AbiWord document."
+ // TODO/FIXME: write as much spaces as AbiWord does for the following line.
+ *m_streamOut << "<!-- This file is an AbiWord document. -->\n";
+ // We have chosen NOT to have the full comment header that AbiWord files normally have.
+ // ### TODO: perhaps we should add the comment: do not edit the file
+ *m_streamOut << "\n";
+
+
+ return true;
+}
+
+void AbiWordWorker::writePictureData(const TQString& koStoreName, const TQString& keyName)
+{
+ kdDebug(30506) << "AbiWordWorker::writeImageData" << endl;
+
+ TQByteArray image;
+
+ TQString strExtension(koStoreName.lower());
+ const int result=koStoreName.findRev(".");
+ if (result>=0)
+ {
+ strExtension=koStoreName.mid(result+1);
+ }
+
+ bool isImageLoaded=false;
+
+ if (strExtension=="png")
+ {
+ isImageLoaded=loadSubFile(koStoreName,image);
+ }
+ else
+ {
+ // All other picture types must be converted to PNG
+ // (yes, even JPEG, SVG or WMF!)
+ isImageLoaded=loadAndConvertToImage(koStoreName,strExtension,"PNG",image);
+ }
+
+ if (isImageLoaded)
+ {
+ *m_streamOut << "<d name=\"" << keyName << "\""
+ << " base64=\"yes\""
+ << " mime=\"image/png\">\n";
+
+ TQCString base64=KCodecs::base64Encode(image,true);
+
+ *m_streamOut << base64 << "\n"; // TQCString is taken as Latin1 by TQTextStream
+
+ *m_streamOut << "</d>\n";
+ }
+ else
+ {
+ kdWarning(30506) << "Unable to load picture: " << koStoreName << endl;
+ }
+}
+
+bool AbiWordWorker::doCloseDocument(void)
+{
+ // Before writing the <data> element,
+ // we must be sure that we have data and that we can retrieve it.
+
+ if (m_kwordLeader && !m_mapPictureData.isEmpty())
+ {
+ *m_streamOut << "<data>\n";
+
+ TQMap<TQString,KoPictureKey>::ConstIterator it;
+ TQMap<TQString,KoPictureKey>::ConstIterator end(m_mapPictureData.end());
+ // all images first
+ for (it=m_mapPictureData.begin(); it!=end; ++it)
+ {
+ // Warning: do not mix up KWord's key and the iterator's key!
+ writePictureData(it.key(),it.data().filename());
+ }
+
+ *m_streamOut << "</data>\n";
+ }
+
+ *m_streamOut << "</abiword>\n"; //Close the file for XML
+ return true;
+}
+
+bool AbiWordWorker::doOpenTextFrameSet(void)
+{
+ *m_streamOut << "<section props=\"";
+ *m_streamOut << "page-margin-top: ";
+ *m_streamOut << m_paperBorderTop;
+ *m_streamOut << "pt; ";
+ *m_streamOut << "page-margin-left: ";
+ *m_streamOut << m_paperBorderLeft;
+ *m_streamOut << "pt; ";
+ *m_streamOut << "page-margin-bottom: ";
+ *m_streamOut << m_paperBorderBottom;
+ *m_streamOut << "pt; ";
+ *m_streamOut << "page-margin-right: ";
+ *m_streamOut << m_paperBorderRight;
+ *m_streamOut << "pt"; // Last one, so no semi-comma
+ *m_streamOut << "\">\n";
+ return true;
+}
+
+bool AbiWordWorker::doCloseTextFrameSet(void)
+{
+ *m_streamOut << "</section>\n";
+ return true;
+}
+
+bool AbiWordWorker::doOpenStyles(void)
+{
+ *m_streamOut << "<styles>\n";
+ return true;
+}
+
+bool AbiWordWorker::doCloseStyles(void)
+{
+ *m_streamOut << "</styles>\n";
+ return true;
+}
+
+TQString AbiWordWorker::textFormatToAbiProps(const TextFormatting& formatOrigin,
+ const TextFormatting& formatData, const bool force) const
+{
+ // TODO: rename variable formatData
+ TQString strElement; // TODO: rename this variable
+
+ // Font name
+ TQString fontName = formatData.fontName;
+ if ( !fontName.isEmpty()
+ && (force || (formatOrigin.fontName!=formatData.fontName)))
+ {
+ strElement+="font-family: ";
+ strElement+= escapeAbiWordText(fontName); // TODO: add alternative font names
+ strElement+="; ";
+ }
+
+ if (force || (formatOrigin.italic!=formatData.italic))
+ {
+ // Font style
+ strElement+="font-style: ";
+ if ( formatData.italic )
+ {
+ strElement+="italic";
+ }
+ else
+ {
+ strElement+="normal";
+ }
+ strElement+="; ";
+ }
+
+ if (force || ((formatOrigin.weight>=75)!=(formatData.weight>=75)))
+ {
+ strElement+="font-weight: ";
+ if ( formatData.weight >= 75 )
+ {
+ strElement+="bold";
+ }
+ else
+ {
+ strElement+="normal";
+ }
+ strElement+="; ";
+ }
+
+ if (force || (formatOrigin.fontSize!=formatData.fontSize))
+ {
+ const int size=formatData.fontSize;
+ if (size>0)
+ {
+ // We use absolute font sizes.
+ strElement+="font-size: ";
+ strElement+=TQString::number(size,10);
+ strElement+="pt; ";
+ }
+ }
+
+ if (force || (formatOrigin.fgColor!=formatData.fgColor))
+ {
+ if ( formatData.fgColor.isValid() )
+ {
+ // Give colour
+ strElement+="color: ";
+
+ // No leading # (unlike CSS2)
+ // We must have two hex digits for each colour channel!
+ const int red=formatData.fgColor.red();
+ strElement += TQString::number((red&0xf0)>>4,16);
+ strElement += TQString::number(red&0x0f,16);
+
+ const int green=formatData.fgColor.green();
+ strElement += TQString::number((green&0xf0)>>4,16);
+ strElement += TQString::number(green&0x0f,16);
+
+ const int blue=formatData.fgColor.blue();
+ strElement += TQString::number((blue&0xf0)>>4,16);
+ strElement += TQString::number(blue&0x0f,16);
+
+ strElement+="; ";
+ }
+ }
+
+ if (force || (formatOrigin.bgColor!=formatData.bgColor))
+ {
+ if ( formatData.bgColor.isValid() )
+ {
+ // Give background colour
+ strElement+="bgcolor: ";
+
+ // No leading # (unlike CSS2)
+ // We must have two hex digits for each colour channel!
+ const int red=formatData.bgColor.red();
+ strElement += TQString::number((red&0xf0)>>4,16);
+ strElement += TQString::number(red&0x0f,16);
+
+ const int green=formatData.bgColor.green();
+ strElement += TQString::number((green&0xf0)>>4,16);
+ strElement += TQString::number(green&0x0f,16);
+
+ const int blue=formatData.bgColor.blue();
+ strElement += TQString::number((blue&0xf0)>>4,16);
+ strElement += TQString::number(blue&0x0f,16);
+
+ strElement+="; ";
+ }
+ }
+
+ if (force || (formatOrigin.underline!=formatData.underline)
+ || (formatOrigin.strikeout!=formatData.strikeout))
+ {
+ strElement+="text-decoration: ";
+ if ( formatData.underline )
+ {
+ strElement+="underline";
+ }
+ else if ( formatData.strikeout )
+ {
+ strElement+="line-through";
+ }
+ else
+ {
+ strElement+="none";
+ }
+ strElement+="; ";
+ }
+
+ return strElement;
+}
+
+bool AbiWordWorker::makeTable(const FrameAnchor& anchor)
+{
+#if 0
+ *m_streamOut << "</p>\n"; // Close previous paragraph ### TODO: do it correctly like for HTML
+ *m_streamOut << "<table>\n";
+#endif
+
+ TQValueList<TableCell>::ConstIterator itCell;
+ for (itCell=anchor.table.cellList.begin();
+ itCell!=anchor.table.cellList.end(); itCell++)
+ {
+#if 0
+ // ### TODO: rowspan, colspan
+
+ // AbiWord seems to work by attaching to the cell borders
+ *m_streamOut << "<cell props=\"";
+ *m_streamOut << "left-attach:" << (*itCell).col << "; ";
+ *m_streamOut << "right-attach:" << (*itCell).col + 1 << "; ";
+ *m_streamOut << "top-attach:" << (*itCell).row << "; ";
+ *m_streamOut << "bot-attach:" << (*itCell).row + 1;
+ *m_streamOut << "\">\n";
+#endif
+ if (!doFullAllParagraphs(*(*itCell).paraList))
+ {
+ return false;
+ }
+#if 0
+ *m_streamOut << "</cell>\n";
+#endif
+ }
+#if 0
+ *m_streamOut << "</table>\n";
+ *m_streamOut << "<p>\n"; // Re-open the "previous" paragraph ### TODO: do it correctly like for HTML
+#endif
+ return true;
+}
+
+bool AbiWordWorker::makePicture(const FrameAnchor& anchor)
+{
+ kdDebug(30506) << "New image/clipart: " << anchor.picture.koStoreName
+ << " , " << anchor.picture.key.toString() << endl;
+
+ const double height=anchor.frame.bottom - anchor.frame.top;
+ const double width =anchor.frame.right - anchor.frame.left;
+
+ // TODO: we are only using the filename, not the rest of the key
+ // TODO: (bad if there are two images of the same name, but of a different key)
+ *m_streamOut << "<image dataid=\"" << anchor.picture.key.filename() << "\"";
+ *m_streamOut << " props= \"height:" << height << "pt;width:" << width << "pt\"";
+ *m_streamOut << "/>"; // NO end of line!
+ // TODO: other props for image
+
+ m_mapPictureData[anchor.picture.koStoreName]=anchor.picture.key;
+
+ return true;
+}
+
+void AbiWordWorker::writeAbiProps (const TextFormatting& formatLayout, const TextFormatting& format)
+{
+ TQString abiprops=textFormatToAbiProps(formatLayout,format,false);
+
+ // Erase the last semi-comma (as in CSS2, semi-commas only separate instructions and do not terminate them)
+ const int result=abiprops.findRev(";");
+
+ if (result>=0)
+ {
+ // Remove the last semi-comma and the space thereafter
+ abiprops.remove(result,2);
+ }
+
+ if (!abiprops.isEmpty())
+ {
+ *m_streamOut << " props=\"" << abiprops << "\"";
+ }
+}
+
+void AbiWordWorker::processNormalText ( const TQString &paraText,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData)
+{
+ // Retrieve text and escape it
+ TQString partialText=escapeAbiWordText(paraText.mid(formatData.pos,formatData.len));
+
+ // Replace line feeds by line breaks
+ int pos;
+ while ((pos=partialText.find(TQChar(10)))>-1)
+ {
+ partialText.replace(pos,1,"<br/>");
+ }
+
+ if (formatData.text.missing)
+ {
+ // It's just normal text, so we do not need a <c> element!
+ *m_streamOut << partialText;
+ }
+ else
+ { // Text with properties, so use a <c> element!
+ *m_streamOut << "<c";
+ writeAbiProps(formatLayout,formatData.text);
+ *m_streamOut << ">" << partialText << "</c>";
+ }
+}
+
+void AbiWordWorker::processVariable ( const TQString&,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData)
+{
+ if (0==formatData.variable.m_type)
+ {
+ // As AbiWord's field is inflexible, we cannot make the date custom
+ *m_streamOut << "<field type=\"date_ntdfl\"";
+ writeAbiProps(formatLayout,formatData.text);
+ *m_streamOut << "/>";
+ }
+ else if (2==formatData.variable.m_type)
+ {
+ // As AbiWord's field is inflexible, we cannot make the time custom
+ *m_streamOut << "<field type=\"time\"";
+ writeAbiProps(formatLayout,formatData.text);
+ *m_streamOut << "/>";
+ }
+ else if (4==formatData.variable.m_type)
+ {
+ // As AbiWord's field is inflexible, we cannot make the time custom
+ TQString strFieldType;
+ if (formatData.variable.isPageNumber())
+ {
+ strFieldType="page_number";
+ }
+ else if (formatData.variable.isPageCount())
+ {
+ strFieldType="page_count";
+ }
+ if (strFieldType.isEmpty())
+ {
+ // Unknown subtype, therefore write out the result
+ *m_streamOut << formatData.variable.m_text;
+ }
+ else
+ {
+ *m_streamOut << "<field type=\"" << strFieldType <<"\"";
+ writeAbiProps(formatLayout,formatData.text);
+ *m_streamOut << "/>";
+ }
+ }
+ else if (9==formatData.variable.m_type)
+ {
+ // A link
+ *m_streamOut << "<a xlink:href=\""
+ << escapeAbiWordText(formatData.variable.getHrefName())
+ << "\"><c"; // In AbiWord, an anchor <a> has always a <c> child
+ writeAbiProps(formatLayout,formatData.text);
+ *m_streamOut << ">"
+ << escapeAbiWordText(formatData.variable.getLinkName())
+ << "</c></a>";
+ }
+#if 0
+ else if (11==(*paraFormatDataIt).variable.m_type)
+ {
+ // Footnote
+ TQString value = (*paraFormatDataIt).variable.getFootnoteValue();
+ bool automatic = (*paraFormatDataIt).variable.getFootnoteAuto();
+ TQValueList<ParaData> *paraList = (*paraFormatDataIt).variable.getFootnotePara();
+ if( paraList )
+ {
+ TQString fstr;
+ TQValueList<ParaData>::ConstIterator it;
+ for (it=paraList->begin();it!=paraList->end();it++)
+ fstr += ProcessParagraphData( (*it).text, (*it).layout,(*it).formattingList);
+ str += "{\\super ";
+ str += automatic ? "\\chftn " : value;
+ str += "{\\footnote ";
+ str += "{\\super ";
+ str += automatic ? "\\chftn " : value;
+ str += fstr;
+ str += " }";
+ str += " }";
+ str += " }";
+ }
+ }
+#endif
+ else
+ {
+ // Generic variable
+ *m_streamOut << formatData.variable.m_text;
+ }
+}
+
+void AbiWordWorker::processAnchor ( const TQString&,
+ const TextFormatting& /*formatLayout*/, //TODO
+ const FormatData& formatData)
+{
+ // We have an image or a table
+ if ( (2==formatData.frameAnchor.type) // <IMAGE> or <PICTURE>
+ || (5==formatData.frameAnchor.type) ) // <CLIPART>
+ {
+ makePicture(formatData.frameAnchor);
+ }
+ else if (6==formatData.frameAnchor.type)
+ {
+ makeTable(formatData.frameAnchor);
+ }
+ else
+ {
+ kdWarning(30506) << "Unsupported anchor type: "
+ << formatData.frameAnchor.type << endl;
+ }
+}
+
+void AbiWordWorker::processParagraphData ( const TQString &paraText,
+ const TextFormatting& formatLayout,
+ const ValueListFormatData &paraFormatDataList)
+{
+ if ( paraText.length () > 0 )
+ {
+ ValueListFormatData::ConstIterator paraFormatDataIt;
+
+ for ( paraFormatDataIt = paraFormatDataList.begin ();
+ paraFormatDataIt != paraFormatDataList.end ();
+ paraFormatDataIt++ )
+ {
+ if (1==(*paraFormatDataIt).id)
+ {
+ processNormalText(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if (4==(*paraFormatDataIt).id)
+ {
+ processVariable(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if (6==(*paraFormatDataIt).id)
+ {
+ processAnchor(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ }
+ }
+}
+
+TQString AbiWordWorker::layoutToCss(const LayoutData& layoutOrigin,
+ const LayoutData& layout, const bool force) const
+{
+ TQString props;
+
+ if (force || (layoutOrigin.alignment!=layout.alignment))
+ {
+ // Check if the current alignment is a valid one for AbiWord.
+ if ((layout.alignment == "left") || (layout.alignment == "right")
+ || (layout.alignment == "center") || (layout.alignment == "justify"))
+ {
+ props += "text-align:";
+ props += layout.alignment;
+ props += "; ";
+ }
+ else if (layout.alignment == "auto")
+ {
+ // We assume a left alignment as AbiWord is not really bi-di (and this filter even less.)
+ props += "text-align:left; ";
+ }
+ else
+ {
+ kdWarning(30506) << "Unknown alignment: " << layout.alignment << endl;
+ }
+ }
+
+ // TODO/FIXME: what if all tabulators must be erased?
+#if 0
+ // DEPRECATED!
+ if (!layout.tabulator.isEmpty()
+ && (force || (layoutOrigin.tabulator!=layout.tabulator)))
+ {
+ props += "tabstops:";
+ props += layout.tabulator;
+ props += "; ";
+ }
+#endif
+ if (!layout.tabulatorList.isEmpty()
+ && (force || (layoutOrigin.tabulatorList!=layout.tabulatorList) ))
+ {
+ props += "tabstops:";
+ bool first=true;
+ TabulatorList::ConstIterator it;
+ TabulatorList::ConstIterator end(layout.tabulatorList.end());
+ for (it=layout.tabulatorList.begin();it!=end;++it)
+ {
+ if (first)
+ {
+ first=false;
+ }
+ else
+ {
+ props += ",";
+ }
+ props += TQString::number((*it).m_ptpos);
+ props += "pt";
+
+ switch ((*it).m_type)
+ {
+ case 0: props += "/L"; break;
+ case 1: props += "/C"; break;
+ case 2: props += "/R"; break;
+ case 3: props += "/D"; break;
+ default: props += "/L";
+ }
+
+ props += "0"; // No filling
+ }
+ props += "; ";
+ }
+
+ if ((layout.indentLeft>=0.0)
+ && (force || (layoutOrigin.indentLeft!=layout.indentLeft)))
+ {
+ props += TQString("margin-left:%1pt; ").arg(layout.indentLeft);
+ }
+
+ if ((layout.indentRight>=0.0)
+ && (force || (layoutOrigin.indentRight!=layout.indentRight)))
+ {
+ props += TQString("margin-right:%1pt; ").arg(layout.indentRight);
+ }
+
+ if (force || (layoutOrigin.indentLeft!=layout.indentLeft))
+ {
+ props += "text-indent: ";
+ props += TQString::number(layout.indentFirst);
+ props += "pt; ";
+ }
+
+ if ((layout.marginBottom>=0.0)
+ && ( force || ( layoutOrigin.marginBottom != layout.marginBottom ) ) )
+ {
+ props += TQString("margin-bottom:%1pt; ").arg(layout.marginBottom);
+ }
+
+ if ((layout.marginTop>=0.0)
+ && ( force || ( layoutOrigin.marginTop != layout.marginTop ) ) )
+ {
+ props += TQString("margin-top:%1pt; ").arg(layout.marginTop);
+ }
+
+ if (force
+ || ( layoutOrigin.lineSpacingType != layout.lineSpacingType )
+ || ( layoutOrigin.lineSpacing != layout.lineSpacing ) )
+ {
+ switch ( layout.lineSpacingType )
+ {
+ case LayoutData::LS_CUSTOM:
+ {
+ // We have a custom line spacing (in points). However AbiWord cannot do it, so transform in "at-least"
+ props += "line-height=:";
+ props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
+ props += "pt+; ";
+ break;
+ }
+ case LayoutData::LS_SINGLE:
+ {
+ props += "line-height:1.0; "; // One
+ break;
+ }
+ case LayoutData::LS_ONEANDHALF:
+ {
+ props += "line-height:1.5; "; // One-and-half
+ break;
+ }
+ case LayoutData::LS_DOUBLE:
+ {
+ props += "line-height:2.0; "; // Two
+ break;
+ }
+ case LayoutData::LS_MULTIPLE:
+ {
+ props += "line-height:";
+ props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
+ props += "; ";
+ break;
+ }
+ case LayoutData::LS_FIXED:
+ {
+ // We have a fixed line height (in points)
+ props += "line-height:";
+ props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
+ props += "pt; ";
+ break;
+ }
+ case LayoutData::LS_ATLEAST:
+ {
+ // We have an "at-least" line height (in points)
+ props += "line-height=:";
+ props += TQString::number( layout.lineSpacing ); // ### TODO: rounding?
+ props += "pt+; "; // The + makes the difference
+ break;
+ }
+ default:
+ {
+ kdWarning(30506) << "Unsupported lineSpacingType: " << layout.lineSpacingType << " (Ignoring!)" << endl;
+ break;
+ }
+ }
+ }
+
+ // Add all AbiWord properties collected in the <FORMAT> element
+ props += textFormatToAbiProps(layoutOrigin.formatData.text,layout.formatData.text,force);
+
+ return props;
+}
+
+bool AbiWordWorker::doFullParagraph(const TQString& paraText, const LayoutData& layout,
+ const ValueListFormatData& paraFormatDataList)
+{
+ TQString style=layout.styleName;
+
+ const LayoutData& styleLayout=m_styleMap[style];
+
+ TQString props=layoutToCss(styleLayout,layout,false);
+
+ *m_streamOut << "<p";
+ if (!style.isEmpty())
+ {
+ *m_streamOut << " style=\"" << EscapeXmlText(style,true,true) << "\"";
+ }
+ if (!props.isEmpty())
+ {
+ // Find the last semi-comma
+ // Note: as in CSS2, semi-commas only separates instructions (like in PASCAL) and do not terminate them (like in C)
+ const int result=props.findRev(";");
+ if (result>=0)
+ {
+ // Remove the last semi-comma and the space thereafter
+ props.remove(result,2);
+ }
+
+ *m_streamOut << " props=\"" << props << "\"";
+ }
+ *m_streamOut << ">"; //Warning: No trailing white space or else it's in the text!!!
+
+ // Before processing the text, test if we have a page break
+ if (layout.pageBreakBefore)
+ {
+ // We have a page break before the paragraph
+ *m_streamOut << "<pbr/>";
+ }
+
+ processParagraphData(paraText, layout.formatData.text, paraFormatDataList);
+
+ // Before closing the paragraph, test if we have a page break
+ if (layout.pageBreakAfter)
+ {
+ // We have a page break after the paragraph
+ *m_streamOut << "<pbr/>";
+ }
+
+ *m_streamOut << "</p>\n";
+ return true;
+}
+
+bool AbiWordWorker::doFullDefineStyle(LayoutData& layout)
+{
+ //Register style in the style map
+ m_styleMap[layout.styleName]=layout;
+
+ *m_streamOut << "<s";
+
+ // TODO: cook the style name to the standard style names in AbiWord
+ *m_streamOut << " name=\"" << EscapeXmlText(layout.styleName,true,true) << "\"";
+ *m_streamOut << " followedby=\"" << EscapeXmlText(layout.styleFollowing,true,true) << "\"";
+
+ if ( (layout.counter.numbering == CounterData::NUM_CHAPTER)
+ && (layout.counter.depth<10) )
+ {
+ *m_streamOut << " level=\"";
+ *m_streamOut << TQString::number(layout.counter.depth+1,10);
+ *m_streamOut << "\"";
+ }
+
+ TQString abiprops=layoutToCss(layout,layout,true);
+
+ const int result=abiprops.findRev(";");
+ if (result>=0)
+ {
+ // Remove the last semi-comma and the space thereafter
+ abiprops.remove(result,2);
+ }
+
+ *m_streamOut << " props=\"" << abiprops << "\"";
+
+ *m_streamOut << "/>\n";
+
+ return true;
+}
+
+bool AbiWordWorker::doFullPaperFormat(const int format,
+ const double width, const double height, const int orientation)
+{
+ TQString outputText = "<pagesize ";
+
+ switch (format)
+ {
+ // ISO A formats
+ case PG_DIN_A0: // ISO A0
+ case PG_DIN_A1: // ISO A1
+ case PG_DIN_A2: // ISO A2
+ case PG_DIN_A3: // ISO A3
+ case PG_DIN_A4: // ISO A4
+ case PG_DIN_A5: // ISO A5
+ case PG_DIN_A6: // ISO A6
+ // ISO B formats
+ case PG_DIN_B0: // ISO B0
+ case PG_DIN_B1: // ISO B1
+ case PG_DIN_B2: // ISO B2
+ case PG_DIN_B3: // ISO B3
+ case PG_DIN_B4: // ISO B4
+ case PG_DIN_B5: // ISO B5
+ case PG_DIN_B6: // ISO B6
+ // American formats
+ case PG_US_LETTER: // US Letter
+ case PG_US_LEGAL: // US Legal
+ {
+ TQString pagetype=KoPageFormat::formatString(KoFormat(format));
+ outputText+="pagetype=\"";
+ outputText+=pagetype;
+
+ TQString strWidth, strHeight, strUnits;
+ KWEFUtil::GetNativePaperFormat(format, strWidth, strHeight, strUnits);
+ outputText+="\" width=\"";
+ outputText+=strWidth;
+ outputText+="\" height=\"";
+ outputText+=strHeight;
+ outputText+="\" units=\"";
+ outputText+=strUnits;
+ outputText+="\" ";
+ break;
+ }
+ case PG_US_EXECUTIVE: // US Executive (does not exists in AbiWord!)
+ {
+ // FIXME/TODO: AbiWord (CVS 2001-04-25) seems not to like custom formats, so avoid them for now!
+#if 0
+ outputText += "pagetype=\"Custom\" width=\"7.5\" height=\"10.0\" units=\"inch\" ";
+#else
+ // As replacement, use the slightly bigger "letter" format.
+ outputText += "pagetype=\"Letter\" width=\"8.5\" height=\"11.0\" units=\"inch\" ";
+#endif
+ break;
+ }
+ // Other format not supported yet by AbiWord CVS 2001-04-25)
+ case PG_DIN_A7: // ISO A7
+ case PG_DIN_A8: // ISO A8
+ case PG_DIN_A9: // ISO A9
+ case PG_DIN_B10: // ISO B10
+ // Other formats
+ case PG_SCREEN: // Screen
+ case PG_CUSTOM: // Custom
+ default:
+ {
+ // FIXME/TODO: AbiWord (CVS 2001-04-25) seems not to like custom formats, so avoid them for now!
+ if ((width<=1.0) || (height<=1.0) || true)
+ {
+ // Height or width is ridiculous, so assume A4 format
+ outputText += "pagetype=\"A4\" width=\"21.0\" height=\"29.7\" units=\"cm\" ";
+ }
+ else
+ { // We prefer to use inches, as to limit rounding errors (page size is in points!)
+ outputText += TQString("pagetype=\"Custom\" width=\"%1\" height=\"%2\" units=\"inch\" ").arg(width/72.0).arg(height/72.0);
+ }
+ break;
+ }
+ }
+
+ outputText += "orientation=\"";
+ if (1==orientation)
+ {
+ outputText += "landscape";
+ }
+ else
+ {
+ outputText += "portrait";
+ }
+ outputText += "\" ";
+
+ outputText += "page-scale=\"1.0\"/>\n"; // KWord has no page scale, so assume 100%
+
+ m_pagesize=outputText;
+ return true;
+}
+
+bool AbiWordWorker::doFullPaperBorders (const double top, const double left,
+ const double bottom, const double right)
+{
+ m_paperBorderTop=top;
+ m_paperBorderLeft=left;
+ m_paperBorderBottom=bottom;
+ m_paperBorderRight=right;
+ return true;
+}
+
+bool AbiWordWorker::doCloseHead(void)
+{
+ if (!m_pagesize.isEmpty())
+ {
+ *m_streamOut << m_pagesize;
+ }
+ return true;
+}
+
+bool AbiWordWorker::doOpenSpellCheckIgnoreList (void)
+{
+ kdDebug(30506) << "AbiWordWorker::doOpenSpellCheckIgnoreList" << endl;
+ m_inIgnoreWords=false; // reset
+ return true;
+}
+
+bool AbiWordWorker::doCloseSpellCheckIgnoreList (void)
+{
+ kdDebug(30506) << "AbiWordWorker::doCloseSpellCheckIgnoreList" << endl;
+ if (m_inIgnoreWords)
+ *m_streamOut << "</ignorewords>\n";
+ return true;
+}
+
+bool AbiWordWorker::doFullSpellCheckIgnoreWord (const TQString& ignoreword)
+{
+ kdDebug(30506) << "AbiWordWorker::doFullSpellCheckIgnoreWord: " << ignoreword << endl;
+ if (!m_inIgnoreWords)
+ {
+ *m_streamOut << "<ignorewords>\n";
+ m_inIgnoreWords=true;
+ }
+ *m_streamOut << " <iw>" << ignoreword << "</iw>\n";
+ return true;
+}
+
+// Similar to TQDateTime::toString, but guaranteed *not* to be translated
+TQString AbiWordWorker::transformToTextDate(const TQDateTime& dt)
+{
+ if (dt.isValid())
+ {
+ TQString result;
+
+ const TQDate date(dt.date());
+
+ const char* dayName[7] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
+ const int dow = date.dayOfWeek() - 1;
+ if ((dow<0) || (dow>6))
+ result += "Mon"; // Unknown day, rename it Monday.
+ else
+ result += dayName[dow];
+ result += ' ';
+
+ const char* monthName[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+ const int month = date.month() - 1;
+ if ((month<0) || (month>11))
+ result += "Jan"; // Unknown month, rename it January
+ else
+ result += monthName[month];
+ result += ' ';
+
+ TQString temp;
+
+ temp = "00";
+ temp += TQString::number(date.day(), 10);
+ result += temp.right(2);
+ result += ' ';
+
+ const TQTime time(dt.time());
+
+ temp = "00";
+ temp += TQString::number(time.hour(), 10);
+ result += temp.right(2);
+ result += ':';
+
+ temp = "00";
+ temp += TQString::number(time.minute(), 10);
+ result += temp.right(2);
+ result += ':';
+
+ temp = "00";
+ temp += TQString::number(time.second(), 10);
+ result += temp.right(2);
+ result += ' ';
+
+ temp = "0000";
+ temp += TQString::number(date.year(), 10);
+ result += temp.right(4);
+
+ return result;
+ }
+ else
+ {
+ // Invalid, so give back 1970-01-01
+ return "Thu Jan 01 00:00:00 1970";
+ }
+}
+
+bool AbiWordWorker::doFullDocumentInfo(const KWEFDocumentInfo& docInfo)
+{
+ m_docInfo=docInfo;
+
+ *m_streamOut << "<metadata>\n";
+
+ // First all Dublin Core data
+ *m_streamOut << "<m key=\"dc.format\">application/x-abiword</m>\n";
+ if (!m_docInfo.title.isEmpty())
+ {
+ *m_streamOut << "<m key=\"dc.title\">" << escapeAbiWordText(m_docInfo.title) << "</m>\n";
+ }
+ if (!m_docInfo.abstract.isEmpty())
+ {
+ *m_streamOut << "<m key=\"dc.description\">" << escapeAbiWordText(m_docInfo.abstract) << "</m>\n";
+ }
+
+ if ( !m_docInfo.keywords.isEmpty() )
+ {
+ *m_streamOut << "<m key=\"abiword.keywords\">" << escapeAbiWordText(m_docInfo.keywords) << "</m>\n";
+ }
+ if ( !m_docInfo.subject.isEmpty() )
+ {
+ *m_streamOut << "<m key=\"dc.subject\">" << escapeAbiWordText(m_docInfo.subject) << "</m>\n";
+ }
+
+ // Say who we are (with the CVS revision number) in case we have a bug in our filter output!
+ *m_streamOut << "<m key=\"abiword.generator\">KWord Export Filter";
+
+ TQString strVersion("$Revision: 508787 $");
+ // Remove the dollar signs
+ // (We don't want that the version number changes if the AbiWord file is itself put in a CVS storage.)
+ *m_streamOut << strVersion.mid(10).remove('$');
+
+ *m_streamOut << "</m>\n";
+
+ TQDateTime now (TQDateTime::currentDateTime(Qt::UTC)); // current time in UTC
+ *m_streamOut << "<m key=\"abiword.date_last_changed\">"
+ << escapeAbiWordText(transformToTextDate(now))
+ << "</m>\n";
+
+ *m_streamOut << "</metadata>\n";
+
+ return true;
+}
+
+
+// ==========================================================================================
+
+ABIWORDExport::ABIWORDExport(KoFilter */*parent*/, const char */*name*/, const TQStringList &) :
+ KoFilter() {
+}
+
+KoFilter::ConversionStatus ABIWORDExport::convert( const TQCString& from, const TQCString& to )
+{
+ if ( to != "application/x-abiword" || from != "application/x-kword" )
+ {
+ return KoFilter::NotImplemented;
+ }
+
+ // We need KimageIO's help in AbiWordWorker::convertUnknownImage
+ KImageIO::registerFormats();
+
+ AbiWordWorker* worker=new AbiWordWorker();
+
+ if (!worker)
+ {
+ kdError(30506) << "Cannot create Worker! Aborting!" << endl;
+ return KoFilter::StupidError;
+ }
+
+ KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
+
+ if (!leader)
+ {
+ kdError(30506) << "Cannot create Worker! Aborting!" << endl;
+ delete worker;
+ return KoFilter::StupidError;
+ }
+
+ KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
+
+ delete leader;
+ delete worker;
+
+ return result;
+}
diff --git a/filters/kword/abiword/abiwordimport.cc b/filters/kword/abiword/abiwordimport.cpp
index bd6ea1e38..bd6ea1e38 100644
--- a/filters/kword/abiword/abiwordimport.cc
+++ b/filters/kword/abiword/abiwordimport.cpp
diff --git a/filters/kword/amipro/Makefile.am b/filters/kword/amipro/Makefile.am
index f872af037..845049868 100644
--- a/filters/kword/amipro/Makefile.am
+++ b/filters/kword/amipro/Makefile.am
@@ -11,8 +11,8 @@ libamiproexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.l
kde_module_LTLIBRARIES = libamiproimport.la libamiproexport.la
-libamiproimport_la_SOURCES = amiproimport.cc amiproparser.cpp
-libamiproexport_la_SOURCES = amiproexport.cc
+libamiproimport_la_SOURCES = amiproimport.cpp amiproparser.cpp
+libamiproexport_la_SOURCES = amiproexport.cpp
noinst_HEADERS = amiproparser.h
diff --git a/filters/kword/amipro/amiproexport.cc b/filters/kword/amipro/amiproexport.cpp
index e6703fc02..e6703fc02 100644
--- a/filters/kword/amipro/amiproexport.cc
+++ b/filters/kword/amipro/amiproexport.cpp
diff --git a/filters/kword/amipro/amiproimport.cc b/filters/kword/amipro/amiproimport.cpp
index fe45ca18e..fe45ca18e 100644
--- a/filters/kword/amipro/amiproimport.cc
+++ b/filters/kword/amipro/amiproimport.cpp
diff --git a/filters/kword/applixword/Makefile.am b/filters/kword/applixword/Makefile.am
index 14e899746..7bc406c7d 100644
--- a/filters/kword/applixword/Makefile.am
+++ b/filters/kword/applixword/Makefile.am
@@ -7,7 +7,7 @@ libapplixwordimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-und
kde_module_LTLIBRARIES = libapplixwordimport.la
-libapplixwordimport_la_SOURCES = applixwordimport.cc
+libapplixwordimport_la_SOURCES = applixwordimport.cpp
libapplixwordimport_la_LIBADD = $(KOFFICE_LIBS)
noinst_HEADERS = applixwordimport.h
diff --git a/filters/kword/applixword/applixwordimport.cc b/filters/kword/applixword/applixwordimport.cpp
index 4c8b6620a..4c8b6620a 100644
--- a/filters/kword/applixword/applixwordimport.cc
+++ b/filters/kword/applixword/applixwordimport.cpp
diff --git a/filters/kword/ascii/ExportDialog.cc b/filters/kword/ascii/ExportDialog.cpp
index 577fb72b9..577fb72b9 100644
--- a/filters/kword/ascii/ExportDialog.cc
+++ b/filters/kword/ascii/ExportDialog.cpp
diff --git a/filters/kword/ascii/ImportDialog.cc b/filters/kword/ascii/ImportDialog.cpp
index 09c81a090..09c81a090 100644
--- a/filters/kword/ascii/ImportDialog.cc
+++ b/filters/kword/ascii/ImportDialog.cpp
diff --git a/filters/kword/ascii/Makefile.am b/filters/kword/ascii/Makefile.am
index 74b9dde20..22a5d5555 100644
--- a/filters/kword/ascii/Makefile.am
+++ b/filters/kword/ascii/Makefile.am
@@ -12,9 +12,9 @@ libasciiexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.la
kde_module_LTLIBRARIES = libasciiimport.la libasciiexport.la
-libasciiimport_la_SOURCES = asciiimport.cc ImportDialogUI.ui ImportDialog.cc
+libasciiimport_la_SOURCES = asciiimport.cpp ImportDialogUI.ui ImportDialog.cpp
-libasciiexport_la_SOURCES = asciiexport.cc ExportDialogUI.ui ExportDialog.cc
+libasciiexport_la_SOURCES = asciiexport.cpp ExportDialogUI.ui ExportDialog.cpp
noinst_HEADERS = asciiimport.h ImportDialog.h asciiexport.h ExportDialog.h
diff --git a/filters/kword/ascii/asciiexport.cc b/filters/kword/ascii/asciiexport.cpp
index 1bea9a269..1bea9a269 100644
--- a/filters/kword/ascii/asciiexport.cc
+++ b/filters/kword/ascii/asciiexport.cpp
diff --git a/filters/kword/ascii/asciiimport.cc b/filters/kword/ascii/asciiimport.cpp
index b7c4c0f5e..b7c4c0f5e 100644
--- a/filters/kword/ascii/asciiimport.cc
+++ b/filters/kword/ascii/asciiimport.cpp
diff --git a/filters/kword/docbook/Makefile.am b/filters/kword/docbook/Makefile.am
index 9ce299cbb..93967bc11 100644
--- a/filters/kword/docbook/Makefile.am
+++ b/filters/kword/docbook/Makefile.am
@@ -8,7 +8,7 @@ libdocbookexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.
kde_module_LTLIBRARIES = libdocbookexport.la
-libdocbookexport_la_SOURCES = docbookexport.cc
+libdocbookexport_la_SOURCES = docbookexport.cpp
noinst_HEADERS = docbookexport.h
diff --git a/filters/kword/docbook/docbookexport.cc b/filters/kword/docbook/docbookexport.cpp
index f54bec6b1..f54bec6b1 100644
--- a/filters/kword/docbook/docbookexport.cc
+++ b/filters/kword/docbook/docbookexport.cpp
diff --git a/filters/kword/html/export/ExportBasic.cc b/filters/kword/html/export/ExportBasic.cpp
index d222d7df4..d222d7df4 100644
--- a/filters/kword/html/export/ExportBasic.cc
+++ b/filters/kword/html/export/ExportBasic.cpp
diff --git a/filters/kword/html/export/ExportCss.cc b/filters/kword/html/export/ExportCss.cpp
index 2388477c3..2388477c3 100644
--- a/filters/kword/html/export/ExportCss.cc
+++ b/filters/kword/html/export/ExportCss.cpp
diff --git a/filters/kword/html/export/ExportDialog.cc b/filters/kword/html/export/ExportDialog.cpp
index 5fc3fdc59..5fc3fdc59 100644
--- a/filters/kword/html/export/ExportDialog.cc
+++ b/filters/kword/html/export/ExportDialog.cpp
diff --git a/filters/kword/html/export/ExportDocStruct.cc b/filters/kword/html/export/ExportDocStruct.cpp
index eccdead1d..eccdead1d 100644
--- a/filters/kword/html/export/ExportDocStruct.cc
+++ b/filters/kword/html/export/ExportDocStruct.cpp
diff --git a/filters/kword/html/export/ExportFilter.cc b/filters/kword/html/export/ExportFilter.cpp
index 96f0b6c5b..96f0b6c5b 100644
--- a/filters/kword/html/export/ExportFilter.cc
+++ b/filters/kword/html/export/ExportFilter.cpp
diff --git a/filters/kword/html/export/Makefile.am b/filters/kword/html/export/Makefile.am
index e35b70a5a..280dbb5e4 100644
--- a/filters/kword/html/export/Makefile.am
+++ b/filters/kword/html/export/Makefile.am
@@ -10,8 +10,8 @@ libhtmlexport_la_LIBADD = $(KOFFICE_LIBS) ../../libexport/libkwordexportfilters.
kde_module_LTLIBRARIES = libhtmlexport.la
-libhtmlexport_la_SOURCES = htmlexport.cc ExportDialog.cc ExportDialogUI.ui \
-ExportFilter.cc ExportCss.cc ExportDocStruct.cc ExportBasic.cc
+libhtmlexport_la_SOURCES = htmlexport.cpp ExportDialog.cpp ExportDialogUI.ui \
+ExportFilter.cpp ExportCss.cpp ExportDocStruct.cpp ExportBasic.cpp
noinst_HEADERS = htmlexport.h ExportDialog.h ExportDialogUI.h ExportFilter.h \
ExportCss.h ExportDocStruct.h ExportBasic.h
diff --git a/filters/kword/html/export/htmlexport.cc b/filters/kword/html/export/htmlexport.cc
deleted file mode 100644
index 285735176..000000000
--- a/filters/kword/html/export/htmlexport.cc
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- This file is part of the KDE project
- Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <tqtextcodec.h>
-
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <KoFilterChain.h>
-#include <KoFilterManager.h>
-
-#include <KWEFBaseWorker.h>
-#include <KWEFKWordLeader.h>
-
-#include "ExportDialog.h"
-#include "ExportFilter.h"
-#include "ExportCss.h"
-#include "ExportBasic.h"
-#include "ExportDocStruct.h"
-
-#include <htmlexport.h>
-#include <htmlexport.moc>
-
-typedef KGenericFactory<HTMLExport, KoFilter> HTMLExportFactory;
-K_EXPORT_COMPONENT_FACTORY( libhtmlexport, HTMLExportFactory( "kofficefilters" ) )
-
-//
-// HTMLExport
-//
-
-HTMLExport::HTMLExport(KoFilter *, const char *, const TQStringList &) :
- KoFilter() {
-}
-
-KoFilter::ConversionStatus HTMLExport::convert( const TQCString& from, const TQCString& to )
-{
- if ((from != "application/x-kword") || (to != "text/html"))
- {
- return KoFilter::NotImplemented;
- }
-
- bool batch=false;
- if ( m_chain->manager() )
- batch = m_chain->manager()->getBatchMode();
-
- HtmlWorker* worker;
-
- if (batch)
- {
- worker=new HtmlCssWorker();
- worker->setXML(true);
- worker->setCodec(TQTextCodec::codecForName("UTF-8"));
- }
- else
- {
- HtmlExportDialog dialog;
-
- if (!dialog.exec())
- {
- kdDebug(30503) << "Dialog was aborted! Aborting filter!" << endl;
- return KoFilter::UserCancelled;
- }
-
- const HtmlExportDialog::Mode mode = dialog.getMode();
- switch (mode)
- {
- case HtmlExportDialog::Light:
- worker=new HtmlDocStructWorker();
- break;
- case HtmlExportDialog::Basic:
- worker=new HtmlBasicWorker();
- break;
- case HtmlExportDialog::CustomCSS:
- worker=new HtmlBasicWorker( dialog.cssURL() );
- break;
- default: // Default CSS
- worker=new HtmlCssWorker();
- }
-
- worker->setXML(dialog.isXHtml());
- worker->setCodec(dialog.getCodec());
- }
-
- KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
-
- if (!leader)
- {
- kdError(30503) << "Cannot create Worker! Aborting!" << endl;
- delete worker;
- return KoFilter::StupidError;
- }
- KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
-
- delete leader;
- delete worker;
-
- return result;
-}
diff --git a/filters/kword/html/export/htmlexport.cpp b/filters/kword/html/export/htmlexport.cpp
new file mode 100644
index 000000000..76d780527
--- /dev/null
+++ b/filters/kword/html/export/htmlexport.cpp
@@ -0,0 +1,127 @@
+/*
+ This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <tqtextcodec.h>
+
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <KoFilterChain.h>
+#include <KoFilterManager.h>
+
+#include <KWEFBaseWorker.h>
+#include <KWEFKWordLeader.h>
+
+#include "ExportDialog.h"
+#include "ExportFilter.h"
+#include "ExportCss.h"
+#include "ExportBasic.h"
+#include "ExportDocStruct.h"
+
+#include <htmlexport.h>
+#include <htmlexport.moc>
+
+typedef KGenericFactory<HTMLExport, KoFilter> HTMLExportFactory;
+K_EXPORT_COMPONENT_FACTORY( libhtmlexport, HTMLExportFactory( "kofficefilters" ) )
+
+//
+// HTMLExport
+//
+
+HTMLExport::HTMLExport(KoFilter *, const char *, const TQStringList &) :
+ KoFilter() {
+}
+
+KoFilter::ConversionStatus HTMLExport::convert( const TQCString& from, const TQCString& to )
+{
+ if ((from != "application/x-kword") || (to != "text/html"))
+ {
+ return KoFilter::NotImplemented;
+ }
+
+ bool batch=false;
+ if ( m_chain->manager() )
+ batch = m_chain->manager()->getBatchMode();
+
+ HtmlWorker* worker;
+
+ if (batch)
+ {
+ worker=new HtmlCssWorker();
+ worker->setXML(true);
+ worker->setCodec(TQTextCodec::codecForName("UTF-8"));
+ }
+ else
+ {
+ HtmlExportDialog dialog;
+
+ if (!dialog.exec())
+ {
+ kdDebug(30503) << "Dialog was aborted! Aborting filter!" << endl;
+ return KoFilter::UserCancelled;
+ }
+
+ const HtmlExportDialog::Mode mode = dialog.getMode();
+ switch (mode)
+ {
+ case HtmlExportDialog::Light:
+ worker=new HtmlDocStructWorker();
+ break;
+ case HtmlExportDialog::Basic:
+ worker=new HtmlBasicWorker();
+ break;
+ case HtmlExportDialog::CustomCSS:
+ worker=new HtmlBasicWorker( dialog.cssURL() );
+ break;
+ default: // Default CSS
+ worker=new HtmlCssWorker();
+ }
+
+ worker->setXML(dialog.isXHtml());
+ worker->setCodec(dialog.getCodec());
+ }
+
+ KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
+
+ if (!leader)
+ {
+ kdError(30503) << "Cannot create Worker! Aborting!" << endl;
+ delete worker;
+ return KoFilter::StupidError;
+ }
+ KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
+
+ delete leader;
+ delete worker;
+
+ return result;
+}
diff --git a/filters/kword/latex/export/Makefile.am b/filters/kword/latex/export/Makefile.am
index 75552b425..85488d7bd 100644
--- a/filters/kword/latex/export/Makefile.am
+++ b/filters/kword/latex/export/Makefile.am
@@ -8,17 +8,17 @@ libkwordlatexexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA) $(LIBMAGICK_LIB
kde_module_LTLIBRARIES = libkwordlatexexport.la
-libkwordlatexexport_la_SOURCES = anchor.cc config.cc document.cc element.cc fileheader.cc \
- latexexportdia.ui footnote.cc format.cc formula.cc key.cc \
- kwordlatexexportdia.cc latexexport.cc latexexportIface.cc \
- latexexportIface.skel layout.cc listtable.cc para.cc \
- pixmapFrame.cc table.cc \
- textFrame.cc textformat.cc textzone.cc variableformat.cc \
- variablezone.cc xml2latexparser.cc xmlparser.cc
+libkwordlatexexport_la_SOURCES = anchor.cpp config.cpp document.cpp element.cpp fileheader.cpp \
+ latexexportdia.ui footnote.cpp format.cpp formula.cpp key.cpp \
+ kwordlatexexportdia.cpp latexexport.cpp latexexportIface.cpp \
+ latexexportIface.skel layout.cpp listtable.cpp para.cpp \
+ pixmapFrame.cpp table.cpp \
+ textFrame.cpp textformat.cpp textzone.cpp variableformat.cpp \
+ variablezone.cpp xml2latexparser.cpp xmlparser.cpp
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kword/latex/export/anchor.cc b/filters/kword/latex/export/anchor.cpp
index 999153847..999153847 100644
--- a/filters/kword/latex/export/anchor.cc
+++ b/filters/kword/latex/export/anchor.cpp
diff --git a/filters/kword/latex/export/config.cc b/filters/kword/latex/export/config.cpp
index 8460aae41..8460aae41 100644
--- a/filters/kword/latex/export/config.cc
+++ b/filters/kword/latex/export/config.cpp
diff --git a/filters/kword/latex/export/document.cc b/filters/kword/latex/export/document.cpp
index 13d40415f..13d40415f 100644
--- a/filters/kword/latex/export/document.cc
+++ b/filters/kword/latex/export/document.cpp
diff --git a/filters/kword/latex/export/element.cc b/filters/kword/latex/export/element.cpp
index 992293243..992293243 100644
--- a/filters/kword/latex/export/element.cc
+++ b/filters/kword/latex/export/element.cpp
diff --git a/filters/kword/latex/export/fileheader.cc b/filters/kword/latex/export/fileheader.cpp
index 8da25a16e..8da25a16e 100644
--- a/filters/kword/latex/export/fileheader.cc
+++ b/filters/kword/latex/export/fileheader.cpp
diff --git a/filters/kword/latex/export/footnote.cc b/filters/kword/latex/export/footnote.cpp
index fbfba354f..fbfba354f 100644
--- a/filters/kword/latex/export/footnote.cc
+++ b/filters/kword/latex/export/footnote.cpp
diff --git a/filters/kword/latex/export/format.cc b/filters/kword/latex/export/format.cpp
index d2e7d4a2b..d2e7d4a2b 100644
--- a/filters/kword/latex/export/format.cc
+++ b/filters/kword/latex/export/format.cpp
diff --git a/filters/kword/latex/export/formula.cc b/filters/kword/latex/export/formula.cpp
index 98f173797..98f173797 100644
--- a/filters/kword/latex/export/formula.cc
+++ b/filters/kword/latex/export/formula.cpp
diff --git a/filters/kword/latex/export/key.cc b/filters/kword/latex/export/key.cpp
index dccf89c6e..dccf89c6e 100644
--- a/filters/kword/latex/export/key.cc
+++ b/filters/kword/latex/export/key.cpp
diff --git a/filters/kword/latex/export/kwordlatexexportdia.cc b/filters/kword/latex/export/kwordlatexexportdia.cpp
index 3498bcdb9..3498bcdb9 100644
--- a/filters/kword/latex/export/kwordlatexexportdia.cc
+++ b/filters/kword/latex/export/kwordlatexexportdia.cpp
diff --git a/filters/kword/latex/export/latexexport.cc b/filters/kword/latex/export/latexexport.cpp
index fed29704f..fed29704f 100644
--- a/filters/kword/latex/export/latexexport.cc
+++ b/filters/kword/latex/export/latexexport.cpp
diff --git a/filters/kword/latex/export/latexexportIface.cc b/filters/kword/latex/export/latexexportIface.cpp
index 102845b10..102845b10 100644
--- a/filters/kword/latex/export/latexexportIface.cc
+++ b/filters/kword/latex/export/latexexportIface.cpp
diff --git a/filters/kword/latex/export/layout.cc b/filters/kword/latex/export/layout.cpp
index 74cee48ba..74cee48ba 100644
--- a/filters/kword/latex/export/layout.cc
+++ b/filters/kword/latex/export/layout.cpp
diff --git a/filters/kword/latex/export/listeformat.cc b/filters/kword/latex/export/listeformat.cpp
index 1122e70bb..1122e70bb 100644
--- a/filters/kword/latex/export/listeformat.cc
+++ b/filters/kword/latex/export/listeformat.cpp
diff --git a/filters/kword/latex/export/listelement.cc b/filters/kword/latex/export/listelement.cpp
index bb309ee93..bb309ee93 100644
--- a/filters/kword/latex/export/listelement.cc
+++ b/filters/kword/latex/export/listelement.cpp
diff --git a/filters/kword/latex/export/listepara.cc b/filters/kword/latex/export/listepara.cpp
index 0eb8dcad2..0eb8dcad2 100644
--- a/filters/kword/latex/export/listepara.cc
+++ b/filters/kword/latex/export/listepara.cpp
diff --git a/filters/kword/latex/export/listtable.cc b/filters/kword/latex/export/listtable.cpp
index 55cbf2382..55cbf2382 100644
--- a/filters/kword/latex/export/listtable.cc
+++ b/filters/kword/latex/export/listtable.cpp
diff --git a/filters/kword/latex/export/para.cc b/filters/kword/latex/export/para.cpp
index 9cc829b57..9cc829b57 100644
--- a/filters/kword/latex/export/para.cc
+++ b/filters/kword/latex/export/para.cpp
diff --git a/filters/kword/latex/export/pixmapFrame.cc b/filters/kword/latex/export/pixmapFrame.cpp
index 25f5951d7..25f5951d7 100644
--- a/filters/kword/latex/export/pixmapFrame.cc
+++ b/filters/kword/latex/export/pixmapFrame.cpp
diff --git a/filters/kword/latex/export/table.cc b/filters/kword/latex/export/table.cpp
index 90fdc378c..90fdc378c 100644
--- a/filters/kword/latex/export/table.cc
+++ b/filters/kword/latex/export/table.cpp
diff --git a/filters/kword/latex/export/texlauncher.cc b/filters/kword/latex/export/texlauncher.cpp
index 17c00b7d9..17c00b7d9 100644
--- a/filters/kword/latex/export/texlauncher.cc
+++ b/filters/kword/latex/export/texlauncher.cpp
diff --git a/filters/kword/latex/export/textFrame.cc b/filters/kword/latex/export/textFrame.cpp
index d6141e966..d6141e966 100644
--- a/filters/kword/latex/export/textFrame.cc
+++ b/filters/kword/latex/export/textFrame.cpp
diff --git a/filters/kword/latex/export/textformat.cc b/filters/kword/latex/export/textformat.cpp
index 02576354d..02576354d 100644
--- a/filters/kword/latex/export/textformat.cc
+++ b/filters/kword/latex/export/textformat.cpp
diff --git a/filters/kword/latex/export/textzone.cc b/filters/kword/latex/export/textzone.cpp
index 0bf4e436e..0bf4e436e 100644
--- a/filters/kword/latex/export/textzone.cc
+++ b/filters/kword/latex/export/textzone.cpp
diff --git a/filters/kword/latex/export/variableformat.cc b/filters/kword/latex/export/variableformat.cpp
index 5c6f9f40e..5c6f9f40e 100644
--- a/filters/kword/latex/export/variableformat.cc
+++ b/filters/kword/latex/export/variableformat.cpp
diff --git a/filters/kword/latex/export/variablezone.cc b/filters/kword/latex/export/variablezone.cpp
index b73788b3e..b73788b3e 100644
--- a/filters/kword/latex/export/variablezone.cc
+++ b/filters/kword/latex/export/variablezone.cpp
diff --git a/filters/kword/latex/export/xml2latexparser.cc b/filters/kword/latex/export/xml2latexparser.cpp
index 88936c9a1..88936c9a1 100644
--- a/filters/kword/latex/export/xml2latexparser.cc
+++ b/filters/kword/latex/export/xml2latexparser.cpp
diff --git a/filters/kword/latex/export/xmlparser.cc b/filters/kword/latex/export/xmlparser.cpp
index 9d83bedb8..9d83bedb8 100644
--- a/filters/kword/latex/export/xmlparser.cc
+++ b/filters/kword/latex/export/xmlparser.cpp
diff --git a/filters/kword/latex/import/Makefile.am b/filters/kword/latex/import/Makefile.am
index e55af45a2..f766e72a8 100644
--- a/filters/kword/latex/import/Makefile.am
+++ b/filters/kword/latex/import/Makefile.am
@@ -10,14 +10,14 @@ libkwordlateximport_la_LIBADD = $(KOFFICE_LIBS) parser/liblatexparser.la generat
kde_module_LTLIBRARIES = libkwordlateximport.la
-libkwordlateximport_la_SOURCES = config.cc lateximport.cc \
- lateximportdia.cc lateximportdia.skel
+libkwordlateximport_la_SOURCES = config.cpp lateximport.cpp \
+ lateximportdia.cpp lateximportdia.skel
noinst_HEADERS = config.h lateximport.h lateximportdia.h
######## Debug
#check_PROGRAMS = texlauncher
-#texlauncher_SOURCES = texlauncher.cc
+#texlauncher_SOURCES = texlauncher.cpp
#texlauncher_LDADD = liblatexexport.la
#texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kword/latex/import/config.cc b/filters/kword/latex/import/config.cpp
index d4594f700..d4594f700 100644
--- a/filters/kword/latex/import/config.cc
+++ b/filters/kword/latex/import/config.cpp
diff --git a/filters/kword/latex/import/generator/Makefile.am b/filters/kword/latex/import/generator/Makefile.am
index 089014e34..308e11c69 100644
--- a/filters/kword/latex/import/generator/Makefile.am
+++ b/filters/kword/latex/import/generator/Makefile.am
@@ -8,7 +8,7 @@ liblatexgenerator_la_LIBADD = -lm $(KOFFICE_LIBS)
kde_module_LTLIBRARIES = liblatexgenerator.la
-liblatexgenerator_la_SOURCES = body.cc document.cc kwordgenerator.cc latex.cc paragraph.cc
+liblatexgenerator_la_SOURCES = body.cpp document.cpp kwordgenerator.cpp latex.cpp paragraph.cpp
noinst_HEADERS = body.h document.h kwordgenerator.h latex.h paragraph.h
diff --git a/filters/kword/latex/import/generator/body.cc b/filters/kword/latex/import/generator/body.cpp
index fcf5e534c..fcf5e534c 100644
--- a/filters/kword/latex/import/generator/body.cc
+++ b/filters/kword/latex/import/generator/body.cpp
diff --git a/filters/kword/latex/import/generator/document.cc b/filters/kword/latex/import/generator/document.cpp
index cb333d41f..cb333d41f 100644
--- a/filters/kword/latex/import/generator/document.cc
+++ b/filters/kword/latex/import/generator/document.cpp
diff --git a/filters/kword/latex/import/generator/kwordgenerator.cc b/filters/kword/latex/import/generator/kwordgenerator.cpp
index 945c3869b..945c3869b 100644
--- a/filters/kword/latex/import/generator/kwordgenerator.cc
+++ b/filters/kword/latex/import/generator/kwordgenerator.cpp
diff --git a/filters/kword/latex/import/generator/latex.cc b/filters/kword/latex/import/generator/latex.cpp
index 22c773d83..22c773d83 100644
--- a/filters/kword/latex/import/generator/latex.cc
+++ b/filters/kword/latex/import/generator/latex.cpp
diff --git a/filters/kword/latex/import/generator/paragraph.cc b/filters/kword/latex/import/generator/paragraph.cpp
index c25ab9946..c25ab9946 100644
--- a/filters/kword/latex/import/generator/paragraph.cc
+++ b/filters/kword/latex/import/generator/paragraph.cpp
diff --git a/filters/kword/latex/import/lateximport.cc b/filters/kword/latex/import/lateximport.cpp
index 5bea13ccb..5bea13ccb 100644
--- a/filters/kword/latex/import/lateximport.cc
+++ b/filters/kword/latex/import/lateximport.cpp
diff --git a/filters/kword/latex/import/lateximportdia.cc b/filters/kword/latex/import/lateximportdia.cc
deleted file mode 100644
index c69b7e901..000000000
--- a/filters/kword/latex/import/lateximportdia.cc
+++ /dev/null
@@ -1,170 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001 Robert JACOLIN <rjacolin@ifrance.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the file :
- koffice/filters/kword/html/htmlexportdia.cc
- Copyright (C) 2001 Nicolas Goutte <goutte@kde.org>
-
- which was based on the old file:
- /home/kde/koffice/filters/kspread/csv/csvfilterdia.cc
-
- The old file was copyrighted by
- Copyright (C) 1999 David Faure <faure@kde.org>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <tdeapplication.h>
-#include <lateximportdia.h>
-#include <lateximportdia.moc>
-#include <dcopclient.h>
-#include <tdetempfile.h>
-#include <tqptrlist.h>
-
-#include "latexparser.h"
-#include "config.h"
-
-#include "generator/kwordgenerator.h"
-
-LATEXImportDia::LATEXImportDia(KoStore* out, TQWidget *parent, const char *name) :
- KDialogBase(parent, name, true, i18n("Latex Import Filter Parameters"),
- Ok|Cancel),
- DCOPObject("FilterConfigDia"), _out(out)
-{
- _out = out;
- kapp->restoreOverrideCursor();
- createDialog();
- if(!kapp->dcopClient()->isRegistered() )
- {
- kapp->dcopClient()->registerAs("FilterConfigDia");
- kapp->dcopClient()->setDefaultObject(objId());
- }
-}
-
-void LATEXImportDia::createDialog()
-{
- resize(size());
- TQWidget *page = new TQWidget( this );
- setMainWidget(page);
- TQBoxLayout *mainLayout = new TQVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());
- styleBox = new TQVButtonGroup(i18n("Document Style"), page);
- mainLayout->addWidget(styleBox);
-
- /* First part */
- TQBoxLayout *styleLayout = new TQVBoxLayout(page);
-
- latexStyleRBtn = new TQRadioButton(i18n("Latex style"), styleBox);
- styleLayout->addWidget(latexStyleRBtn);
-
- kwordStyleRBtn = new TQRadioButton(i18n("KWord style"), styleBox);
- styleLayout->addWidget(kwordStyleRBtn);
-
- /*typeLabel = new ...
- styleLayout->addWidget(typeLabel);
- typeCBox = new ...
- styleLayout->addWidget(typeCBox);
- */
- styleBox->setExclusive(true);
- styleBox->setButton(0); /* LATEX STYLE IS DEFAULT */
- styleLayout->activate();
-
- /* Second part */
- langBox = new TQVButtonGroup(i18n("Language"), page);
- mainLayout->addWidget(langBox);
-
- TQBoxLayout *langLayout = new TQVBoxLayout(langBox);
-
- unicodeRBtn = new TQRadioButton(i18n("Unicode"), langBox);
- langLayout->addWidget(unicodeRBtn);
-
- latin1RBtn = new TQRadioButton(i18n("latin1"), langBox);
- langLayout->addWidget(latin1RBtn);
-
- /*babelCheckBox = new ...
- langLayout->addWidget(babelCheckBox);
-
- babelCBox = new ...
- langLayout->addWidget(babelCBox);
- */
- langBox->setExclusive(true);
- langBox->setButton(1); /* LATIN1 IS THE DEFAULT. */
- langLayout->activate();
-
- /* Third part */
- docBox = new TQVButtonGroup(i18n("Document Type"), page);
- mainLayout->addWidget(docBox);
-
- TQBoxLayout *docLayout = new TQVBoxLayout(docBox);
-
- newDocRBtn = new TQRadioButton(i18n("New document"), docBox);
- docLayout->addWidget(newDocRBtn);
-
- embededRBtn = new TQRadioButton(i18n("Embedded document"), docBox);
- docLayout->addWidget(embededRBtn);
-
- docBox->setExclusive(true);
- docBox->setButton(0); /* NEW DOC IS THE DEFAULT. */
- docLayout->activate();
-
- /* Display the main layout */
- mainLayout->addStretch(5);
- mainLayout->activate();
-}
-
-void LATEXImportDia::state()
-{
- Config config;
-
- if(newDocRBtn == docBox->selected())
- config.setType(TYPE_DOC);
- else if(embededRBtn == docBox->selected())
- config.setType(TYPE_EMBEDED);
-
- if(unicodeRBtn == langBox->selected())
- config.setEncoding(ENC_UNICODE);
- else if(latin1RBtn == langBox->selected())
- config.setEncoding(ENC_LATIN1);
-
- /*if(latexStyleRBtn == styleBox->selected())
- config.result += "LATEX";
- else if(kwordStyleRBtn == styleBox->selected())
- result += "KWORD";*/
-}
-
-void LATEXImportDia::slotOk()
-{
- hide();
- state();
- kdDebug(30522) << "LATEX FILTER --> BEGIN" << endl;
- LatexParser parser(_fileIn);
- TQPtrList<Element>* root = parser.parse();
- kdDebug(30522) << "---------- generate file -------------" << endl;
- kdDebug(30522) << "command: " << root->count() << endl;
- Element* elt;
- for(elt = root->first(); elt; elt = root->next())
- {
- elt->print();
- }
- KwordGenerator generator(root);
- generator.convert(_out);
- kdDebug(30522) << "LATEX FILTER --> END" << endl;
- reject();
-}
diff --git a/filters/kword/latex/import/lateximportdia.cpp b/filters/kword/latex/import/lateximportdia.cpp
new file mode 100644
index 000000000..f0dd908bd
--- /dev/null
+++ b/filters/kword/latex/import/lateximportdia.cpp
@@ -0,0 +1,170 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001 Robert JACOLIN <rjacolin@ifrance.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the file :
+ koffice/filters/kword/html/htmlexportdia.cpp
+ Copyright (C) 2001 Nicolas Goutte <goutte@kde.org>
+
+ which was based on the old file:
+ /home/kde/koffice/filters/kspread/csv/csvfilterdia.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1999 David Faure <faure@kde.org>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <tdeapplication.h>
+#include <lateximportdia.h>
+#include <lateximportdia.moc>
+#include <dcopclient.h>
+#include <tdetempfile.h>
+#include <tqptrlist.h>
+
+#include "latexparser.h"
+#include "config.h"
+
+#include "generator/kwordgenerator.h"
+
+LATEXImportDia::LATEXImportDia(KoStore* out, TQWidget *parent, const char *name) :
+ KDialogBase(parent, name, true, i18n("Latex Import Filter Parameters"),
+ Ok|Cancel),
+ DCOPObject("FilterConfigDia"), _out(out)
+{
+ _out = out;
+ kapp->restoreOverrideCursor();
+ createDialog();
+ if(!kapp->dcopClient()->isRegistered() )
+ {
+ kapp->dcopClient()->registerAs("FilterConfigDia");
+ kapp->dcopClient()->setDefaultObject(objId());
+ }
+}
+
+void LATEXImportDia::createDialog()
+{
+ resize(size());
+ TQWidget *page = new TQWidget( this );
+ setMainWidget(page);
+ TQBoxLayout *mainLayout = new TQVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());
+ styleBox = new TQVButtonGroup(i18n("Document Style"), page);
+ mainLayout->addWidget(styleBox);
+
+ /* First part */
+ TQBoxLayout *styleLayout = new TQVBoxLayout(page);
+
+ latexStyleRBtn = new TQRadioButton(i18n("Latex style"), styleBox);
+ styleLayout->addWidget(latexStyleRBtn);
+
+ kwordStyleRBtn = new TQRadioButton(i18n("KWord style"), styleBox);
+ styleLayout->addWidget(kwordStyleRBtn);
+
+ /*typeLabel = new ...
+ styleLayout->addWidget(typeLabel);
+ typeCBox = new ...
+ styleLayout->addWidget(typeCBox);
+ */
+ styleBox->setExclusive(true);
+ styleBox->setButton(0); /* LATEX STYLE IS DEFAULT */
+ styleLayout->activate();
+
+ /* Second part */
+ langBox = new TQVButtonGroup(i18n("Language"), page);
+ mainLayout->addWidget(langBox);
+
+ TQBoxLayout *langLayout = new TQVBoxLayout(langBox);
+
+ unicodeRBtn = new TQRadioButton(i18n("Unicode"), langBox);
+ langLayout->addWidget(unicodeRBtn);
+
+ latin1RBtn = new TQRadioButton(i18n("latin1"), langBox);
+ langLayout->addWidget(latin1RBtn);
+
+ /*babelCheckBox = new ...
+ langLayout->addWidget(babelCheckBox);
+
+ babelCBox = new ...
+ langLayout->addWidget(babelCBox);
+ */
+ langBox->setExclusive(true);
+ langBox->setButton(1); /* LATIN1 IS THE DEFAULT. */
+ langLayout->activate();
+
+ /* Third part */
+ docBox = new TQVButtonGroup(i18n("Document Type"), page);
+ mainLayout->addWidget(docBox);
+
+ TQBoxLayout *docLayout = new TQVBoxLayout(docBox);
+
+ newDocRBtn = new TQRadioButton(i18n("New document"), docBox);
+ docLayout->addWidget(newDocRBtn);
+
+ embededRBtn = new TQRadioButton(i18n("Embedded document"), docBox);
+ docLayout->addWidget(embededRBtn);
+
+ docBox->setExclusive(true);
+ docBox->setButton(0); /* NEW DOC IS THE DEFAULT. */
+ docLayout->activate();
+
+ /* Display the main layout */
+ mainLayout->addStretch(5);
+ mainLayout->activate();
+}
+
+void LATEXImportDia::state()
+{
+ Config config;
+
+ if(newDocRBtn == docBox->selected())
+ config.setType(TYPE_DOC);
+ else if(embededRBtn == docBox->selected())
+ config.setType(TYPE_EMBEDED);
+
+ if(unicodeRBtn == langBox->selected())
+ config.setEncoding(ENC_UNICODE);
+ else if(latin1RBtn == langBox->selected())
+ config.setEncoding(ENC_LATIN1);
+
+ /*if(latexStyleRBtn == styleBox->selected())
+ config.result += "LATEX";
+ else if(kwordStyleRBtn == styleBox->selected())
+ result += "KWORD";*/
+}
+
+void LATEXImportDia::slotOk()
+{
+ hide();
+ state();
+ kdDebug(30522) << "LATEX FILTER --> BEGIN" << endl;
+ LatexParser parser(_fileIn);
+ TQPtrList<Element>* root = parser.parse();
+ kdDebug(30522) << "---------- generate file -------------" << endl;
+ kdDebug(30522) << "command: " << root->count() << endl;
+ Element* elt;
+ for(elt = root->first(); elt; elt = root->next())
+ {
+ elt->print();
+ }
+ KwordGenerator generator(root);
+ generator.convert(_out);
+ kdDebug(30522) << "LATEX FILTER --> END" << endl;
+ reject();
+}
diff --git a/filters/kword/latex/import/parser/Makefile.am b/filters/kword/latex/import/parser/Makefile.am
index 7cb99e348..4a3b963cf 100644
--- a/filters/kword/latex/import/parser/Makefile.am
+++ b/filters/kword/latex/import/parser/Makefile.am
@@ -8,22 +8,22 @@ liblatexparser_la_LIBADD = -lm $(KOFFICE_LIBS)
kde_module_LTLIBRARIES = liblatexparser.la
-liblatexparser_la_SOURCES = command.cc comment.cc element.cc env.cc group.cc \
- latexparser.cc param.cc text.cc texparser.cc \
- texscaner.cc
+liblatexparser_la_SOURCES = command.cpp comment.cpp element.cpp env.cpp group.cpp \
+ latexparser.cpp param.cpp text.cpp texparser.cpp \
+ texscaner.cpp
noinst_HEADERS = command.h comment.h element.h env.h group.h \
latexparser.h param.h text.h
-texparser.cc: $(srcdir)/texparser.l texscaner.cc
- flex -B -8 -otexparser.cc $(srcdir)/texparser.l
+texparser.cpp: $(srcdir)/texparser.l texscaner.cpp
+ flex -B -8 -otexparser.cpp $(srcdir)/texparser.l
-texscaner.cc: $(srcdir)/texscaner.y
- bison --debug --verbose -d -o texscaner.cc $(srcdir)/texscaner.y && mv -f texscaner.cc.h texscaner.hh
+texscaner.cpp: $(srcdir)/texscaner.y
+ bison --debug --verbose -d -o texscaner.cpp $(srcdir)/texscaner.y && mv -f texscaner.cpp.h texscaner.hh
# -p texparser
######## Debug
check_PROGRAMS = texlauncher
-texlauncher_SOURCES = texlauncher.cc
+texlauncher_SOURCES = texlauncher.cpp
texlauncher_LDADD = liblatexexport.la
texlauncher_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_TQT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_TDEIO) -ltdetexteditor
diff --git a/filters/kword/latex/import/parser/command.cc b/filters/kword/latex/import/parser/command.cpp
index d110c0899..d110c0899 100644
--- a/filters/kword/latex/import/parser/command.cc
+++ b/filters/kword/latex/import/parser/command.cpp
diff --git a/filters/kword/latex/import/parser/comment.cc b/filters/kword/latex/import/parser/comment.cpp
index ba52332e0..ba52332e0 100644
--- a/filters/kword/latex/import/parser/comment.cc
+++ b/filters/kword/latex/import/parser/comment.cpp
diff --git a/filters/kword/latex/import/parser/element.cc b/filters/kword/latex/import/parser/element.cpp
index 40a5ab981..40a5ab981 100644
--- a/filters/kword/latex/import/parser/element.cc
+++ b/filters/kword/latex/import/parser/element.cpp
diff --git a/filters/kword/latex/import/parser/env.cc b/filters/kword/latex/import/parser/env.cpp
index 14abad37a..14abad37a 100644
--- a/filters/kword/latex/import/parser/env.cc
+++ b/filters/kword/latex/import/parser/env.cpp
diff --git a/filters/kword/latex/import/parser/group.cc b/filters/kword/latex/import/parser/group.cpp
index 6654ea73f..6654ea73f 100644
--- a/filters/kword/latex/import/parser/group.cc
+++ b/filters/kword/latex/import/parser/group.cpp
diff --git a/filters/kword/latex/import/parser/latexparser.cc b/filters/kword/latex/import/parser/latexparser.cpp
index a5b3a8228..a5b3a8228 100644
--- a/filters/kword/latex/import/parser/latexparser.cc
+++ b/filters/kword/latex/import/parser/latexparser.cpp
diff --git a/filters/kword/latex/import/parser/main.cc b/filters/kword/latex/import/parser/main.cpp
index bce8e7714..bce8e7714 100644
--- a/filters/kword/latex/import/parser/main.cc
+++ b/filters/kword/latex/import/parser/main.cpp
diff --git a/filters/kword/latex/import/parser/param.cc b/filters/kword/latex/import/parser/param.cpp
index 66bb7fffb..66bb7fffb 100644
--- a/filters/kword/latex/import/parser/param.cc
+++ b/filters/kword/latex/import/parser/param.cpp
diff --git a/filters/kword/latex/import/parser/texparser.l b/filters/kword/latex/import/parser/texparser.l
index c187f29d6..ea78619fe 100644
--- a/filters/kword/latex/import/parser/texparser.l
+++ b/filters/kword/latex/import/parser/texparser.l
@@ -2,8 +2,8 @@
* Ajouter une pile contenant tout les environnements.
*
* To compil :
- * flex -+ -otexparser.cc texparser.lex
- * g++ -o texparser texparser.cc -lfl -lm
+ * flex -+ -otexparser.cpp texparser.lex
+ * g++ -o texparser texparser.cpp -lfl -lm
*
*/
diff --git a/filters/kword/latex/import/parser/texparser.lex b/filters/kword/latex/import/parser/texparser.lex
index eb9b27aac..e945f48dd 100644
--- a/filters/kword/latex/import/parser/texparser.lex
+++ b/filters/kword/latex/import/parser/texparser.lex
@@ -2,8 +2,8 @@
* Ajouter une pile contenant tout les environnements.
*
* To compil :
- * flex -+ -otexparser.cc texparser.lex
- * g++ -o texparser texparser.cc -lfl -lm
+ * flex -+ -otexparser.cpp texparser.lex
+ * g++ -o texparser texparser.cpp -lfl -lm
*
*/
diff --git a/filters/kword/latex/import/parser/text.cc b/filters/kword/latex/import/parser/text.cpp
index 62fd09982..62fd09982 100644
--- a/filters/kword/latex/import/parser/text.cc
+++ b/filters/kword/latex/import/parser/text.cpp
diff --git a/filters/kword/libexport/KWEFBaseWorker.cc b/filters/kword/libexport/KWEFBaseWorker.cpp
index a47f647da..a47f647da 100644
--- a/filters/kword/libexport/KWEFBaseWorker.cc
+++ b/filters/kword/libexport/KWEFBaseWorker.cpp
diff --git a/filters/kword/libexport/KWEFKWordLeader.cc b/filters/kword/libexport/KWEFKWordLeader.cc
deleted file mode 100644
index b0a7913d8..000000000
--- a/filters/kword/libexport/KWEFKWordLeader.cc
+++ /dev/null
@@ -1,1430 +0,0 @@
-/*
- This file is part of the KDE project
- Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
- Copyright (c) 2001 IABG mbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@IABG.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- Part of this code comes from the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Wolf-Michael.Bolle@GMX.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <tqfile.h>
-#include <tqdom.h>
-
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <tdemessagebox.h>
-
-#include <KoGlobal.h>
-#include <KoStore.h>
-
-#include "KWEFStructures.h"
-#include "TagProcessing.h"
-#include "ProcessDocument.h"
-#include "KWEFBaseWorker.h"
-#include "KWEFKWordLeader.h"
-
-KWEFKWordLeader::KWEFKWordLeader(void)
- : m_syntaxVersion(-1), m_oldSyntax(false), m_worker(NULL), m_chain(NULL), m_hType(0), m_fType(0)
-{
-}
-
-KWEFKWordLeader::KWEFKWordLeader(KWEFBaseWorker* newWorker)
- : m_syntaxVersion(-1), m_oldSyntax(false), m_worker(newWorker), m_chain(NULL)
-{
- if (newWorker) newWorker->registerKWordLeader(this);
-}
-
-KWEFKWordLeader::~KWEFKWordLeader(void)
-{
-}
-
-static FrameAnchor *findAnchor ( const KoPictureKey& key,
- TQValueList<ParaData>& paraList )
-{
- kdDebug(30508) << "findAnchor " << key.toString() << endl;
- TQValueList<ParaData>::Iterator paraIt;
-
- for ( paraIt = paraList.begin (); paraIt != paraList.end (); ++paraIt )
- {
- ValueListFormatData::Iterator formattingIt;
-
- for ( formattingIt = (*paraIt).formattingList.begin ();
- formattingIt != (*paraIt).formattingList.end ();
- formattingIt++ )
- {
- if ( (*formattingIt).id == 6 &&
- (*formattingIt).frameAnchor.key == key )
- {
- kdDebug(30508) << "Found anchor " << (*formattingIt).frameAnchor.key.toString() << endl;
- return &(*formattingIt).frameAnchor;
- }
- }
- }
-
- kdWarning(30508) << "findAnchor returning NULL!" << endl;
- return NULL;
-}
-
-static void ProcessHardBrkTag ( TQDomNode myNode, void* tagData, KWEFKWordLeader* )
-{
- // <HARDBRK>
- bool* flag = (bool*) tagData;
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "frame", *flag );
- ProcessAttributes (myNode, attrProcessingList);
- if (*flag)
- kdDebug(30508) << "<HARDBRK frame=\"1\"> found" << endl;
-}
-
-static void InsertBookmarkFormatData (const int pos, const TQString& name, const bool start,
- ValueListFormatData &paraFormatDataList)
-{
- ValueListFormatData::Iterator paraFormatDataIt;
-
- FormatData book( start ? 1001 : 1002 , pos, 0 );
- book.variable.m_text = name;
-
- for (paraFormatDataIt = paraFormatDataList.begin ();
- paraFormatDataIt != paraFormatDataList.end ();
- paraFormatDataIt++)
- {
- if ( pos <= (*paraFormatDataIt).pos )
- {
- paraFormatDataList.insert ( paraFormatDataIt, book );
- return;
-
- }
- if ( ( pos > (*paraFormatDataIt).pos ) && ( pos < (*paraFormatDataIt).pos + (*paraFormatDataIt).len ) )
- {
- // Somewhere in the middle, we have to split the FormatData
- FormatData split ( *paraFormatDataIt );
- //const int oldlen = (*paraFormatDataIt).len;
- split.len = pos - (*paraFormatDataIt).pos;
- (*paraFormatDataIt).len -= split.len;
- (*paraFormatDataIt).pos = pos;
- paraFormatDataList.insert ( paraFormatDataIt, split );
- paraFormatDataList.insert ( paraFormatDataIt, book );
- return;
- }
- }
-
- // Still here? So we need to put the bookmark here:
- paraFormatDataList.append ( book );
-}
-
-
-void KWEFKWordLeader::createBookmarkFormatData( ParaData& paraData )
-{
- const int paraCount = m_paraCountMap[ m_currentFramesetName ];
-
- TQValueList<Bookmark>::ConstIterator it;
- for (it = m_bookmarkList.begin(); it != m_bookmarkList.end(); ++it )
- {
- if ( (*(it)).m_frameset != m_currentFramesetName )
- {
- continue;
- }
- // As we always insert before, make first endings, then startings (problem is zero-length bookmark)
- if ( (*(it)).m_endparag == paraCount )
- {
- kdDebug(30508) << "Paragraph: " << paraCount << " end: " << (*(it)).m_name << endl;
- InsertBookmarkFormatData( (*(it)).m_cursorIndexEnd, (*(it)).m_name, false, paraData.formattingList);
-
- }
- if ( (*(it)).m_startparag == paraCount )
- {
- kdDebug(30508) << "Paragraph: " << paraCount << " begin: " << (*(it)).m_name << endl;
- InsertBookmarkFormatData( (*(it)).m_cursorIndexStart, (*(it)).m_name, true, paraData.formattingList);
- }
- }
-}
-
-static void ProcessParagraphTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
-#if 0
- kdDebug (30508) << "ProcessParagraphTag () - Begin" << endl;
-#endif
-
- TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
-
- AllowNoAttributes (myNode);
-
- // We need to adjust the paragraph number (0 if first)
- TQMap<TQString,int>::Iterator it = leader->m_paraCountMap.find( leader->m_currentFramesetName );
- if ( it == leader->m_paraCountMap.end() )
- leader->m_paraCountMap.insert( leader->m_currentFramesetName, 0 );
- else
- ++(*it);
-
- ParaData paraData;
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "TEXT", ProcessTextTag, &paraData.text )
- << TagProcessing ( "FORMATS", ProcessFormatsTag, &paraData.formattingList )
- << TagProcessing ( "LAYOUT", ProcessLayoutTag, &paraData.layout );
-
- if ( leader->m_oldSyntax )
- {
- tagProcessingList.append( TagProcessing( "HARDBRK", ProcessHardBrkTag, &paraData.layout.pageBreakBefore ) );
- }
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- leader->createBookmarkFormatData( paraData );
- CreateMissingFormatData (paraData.text, paraData.formattingList);
-
- // TODO/FIXME: why !paraData.text.isEmpty()
- if ( paraData.formattingList.isEmpty () && !paraData.text.isEmpty () )
- {
- if ( paraData.layout.formatData.id == 1 )
- {
- paraData.formattingList << paraData.layout.formatData;
- }
- else
- {
- kdWarning (30508) << "No useful FORMAT tag found for text in PARAGRAPH" << endl;
- }
- }
-
-
- *paraList << paraData;
-
-#if 0
- kdDebug (30508) << "ProcessParagraphTag () - End " << paraText << endl;
-#endif
-}
-
-
-static void ProcessFrameTag ( TQDomNode myNode, void *tagData,
- KWEFKWordLeader *leader )
-{
- FrameAnchor* frameAnchor= (FrameAnchor*) tagData;
-
- int lRed=0, lBlue=0, lGreen=0;
- int rRed=0, rBlue=0, rGreen=0;
- int tRed=0, tBlue=0, tGreen=0;
- int bRed=0, bBlue=0, bGreen=0;
- int bkRed=255, bkBlue=255, bkGreen=255;
-
- frameAnchor->frame.lWidth=0.0;
- frameAnchor->frame.rWidth=0.0;
- frameAnchor->frame.tWidth=0.0;
- frameAnchor->frame.bWidth=0.0;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "right", frameAnchor->frame.right )
- << AttrProcessing ( "left", frameAnchor->frame.left )
- << AttrProcessing ( "top", frameAnchor->frame.top )
- << AttrProcessing ( "bottom", frameAnchor->frame.bottom )
-
- << AttrProcessing ( "min-height", frameAnchor->frame.minHeight )
-
- << AttrProcessing ( "runaround", frameAnchor->frame.runaround )
- << AttrProcessing ( "runaroundSide", frameAnchor->frame.runaroundSide )
- << AttrProcessing ( "runaroundGap", frameAnchor->frame.runaroundGap )
-
- << AttrProcessing ( "autoCreateNewFrame", frameAnchor->frame.autoCreateNewFrame )
- << AttrProcessing ( "newFrameBehavior", frameAnchor->frame.newFrameBehavior )
- << AttrProcessing ( "newFrameBehaviour", frameAnchor->frame.newFrameBehavior ) // Depreciated name
-
- << AttrProcessing ( "copy", frameAnchor->frame.copy )
- << AttrProcessing ( "sheetSide", frameAnchor->frame.sheetSide )
-
- << AttrProcessing ( "lWidth", frameAnchor->frame.lWidth )
- << AttrProcessing ( "rWidth", frameAnchor->frame.rWidth )
- << AttrProcessing ( "tWidth", frameAnchor->frame.tWidth )
- << AttrProcessing ( "bWidth", frameAnchor->frame.bWidth )
-
- << AttrProcessing ( "lRed", lRed )
- << AttrProcessing ( "lGreen", lGreen )
- << AttrProcessing ( "lBlue", lBlue )
-
- << AttrProcessing ( "rRed", rRed )
- << AttrProcessing ( "rGreen", rGreen )
- << AttrProcessing ( "rBlue", rBlue )
-
- << AttrProcessing ( "tRed", tRed )
- << AttrProcessing ( "tGreen", tGreen )
- << AttrProcessing ( "tBlue", tBlue )
-
- << AttrProcessing ( "bRed", bRed )
- << AttrProcessing ( "bGreen", bGreen )
- << AttrProcessing ( "bBlue", bBlue )
-
- << AttrProcessing ( "lStyle", frameAnchor->frame.lStyle )
- << AttrProcessing ( "rStyle", frameAnchor->frame.rStyle )
- << AttrProcessing ( "tStyle", frameAnchor->frame.tStyle )
- << AttrProcessing ( "bStyle", frameAnchor->frame.bStyle )
-
- << AttrProcessing ( "bkRed", bkRed )
- << AttrProcessing ( "bkGreen", bkGreen )
- << AttrProcessing ( "bkBlue", bkBlue )
-
- << AttrProcessing ( "bkStyle", frameAnchor->frame.bkStyle )
-
- << AttrProcessing ( "bleftpt", frameAnchor->frame.bleftpt )
- << AttrProcessing ( "brightpt", frameAnchor->frame.brightpt )
- << AttrProcessing ( "btoppt", frameAnchor->frame.btoppt )
- << AttrProcessing ( "bbottompt", frameAnchor->frame.bbottompt )
- ;
-
- if ( leader->m_oldSyntax )
- {
- attrProcessingList
- << AttrProcessing ( "bleftmm" )
- << AttrProcessing ( "bleftinch" )
- << AttrProcessing ( "brightmm" )
- << AttrProcessing ( "brightinch" )
- << AttrProcessing ( "btopmm" )
- << AttrProcessing ( "btopinch" )
- << AttrProcessing ( "bbottommm" )
- << AttrProcessing ( "bbottominch" )
- ;
- }
-
- ProcessAttributes (myNode, attrProcessingList);
-
- frameAnchor->frame.lColor.setRgb( lRed, lGreen, lBlue );
- frameAnchor->frame.rColor.setRgb( rRed, rGreen, rBlue );
- frameAnchor->frame.tColor.setRgb( tRed, tGreen, tBlue );
- frameAnchor->frame.bColor.setRgb( bRed, bGreen, bBlue );
- frameAnchor->frame.bkColor.setRgb( bkRed, bkGreen, bkBlue );
-
- AllowNoSubtags (myNode, leader);
-}
-
-static void ProcessPictureAnchor( TQDomNode myNode, KWEFKWordLeader *leader, FrameAnchor* frameAnchor, const int frameType )
-{
- frameAnchor->type = frameType;
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList
- << TagProcessing ( "FRAME", ProcessFrameTag, frameAnchor )
- << TagProcessing ( "PICTURE", ProcessImageTag, &frameAnchor->picture.key )
- << TagProcessing ( "IMAGE", ProcessImageTag, &frameAnchor->picture.key )
- << TagProcessing ( "CLIPART", ProcessImageTag, &frameAnchor->picture.key )
- ;
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- kdDebug (30508) << "FRAMESET PICTURE KEY " << frameAnchor->picture.key.toString() << endl;
-
- frameAnchor->key = frameAnchor->picture.key;
-}
-
-static void ProcessTableAnchor( TQDomNode myNode, KWEFKWordLeader *leader, FrameAnchor* frameAnchor,
- const int col, const int row, const int cols, const int rows )
-{
- frameAnchor->type = 6; // Table
-
- TQValueList<ParaData> cellParaList;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "FRAME", ProcessFrameTag, frameAnchor )
- << TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &cellParaList );
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- frameAnchor->table.addCell (col, row, cols, rows, cellParaList, frameAnchor->frame);
-}
-
-static void ProcessFramesetTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
-#if 0
- kdDebug (30508) << "ProcessFramesetTag () - Begin" << endl;
-#endif
-
- TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
-
- int frameType = -1;
- int frameInfo = -1;
- int col = -1;
- int row = -1;
- int cols = -1;
- int rows = -1;
- TQString grpMgr;
-
- const TQString oldName ( leader->m_currentFramesetName );
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "name", leader->m_currentFramesetName )
- << AttrProcessing ( "frameType", frameType )
- << AttrProcessing ( "frameInfo", frameInfo )
- << AttrProcessing ( "removable" )
- << AttrProcessing ( "visible" )
- << AttrProcessing ( "grpMgr", grpMgr )
- << AttrProcessing ( "row", row )
- << AttrProcessing ( "col", col )
- << AttrProcessing ( "rows", rows )
- << AttrProcessing ( "cols", cols )
- << AttrProcessing ( "protectSize" )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- switch ( frameType )
- {
- case 1:
- if ( grpMgr.isEmpty () )
- {
- // As we do not support anything else than normal text, process only normal text.
- // TODO: Treat the other types of frames (frameType)
- if (frameInfo==0)
- {
- // Normal Text
- kdDebug(30508) << "Processing Frameset: " << leader->m_currentFramesetName << endl;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, paraList ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- }
- else if (frameInfo==1)
- {
- // header for first page
- HeaderData header;
- header.page = HeaderData::PAGE_FIRST;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
-
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doHeader( header );
- }
- else if (frameInfo==2)
- {
- // header for even page
- HeaderData header;
- header.page = HeaderData::PAGE_EVEN;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doHeader( header );
- }
- else if (frameInfo==3)
- {
- // header for odd page (or all page, if hType=0)
- HeaderData header;
- header.page = (leader->headerType() != 0 ) ? HeaderData::PAGE_ODD : HeaderData::PAGE_ALL;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doHeader( header );
- }
- else if (frameInfo==4)
- {
- // footer for first page
- FooterData footer;
- footer.page = FooterData::PAGE_FIRST;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doFooter( footer );
- }
- else if (frameInfo==5)
- {
- // footer for even page
- FooterData footer;
- footer.page = FooterData::PAGE_EVEN;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doFooter( footer );
- }
- else if (frameInfo==6)
- {
- // footer for odd page (or all page, if fType=0)
- FooterData footer;
- footer.page = (leader->footerType() != 0) ? FooterData::PAGE_ODD : FooterData::PAGE_ALL;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->doFooter( footer );
- }
- }
- else
- {
- if ( col != -1 && row != -1 )
- {
- if ( cols > 0 && rows > 0 )
- {
-#if 0
- kdDebug (30508) << "DEBUG - FRAMESET: table " << name << " col, row = "
- << col << ", " << row << ", Mgr = "<< grpMgr << endl;
-#endif
- FrameAnchor *frameAnchor = findAnchor (grpMgr, *paraList);
- if ( frameAnchor )
- {
- ProcessTableAnchor( myNode, leader, frameAnchor, col, row, cols, rows );
- }
- else
- {
- bool found = false;
- KoPictureKey key( grpMgr );
- TQValueList<FrameAnchor>::Iterator it;
- for ( it = leader->m_nonInlinedTableAnchors.begin(); it != leader->m_nonInlinedTableAnchors.end(); ++it )
- {
- if ( (*it).key == key )
- {
- kdDebug(30508) << "Found pseudo-anchor for table: " << (*it).key.toString() << endl;
- found = true;
- break;
- }
- }
-
- if ( found )
- {
- ProcessTableAnchor( myNode, leader, &(*it), col, row, cols, rows );
- }
- else
- {
- kdWarning(30508) << "Table anchor not found: " << grpMgr << endl;
- FrameAnchor anchor;
- ProcessTableAnchor( myNode, leader, &anchor, col, row, cols, rows );
- anchor.key = key; // Needed, so that the pseudo-anchor can be found again
- leader->m_nonInlinedTableAnchors << anchor;
- leader->m_unanchoredFramesets.append( grpMgr );
- }
- }
- }
- else
- {
- kdWarning (30508) << "Unexpected value for one of, or all FRAMESET attribute cols, rows: "
- << cols << ", " << rows << "!" << endl;
- AllowNoSubtags (myNode, leader);
- }
- }
- else
- {
- kdWarning (30508) << "Unset value for one of, or all FRAMESET attributes col, row: "
- << col << ", " << row << "!" << endl;
- AllowNoSubtags (myNode, leader);
- leader->m_unanchoredFramesets.append( leader->m_currentFramesetName );
- }
- }
- break;
-
- case 2: // PICTURE
- case 5: // CLIPART: deprecated (up to KOffice 1.2 Beta 2)
- {
-#if 0
- kdDebug (30508) << "DEBUG: FRAMESET name of picture is " << name << endl;
-#endif
-
- FrameAnchor *frameAnchor = findAnchor ( leader->m_currentFramesetName, *paraList );
-
- if ( frameAnchor )
- {
- ProcessPictureAnchor( myNode, leader, frameAnchor, frameType );
- }
- else
- {
- // ### TODO: non-inlined picture?
- // No anchor found, so the picture is not inlined
- kdDebug (30508) << "ProcessFramesetTag: Couldn't find anchor " << leader->m_currentFramesetName << endl;
- FrameAnchor anchor;
- ProcessPictureAnchor( myNode, leader, &anchor, frameType );
- leader->m_nonInlinedPictureAnchors << anchor;
- leader->m_unanchoredFramesets.append( leader->m_currentFramesetName ); // DEBUG
- }
-
- break;
- }
-
- case 4: // KFormula
- {
- kdWarning(30508) << "KFormula frameset not supported yet!" << endl; // ### TODO
- break;
- }
- default:
- kdWarning (30508) << "Unexpected frametype " << frameType << " (in ProcessFramesetTag)" << endl;
- }
-
- leader->m_currentFramesetName = oldName;
-
-#if 0
- kdDebug (30508) << "ProcessFramesetTag () - End" << endl;
-#endif
-}
-
-
-static void ProcessFramesetsTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "FRAMESET", ProcessFramesetTag, tagData );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-
-static void ProcessStyleTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
-{
- LayoutData layout;
-
- ProcessLayoutTag (myNode, &layout, leader);
-
- leader->doFullDefineStyle (layout);
-}
-
-
-static void ProcessStylesPluralTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- leader->doOpenStyles ();
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "STYLE", ProcessStyleTag, leader );
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- leader->doCloseStyles ();
-}
-
-
-static void ProcessPaperBordersTag (TQDomNode myNode, void*, KWEFKWordLeader* leader)
-{
-
- double left = 0.0;
- double right = 0.0;
- double top = 0.0;
- double bottom = 0.0;
-
- TQValueList<AttrProcessing> attrProcessingList;
- if ( leader->m_oldSyntax )
- {
- attrProcessingList
- << AttrProcessing ( "ptLeft", left )
- << AttrProcessing ( "ptRight", right )
- << AttrProcessing ( "ptTop", top )
- << AttrProcessing ( "ptBottom", bottom )
- << AttrProcessing ( "mmLeft" )
- << AttrProcessing ( "mmRight" )
- << AttrProcessing ( "mmTop" )
- << AttrProcessing ( "mmBottom" )
- << AttrProcessing ( "inchLeft" )
- << AttrProcessing ( "inchRight" )
- << AttrProcessing ( "inchTop" )
- << AttrProcessing ( "inchBottom" )
- ;
- }
- else
- {
- attrProcessingList
- << AttrProcessing ( "left", left )
- << AttrProcessing ( "right", right )
- << AttrProcessing ( "top", top )
- << AttrProcessing ( "bottom", bottom )
- ;
- }
- ProcessAttributes (myNode, attrProcessingList);
-
- leader->doFullPaperBorders(top, left, bottom, right);
-
- AllowNoSubtags (myNode, leader);
-}
-
-static void ProcessPaperTag (TQDomNode myNode, void *, KWEFKWordLeader *leader)
-{
-
- int format = -1;
- int orientation = -1;
- double width = -1.0;
- double height = -1.0;
- int hType = -1;
- int fType = -1;
- int columns = 1;
- double columnspacing = 36.0; // Half-inch
- int numPages = -1;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "format", format )
- << AttrProcessing ( "width", width )
- << AttrProcessing ( "height", height )
- << AttrProcessing ( "orientation", orientation )
- << AttrProcessing ( "columns", columns )
- << AttrProcessing ( "columnspacing", columnspacing )
- << AttrProcessing ( "pages", numPages )
- << AttrProcessing ( "hType", hType )
- << AttrProcessing ( "fType", fType )
- << AttrProcessing ( "spHeadBody" )
- << AttrProcessing ( "spFootBody" )
- << AttrProcessing ( "spFootNoteBody" )
- << AttrProcessing ( "slFootNotePosition" )
- << AttrProcessing ( "slFootNoteLength" )
- << AttrProcessing ( "slFootNoteWidth" )
- << AttrProcessing ( "slFootNoteType" );
-
- if ( leader->m_oldSyntax )
- {
- // ### TODO: in syntax 1 hType and fType have other values!
- attrProcessingList
- << AttrProcessing ( "ptWidth", width )
- << AttrProcessing ( "ptHeight", height )
- << AttrProcessing ( "ptColumnspc", columnspacing )
- << AttrProcessing ( "mmWidth" )
- << AttrProcessing ( "mmHeight" )
- << AttrProcessing ( "mmColumnspc" )
- << AttrProcessing ( "inchWidth" )
- << AttrProcessing ( "inchHeight" )
- << AttrProcessing ( "inchColumnspc" )
- ;
- }
-
- ProcessAttributes (myNode, attrProcessingList);
-
- leader->setHeaderType( hType );
- leader->setFooterType( fType );
-
- leader->doPageInfo ( hType, fType );
- leader->doFullPaperFormat (format, width, height, orientation);
- leader->doFullPaperFormatOther( columns, columnspacing, numPages );
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList
- << TagProcessing ( "PAPERBORDERS", ProcessPaperBordersTag, NULL )
- ;
-
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-static void ProcessVariableSettingsTag (TQDomNode myNode, void *, KWEFKWordLeader *leader)
-{
- VariableSettingsData vs;
- TQString print, creation, modification; // Dates (in ISO 8601 format)
- int creationYear = -1;
- int creationMonth = -1;
- int creationDay = -1;
- int modificationYear = -1;
- int modificationMonth = -1;
- int modificationDay = -1;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "startingPageNumber", vs.startingPageNumber )
- << AttrProcessing ( "displaylink", vs.displaylink )
- << AttrProcessing ( "underlinelink", vs.underlinelink )
- << AttrProcessing ( "displaycomment", vs.displaycomment )
- << AttrProcessing ( "displayfieldcode", vs.displayfieldcode )
- ;
-
-
- // The following 3 attributes are from syntax 3 but at least the RTF import filter generate them with syntax 2.
- attrProcessingList
- << AttrProcessing ( "lastPrintingDate", print )
- << AttrProcessing ( "creationDate", creation )
- << AttrProcessing ( "modificationDate", modification );
- ;
-
- // Some files have the creation and modification date not in one attribute but in an attribute for each the year, the month, the day
- // ( e.g. syntax 2 file kofficetests/documents/export/kword/text/all.kwd )
- attrProcessingList
- << AttrProcessing( "modifyFileYear", modificationYear )
- << AttrProcessing( "modifyFileMonth", modificationMonth )
- << AttrProcessing( "modifyFileDay", modificationDay )
- << AttrProcessing( "createFileYear", creationYear )
- << AttrProcessing( "createFileMonth", creationMonth )
- << AttrProcessing( "createFileDay", creationDay )
- ;
-
- ProcessAttributes (myNode, attrProcessingList);
-
- if ( creation.isEmpty() )
- {
- if ( ( creationYear >= 1970 ) && TQDate::isValid( creationYear, creationMonth, creationDay ) )
- {
- vs.creationTime = TQDateTime( TQDate( creationYear, creationMonth, creationDay ) );
- }
- }
- else
- vs.creationTime=TQDateTime::fromString(creation, Qt::ISODate);
- //kdDebug(30508) << "Creation time: " << vs.creationTime.toString( Qt::ISODate ) << endl;
-
- if ( modification.isEmpty() )
- {
- if ( ( modificationYear >= 1970 ) && TQDate::isValid( modificationYear, modificationMonth, modificationDay ) )
- {
- vs.modificationTime = TQDateTime( TQDate( modificationYear, modificationMonth, modificationDay ) );
- }
- }
- else
- vs.modificationTime=TQDateTime::fromString(modification, Qt::ISODate);
- //kdDebug(30508) << "Modification time: " << vs.modificationTime.toString( Qt::ISODate ) << endl;
-
- if (!print.isEmpty())
- vs.printTime=TQDateTime::fromString(print, Qt::ISODate);
- //kdDebug(30508) << "Print time: " << vs.printTime.toString( Qt::ISODate ) << endl;
-
- leader->doVariableSettings (vs);
-}
-
-static void ProcessSpellCheckIgnoreWordTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
-{
- TQString ignoreword;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "word", ignoreword )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- leader->doFullSpellCheckIgnoreWord (ignoreword);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessSpellCheckIgnoreListTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- leader->doOpenSpellCheckIgnoreList ();
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "SPELLCHECKIGNOREWORD", ProcessSpellCheckIgnoreWordTag, leader );
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- leader->doCloseSpellCheckIgnoreList ();
-}
-
-
-static void ProcessPixmapsKeyTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
-
- KoPictureKey key;
-
- // Let KoPictureKey do most of the loading
- key.loadAttributes(myNode.toElement());
- const TQString name(myNode.toElement().attribute("name"));
-
- kdDebug(30508) << "search anchors: " << key.toString() << endl;
- bool found = false;
-
- // NOTE: we must always search in both inlined and non-inlined pictures. A picture can be used in both ways and a few times in each!
-
- // Process inlined pictures
- TQValueList<ParaData>::Iterator paraIt;
-
- for ( paraIt = paraList->begin(); paraIt != paraList->end(); ++paraIt )
- {
- ValueListFormatData::Iterator formattingIt;
- for ( formattingIt = (*paraIt).formattingList.begin();
- formattingIt != (*paraIt).formattingList.end();
- formattingIt++ )
- {
- if ( ( ( (*formattingIt).id == 6 ) || ( (*formattingIt).id == 2 ) )
- && (*formattingIt).frameAnchor.key == key )
- {
- kdDebug(30508) << "Found anchor for inlined picture: " << (*formattingIt).frameAnchor.key.toString() << endl;
- (*formattingIt).frameAnchor.picture.koStoreName = name;
- found = true;
- }
- }
- }
- // Process non-inline pictures
- TQValueList<FrameAnchor>::Iterator it;
- for ( it = leader->m_nonInlinedPictureAnchors.begin(); it != leader->m_nonInlinedPictureAnchors.end(); ++it )
- {
- if ( (*it).key == key )
- {
- kdDebug(30508) << "Found pseudo-anchor for non-inlined picture: " << (*it).key.toString() << endl;
- (*it).picture.koStoreName = name;
- found = true;
- }
- }
-
- if ( !found )
- {
- kdWarning (30508) << "Could not find any anchor for picture " << key.toString() << endl;
- }
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessPixmapsTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "KEY", ProcessPixmapsKeyTag, tagData );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-
-static void FreeCellParaLists ( TQValueList<ParaData> &paraList )
-{
- TQValueList<ParaData>::Iterator paraIt;
-
- for ( paraIt = paraList.begin (); paraIt != paraList.end (); ++paraIt )
- {
- ValueListFormatData::Iterator formattingIt;
-
- for ( formattingIt = (*paraIt).formattingList.begin ();
- formattingIt != (*paraIt).formattingList.end ();
- formattingIt++ )
- {
- if ( (*formattingIt).id == 6 && (*formattingIt).frameAnchor.type == 6 )
- {
- TQValueList<TableCell>::Iterator cellIt;
-
- for ( cellIt = (*formattingIt).frameAnchor.table.cellList.begin ();
- cellIt != (*formattingIt).frameAnchor.table.cellList.end ();
- cellIt++ )
- {
- FreeCellParaLists ( *(*cellIt).paraList ); // recursion is great
- delete (*cellIt).paraList;
- }
- }
- }
- }
-}
-
-// like ProcessFramesetTag, but only handle footnotes
-static void ProcessFootnoteFramesetTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- TQString frameName;
- int frameType = -1, frameInfo = -1;
- bool visible = false;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "name", frameName )
- << AttrProcessing ( "frameType", frameType )
- << AttrProcessing ( "frameInfo", frameInfo )
- << AttrProcessing ( "removable" )
- << AttrProcessing ( "visible", visible )
- << AttrProcessing ( "grpMgr" )
- << AttrProcessing ( "row" )
- << AttrProcessing ( "col" )
- << AttrProcessing ( "rows" )
- << AttrProcessing ( "cols" )
- << AttrProcessing ( "protectSize" )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- // for footnote frame, frameType is 1 and frameInfo is 7
- if( ( frameType == 1 ) && ( frameInfo == 7 ) )
- {
- FootnoteData footnote;
- footnote.frameName = frameName;
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing ( "FRAME" ));
- tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footnote.para ));
- ProcessSubtags (myNode, tagProcessingList, leader);
- leader->footnoteList.append( footnote );
- }
-}
-
-// like ProcessFramesetsTag, but only handle footnotes
-static void ProcessFootnoteFramesetsTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "FRAMESET", ProcessFootnoteFramesetTag, tagData );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-static void ProcessBookmarkItemTag ( TQDomNode myNode, void* tag, KWEFKWordLeader *leader )
-{
- TQValueList<Bookmark> * bookmarkList = static_cast< TQValueList<Bookmark> * > ( tag );
-
- Bookmark bookmark;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "name", bookmark.m_name )
- << AttrProcessing ( "cursorIndexStart", bookmark.m_cursorIndexStart )
- << AttrProcessing ( "cursorIndexEnd", bookmark.m_cursorIndexEnd )
- << AttrProcessing ( "frameset", bookmark.m_frameset )
- << AttrProcessing ( "startparag", bookmark.m_startparag )
- << AttrProcessing ( "endparag", bookmark.m_endparag )
- ;
-
- ProcessAttributes (myNode, attrProcessingList);
-
- AllowNoSubtags( myNode, leader );
-
- // ### TODO: some verifications
-
- kdDebug(30508) << "Bookmark: " << bookmark.m_name << " in frameset " << bookmark.m_frameset << endl;
-
- bookmarkList->append( bookmark );
-}
-
-static void ProcessBookmarksTag ( TQDomNode myNode, void* tag, KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "BOOKMARKITEM", ProcessBookmarkItemTag, tag );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-void ProcessDocTag ( TQDomNode myNode,
- void* /*tagData*/, KWEFKWordLeader* leader )
-{
- //kdDebug (30508) << "Entering ProcessDocTag" << endl;
-
- TQString editor, author;
-
- TQValueList<AttrProcessing> attrProcessingList;
-
- attrProcessingList
- << AttrProcessing ( "xmlns" )
- << AttrProcessing ( "editor", editor )
- << AttrProcessing ( "mime" )
- << AttrProcessing ( "syntaxVersion", leader->m_syntaxVersion )
- << AttrProcessing ( "author", author )
- << AttrProcessing ( "email" )
- ;
-
- ProcessAttributes( myNode, attrProcessingList );
-
- kdDebug(30508) << "Document written by " << editor << endl;
- kdDebug(30508) << "Document of syntax version " << leader->m_syntaxVersion << endl;
-
- if ( leader->m_syntaxVersion == 1 )
- {
- leader->m_oldSyntax = true; // Syntax 1 is old syntax
- }
- else if ( leader->m_syntaxVersion == -1 )
- {
- // We do not know the version, but it still might be an old syntax.
- // However such old documents have still an author attribute, so check its value
- if ( author == "Reginald Stadlbauer and Torben Weis" )
- {
- kdDebug(30508) << "No syntax version but author attribute matches => assuming old syntax" << endl;
- leader->m_oldSyntax = true;
- }
- else
- {
- kdWarning(30508) << "No syntax version found, author attribute does not match => assuming new syntax" << endl;
- }
- }
-
- leader->doOpenHead();
-
- // At first, process <SPELLCHECKIGNORELIST>, even if mostly it will not be needed
- TQDomNode nodeIgnoreList=myNode.namedItem("SPELLCHECKIGNORELIST");
- if ( nodeIgnoreList.isNull () )
- kdDebug (30508) << "No <SPELLCHECKIGNORELIST>" << endl; // Most files will not have it!
- else
- ProcessSpellCheckIgnoreListTag (nodeIgnoreList, NULL, leader);
-
- // Process <PAPER> now, even if mostly the output will need to be delayed.
- TQDomNode nodePaper=myNode.namedItem("PAPER");
- if ( nodePaper.isNull () )
- kdWarning (30508) << "No <PAPER>" << endl;
- else
- ProcessPaperTag (nodePaper, NULL, leader);
-
- // Process <VARIABLESETTINGS>
- TQDomNode nodeVariableSettings=myNode.namedItem("VARIABLESETTINGS");
- if ( nodeVariableSettings.isNull () )
- kdWarning (30508) << "No <VARIABLESETTINGS>" << endl;
- else
- ProcessVariableSettingsTag (nodeVariableSettings, NULL, leader);
-
- // Then we process the styles
- TQDomNode nodeStyles=myNode.namedItem("STYLES");
- if ( nodeStyles.isNull () )
- kdWarning (30508) << "No <STYLES>" << endl;
- else
- ProcessStylesPluralTag (nodeStyles, NULL, leader);
-
- // Process framesets, but only to find and extract footnotes (also endnotes)
- TQValueList<FootnoteData> footnotes;
- TQDomNode nodeFramesets=myNode.namedItem("FRAMESETS");
- if ( !nodeFramesets.isNull() )
- ProcessFootnoteFramesetsTag(nodeFramesets, &footnotes, leader );
-
- // Process all framesets and pictures
- TQValueList<TagProcessing> tagProcessingList;
- TQValueList<ParaData> paraList;
-
- tagProcessingList
- << TagProcessing ( "PAPER" ) // Already done
- << TagProcessing ( "ATTRIBUTES" )
- << TagProcessing ( "FRAMESETS", ProcessFramesetsTag, &paraList )
- << TagProcessing ( "STYLES" ) // Already done
- << TagProcessing ( "PICTURES", ProcessPixmapsTag, &paraList )
- << TagProcessing ( "PIXMAPS", ProcessPixmapsTag, &paraList )
- << TagProcessing ( "CLIPARTS", ProcessPixmapsTag, &paraList )
- << TagProcessing ( "EMBEDDED" )
- << TagProcessing ( "BOOKMARKS", ProcessBookmarksTag, &leader->m_bookmarkList )
- ;
-
- // TODO: why are the followings used by KWord 1.2 but are not in its DTD?
- tagProcessingList << TagProcessing ( "SERIALL" );
- tagProcessingList << TagProcessing ( "FOOTNOTEMGR" );
-
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- leader->doCloseHead();
- leader->doDeclareNonInlinedFramesets( leader->m_nonInlinedPictureAnchors, leader->m_nonInlinedTableAnchors );
- leader->doOpenBody();
-
- leader->doFullDocument (paraList);
-
- kdDebug(30508) << "Unachored Framesets : START" << endl;
- TQStringList::ConstIterator it;
- for ( it = leader->m_unanchoredFramesets.begin(); it != leader->m_unanchoredFramesets.end(); ++it )
- {
- kdDebug(30508) << (*it) << endl;
- }
- kdDebug(30508) << "Unachored Framesets : END" << endl;
-
- FreeCellParaLists (paraList);
-
- leader->doCloseBody();
-
- //kdDebug (30508) << "Exiting ProcessDocTag" << endl;
-}
-
-
-void KWEFKWordLeader::setWorker ( KWEFBaseWorker *newWorker )
-{
- m_worker = newWorker;
-
- if (newWorker)
- newWorker->registerKWordLeader(this);
-}
-
-
-KWEFBaseWorker *KWEFKWordLeader::getWorker(void) const
-{
- return m_worker;
-}
-
-
-// Short simple definition for methods with void parameter
-#define DO_VOID_DEFINITION(string) \
- bool KWEFKWordLeader::string() \
- {\
- if (m_worker) \
- return m_worker->string(); \
- return false; \
- }
-
-
-bool KWEFKWordLeader::doOpenFile ( const TQString &filenameOut, const TQString &to )
-{
- if ( m_worker )
- return m_worker->doOpenFile (filenameOut, to);
-
- // As it would be the first method to be called, warn if worker is NULL
- kdError (30508) << "No Worker! (in KWEFKWordLeader::doOpenFile)" << endl;
-
- return false;
-}
-
-
-DO_VOID_DEFINITION (doCloseFile)
-DO_VOID_DEFINITION (doAbortFile)
-DO_VOID_DEFINITION (doOpenDocument)
-DO_VOID_DEFINITION (doCloseDocument)
-DO_VOID_DEFINITION (doOpenStyles)
-DO_VOID_DEFINITION (doCloseStyles)
-DO_VOID_DEFINITION (doOpenHead)
-DO_VOID_DEFINITION (doCloseHead)
-DO_VOID_DEFINITION (doOpenBody)
-DO_VOID_DEFINITION (doCloseBody)
-DO_VOID_DEFINITION (doOpenSpellCheckIgnoreList)
-DO_VOID_DEFINITION (doCloseSpellCheckIgnoreList)
-
-bool KWEFKWordLeader::doFullDocumentInfo (const KWEFDocumentInfo &docInfo)
-{
- if ( m_worker )
- return m_worker->doFullDocumentInfo (docInfo);
-
- return false;
-}
-
-
-bool KWEFKWordLeader::doVariableSettings (const VariableSettingsData &varSettings)
-{
- if ( m_worker )
- return m_worker->doVariableSettings (varSettings);
-
- return false;
-}
-
-
-bool KWEFKWordLeader::doFullDocument (const TQValueList<ParaData> &paraList)
-{
- if ( m_worker )
- return m_worker->doFullDocument (paraList);
-
- return false;
-}
-
-bool KWEFKWordLeader::doPageInfo ( const int headerType, const int footerType )
-{
- if ( m_worker )
- return m_worker->doPageInfo ( headerType, footerType );
-
- return false;
-}
-
-bool KWEFKWordLeader::doFullPaperFormat ( const int format, const double width, const double height, const int orientation )
-{
- if ( m_worker )
- return m_worker->doFullPaperFormat (format, width, height, orientation);
-
- return false;
-}
-
-bool KWEFKWordLeader::doFullPaperBorders (const double top, const double left, const double bottom, const double right)
-{
- if ( m_worker )
- return m_worker->doFullPaperBorders (top, left, bottom, right);
-
- return false;
-}
-
-bool KWEFKWordLeader::doFullPaperFormatOther ( const int columns, const double columnspacing, const int numPages )
-{
- if ( m_worker )
- return m_worker->doFullPaperFormatOther ( columns, columnspacing, numPages );
-
- return false;
-}
-
-bool KWEFKWordLeader::doFullDefineStyle ( LayoutData &layout )
-{
- if ( m_worker )
- return m_worker->doFullDefineStyle (layout);
-
- return false;
-}
-
-bool KWEFKWordLeader::doFullSpellCheckIgnoreWord (const TQString& ignoreword)
-{
- if ( m_worker )
- return m_worker->doFullSpellCheckIgnoreWord (ignoreword);
-
- return false;
-}
-
-bool KWEFKWordLeader::doHeader ( const HeaderData& header )
-{
- if ( m_worker )
- return m_worker->doHeader (header);
-
- return false;
-}
-
-bool KWEFKWordLeader::doFooter ( const FooterData& footer )
-{
- if ( m_worker )
- return m_worker->doFooter (footer);
-
- return false;
-}
-
-bool KWEFKWordLeader::doDeclareNonInlinedFramesets( TQValueList<FrameAnchor>& pictureAnchors, TQValueList<FrameAnchor>& tableAnchors )
-{
- if ( m_worker )
- return m_worker->doDeclareNonInlinedFramesets( pictureAnchors, tableAnchors );
-
- return false;
-}
-
-static bool ParseFile ( TQIODevice* subFile, TQDomDocument& doc)
-{
- TQString errorMsg;
- int errorLine;
- int errorColumn;
-
- if ( !doc.setContent (subFile, &errorMsg, &errorLine, &errorColumn) )
- {
- kdError (30508) << "Parsing Error! Aborting! (in ParseFile)" << endl
- << " Line: " << errorLine << " Column: " << errorColumn << endl
- << " Message: " << errorMsg << endl;
- // ### TODO: the error is in which sub-file?
- KMessageBox::error( 0L, i18n("An error has occurred while parsing the KWord file.\nAt line: %1, column %2\nError message: %3")
- .arg( errorLine ).arg( errorColumn ).arg(i18n( "TQXml", errorMsg.utf8() ) ),
- i18n("KWord Export Filter Library"), 0 );
- return false;
- }
- return true;
-}
-
-static bool ProcessStoreFile ( TQIODevice* subFile,
- void (*processor) (TQDomNode, void *, KWEFKWordLeader *),
- KWEFKWordLeader* leader)
-{
- if (!subFile)
- {
- kdWarning(30508) << "Could not get a device for the document!" << endl;
- }
- else if ( subFile->open ( IO_ReadOnly ) )
- {
- kdDebug (30508) << "Processing Document..." << endl;
- TQDomDocument doc;
- if (!ParseFile(subFile, doc))
- {
- subFile->close();
- return false;
- }
- // We must close the subFile before processing,
- // as the processing could open other sub files.
- // However, it would crash if two sub files are opened together
- subFile->close();
-
- TQDomNode docNode = doc.documentElement();
- processor (docNode, NULL, leader);
- return true;
- }
- else
- {
- // Note: we do not worry too much if we cannot open the document info!
- kdWarning (30508) << "Unable to open document!" << endl;
- }
- return false;
-}
-
-TQIODevice* KWEFKWordLeader::getSubFileDevice(const TQString& fileName)
-{
- KoStoreDevice* subFile;
-
- subFile=m_chain->storageFile(fileName,KoStore::Read);
-
- if (!subFile)
- {
- kdError(30508) << "Could not get a device for sub-file: " << fileName << endl;
- return NULL;
- }
- return subFile;
-}
-
-
-bool KWEFKWordLeader::loadSubFile(const TQString& fileName, TQByteArray& array)
-{
- KoStoreDevice* subFile;
-
- subFile=m_chain->storageFile(fileName,KoStore::Read);
-
- if (!subFile)
- {
- kdError(30508) << "Could not get a device for sub-file: " << fileName << endl;
- return false;
- }
- else if ( subFile->open ( IO_ReadOnly ) )
- {
- array = subFile->readAll();
- subFile->close ();
- }
- else
- {
- kdError(30508) << "Unable to open " << fileName << " sub-file" << endl;
- return false;
- }
-
- return true;
-}
-
-KoFilter::ConversionStatus KWEFKWordLeader::convert( KoFilterChain* chain,
- const TQCString& from, const TQCString& to)
-{
- if ( from != "application/x-kword" )
- {
- return KoFilter::NotImplemented;
- }
-
- if (!chain)
- {
- kdError(30508) << "'Chain' is NULL! Internal error of the filter system?" << endl;
- return KoFilter::StupidError;
- }
-
- m_chain=chain;
-
- if ( !doOpenFile (chain->outputFile(),to) )
- {
- kdError (30508) << "Worker could not open export file! Aborting!" << endl;
- return KoFilter::StupidError;
- }
-
- if ( !doOpenDocument () )
- {
- kdError (30508) << "Worker could not open document! Aborting!" << endl;
- doAbortFile ();
- return KoFilter::StupidError;
- }
-
- KoStoreDevice* subFile;
-
- subFile=chain->storageFile("documentinfo.xml",KoStore::Read);
- kdDebug (30508) << "Processing documentinfo.xml..." << endl;
- // Do not care if we cannot open the document info.
- ProcessStoreFile (subFile, ProcessDocumentInfoTag, this);
-
- subFile=chain->storageFile("root",KoStore::Read);
- kdDebug (30508) << "Processing root..." << endl;
- if (!ProcessStoreFile (subFile, ProcessDocTag, this))
- {
- kdWarning(30508) << "Opening root has failed. Trying raw XML file!" << endl;
-
- const TQString filename( chain->inputFile() );
- if (filename.isEmpty() )
- {
- kdError(30508) << "Could not open document as raw XML! Aborting!" << endl;
- doAbortFile();
- return KoFilter::StupidError;
- }
- else
- {
- TQFile file( filename );
- if ( ! ProcessStoreFile( TQT_TQIODEVICE(&file), ProcessDocTag, this ) )
- {
- kdError(30508) << "Could not process document! Aborting!" << endl;
- doAbortFile();
- return KoFilter::StupidError;
- }
- }
- }
-
- doCloseDocument ();
-
- doCloseFile ();
-
- return KoFilter::OK;
-}
diff --git a/filters/kword/libexport/KWEFKWordLeader.cpp b/filters/kword/libexport/KWEFKWordLeader.cpp
new file mode 100644
index 000000000..05e4024a5
--- /dev/null
+++ b/filters/kword/libexport/KWEFKWordLeader.cpp
@@ -0,0 +1,1430 @@
+/*
+ This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
+ Copyright (c) 2001 IABG mbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@IABG.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ Part of this code comes from the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Wolf-Michael.Bolle@GMX.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <tqfile.h>
+#include <tqdom.h>
+
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <tdemessagebox.h>
+
+#include <KoGlobal.h>
+#include <KoStore.h>
+
+#include "KWEFStructures.h"
+#include "TagProcessing.h"
+#include "ProcessDocument.h"
+#include "KWEFBaseWorker.h"
+#include "KWEFKWordLeader.h"
+
+KWEFKWordLeader::KWEFKWordLeader(void)
+ : m_syntaxVersion(-1), m_oldSyntax(false), m_worker(NULL), m_chain(NULL), m_hType(0), m_fType(0)
+{
+}
+
+KWEFKWordLeader::KWEFKWordLeader(KWEFBaseWorker* newWorker)
+ : m_syntaxVersion(-1), m_oldSyntax(false), m_worker(newWorker), m_chain(NULL)
+{
+ if (newWorker) newWorker->registerKWordLeader(this);
+}
+
+KWEFKWordLeader::~KWEFKWordLeader(void)
+{
+}
+
+static FrameAnchor *findAnchor ( const KoPictureKey& key,
+ TQValueList<ParaData>& paraList )
+{
+ kdDebug(30508) << "findAnchor " << key.toString() << endl;
+ TQValueList<ParaData>::Iterator paraIt;
+
+ for ( paraIt = paraList.begin (); paraIt != paraList.end (); ++paraIt )
+ {
+ ValueListFormatData::Iterator formattingIt;
+
+ for ( formattingIt = (*paraIt).formattingList.begin ();
+ formattingIt != (*paraIt).formattingList.end ();
+ formattingIt++ )
+ {
+ if ( (*formattingIt).id == 6 &&
+ (*formattingIt).frameAnchor.key == key )
+ {
+ kdDebug(30508) << "Found anchor " << (*formattingIt).frameAnchor.key.toString() << endl;
+ return &(*formattingIt).frameAnchor;
+ }
+ }
+ }
+
+ kdWarning(30508) << "findAnchor returning NULL!" << endl;
+ return NULL;
+}
+
+static void ProcessHardBrkTag ( TQDomNode myNode, void* tagData, KWEFKWordLeader* )
+{
+ // <HARDBRK>
+ bool* flag = (bool*) tagData;
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "frame", *flag );
+ ProcessAttributes (myNode, attrProcessingList);
+ if (*flag)
+ kdDebug(30508) << "<HARDBRK frame=\"1\"> found" << endl;
+}
+
+static void InsertBookmarkFormatData (const int pos, const TQString& name, const bool start,
+ ValueListFormatData &paraFormatDataList)
+{
+ ValueListFormatData::Iterator paraFormatDataIt;
+
+ FormatData book( start ? 1001 : 1002 , pos, 0 );
+ book.variable.m_text = name;
+
+ for (paraFormatDataIt = paraFormatDataList.begin ();
+ paraFormatDataIt != paraFormatDataList.end ();
+ paraFormatDataIt++)
+ {
+ if ( pos <= (*paraFormatDataIt).pos )
+ {
+ paraFormatDataList.insert ( paraFormatDataIt, book );
+ return;
+
+ }
+ if ( ( pos > (*paraFormatDataIt).pos ) && ( pos < (*paraFormatDataIt).pos + (*paraFormatDataIt).len ) )
+ {
+ // Somewhere in the middle, we have to split the FormatData
+ FormatData split ( *paraFormatDataIt );
+ //const int oldlen = (*paraFormatDataIt).len;
+ split.len = pos - (*paraFormatDataIt).pos;
+ (*paraFormatDataIt).len -= split.len;
+ (*paraFormatDataIt).pos = pos;
+ paraFormatDataList.insert ( paraFormatDataIt, split );
+ paraFormatDataList.insert ( paraFormatDataIt, book );
+ return;
+ }
+ }
+
+ // Still here? So we need to put the bookmark here:
+ paraFormatDataList.append ( book );
+}
+
+
+void KWEFKWordLeader::createBookmarkFormatData( ParaData& paraData )
+{
+ const int paraCount = m_paraCountMap[ m_currentFramesetName ];
+
+ TQValueList<Bookmark>::ConstIterator it;
+ for (it = m_bookmarkList.begin(); it != m_bookmarkList.end(); ++it )
+ {
+ if ( (*(it)).m_frameset != m_currentFramesetName )
+ {
+ continue;
+ }
+ // As we always insert before, make first endings, then startings (problem is zero-length bookmark)
+ if ( (*(it)).m_endparag == paraCount )
+ {
+ kdDebug(30508) << "Paragraph: " << paraCount << " end: " << (*(it)).m_name << endl;
+ InsertBookmarkFormatData( (*(it)).m_cursorIndexEnd, (*(it)).m_name, false, paraData.formattingList);
+
+ }
+ if ( (*(it)).m_startparag == paraCount )
+ {
+ kdDebug(30508) << "Paragraph: " << paraCount << " begin: " << (*(it)).m_name << endl;
+ InsertBookmarkFormatData( (*(it)).m_cursorIndexStart, (*(it)).m_name, true, paraData.formattingList);
+ }
+ }
+}
+
+static void ProcessParagraphTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+#if 0
+ kdDebug (30508) << "ProcessParagraphTag () - Begin" << endl;
+#endif
+
+ TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
+
+ AllowNoAttributes (myNode);
+
+ // We need to adjust the paragraph number (0 if first)
+ TQMap<TQString,int>::Iterator it = leader->m_paraCountMap.find( leader->m_currentFramesetName );
+ if ( it == leader->m_paraCountMap.end() )
+ leader->m_paraCountMap.insert( leader->m_currentFramesetName, 0 );
+ else
+ ++(*it);
+
+ ParaData paraData;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "TEXT", ProcessTextTag, &paraData.text )
+ << TagProcessing ( "FORMATS", ProcessFormatsTag, &paraData.formattingList )
+ << TagProcessing ( "LAYOUT", ProcessLayoutTag, &paraData.layout );
+
+ if ( leader->m_oldSyntax )
+ {
+ tagProcessingList.append( TagProcessing( "HARDBRK", ProcessHardBrkTag, &paraData.layout.pageBreakBefore ) );
+ }
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ leader->createBookmarkFormatData( paraData );
+ CreateMissingFormatData (paraData.text, paraData.formattingList);
+
+ // TODO/FIXME: why !paraData.text.isEmpty()
+ if ( paraData.formattingList.isEmpty () && !paraData.text.isEmpty () )
+ {
+ if ( paraData.layout.formatData.id == 1 )
+ {
+ paraData.formattingList << paraData.layout.formatData;
+ }
+ else
+ {
+ kdWarning (30508) << "No useful FORMAT tag found for text in PARAGRAPH" << endl;
+ }
+ }
+
+
+ *paraList << paraData;
+
+#if 0
+ kdDebug (30508) << "ProcessParagraphTag () - End " << paraText << endl;
+#endif
+}
+
+
+static void ProcessFrameTag ( TQDomNode myNode, void *tagData,
+ KWEFKWordLeader *leader )
+{
+ FrameAnchor* frameAnchor= (FrameAnchor*) tagData;
+
+ int lRed=0, lBlue=0, lGreen=0;
+ int rRed=0, rBlue=0, rGreen=0;
+ int tRed=0, tBlue=0, tGreen=0;
+ int bRed=0, bBlue=0, bGreen=0;
+ int bkRed=255, bkBlue=255, bkGreen=255;
+
+ frameAnchor->frame.lWidth=0.0;
+ frameAnchor->frame.rWidth=0.0;
+ frameAnchor->frame.tWidth=0.0;
+ frameAnchor->frame.bWidth=0.0;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "right", frameAnchor->frame.right )
+ << AttrProcessing ( "left", frameAnchor->frame.left )
+ << AttrProcessing ( "top", frameAnchor->frame.top )
+ << AttrProcessing ( "bottom", frameAnchor->frame.bottom )
+
+ << AttrProcessing ( "min-height", frameAnchor->frame.minHeight )
+
+ << AttrProcessing ( "runaround", frameAnchor->frame.runaround )
+ << AttrProcessing ( "runaroundSide", frameAnchor->frame.runaroundSide )
+ << AttrProcessing ( "runaroundGap", frameAnchor->frame.runaroundGap )
+
+ << AttrProcessing ( "autoCreateNewFrame", frameAnchor->frame.autoCreateNewFrame )
+ << AttrProcessing ( "newFrameBehavior", frameAnchor->frame.newFrameBehavior )
+ << AttrProcessing ( "newFrameBehaviour", frameAnchor->frame.newFrameBehavior ) // Depreciated name
+
+ << AttrProcessing ( "copy", frameAnchor->frame.copy )
+ << AttrProcessing ( "sheetSide", frameAnchor->frame.sheetSide )
+
+ << AttrProcessing ( "lWidth", frameAnchor->frame.lWidth )
+ << AttrProcessing ( "rWidth", frameAnchor->frame.rWidth )
+ << AttrProcessing ( "tWidth", frameAnchor->frame.tWidth )
+ << AttrProcessing ( "bWidth", frameAnchor->frame.bWidth )
+
+ << AttrProcessing ( "lRed", lRed )
+ << AttrProcessing ( "lGreen", lGreen )
+ << AttrProcessing ( "lBlue", lBlue )
+
+ << AttrProcessing ( "rRed", rRed )
+ << AttrProcessing ( "rGreen", rGreen )
+ << AttrProcessing ( "rBlue", rBlue )
+
+ << AttrProcessing ( "tRed", tRed )
+ << AttrProcessing ( "tGreen", tGreen )
+ << AttrProcessing ( "tBlue", tBlue )
+
+ << AttrProcessing ( "bRed", bRed )
+ << AttrProcessing ( "bGreen", bGreen )
+ << AttrProcessing ( "bBlue", bBlue )
+
+ << AttrProcessing ( "lStyle", frameAnchor->frame.lStyle )
+ << AttrProcessing ( "rStyle", frameAnchor->frame.rStyle )
+ << AttrProcessing ( "tStyle", frameAnchor->frame.tStyle )
+ << AttrProcessing ( "bStyle", frameAnchor->frame.bStyle )
+
+ << AttrProcessing ( "bkRed", bkRed )
+ << AttrProcessing ( "bkGreen", bkGreen )
+ << AttrProcessing ( "bkBlue", bkBlue )
+
+ << AttrProcessing ( "bkStyle", frameAnchor->frame.bkStyle )
+
+ << AttrProcessing ( "bleftpt", frameAnchor->frame.bleftpt )
+ << AttrProcessing ( "brightpt", frameAnchor->frame.brightpt )
+ << AttrProcessing ( "btoppt", frameAnchor->frame.btoppt )
+ << AttrProcessing ( "bbottompt", frameAnchor->frame.bbottompt )
+ ;
+
+ if ( leader->m_oldSyntax )
+ {
+ attrProcessingList
+ << AttrProcessing ( "bleftmm" )
+ << AttrProcessing ( "bleftinch" )
+ << AttrProcessing ( "brightmm" )
+ << AttrProcessing ( "brightinch" )
+ << AttrProcessing ( "btopmm" )
+ << AttrProcessing ( "btopinch" )
+ << AttrProcessing ( "bbottommm" )
+ << AttrProcessing ( "bbottominch" )
+ ;
+ }
+
+ ProcessAttributes (myNode, attrProcessingList);
+
+ frameAnchor->frame.lColor.setRgb( lRed, lGreen, lBlue );
+ frameAnchor->frame.rColor.setRgb( rRed, rGreen, rBlue );
+ frameAnchor->frame.tColor.setRgb( tRed, tGreen, tBlue );
+ frameAnchor->frame.bColor.setRgb( bRed, bGreen, bBlue );
+ frameAnchor->frame.bkColor.setRgb( bkRed, bkGreen, bkBlue );
+
+ AllowNoSubtags (myNode, leader);
+}
+
+static void ProcessPictureAnchor( TQDomNode myNode, KWEFKWordLeader *leader, FrameAnchor* frameAnchor, const int frameType )
+{
+ frameAnchor->type = frameType;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList
+ << TagProcessing ( "FRAME", ProcessFrameTag, frameAnchor )
+ << TagProcessing ( "PICTURE", ProcessImageTag, &frameAnchor->picture.key )
+ << TagProcessing ( "IMAGE", ProcessImageTag, &frameAnchor->picture.key )
+ << TagProcessing ( "CLIPART", ProcessImageTag, &frameAnchor->picture.key )
+ ;
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ kdDebug (30508) << "FRAMESET PICTURE KEY " << frameAnchor->picture.key.toString() << endl;
+
+ frameAnchor->key = frameAnchor->picture.key;
+}
+
+static void ProcessTableAnchor( TQDomNode myNode, KWEFKWordLeader *leader, FrameAnchor* frameAnchor,
+ const int col, const int row, const int cols, const int rows )
+{
+ frameAnchor->type = 6; // Table
+
+ TQValueList<ParaData> cellParaList;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "FRAME", ProcessFrameTag, frameAnchor )
+ << TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &cellParaList );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ frameAnchor->table.addCell (col, row, cols, rows, cellParaList, frameAnchor->frame);
+}
+
+static void ProcessFramesetTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+#if 0
+ kdDebug (30508) << "ProcessFramesetTag () - Begin" << endl;
+#endif
+
+ TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
+
+ int frameType = -1;
+ int frameInfo = -1;
+ int col = -1;
+ int row = -1;
+ int cols = -1;
+ int rows = -1;
+ TQString grpMgr;
+
+ const TQString oldName ( leader->m_currentFramesetName );
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "name", leader->m_currentFramesetName )
+ << AttrProcessing ( "frameType", frameType )
+ << AttrProcessing ( "frameInfo", frameInfo )
+ << AttrProcessing ( "removable" )
+ << AttrProcessing ( "visible" )
+ << AttrProcessing ( "grpMgr", grpMgr )
+ << AttrProcessing ( "row", row )
+ << AttrProcessing ( "col", col )
+ << AttrProcessing ( "rows", rows )
+ << AttrProcessing ( "cols", cols )
+ << AttrProcessing ( "protectSize" )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ switch ( frameType )
+ {
+ case 1:
+ if ( grpMgr.isEmpty () )
+ {
+ // As we do not support anything else than normal text, process only normal text.
+ // TODO: Treat the other types of frames (frameType)
+ if (frameInfo==0)
+ {
+ // Normal Text
+ kdDebug(30508) << "Processing Frameset: " << leader->m_currentFramesetName << endl;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, paraList ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ }
+ else if (frameInfo==1)
+ {
+ // header for first page
+ HeaderData header;
+ header.page = HeaderData::PAGE_FIRST;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
+
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doHeader( header );
+ }
+ else if (frameInfo==2)
+ {
+ // header for even page
+ HeaderData header;
+ header.page = HeaderData::PAGE_EVEN;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doHeader( header );
+ }
+ else if (frameInfo==3)
+ {
+ // header for odd page (or all page, if hType=0)
+ HeaderData header;
+ header.page = (leader->headerType() != 0 ) ? HeaderData::PAGE_ODD : HeaderData::PAGE_ALL;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &header.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doHeader( header );
+ }
+ else if (frameInfo==4)
+ {
+ // footer for first page
+ FooterData footer;
+ footer.page = FooterData::PAGE_FIRST;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doFooter( footer );
+ }
+ else if (frameInfo==5)
+ {
+ // footer for even page
+ FooterData footer;
+ footer.page = FooterData::PAGE_EVEN;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doFooter( footer );
+ }
+ else if (frameInfo==6)
+ {
+ // footer for odd page (or all page, if fType=0)
+ FooterData footer;
+ footer.page = (leader->footerType() != 0) ? FooterData::PAGE_ODD : FooterData::PAGE_ALL;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footer.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->doFooter( footer );
+ }
+ }
+ else
+ {
+ if ( col != -1 && row != -1 )
+ {
+ if ( cols > 0 && rows > 0 )
+ {
+#if 0
+ kdDebug (30508) << "DEBUG - FRAMESET: table " << name << " col, row = "
+ << col << ", " << row << ", Mgr = "<< grpMgr << endl;
+#endif
+ FrameAnchor *frameAnchor = findAnchor (grpMgr, *paraList);
+ if ( frameAnchor )
+ {
+ ProcessTableAnchor( myNode, leader, frameAnchor, col, row, cols, rows );
+ }
+ else
+ {
+ bool found = false;
+ KoPictureKey key( grpMgr );
+ TQValueList<FrameAnchor>::Iterator it;
+ for ( it = leader->m_nonInlinedTableAnchors.begin(); it != leader->m_nonInlinedTableAnchors.end(); ++it )
+ {
+ if ( (*it).key == key )
+ {
+ kdDebug(30508) << "Found pseudo-anchor for table: " << (*it).key.toString() << endl;
+ found = true;
+ break;
+ }
+ }
+
+ if ( found )
+ {
+ ProcessTableAnchor( myNode, leader, &(*it), col, row, cols, rows );
+ }
+ else
+ {
+ kdWarning(30508) << "Table anchor not found: " << grpMgr << endl;
+ FrameAnchor anchor;
+ ProcessTableAnchor( myNode, leader, &anchor, col, row, cols, rows );
+ anchor.key = key; // Needed, so that the pseudo-anchor can be found again
+ leader->m_nonInlinedTableAnchors << anchor;
+ leader->m_unanchoredFramesets.append( grpMgr );
+ }
+ }
+ }
+ else
+ {
+ kdWarning (30508) << "Unexpected value for one of, or all FRAMESET attribute cols, rows: "
+ << cols << ", " << rows << "!" << endl;
+ AllowNoSubtags (myNode, leader);
+ }
+ }
+ else
+ {
+ kdWarning (30508) << "Unset value for one of, or all FRAMESET attributes col, row: "
+ << col << ", " << row << "!" << endl;
+ AllowNoSubtags (myNode, leader);
+ leader->m_unanchoredFramesets.append( leader->m_currentFramesetName );
+ }
+ }
+ break;
+
+ case 2: // PICTURE
+ case 5: // CLIPART: deprecated (up to KOffice 1.2 Beta 2)
+ {
+#if 0
+ kdDebug (30508) << "DEBUG: FRAMESET name of picture is " << name << endl;
+#endif
+
+ FrameAnchor *frameAnchor = findAnchor ( leader->m_currentFramesetName, *paraList );
+
+ if ( frameAnchor )
+ {
+ ProcessPictureAnchor( myNode, leader, frameAnchor, frameType );
+ }
+ else
+ {
+ // ### TODO: non-inlined picture?
+ // No anchor found, so the picture is not inlined
+ kdDebug (30508) << "ProcessFramesetTag: Couldn't find anchor " << leader->m_currentFramesetName << endl;
+ FrameAnchor anchor;
+ ProcessPictureAnchor( myNode, leader, &anchor, frameType );
+ leader->m_nonInlinedPictureAnchors << anchor;
+ leader->m_unanchoredFramesets.append( leader->m_currentFramesetName ); // DEBUG
+ }
+
+ break;
+ }
+
+ case 4: // KFormula
+ {
+ kdWarning(30508) << "KFormula frameset not supported yet!" << endl; // ### TODO
+ break;
+ }
+ default:
+ kdWarning (30508) << "Unexpected frametype " << frameType << " (in ProcessFramesetTag)" << endl;
+ }
+
+ leader->m_currentFramesetName = oldName;
+
+#if 0
+ kdDebug (30508) << "ProcessFramesetTag () - End" << endl;
+#endif
+}
+
+
+static void ProcessFramesetsTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "FRAMESET", ProcessFramesetTag, tagData );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+
+static void ProcessStyleTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
+{
+ LayoutData layout;
+
+ ProcessLayoutTag (myNode, &layout, leader);
+
+ leader->doFullDefineStyle (layout);
+}
+
+
+static void ProcessStylesPluralTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ leader->doOpenStyles ();
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "STYLE", ProcessStyleTag, leader );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ leader->doCloseStyles ();
+}
+
+
+static void ProcessPaperBordersTag (TQDomNode myNode, void*, KWEFKWordLeader* leader)
+{
+
+ double left = 0.0;
+ double right = 0.0;
+ double top = 0.0;
+ double bottom = 0.0;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ if ( leader->m_oldSyntax )
+ {
+ attrProcessingList
+ << AttrProcessing ( "ptLeft", left )
+ << AttrProcessing ( "ptRight", right )
+ << AttrProcessing ( "ptTop", top )
+ << AttrProcessing ( "ptBottom", bottom )
+ << AttrProcessing ( "mmLeft" )
+ << AttrProcessing ( "mmRight" )
+ << AttrProcessing ( "mmTop" )
+ << AttrProcessing ( "mmBottom" )
+ << AttrProcessing ( "inchLeft" )
+ << AttrProcessing ( "inchRight" )
+ << AttrProcessing ( "inchTop" )
+ << AttrProcessing ( "inchBottom" )
+ ;
+ }
+ else
+ {
+ attrProcessingList
+ << AttrProcessing ( "left", left )
+ << AttrProcessing ( "right", right )
+ << AttrProcessing ( "top", top )
+ << AttrProcessing ( "bottom", bottom )
+ ;
+ }
+ ProcessAttributes (myNode, attrProcessingList);
+
+ leader->doFullPaperBorders(top, left, bottom, right);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+static void ProcessPaperTag (TQDomNode myNode, void *, KWEFKWordLeader *leader)
+{
+
+ int format = -1;
+ int orientation = -1;
+ double width = -1.0;
+ double height = -1.0;
+ int hType = -1;
+ int fType = -1;
+ int columns = 1;
+ double columnspacing = 36.0; // Half-inch
+ int numPages = -1;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "format", format )
+ << AttrProcessing ( "width", width )
+ << AttrProcessing ( "height", height )
+ << AttrProcessing ( "orientation", orientation )
+ << AttrProcessing ( "columns", columns )
+ << AttrProcessing ( "columnspacing", columnspacing )
+ << AttrProcessing ( "pages", numPages )
+ << AttrProcessing ( "hType", hType )
+ << AttrProcessing ( "fType", fType )
+ << AttrProcessing ( "spHeadBody" )
+ << AttrProcessing ( "spFootBody" )
+ << AttrProcessing ( "spFootNoteBody" )
+ << AttrProcessing ( "slFootNotePosition" )
+ << AttrProcessing ( "slFootNoteLength" )
+ << AttrProcessing ( "slFootNoteWidth" )
+ << AttrProcessing ( "slFootNoteType" );
+
+ if ( leader->m_oldSyntax )
+ {
+ // ### TODO: in syntax 1 hType and fType have other values!
+ attrProcessingList
+ << AttrProcessing ( "ptWidth", width )
+ << AttrProcessing ( "ptHeight", height )
+ << AttrProcessing ( "ptColumnspc", columnspacing )
+ << AttrProcessing ( "mmWidth" )
+ << AttrProcessing ( "mmHeight" )
+ << AttrProcessing ( "mmColumnspc" )
+ << AttrProcessing ( "inchWidth" )
+ << AttrProcessing ( "inchHeight" )
+ << AttrProcessing ( "inchColumnspc" )
+ ;
+ }
+
+ ProcessAttributes (myNode, attrProcessingList);
+
+ leader->setHeaderType( hType );
+ leader->setFooterType( fType );
+
+ leader->doPageInfo ( hType, fType );
+ leader->doFullPaperFormat (format, width, height, orientation);
+ leader->doFullPaperFormatOther( columns, columnspacing, numPages );
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList
+ << TagProcessing ( "PAPERBORDERS", ProcessPaperBordersTag, NULL )
+ ;
+
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+static void ProcessVariableSettingsTag (TQDomNode myNode, void *, KWEFKWordLeader *leader)
+{
+ VariableSettingsData vs;
+ TQString print, creation, modification; // Dates (in ISO 8601 format)
+ int creationYear = -1;
+ int creationMonth = -1;
+ int creationDay = -1;
+ int modificationYear = -1;
+ int modificationMonth = -1;
+ int modificationDay = -1;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "startingPageNumber", vs.startingPageNumber )
+ << AttrProcessing ( "displaylink", vs.displaylink )
+ << AttrProcessing ( "underlinelink", vs.underlinelink )
+ << AttrProcessing ( "displaycomment", vs.displaycomment )
+ << AttrProcessing ( "displayfieldcode", vs.displayfieldcode )
+ ;
+
+
+ // The following 3 attributes are from syntax 3 but at least the RTF import filter generate them with syntax 2.
+ attrProcessingList
+ << AttrProcessing ( "lastPrintingDate", print )
+ << AttrProcessing ( "creationDate", creation )
+ << AttrProcessing ( "modificationDate", modification );
+ ;
+
+ // Some files have the creation and modification date not in one attribute but in an attribute for each the year, the month, the day
+ // ( e.g. syntax 2 file kofficetests/documents/export/kword/text/all.kwd )
+ attrProcessingList
+ << AttrProcessing( "modifyFileYear", modificationYear )
+ << AttrProcessing( "modifyFileMonth", modificationMonth )
+ << AttrProcessing( "modifyFileDay", modificationDay )
+ << AttrProcessing( "createFileYear", creationYear )
+ << AttrProcessing( "createFileMonth", creationMonth )
+ << AttrProcessing( "createFileDay", creationDay )
+ ;
+
+ ProcessAttributes (myNode, attrProcessingList);
+
+ if ( creation.isEmpty() )
+ {
+ if ( ( creationYear >= 1970 ) && TQDate::isValid( creationYear, creationMonth, creationDay ) )
+ {
+ vs.creationTime = TQDateTime( TQDate( creationYear, creationMonth, creationDay ) );
+ }
+ }
+ else
+ vs.creationTime=TQDateTime::fromString(creation, Qt::ISODate);
+ //kdDebug(30508) << "Creation time: " << vs.creationTime.toString( Qt::ISODate ) << endl;
+
+ if ( modification.isEmpty() )
+ {
+ if ( ( modificationYear >= 1970 ) && TQDate::isValid( modificationYear, modificationMonth, modificationDay ) )
+ {
+ vs.modificationTime = TQDateTime( TQDate( modificationYear, modificationMonth, modificationDay ) );
+ }
+ }
+ else
+ vs.modificationTime=TQDateTime::fromString(modification, Qt::ISODate);
+ //kdDebug(30508) << "Modification time: " << vs.modificationTime.toString( Qt::ISODate ) << endl;
+
+ if (!print.isEmpty())
+ vs.printTime=TQDateTime::fromString(print, Qt::ISODate);
+ //kdDebug(30508) << "Print time: " << vs.printTime.toString( Qt::ISODate ) << endl;
+
+ leader->doVariableSettings (vs);
+}
+
+static void ProcessSpellCheckIgnoreWordTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
+{
+ TQString ignoreword;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "word", ignoreword )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ leader->doFullSpellCheckIgnoreWord (ignoreword);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessSpellCheckIgnoreListTag (TQDomNode myNode, void *, KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ leader->doOpenSpellCheckIgnoreList ();
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "SPELLCHECKIGNOREWORD", ProcessSpellCheckIgnoreWordTag, leader );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ leader->doCloseSpellCheckIgnoreList ();
+}
+
+
+static void ProcessPixmapsKeyTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ TQValueList<ParaData> *paraList = (TQValueList<ParaData> *) tagData;
+
+ KoPictureKey key;
+
+ // Let KoPictureKey do most of the loading
+ key.loadAttributes(myNode.toElement());
+ const TQString name(myNode.toElement().attribute("name"));
+
+ kdDebug(30508) << "search anchors: " << key.toString() << endl;
+ bool found = false;
+
+ // NOTE: we must always search in both inlined and non-inlined pictures. A picture can be used in both ways and a few times in each!
+
+ // Process inlined pictures
+ TQValueList<ParaData>::Iterator paraIt;
+
+ for ( paraIt = paraList->begin(); paraIt != paraList->end(); ++paraIt )
+ {
+ ValueListFormatData::Iterator formattingIt;
+ for ( formattingIt = (*paraIt).formattingList.begin();
+ formattingIt != (*paraIt).formattingList.end();
+ formattingIt++ )
+ {
+ if ( ( ( (*formattingIt).id == 6 ) || ( (*formattingIt).id == 2 ) )
+ && (*formattingIt).frameAnchor.key == key )
+ {
+ kdDebug(30508) << "Found anchor for inlined picture: " << (*formattingIt).frameAnchor.key.toString() << endl;
+ (*formattingIt).frameAnchor.picture.koStoreName = name;
+ found = true;
+ }
+ }
+ }
+ // Process non-inline pictures
+ TQValueList<FrameAnchor>::Iterator it;
+ for ( it = leader->m_nonInlinedPictureAnchors.begin(); it != leader->m_nonInlinedPictureAnchors.end(); ++it )
+ {
+ if ( (*it).key == key )
+ {
+ kdDebug(30508) << "Found pseudo-anchor for non-inlined picture: " << (*it).key.toString() << endl;
+ (*it).picture.koStoreName = name;
+ found = true;
+ }
+ }
+
+ if ( !found )
+ {
+ kdWarning (30508) << "Could not find any anchor for picture " << key.toString() << endl;
+ }
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessPixmapsTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "KEY", ProcessPixmapsKeyTag, tagData );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+
+static void FreeCellParaLists ( TQValueList<ParaData> &paraList )
+{
+ TQValueList<ParaData>::Iterator paraIt;
+
+ for ( paraIt = paraList.begin (); paraIt != paraList.end (); ++paraIt )
+ {
+ ValueListFormatData::Iterator formattingIt;
+
+ for ( formattingIt = (*paraIt).formattingList.begin ();
+ formattingIt != (*paraIt).formattingList.end ();
+ formattingIt++ )
+ {
+ if ( (*formattingIt).id == 6 && (*formattingIt).frameAnchor.type == 6 )
+ {
+ TQValueList<TableCell>::Iterator cellIt;
+
+ for ( cellIt = (*formattingIt).frameAnchor.table.cellList.begin ();
+ cellIt != (*formattingIt).frameAnchor.table.cellList.end ();
+ cellIt++ )
+ {
+ FreeCellParaLists ( *(*cellIt).paraList ); // recursion is great
+ delete (*cellIt).paraList;
+ }
+ }
+ }
+ }
+}
+
+// like ProcessFramesetTag, but only handle footnotes
+static void ProcessFootnoteFramesetTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ TQString frameName;
+ int frameType = -1, frameInfo = -1;
+ bool visible = false;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "name", frameName )
+ << AttrProcessing ( "frameType", frameType )
+ << AttrProcessing ( "frameInfo", frameInfo )
+ << AttrProcessing ( "removable" )
+ << AttrProcessing ( "visible", visible )
+ << AttrProcessing ( "grpMgr" )
+ << AttrProcessing ( "row" )
+ << AttrProcessing ( "col" )
+ << AttrProcessing ( "rows" )
+ << AttrProcessing ( "cols" )
+ << AttrProcessing ( "protectSize" )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ // for footnote frame, frameType is 1 and frameInfo is 7
+ if( ( frameType == 1 ) && ( frameInfo == 7 ) )
+ {
+ FootnoteData footnote;
+ footnote.frameName = frameName;
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing ( "FRAME" ));
+ tagProcessingList.append(TagProcessing ( "PARAGRAPH", ProcessParagraphTag, &footnote.para ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+ leader->footnoteList.append( footnote );
+ }
+}
+
+// like ProcessFramesetsTag, but only handle footnotes
+static void ProcessFootnoteFramesetsTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "FRAMESET", ProcessFootnoteFramesetTag, tagData );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+static void ProcessBookmarkItemTag ( TQDomNode myNode, void* tag, KWEFKWordLeader *leader )
+{
+ TQValueList<Bookmark> * bookmarkList = static_cast< TQValueList<Bookmark> * > ( tag );
+
+ Bookmark bookmark;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "name", bookmark.m_name )
+ << AttrProcessing ( "cursorIndexStart", bookmark.m_cursorIndexStart )
+ << AttrProcessing ( "cursorIndexEnd", bookmark.m_cursorIndexEnd )
+ << AttrProcessing ( "frameset", bookmark.m_frameset )
+ << AttrProcessing ( "startparag", bookmark.m_startparag )
+ << AttrProcessing ( "endparag", bookmark.m_endparag )
+ ;
+
+ ProcessAttributes (myNode, attrProcessingList);
+
+ AllowNoSubtags( myNode, leader );
+
+ // ### TODO: some verifications
+
+ kdDebug(30508) << "Bookmark: " << bookmark.m_name << " in frameset " << bookmark.m_frameset << endl;
+
+ bookmarkList->append( bookmark );
+}
+
+static void ProcessBookmarksTag ( TQDomNode myNode, void* tag, KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "BOOKMARKITEM", ProcessBookmarkItemTag, tag );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+void ProcessDocTag ( TQDomNode myNode,
+ void* /*tagData*/, KWEFKWordLeader* leader )
+{
+ //kdDebug (30508) << "Entering ProcessDocTag" << endl;
+
+ TQString editor, author;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+
+ attrProcessingList
+ << AttrProcessing ( "xmlns" )
+ << AttrProcessing ( "editor", editor )
+ << AttrProcessing ( "mime" )
+ << AttrProcessing ( "syntaxVersion", leader->m_syntaxVersion )
+ << AttrProcessing ( "author", author )
+ << AttrProcessing ( "email" )
+ ;
+
+ ProcessAttributes( myNode, attrProcessingList );
+
+ kdDebug(30508) << "Document written by " << editor << endl;
+ kdDebug(30508) << "Document of syntax version " << leader->m_syntaxVersion << endl;
+
+ if ( leader->m_syntaxVersion == 1 )
+ {
+ leader->m_oldSyntax = true; // Syntax 1 is old syntax
+ }
+ else if ( leader->m_syntaxVersion == -1 )
+ {
+ // We do not know the version, but it still might be an old syntax.
+ // However such old documents have still an author attribute, so check its value
+ if ( author == "Reginald Stadlbauer and Torben Weis" )
+ {
+ kdDebug(30508) << "No syntax version but author attribute matches => assuming old syntax" << endl;
+ leader->m_oldSyntax = true;
+ }
+ else
+ {
+ kdWarning(30508) << "No syntax version found, author attribute does not match => assuming new syntax" << endl;
+ }
+ }
+
+ leader->doOpenHead();
+
+ // At first, process <SPELLCHECKIGNORELIST>, even if mostly it will not be needed
+ TQDomNode nodeIgnoreList=myNode.namedItem("SPELLCHECKIGNORELIST");
+ if ( nodeIgnoreList.isNull () )
+ kdDebug (30508) << "No <SPELLCHECKIGNORELIST>" << endl; // Most files will not have it!
+ else
+ ProcessSpellCheckIgnoreListTag (nodeIgnoreList, NULL, leader);
+
+ // Process <PAPER> now, even if mostly the output will need to be delayed.
+ TQDomNode nodePaper=myNode.namedItem("PAPER");
+ if ( nodePaper.isNull () )
+ kdWarning (30508) << "No <PAPER>" << endl;
+ else
+ ProcessPaperTag (nodePaper, NULL, leader);
+
+ // Process <VARIABLESETTINGS>
+ TQDomNode nodeVariableSettings=myNode.namedItem("VARIABLESETTINGS");
+ if ( nodeVariableSettings.isNull () )
+ kdWarning (30508) << "No <VARIABLESETTINGS>" << endl;
+ else
+ ProcessVariableSettingsTag (nodeVariableSettings, NULL, leader);
+
+ // Then we process the styles
+ TQDomNode nodeStyles=myNode.namedItem("STYLES");
+ if ( nodeStyles.isNull () )
+ kdWarning (30508) << "No <STYLES>" << endl;
+ else
+ ProcessStylesPluralTag (nodeStyles, NULL, leader);
+
+ // Process framesets, but only to find and extract footnotes (also endnotes)
+ TQValueList<FootnoteData> footnotes;
+ TQDomNode nodeFramesets=myNode.namedItem("FRAMESETS");
+ if ( !nodeFramesets.isNull() )
+ ProcessFootnoteFramesetsTag(nodeFramesets, &footnotes, leader );
+
+ // Process all framesets and pictures
+ TQValueList<TagProcessing> tagProcessingList;
+ TQValueList<ParaData> paraList;
+
+ tagProcessingList
+ << TagProcessing ( "PAPER" ) // Already done
+ << TagProcessing ( "ATTRIBUTES" )
+ << TagProcessing ( "FRAMESETS", ProcessFramesetsTag, &paraList )
+ << TagProcessing ( "STYLES" ) // Already done
+ << TagProcessing ( "PICTURES", ProcessPixmapsTag, &paraList )
+ << TagProcessing ( "PIXMAPS", ProcessPixmapsTag, &paraList )
+ << TagProcessing ( "CLIPARTS", ProcessPixmapsTag, &paraList )
+ << TagProcessing ( "EMBEDDED" )
+ << TagProcessing ( "BOOKMARKS", ProcessBookmarksTag, &leader->m_bookmarkList )
+ ;
+
+ // TODO: why are the followings used by KWord 1.2 but are not in its DTD?
+ tagProcessingList << TagProcessing ( "SERIALL" );
+ tagProcessingList << TagProcessing ( "FOOTNOTEMGR" );
+
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ leader->doCloseHead();
+ leader->doDeclareNonInlinedFramesets( leader->m_nonInlinedPictureAnchors, leader->m_nonInlinedTableAnchors );
+ leader->doOpenBody();
+
+ leader->doFullDocument (paraList);
+
+ kdDebug(30508) << "Unachored Framesets : START" << endl;
+ TQStringList::ConstIterator it;
+ for ( it = leader->m_unanchoredFramesets.begin(); it != leader->m_unanchoredFramesets.end(); ++it )
+ {
+ kdDebug(30508) << (*it) << endl;
+ }
+ kdDebug(30508) << "Unachored Framesets : END" << endl;
+
+ FreeCellParaLists (paraList);
+
+ leader->doCloseBody();
+
+ //kdDebug (30508) << "Exiting ProcessDocTag" << endl;
+}
+
+
+void KWEFKWordLeader::setWorker ( KWEFBaseWorker *newWorker )
+{
+ m_worker = newWorker;
+
+ if (newWorker)
+ newWorker->registerKWordLeader(this);
+}
+
+
+KWEFBaseWorker *KWEFKWordLeader::getWorker(void) const
+{
+ return m_worker;
+}
+
+
+// Short simple definition for methods with void parameter
+#define DO_VOID_DEFINITION(string) \
+ bool KWEFKWordLeader::string() \
+ {\
+ if (m_worker) \
+ return m_worker->string(); \
+ return false; \
+ }
+
+
+bool KWEFKWordLeader::doOpenFile ( const TQString &filenameOut, const TQString &to )
+{
+ if ( m_worker )
+ return m_worker->doOpenFile (filenameOut, to);
+
+ // As it would be the first method to be called, warn if worker is NULL
+ kdError (30508) << "No Worker! (in KWEFKWordLeader::doOpenFile)" << endl;
+
+ return false;
+}
+
+
+DO_VOID_DEFINITION (doCloseFile)
+DO_VOID_DEFINITION (doAbortFile)
+DO_VOID_DEFINITION (doOpenDocument)
+DO_VOID_DEFINITION (doCloseDocument)
+DO_VOID_DEFINITION (doOpenStyles)
+DO_VOID_DEFINITION (doCloseStyles)
+DO_VOID_DEFINITION (doOpenHead)
+DO_VOID_DEFINITION (doCloseHead)
+DO_VOID_DEFINITION (doOpenBody)
+DO_VOID_DEFINITION (doCloseBody)
+DO_VOID_DEFINITION (doOpenSpellCheckIgnoreList)
+DO_VOID_DEFINITION (doCloseSpellCheckIgnoreList)
+
+bool KWEFKWordLeader::doFullDocumentInfo (const KWEFDocumentInfo &docInfo)
+{
+ if ( m_worker )
+ return m_worker->doFullDocumentInfo (docInfo);
+
+ return false;
+}
+
+
+bool KWEFKWordLeader::doVariableSettings (const VariableSettingsData &varSettings)
+{
+ if ( m_worker )
+ return m_worker->doVariableSettings (varSettings);
+
+ return false;
+}
+
+
+bool KWEFKWordLeader::doFullDocument (const TQValueList<ParaData> &paraList)
+{
+ if ( m_worker )
+ return m_worker->doFullDocument (paraList);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doPageInfo ( const int headerType, const int footerType )
+{
+ if ( m_worker )
+ return m_worker->doPageInfo ( headerType, footerType );
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFullPaperFormat ( const int format, const double width, const double height, const int orientation )
+{
+ if ( m_worker )
+ return m_worker->doFullPaperFormat (format, width, height, orientation);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFullPaperBorders (const double top, const double left, const double bottom, const double right)
+{
+ if ( m_worker )
+ return m_worker->doFullPaperBorders (top, left, bottom, right);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFullPaperFormatOther ( const int columns, const double columnspacing, const int numPages )
+{
+ if ( m_worker )
+ return m_worker->doFullPaperFormatOther ( columns, columnspacing, numPages );
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFullDefineStyle ( LayoutData &layout )
+{
+ if ( m_worker )
+ return m_worker->doFullDefineStyle (layout);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFullSpellCheckIgnoreWord (const TQString& ignoreword)
+{
+ if ( m_worker )
+ return m_worker->doFullSpellCheckIgnoreWord (ignoreword);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doHeader ( const HeaderData& header )
+{
+ if ( m_worker )
+ return m_worker->doHeader (header);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doFooter ( const FooterData& footer )
+{
+ if ( m_worker )
+ return m_worker->doFooter (footer);
+
+ return false;
+}
+
+bool KWEFKWordLeader::doDeclareNonInlinedFramesets( TQValueList<FrameAnchor>& pictureAnchors, TQValueList<FrameAnchor>& tableAnchors )
+{
+ if ( m_worker )
+ return m_worker->doDeclareNonInlinedFramesets( pictureAnchors, tableAnchors );
+
+ return false;
+}
+
+static bool ParseFile ( TQIODevice* subFile, TQDomDocument& doc)
+{
+ TQString errorMsg;
+ int errorLine;
+ int errorColumn;
+
+ if ( !doc.setContent (subFile, &errorMsg, &errorLine, &errorColumn) )
+ {
+ kdError (30508) << "Parsing Error! Aborting! (in ParseFile)" << endl
+ << " Line: " << errorLine << " Column: " << errorColumn << endl
+ << " Message: " << errorMsg << endl;
+ // ### TODO: the error is in which sub-file?
+ KMessageBox::error( 0L, i18n("An error has occurred while parsing the KWord file.\nAt line: %1, column %2\nError message: %3")
+ .arg( errorLine ).arg( errorColumn ).arg(i18n( "TQXml", errorMsg.utf8() ) ),
+ i18n("KWord Export Filter Library"), 0 );
+ return false;
+ }
+ return true;
+}
+
+static bool ProcessStoreFile ( TQIODevice* subFile,
+ void (*processor) (TQDomNode, void *, KWEFKWordLeader *),
+ KWEFKWordLeader* leader)
+{
+ if (!subFile)
+ {
+ kdWarning(30508) << "Could not get a device for the document!" << endl;
+ }
+ else if ( subFile->open ( IO_ReadOnly ) )
+ {
+ kdDebug (30508) << "Processing Document..." << endl;
+ TQDomDocument doc;
+ if (!ParseFile(subFile, doc))
+ {
+ subFile->close();
+ return false;
+ }
+ // We must close the subFile before processing,
+ // as the processing could open other sub files.
+ // However, it would crash if two sub files are opened together
+ subFile->close();
+
+ TQDomNode docNode = doc.documentElement();
+ processor (docNode, NULL, leader);
+ return true;
+ }
+ else
+ {
+ // Note: we do not worry too much if we cannot open the document info!
+ kdWarning (30508) << "Unable to open document!" << endl;
+ }
+ return false;
+}
+
+TQIODevice* KWEFKWordLeader::getSubFileDevice(const TQString& fileName)
+{
+ KoStoreDevice* subFile;
+
+ subFile=m_chain->storageFile(fileName,KoStore::Read);
+
+ if (!subFile)
+ {
+ kdError(30508) << "Could not get a device for sub-file: " << fileName << endl;
+ return NULL;
+ }
+ return subFile;
+}
+
+
+bool KWEFKWordLeader::loadSubFile(const TQString& fileName, TQByteArray& array)
+{
+ KoStoreDevice* subFile;
+
+ subFile=m_chain->storageFile(fileName,KoStore::Read);
+
+ if (!subFile)
+ {
+ kdError(30508) << "Could not get a device for sub-file: " << fileName << endl;
+ return false;
+ }
+ else if ( subFile->open ( IO_ReadOnly ) )
+ {
+ array = subFile->readAll();
+ subFile->close ();
+ }
+ else
+ {
+ kdError(30508) << "Unable to open " << fileName << " sub-file" << endl;
+ return false;
+ }
+
+ return true;
+}
+
+KoFilter::ConversionStatus KWEFKWordLeader::convert( KoFilterChain* chain,
+ const TQCString& from, const TQCString& to)
+{
+ if ( from != "application/x-kword" )
+ {
+ return KoFilter::NotImplemented;
+ }
+
+ if (!chain)
+ {
+ kdError(30508) << "'Chain' is NULL! Internal error of the filter system?" << endl;
+ return KoFilter::StupidError;
+ }
+
+ m_chain=chain;
+
+ if ( !doOpenFile (chain->outputFile(),to) )
+ {
+ kdError (30508) << "Worker could not open export file! Aborting!" << endl;
+ return KoFilter::StupidError;
+ }
+
+ if ( !doOpenDocument () )
+ {
+ kdError (30508) << "Worker could not open document! Aborting!" << endl;
+ doAbortFile ();
+ return KoFilter::StupidError;
+ }
+
+ KoStoreDevice* subFile;
+
+ subFile=chain->storageFile("documentinfo.xml",KoStore::Read);
+ kdDebug (30508) << "Processing documentinfo.xml..." << endl;
+ // Do not care if we cannot open the document info.
+ ProcessStoreFile (subFile, ProcessDocumentInfoTag, this);
+
+ subFile=chain->storageFile("root",KoStore::Read);
+ kdDebug (30508) << "Processing root..." << endl;
+ if (!ProcessStoreFile (subFile, ProcessDocTag, this))
+ {
+ kdWarning(30508) << "Opening root has failed. Trying raw XML file!" << endl;
+
+ const TQString filename( chain->inputFile() );
+ if (filename.isEmpty() )
+ {
+ kdError(30508) << "Could not open document as raw XML! Aborting!" << endl;
+ doAbortFile();
+ return KoFilter::StupidError;
+ }
+ else
+ {
+ TQFile file( filename );
+ if ( ! ProcessStoreFile( TQT_TQIODEVICE(&file), ProcessDocTag, this ) )
+ {
+ kdError(30508) << "Could not process document! Aborting!" << endl;
+ doAbortFile();
+ return KoFilter::StupidError;
+ }
+ }
+ }
+
+ doCloseDocument ();
+
+ doCloseFile ();
+
+ return KoFilter::OK;
+}
diff --git a/filters/kword/libexport/KWEFStructures.cc b/filters/kword/libexport/KWEFStructures.cpp
index 6c9c301f2..6c9c301f2 100644
--- a/filters/kword/libexport/KWEFStructures.cc
+++ b/filters/kword/libexport/KWEFStructures.cpp
diff --git a/filters/kword/libexport/KWEFStructures.h b/filters/kword/libexport/KWEFStructures.h
index 682606feb..2f8ba74ab 100644
--- a/filters/kword/libexport/KWEFStructures.h
+++ b/filters/kword/libexport/KWEFStructures.h
@@ -22,8 +22,8 @@
/*
The classes in this file are based on a class in the old files:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
- /home/kde/koffice/filters/kword/docbookexpert/docbookexport.cc
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+ /home/kde/koffice/filters/kword/docbookexpert/docbookexport.cpp
The old file was copyrighted by
Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
diff --git a/filters/kword/libexport/KWEFUtil.cc b/filters/kword/libexport/KWEFUtil.cpp
index a02a45ece..a02a45ece 100644
--- a/filters/kword/libexport/KWEFUtil.cc
+++ b/filters/kword/libexport/KWEFUtil.cpp
diff --git a/filters/kword/libexport/Makefile.am b/filters/kword/libexport/Makefile.am
index 6e2581749..cef09322c 100644
--- a/filters/kword/libexport/Makefile.am
+++ b/filters/kword/libexport/Makefile.am
@@ -10,8 +10,8 @@ libkwordexportfilters_la_LIBADD = $(KOFFICE_LIBS)
lib_LTLIBRARIES = libkwordexportfilters.la
-libkwordexportfilters_la_SOURCES = TagProcessing.cc KWEFStructures.cc\
-ProcessDocument.cc KWEFUtil.cc KWEFKWordLeader.cc KWEFBaseWorker.cc
+libkwordexportfilters_la_SOURCES = TagProcessing.cpp KWEFStructures.cpp\
+ProcessDocument.cpp KWEFUtil.cpp KWEFKWordLeader.cpp KWEFBaseWorker.cpp
noinst_HEADERS = TagProcessing.h KWEFStructures.h\
ProcessDocument.h KWEFUtil.h KWEFKWordLeader.h KWEFBaseWorker.h
diff --git a/filters/kword/libexport/ProcessDocument.cc b/filters/kword/libexport/ProcessDocument.cc
deleted file mode 100644
index 3a626f7f1..000000000
--- a/filters/kword/libexport/ProcessDocument.cc
+++ /dev/null
@@ -1,1063 +0,0 @@
-/*
- This file is part of the KDE project
- Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
- Copyright (c) 2001 IABG mbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@IABG.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Wolf-Michael.Bolle@GMX.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-/*
- Part of the code is based on code licensed under the terms of the
- GNU Library General Public License version 2:
- Copyright 2001 Michael Johnson <mikej@xnet.com>
-*/
-
-#include <tqdom.h>
-#include <tqvaluelist.h>
-
-#include <kdebug.h>
-
-#include "KWEFStructures.h"
-#include "TagProcessing.h"
-#include "ProcessDocument.h"
-#include "KWEFKWordLeader.h"
-
-
-// == KOFFICE DOCUMENT INFORMATION ==
-
-// TODO: verify that all document info is read!
-
-void ProcessTextTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- TQString *tagText = (TQString *) tagData;
-
- *tagText = myNode.toElement().text(); // Get the text, also from a CDATA section
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append ( TagProcessing ( "xml:space" ) );
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- AllowNoSubtags (myNode, leader);
-}
-
-static void ProcessAboutTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- KWEFDocumentInfo *docInfo = (KWEFDocumentInfo *) tagData;
-
- AllowNoAttributes (myNode);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append ( TagProcessing ( "title", ProcessTextTag, &docInfo->title ) );
- tagProcessingList.append ( TagProcessing ( "abstract", ProcessTextTag, &docInfo->abstract ) );
- tagProcessingList.append ( TagProcessing ( "keyword", ProcessTextTag, &docInfo->keywords ) );
- tagProcessingList.append ( TagProcessing ( "subject", ProcessTextTag, &docInfo->subject ) );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-
-static void ProcessAuthorTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- KWEFDocumentInfo *docInfo = (KWEFDocumentInfo *) tagData;
-
- AllowNoAttributes (myNode);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append ( TagProcessing ( "full-name", ProcessTextTag, &docInfo->fullName ) );
- tagProcessingList.append ( TagProcessing ( "title", ProcessTextTag, &docInfo->jobTitle ) );
- tagProcessingList.append ( TagProcessing ( "company", ProcessTextTag, &docInfo->company ) );
- tagProcessingList.append ( TagProcessing ( "email", ProcessTextTag, &docInfo->email ) );
- tagProcessingList.append ( TagProcessing ( "telephone", ProcessTextTag, &docInfo->telephone ) );
- tagProcessingList.append ( TagProcessing ( "telephone-work", ProcessTextTag, &docInfo->telephonework ) );
- tagProcessingList.append ( TagProcessing ( "fax", ProcessTextTag, &docInfo->fax ) );
- tagProcessingList.append ( TagProcessing ( "country", ProcessTextTag, &docInfo->country ) );
- tagProcessingList.append ( TagProcessing ( "postal-code", ProcessTextTag, &docInfo->postalCode ) );
- tagProcessingList.append ( TagProcessing ( "city", ProcessTextTag, &docInfo->city ) );
- tagProcessingList.append ( TagProcessing ( "street", ProcessTextTag, &docInfo->street ) );
- tagProcessingList.append ( TagProcessing ( "initial", ProcessTextTag, &docInfo->initial ) );
- tagProcessingList.append ( TagProcessing ( "position", ProcessTextTag, &docInfo->position ) );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-
-void ProcessDocumentInfoTag ( TQDomNode myNode,
- void *,
- KWEFKWordLeader *leader )
-{
- AllowNoAttributes (myNode);
-
- KWEFDocumentInfo docInfo;
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append ( TagProcessing ( "log" ) );
- tagProcessingList.append ( TagProcessing ( "author", ProcessAuthorTag, &docInfo ) );
- tagProcessingList.append ( TagProcessing ( "about", ProcessAboutTag, &docInfo ) );
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- leader->doFullDocumentInfo (docInfo);
-}
-
-
-// == KWORD ==
-
-// Every tag has its own processing function. All of those functions
-// have the same parameters since the functions are passed to
-// ProcessSubtags throuch the TagProcessing class. The top level
-// function is ProcessDocTag and can be called with the node returned
-// by TQDomDocument::documentElement (). The tagData argument can be
-// used to either pass variables down to the subtags or to allow
-// subtags to return values. As a bare minimum the tag processing
-// functions must handle the tag's attributes and the tag's subtags
-// (which it can choose to ignore). Currently implemented is
-// processing for the following tags and attributes:
-//
-// TODO: make this list up-to-date
-//
-// DOC
-// FRAMESETS
-// FRAMESET
-// PARAGRAPH
-// TEXT - Text Element
-// FORMATS
-// FORMAT id=1 pos= len=
-// LAYOUT
-// NAME value=
-
-
-// --------------------------------------------------------------------------------
-
-
-static void ProcessOneAttrTag ( TQDomNode myNode,
- TQString attrName,
- TQString attrType,
- void *attrData,
- KWEFKWordLeader *leader )
-{
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing (attrName, attrType, attrData);
- ProcessAttributes (myNode, attrProcessingList);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessColorAttrTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader * )
-{
- TQColor *attrValue = (TQColor *) tagData;
-
- int red, green, blue;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "red", red );
- attrProcessingList << AttrProcessing ( "green", green );
- attrProcessingList << AttrProcessing ( "blue", blue );
- ProcessAttributes (myNode, attrProcessingList);
-
- attrValue->setRgb (red, green, blue);
-}
-
-
-static void ProcessBoolIntAttrTag ( TQDomNode myNode,
- TQString attrName,
- void *attrData,
- KWEFKWordLeader *leader )
-{
- ProcessOneAttrTag (myNode, attrName, "bool", attrData, leader);
-}
-
-
-// --------------------------------------------------------------------------------
-
-
-static void ProcessIntValueTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ProcessOneAttrTag (myNode, "value", "int", tagData, leader);
-}
-
-
-static void ProcessBoolIntValueTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ProcessBoolIntAttrTag (myNode, "value", tagData, leader);
-}
-
-
-static void ProcessStringValueTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ProcessOneAttrTag (myNode, "value", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
-}
-
-static void ProcessStringNameTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ProcessOneAttrTag (myNode, "name", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
-}
-
-
-// --------------------------------------------------------------------------------
-
-
-static void ProcessOldLayoutChildTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/)
-{
- TQValueList<AttrProcessing> attrProcessingList;
-
- double* d = (double*) ( tagData );
- *d = 0.0; // Put a sensible default
-
- attrProcessingList
- << AttrProcessing ( "pt", *d )
- << AttrProcessing ( "inch" )
- << AttrProcessing ( "mm" )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-}
-
-static void ProcessUnderlineTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
-{
- TextFormatting* text=(TextFormatting*) tagData;
- TQString str,style;
- TQString strColor;
-
- text->underlineWord = false;
-
- TQValueList<AttrProcessing> attrProcessingList;
-
- attrProcessingList
- << AttrProcessing ( "value", str )
- << AttrProcessing ( "styleline", style )
- << AttrProcessing ( "wordbyword", text->underlineWord )
- << AttrProcessing ( "underlinecolor", strColor )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- str=str.stripWhiteSpace();
- text->underlineValue=str;
- if ( (str=="0") || (str.isEmpty()) )
- {
- text->underline=false;
- }
- else
- {
- // We assume that anything else is underlined
- text->underline=true;
- text->underlineStyle = style;
- text->underlineColor.setNamedColor(strColor);
- }
-}
-
-static void ProcessStrikeoutTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
-{
- TextFormatting* text=(TextFormatting*) tagData;
- TQString type, linestyle;
-
- text->strikeoutWord = false;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ("value" , type );
- attrProcessingList << AttrProcessing ("styleline" , linestyle );
- attrProcessingList << AttrProcessing ( "wordbyword", text->strikeoutWord );
- ProcessAttributes (myNode, attrProcessingList);
-
- if( type.isEmpty() || ( type == "0" ) )
- text->strikeout = false;
- else
- {
- text->strikeout = true;
- text->strikeoutType = type;
- text->strikeoutLineStyle = linestyle;
- if( text->strikeoutType == "1" )
- text->strikeoutType = "single";
- if( text->strikeoutLineStyle.isEmpty() )
- text->strikeoutLineStyle = "solid";
- }
-}
-
-
-void ProcessAnchorTag ( TQDomNode myNode,
- void *tagData,
- KWEFKWordLeader *leader )
-{
- TQString *instance = (TQString *) tagData;
-
- TQString type;
- *instance = TQString();
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "type", type )
- << AttrProcessing ( "instance", TQSTRING_OBJECT_NAME_STRING, instance );
- ProcessAttributes (myNode, attrProcessingList);
-
- if ( type != "frameset" )
- {
- kdWarning (30508) << "Unknown ANCHOR type " << type << "!" << endl;
- }
-
- if ( (*instance).isEmpty () )
- {
- kdWarning (30508) << "Bad ANCHOR instance name!" << endl;
- }
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessLinkTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
-{
- VariableData *variable = (VariableData *) tagData;
-
- TQString linkName, hrefName;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList.append ( AttrProcessing ("linkName", linkName) );
- attrProcessingList.append ( AttrProcessing ("hrefName", hrefName) );
- ProcessAttributes (myNode, attrProcessingList);
-
- variable->setLink(linkName, hrefName);
-}
-
-
-static void ProcessPgNumTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
-{
- VariableData *variable = (VariableData *) tagData;
-
- TQString subtype, value;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList.append ( AttrProcessing ("subtype", subtype) );
- attrProcessingList.append ( AttrProcessing ("value", value ) );
- ProcessAttributes (myNode, attrProcessingList);
-
- variable->setPgNum(subtype, value);
-}
-
-
-static void ProcessTypeTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
-{
- VariableData *variable = (VariableData *) tagData;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList.append ( AttrProcessing ("key", variable->m_key ) );
- attrProcessingList.append ( AttrProcessing ("text", variable->m_text) );
- attrProcessingList.append ( AttrProcessing ("type", variable->m_type) );
- ProcessAttributes (myNode, attrProcessingList);
-}
-
-static void ProcessFieldTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
-{
- VariableData *variable = (VariableData *) tagData;
- int subtype;
- TQString name, value;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList.append ( AttrProcessing ("subtype", subtype) );
- attrProcessingList.append ( AttrProcessing ("value", value ) );
- ProcessAttributes (myNode, attrProcessingList);
-
- switch( subtype )
- {
- case 0: name = "fileName"; break;
- case 1: name = "dirName"; break;
- case 2: name = "authorName"; break;
- case 3: name = "authorEmail"; break;
- case 4: name = "authorCompany"; break;
- case 10: name = "docTitle"; break;
- case 11: name = "docAbstract"; break;
- case 16: name = "authorInitial"; break;
- default: break;
- }
-
- if(!name.isEmpty())
- variable->setField(name, value);
-}
-
-static void ProcessFootnoteTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
-{
- VariableData *variable = (VariableData *) tagData;
- TQString frameset, value, numberingtype, notetype;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "value", value )
- << AttrProcessing ( "numberingtype", numberingtype )
- << AttrProcessing ( "frameset", frameset )
- << AttrProcessing ( "notetype", notetype )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- // search for frameset in the footnoteList
- for(unsigned i=0;i<leader->footnoteList.count();i++)
- {
- if( leader->footnoteList[i].frameName == frameset )
- {
- variable->setFootnote( notetype, numberingtype, value, &leader->footnoteList[i].para );
- break;
- }
- }
-}
-
-static void ProcessNoteTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
-{
- VariableData *variable = (VariableData *) tagData;
-
- TQString note;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList
- << AttrProcessing ( "note", note )
- ;
- ProcessAttributes (myNode, attrProcessingList);
-
- // set it even if note is empty
- variable->setGenericData( "note", note );
-}
-
-// ### TODO: some files have not a <VARIABLE> tag but its supposed children are directly children of <FORMAT id="4">
-static void ProcessVariableTag (TQDomNode myNode, void* tagData, KWEFKWordLeader* leader)
-{
- VariableData *variable = (VariableData *) tagData;
-
- TQValueList<TagProcessing> tagProcessingList;
- // "TYPE|PGNUM|DATE|TIME|CUSTOM|SERIALLETTER|FIELD|LINK|NOTE"
- tagProcessingList
- << TagProcessing ( "TYPE", ProcessTypeTag, variable )
- << TagProcessing ( "PGNUM", ProcessPgNumTag, variable )
- << TagProcessing ( "DATE" )
- << TagProcessing ( "TIME" )
- << TagProcessing ( "CUSTOM" )
- << TagProcessing ( "SERIALLETTER" )
- << TagProcessing ( "FIELD", ProcessFieldTag, variable )
- << TagProcessing ( "LINK", ProcessLinkTag, variable )
- << TagProcessing ( "NOTE", ProcessNoteTag, variable )
- << TagProcessing ( "FOOTNOTE", ProcessFootnoteTag, variable )
- ;
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-static void AppendTagProcessingFormatOne(TQValueList<TagProcessing>& tagProcessingList, FormatData& formatData)
-{
- tagProcessingList
- << TagProcessing ( "COLOR", ProcessColorAttrTag, &formatData.text.fgColor )
- << TagProcessing ( "FONT", ProcessStringNameTag, &formatData.text.fontName )
- << TagProcessing ( "SIZE", ProcessIntValueTag, &formatData.text.fontSize )
- << TagProcessing ( "WEIGHT", ProcessIntValueTag, &formatData.text.weight )
- << TagProcessing ( "ITALIC", ProcessBoolIntValueTag, &formatData.text.italic )
- << TagProcessing ( "UNDERLINE", ProcessUnderlineTag, &formatData.text )
- << TagProcessing ( "STRIKEOUT", ProcessStrikeoutTag, &formatData.text )
- << TagProcessing ( "VERTALIGN", ProcessIntValueTag, &formatData.text.verticalAlignment )
- << TagProcessing ( "SHADOW" )
- << TagProcessing ( "FONTATTRIBUTE", ProcessStringValueTag, &formatData.text.fontAttribute )
- << TagProcessing ( "LANGUAGE", ProcessStringValueTag, &formatData.text.language )
- << TagProcessing ( "ANCHOR" )
- << TagProcessing ( "IMAGE" )
- << TagProcessing ( "PICTURE" )
- << TagProcessing ( "VARIABLE" )
- << TagProcessing ( "TEXTBACKGROUNDCOLOR", ProcessColorAttrTag, &formatData.text.bgColor )
- << TagProcessing ( "OFFSETFROMBASELINE" )
- << TagProcessing ( "CHARSET" ) // Old KWord documents or KWord's RTF import filter
- ;
-
- if ( formatData.text.language == "xx" )
- {
- // The text language should have been named "x-test" or so to follow the specification
- // As it does not, we need to convert it.
- formatData.text.language = "en_US";
- }
-}
-
-
-static void SubProcessFormatOneTag(TQDomNode myNode,
- ValueListFormatData *formatDataList, int formatPos, int formatLen,
- KWEFKWordLeader *leader)
-{
- if ( formatPos == -1 || formatLen == -1 )
- {
- // We have no position and no length defined
- // It can happen in a child of <STYLE>, just put secure values
- formatPos=0;
- formatLen=0;
- kdDebug (30508) << "Missing formatting! Style? "
- << myNode.nodeName()
- << " = " << myNode.nodeValue()
- << endl;
-
- // In the old syntax (KWord 0.8), the comment would be displayed for each paragraph, so do not show it.
- if ( ! leader->m_oldSyntax )
- kdDebug (30508) << "Missing formatting for <FORMAT> (style or syntax version 1 ?)" << endl;
- }
-
- FormatData formatData(1, formatPos, formatLen);
- TQValueList<TagProcessing> tagProcessingList;
- AppendTagProcessingFormatOne(tagProcessingList,formatData);
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- (*formatDataList) << formatData;
-}
-
-
-static void SubProcessFormatTwoTag(TQDomNode myNode,
- ValueListFormatData *formatDataList, int formatPos, int formatLen,
- KWEFKWordLeader *leader)
-{
- if ( (formatPos == -1) )
- {
- // We have no position defined
- kdWarning(30508) << "Missing text image position!" << endl;
- return;
- }
- // In KWord 0.8, the len attribute was not defined
- if (formatLen == -1)
- formatLen = 1;
-
- FormatData formatData(2, formatPos, formatLen);
- TQValueList<TagProcessing> tagProcessingList;
-
- TQString fileName; // KWord 0.8
- KoPictureKey key; // Re-saved by KWord 1.2 or KWord 1.3
- tagProcessingList.append(TagProcessing( "FILENAME", ProcessStringValueTag, &fileName));
- tagProcessingList.append(TagProcessing( "PICTURE", ProcessImageTag, &key ));
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- if ( !fileName.isEmpty() )
- {
- kdDebug(30508) << "KWord 0.8 text image: " << fileName << endl;
- key = KoPictureKey( fileName );
- }
- else
- {
- kdDebug(30508) << "KWord 1.2/1.3 text image: " << key.toString() << endl;
- }
-
- formatData.frameAnchor.key = key;
- formatData.frameAnchor.picture.key = key;
-
- (*formatDataList) << formatData;
-}
-
-
-static void SubProcessFormatThreeTag(TQDomNode myNode,
- ValueListFormatData *formatDataList, int formatPos, int /*formatLen*/,
- KWEFKWordLeader *leader)
-{
- if ( (formatPos == -1) ) // formatLen is never there but is 1.
- {
- // We have no position and no length defined
- kdWarning(30508) << "Missing variable formatting!" << endl;
- return;
- }
- AllowNoSubtags (myNode, leader);
-
- const FormatData formatData(3, formatPos, 1);
- (*formatDataList) << formatData;
-}
-
-static void SubProcessFormatFourTag(TQDomNode myNode,
- ValueListFormatData *formatDataList, int formatPos, int formatLen,
- KWEFKWordLeader *leader)
-{
- if ( (formatPos == -1) || (formatLen == -1) )
- {
- // We have no position and no length defined
- kdWarning(30508) << "Missing variable formatting!" << endl;
- return;
- }
- FormatData formatData(4, formatPos, formatLen);
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList.append(TagProcessing("VARIABLE", ProcessVariableTag, &formatData.variable));
- // As variables can have a formating too, we have to process formating
- AppendTagProcessingFormatOne(tagProcessingList,formatData);
- ProcessSubtags (myNode, tagProcessingList, leader);
-
- (*formatDataList) << formatData;
-}
-
-
-static void SubProcessFormatSixTag(TQDomNode myNode,
- ValueListFormatData *formatDataList, int formatPos, int formatLen,
- KWEFKWordLeader *leader)
-{
- if ( formatPos != -1 && formatLen != -1 )
- {
- TQString instance;
-
- TQValueList<TagProcessing> tagProcessingList;
- // TODO: We can have all layout information as in regular texts
- // They simply apply to the table frames
- // FONT is just the first that we've come across so far
- tagProcessingList << TagProcessing ( "FONT" )
- << TagProcessing ( "ANCHOR", ProcessAnchorTag, &instance );
- ProcessSubtags (myNode, tagProcessingList, leader);
-#if 0
- kdDebug (30508) << "DEBUG: Adding frame anchor " << instance << endl;
-#endif
-
- (*formatDataList) << FormatData ( formatPos, formatLen, FrameAnchor (instance) );
- }
- else
- {
- kdWarning (30508) << "Missing or bad anchor formatting!" << endl;
- }
-}
-
-static void ProcessFormatTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
-{
- ValueListFormatData *formatDataList = (ValueListFormatData *) tagData;
- int formatId = -1;
- int formatPos = -1;
- int formatLen = -1;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "id", formatId );
- attrProcessingList << AttrProcessing ( "pos", formatPos );
- attrProcessingList << AttrProcessing ( "len", formatLen );
- ProcessAttributes (myNode, attrProcessingList);
-
- if ( ( formatId == -1 ) && ( leader->m_oldSyntax ) )
- {
- formatId = 1; // KWord 0.8 did not define it in <LAYOUT>
- }
-
- switch ( formatId )
- {
- case 1: // regular texts
- {
- SubProcessFormatOneTag(myNode, formatDataList, formatPos, formatLen, leader);
- break;
- }
- case 2: // text image (KWord 0.8)
- {
- SubProcessFormatTwoTag(myNode, formatDataList, formatPos, formatLen, leader);
- break;
- }
- case 3: // KWord 0.8 tabulator
- {
- SubProcessFormatThreeTag(myNode, formatDataList, formatPos, formatLen, leader);
- break;
- }
- case 4: // variables
- {
- SubProcessFormatFourTag(myNode, formatDataList, formatPos, formatLen, leader);
- break;
- }
- case 6: // anchors
- {
- SubProcessFormatSixTag(myNode, formatDataList, formatPos, formatLen, leader);
- break;
- }
- case -1:
- {
- kdWarning (30508) << "FORMAT attribute id value not set!" << endl;
- AllowNoSubtags (myNode, leader);
- break;
- }
- case 5: // KWord 0.8 footnote
- default:
- kdWarning(30508) << "Unexpected FORMAT attribute id value " << formatId << endl;
- AllowNoSubtags (myNode, leader);
- }
-
-}
-
-
-void ProcessFormatsTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ValueListFormatData *formatDataList = (ValueListFormatData *) tagData;
-
- AllowNoAttributes (myNode);
-
- (*formatDataList).clear ();
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "FORMAT", ProcessFormatTag, formatDataList );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
-
-// --------------------------------------------------------------------------------
-
-
-static void ProcessCounterTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- CounterData *counter = (CounterData *) tagData;
-
- // Be extra careful with data declared as enum (it could be very different from an int)
- int counterStyle = counter->style;
- int counterNumbering = counter->numbering;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "type", counterStyle );
- attrProcessingList << AttrProcessing ( "depth", counter->depth );
- attrProcessingList << AttrProcessing ( "bullet", counter->customCharacter );
- attrProcessingList << AttrProcessing ( "start", counter->start );
- attrProcessingList << AttrProcessing ( "numberingtype", counterNumbering );
- attrProcessingList << AttrProcessing ( "lefttext", counter->lefttext );
- attrProcessingList << AttrProcessing ( "righttext", counter->righttext );
- attrProcessingList << AttrProcessing ( "bulletfont", counter->customFont );
- attrProcessingList << AttrProcessing ( "customdef" );
- attrProcessingList << AttrProcessing ( "text", counter->text );
- attrProcessingList << AttrProcessing ( "display-levels" );
- attrProcessingList << AttrProcessing ( "align" );
- ProcessAttributes (myNode, attrProcessingList);
-
- counter->style = CounterData::Style( counterStyle );
- counter->numbering = CounterData::Numbering( counterNumbering );
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessLayoutTabulatorTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- TabulatorList* tabulatorList = (TabulatorList*) tagData;
-
- TabulatorData tabulator;
-
- TQValueList<AttrProcessing> attrProcessingList;
-
- attrProcessingList
- << AttrProcessing ( "ptpos", tabulator.m_ptpos )
- << AttrProcessing ( "type", tabulator.m_type )
- << AttrProcessing ( "filling", tabulator.m_filling )
- << AttrProcessing ( "width", tabulator.m_width )
- << AttrProcessing ( "alignchar" )
- ;
-
- if ( leader->m_oldSyntax )
- {
- // Avoid too many warning
- attrProcessingList
- << AttrProcessing ( "mmpos" )
- << AttrProcessing ( "inchpos" ) // Never ever use it, as this value is mostly wrong (e.g. 1.1009e+15)
- ;
- }
-
- ProcessAttributes (myNode, attrProcessingList);
- tabulatorList->append(tabulator);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessIndentsTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- LayoutData *layout = (LayoutData *) tagData;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ("first" , layout->indentFirst );
- attrProcessingList << AttrProcessing ("left" , layout->indentLeft );
- attrProcessingList << AttrProcessing ("right" , layout->indentRight );
- ProcessAttributes (myNode, attrProcessingList);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessLayoutOffsetTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- LayoutData *layout = (LayoutData *) tagData;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ("after" , layout->marginBottom );
- attrProcessingList << AttrProcessing ("before" , layout->marginTop );
- ProcessAttributes (myNode, attrProcessingList);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessLineBreakingTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- LayoutData *layout = (LayoutData *) tagData;
-
- TQString strBefore, strAfter;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "linesTogether", layout->keepLinesTogether );
- attrProcessingList << AttrProcessing ( "hardFrameBreak", layout->pageBreakBefore );
- attrProcessingList << AttrProcessing ( "hardFrameBreakAfter", layout->pageBreakAfter );
- attrProcessingList << AttrProcessing ( "keepWithNext" ); // RTF import filter
- ProcessAttributes (myNode, attrProcessingList);
-
- AllowNoSubtags (myNode, leader);
-}
-
-
-static void ProcessShadowTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
-{
- LayoutData *layout = (LayoutData *) tagData;
-
- int red=0;
- int green=0;
- int blue=0;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "distance", layout->shadowDistance );
- attrProcessingList << AttrProcessing ( "direction", layout->shadowDirection );
- attrProcessingList << AttrProcessing ( "red", red );
- attrProcessingList << AttrProcessing ( "green", green );
- attrProcessingList << AttrProcessing ( "blue", blue );
- ProcessAttributes (myNode, attrProcessingList);
-
- layout->shadowColor.setRgb(red,green,blue);
-
- AllowNoSubtags (myNode, leader);
-}
-
-static void ProcessAnyBorderTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- BorderData *border = static_cast <BorderData*> (tagData);
-
- int red=0;
- int green=0;
- int blue=0;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "red", red );
- attrProcessingList << AttrProcessing ( "green", green );
- attrProcessingList << AttrProcessing ( "blue", blue );
- attrProcessingList << AttrProcessing ( "style", border->style );
- attrProcessingList << AttrProcessing ( "width", border->width );
- ProcessAttributes (myNode, attrProcessingList);
-
- border->color.setRgb(red,green,blue);
-
- AllowNoSubtags (myNode, leader);
-}
-
-static void ProcessFollowingTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- ProcessOneAttrTag (myNode, "name", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
-}
-
-static void ProcessLinespacingTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
-{
- LayoutData *layout = (LayoutData *) tagData;
- TQString oldValue, spacingType;
- double spacingValue;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ("value" , oldValue );
- attrProcessingList << AttrProcessing ("type" , spacingType );
- attrProcessingList << AttrProcessing ("spacingvalue" , spacingValue );
- ProcessAttributes (myNode, attrProcessingList);
-
- // KWord pre-1.2 uses only the "value" attribute (stored in oldValue)
- // while 1.2 uses mainly "type" and "spacingvalue", while keeping "value" for compatibility
-
- if ( spacingType.isEmpty() )
- {
- // for old format
- if( oldValue == "oneandhalf" )
- layout->lineSpacingType = LayoutData::LS_ONEANDHALF;
- else if ( oldValue == "double" )
- layout->lineSpacingType = LayoutData::LS_DOUBLE;
- else
- {
- bool ok = false;
- const double size = oldValue.toDouble( &ok );
- if ( ok && ( size >= 0.0 ) ) // 0 is allowed but negative values are not
- {
- // We have a valid size
- layout->lineSpacingType = LayoutData::LS_CUSTOM; // set to custom
- layout->lineSpacing = size;
- }
- else
- layout->lineSpacingType = LayoutData::LS_SINGLE; // assume single linespace
- }
- }
- else
- {
- // for new format
- if( spacingType == "oneandhalf" )
- layout->lineSpacingType = LayoutData::LS_ONEANDHALF;
- else if ( spacingType == "double" )
- layout->lineSpacingType = LayoutData::LS_DOUBLE;
- else if ( spacingType == "custom" )
- layout->lineSpacingType = LayoutData::LS_CUSTOM;
- else if ( spacingType == "atleast" )
- layout->lineSpacingType = LayoutData::LS_ATLEAST;
- else if ( spacingType == "multiple" )
- layout->lineSpacingType = LayoutData::LS_MULTIPLE;
- else if ( spacingType == "fixed" )
- layout->lineSpacingType = LayoutData::LS_FIXED;
- else
- layout->lineSpacingType = LayoutData::LS_SINGLE; // assume single linespace
- layout->lineSpacing = spacingValue;
- }
-}
-
-static void ProcessLineSpaceTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
-{
- // <LINESPACE> is an old tag, of before syntax 1
- LayoutData *layout = (LayoutData *) tagData;
- double spacingValue = 0.0;
-
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "pt", spacingValue );
- attrProcessingList << AttrProcessing ( "mm" );
- attrProcessingList << AttrProcessing ( "inch" );
- ProcessAttributes (myNode, attrProcessingList);
-
- layout->lineSpacingType = LayoutData::LS_CUSTOM; // set to custom
- layout->lineSpacing = spacingValue;
-}
-
-static void ProcessFlowTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-{
- LayoutData *layout = (LayoutData *) tagData;
-
- TQString oldAlign, normalAlign;
-
- TQValueList<AttrProcessing> attrProcessingList;
- if ( leader->m_oldSyntax )
- {
- // KWord 0.8
- attrProcessingList << AttrProcessing ( "value", oldAlign ); // KWord 0.8
- }
- // New syntax and some files from syntax 1
- attrProcessingList << AttrProcessing ( "align", normalAlign );
- attrProcessingList << AttrProcessing ( "dir" ); // ### TODO
- ProcessAttributes (myNode, attrProcessingList);
-
- if ( leader->m_oldSyntax && normalAlign.isEmpty() )
- {
- if ( oldAlign.isEmpty() )
- {
- layout->alignment = "left"; // KWord 0.8 did not support right-to-left
- }
- else
- {
- const int align = oldAlign.toInt();
- if ( ( align < 0 ) || ( align > 3) )
- {
- kdWarning(30508) << "KWord 0.8 flow unknown: " << oldAlign << endl;
- layout->alignment = "left"; // Unknown, so assume left
- }
- else
- {
- const char* flows[]={"left", "right", "center", "justify" };
- layout->alignment = flows[ align ];
- }
- }
- kdDebug(30508) << "KWord 0.8 flow: " << oldAlign << " corrected: " << layout->alignment << endl;
- }
- else
- {
- layout->alignment = normalAlign;
- }
-
-}
-
-
-void ProcessLayoutTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
-// Processes <LAYOUT> and <STYLE>
-{
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "outline" ); // Only in <STYLE>
- ProcessAttributes (myNode, attrProcessingList);
-
- LayoutData *layout = (LayoutData *) tagData;
-
- ValueListFormatData formatDataList;
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "NAME", ProcessStringValueTag, &layout->styleName );
- tagProcessingList << TagProcessing ( "FOLLOWING", ProcessFollowingTag, &layout->styleFollowing );
- tagProcessingList << TagProcessing ( "FLOW", ProcessFlowTag, layout );
- tagProcessingList << TagProcessing ( "INDENTS", ProcessIndentsTag, layout );
- tagProcessingList << TagProcessing ( "OFFSETS", ProcessLayoutOffsetTag, layout );
- tagProcessingList << TagProcessing ( "LINESPACING", ProcessLinespacingTag, layout );
- tagProcessingList << TagProcessing ( "PAGEBREAKING", ProcessLineBreakingTag, layout );
- tagProcessingList << TagProcessing ( "LEFTBORDER", ProcessAnyBorderTag, &layout->leftBorder );
- tagProcessingList << TagProcessing ( "RIGHTBORDER", ProcessAnyBorderTag, &layout->rightBorder );
- tagProcessingList << TagProcessing ( "TOPBORDER", ProcessAnyBorderTag, &layout->topBorder );
- tagProcessingList << TagProcessing ( "BOTTOMBORDER", ProcessAnyBorderTag, &layout->bottomBorder );
- tagProcessingList << TagProcessing ( "COUNTER", ProcessCounterTag, &layout->counter );
- tagProcessingList << TagProcessing ( "FORMAT", ProcessFormatTag, &formatDataList );
- tagProcessingList << TagProcessing ( "TABULATOR", ProcessLayoutTabulatorTag, &layout->tabulatorList );
- tagProcessingList << TagProcessing ( "SHADOW", ProcessShadowTag, layout );
-
- if ( leader->m_oldSyntax )
- {
- layout->indentLeft = 0.0; // ### TODO: needed or not?
- tagProcessingList
- << TagProcessing ( "OHEAD", ProcessOldLayoutChildTag, &layout->marginTop )
- << TagProcessing ( "OFOOT", ProcessOldLayoutChildTag, &layout->marginBottom )
- << TagProcessing ( "ILEFT", ProcessOldLayoutChildTag, &layout->indentLeft )
- << TagProcessing ( "IFIRST", ProcessOldLayoutChildTag, &layout->indentFirst )
- << TagProcessing ( "LINESPACE", ProcessLineSpaceTag, layout )
- ;
- }
-
- ProcessSubtags (myNode, tagProcessingList, leader);
-
-
- if ( formatDataList.isEmpty () )
- {
- kdWarning (30508) << "No FORMAT tag within LAYOUT/STYLE!" << endl;
- }
- else
- {
- layout->formatData = formatDataList.first ();
-
- if ( formatDataList.count () > 1 )
- {
- kdWarning (30508) << "More than one FORMAT tag within LAYOUT/STYLE!" << endl;
- }
- }
-
- if ( layout->styleName.isEmpty () )
- {
- layout->styleName = "Standard";
- kdWarning (30508) << "Empty layout name!" << endl;
- }
-
-}
-
-
-static void ProcessImageKeyTag ( TQDomNode myNode,
- void *tagData, KWEFKWordLeader *)
-{
- KoPictureKey *key = (KoPictureKey*) tagData;
-
- // Let KoPicture do the loading
- key->loadAttributes(myNode.toElement());
-}
-
-void ProcessImageTag ( TQDomNode myNode,
- void *tagData, KWEFKWordLeader *leader )
-{ // <PICTURE>
- TQValueList<AttrProcessing> attrProcessingList;
- attrProcessingList << AttrProcessing ( "keepAspectRatio" );
- ProcessAttributes (myNode, attrProcessingList);
-
- TQValueList<TagProcessing> tagProcessingList;
- tagProcessingList << TagProcessing ( "KEY", ProcessImageKeyTag, tagData );
- ProcessSubtags (myNode, tagProcessingList, leader);
-}
-
diff --git a/filters/kword/libexport/ProcessDocument.cpp b/filters/kword/libexport/ProcessDocument.cpp
new file mode 100644
index 000000000..69b14857f
--- /dev/null
+++ b/filters/kword/libexport/ProcessDocument.cpp
@@ -0,0 +1,1063 @@
+/*
+ This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
+ Copyright (c) 2001 IABG mbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@IABG.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Wolf-Michael.Bolle@GMX.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+/*
+ Part of the code is based on code licensed under the terms of the
+ GNU Library General Public License version 2:
+ Copyright 2001 Michael Johnson <mikej@xnet.com>
+*/
+
+#include <tqdom.h>
+#include <tqvaluelist.h>
+
+#include <kdebug.h>
+
+#include "KWEFStructures.h"
+#include "TagProcessing.h"
+#include "ProcessDocument.h"
+#include "KWEFKWordLeader.h"
+
+
+// == KOFFICE DOCUMENT INFORMATION ==
+
+// TODO: verify that all document info is read!
+
+void ProcessTextTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ TQString *tagText = (TQString *) tagData;
+
+ *tagText = myNode.toElement().text(); // Get the text, also from a CDATA section
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append ( TagProcessing ( "xml:space" ) );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+static void ProcessAboutTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ KWEFDocumentInfo *docInfo = (KWEFDocumentInfo *) tagData;
+
+ AllowNoAttributes (myNode);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append ( TagProcessing ( "title", ProcessTextTag, &docInfo->title ) );
+ tagProcessingList.append ( TagProcessing ( "abstract", ProcessTextTag, &docInfo->abstract ) );
+ tagProcessingList.append ( TagProcessing ( "keyword", ProcessTextTag, &docInfo->keywords ) );
+ tagProcessingList.append ( TagProcessing ( "subject", ProcessTextTag, &docInfo->subject ) );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+
+static void ProcessAuthorTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ KWEFDocumentInfo *docInfo = (KWEFDocumentInfo *) tagData;
+
+ AllowNoAttributes (myNode);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append ( TagProcessing ( "full-name", ProcessTextTag, &docInfo->fullName ) );
+ tagProcessingList.append ( TagProcessing ( "title", ProcessTextTag, &docInfo->jobTitle ) );
+ tagProcessingList.append ( TagProcessing ( "company", ProcessTextTag, &docInfo->company ) );
+ tagProcessingList.append ( TagProcessing ( "email", ProcessTextTag, &docInfo->email ) );
+ tagProcessingList.append ( TagProcessing ( "telephone", ProcessTextTag, &docInfo->telephone ) );
+ tagProcessingList.append ( TagProcessing ( "telephone-work", ProcessTextTag, &docInfo->telephonework ) );
+ tagProcessingList.append ( TagProcessing ( "fax", ProcessTextTag, &docInfo->fax ) );
+ tagProcessingList.append ( TagProcessing ( "country", ProcessTextTag, &docInfo->country ) );
+ tagProcessingList.append ( TagProcessing ( "postal-code", ProcessTextTag, &docInfo->postalCode ) );
+ tagProcessingList.append ( TagProcessing ( "city", ProcessTextTag, &docInfo->city ) );
+ tagProcessingList.append ( TagProcessing ( "street", ProcessTextTag, &docInfo->street ) );
+ tagProcessingList.append ( TagProcessing ( "initial", ProcessTextTag, &docInfo->initial ) );
+ tagProcessingList.append ( TagProcessing ( "position", ProcessTextTag, &docInfo->position ) );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+
+void ProcessDocumentInfoTag ( TQDomNode myNode,
+ void *,
+ KWEFKWordLeader *leader )
+{
+ AllowNoAttributes (myNode);
+
+ KWEFDocumentInfo docInfo;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append ( TagProcessing ( "log" ) );
+ tagProcessingList.append ( TagProcessing ( "author", ProcessAuthorTag, &docInfo ) );
+ tagProcessingList.append ( TagProcessing ( "about", ProcessAboutTag, &docInfo ) );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ leader->doFullDocumentInfo (docInfo);
+}
+
+
+// == KWORD ==
+
+// Every tag has its own processing function. All of those functions
+// have the same parameters since the functions are passed to
+// ProcessSubtags throuch the TagProcessing class. The top level
+// function is ProcessDocTag and can be called with the node returned
+// by TQDomDocument::documentElement (). The tagData argument can be
+// used to either pass variables down to the subtags or to allow
+// subtags to return values. As a bare minimum the tag processing
+// functions must handle the tag's attributes and the tag's subtags
+// (which it can choose to ignore). Currently implemented is
+// processing for the following tags and attributes:
+//
+// TODO: make this list up-to-date
+//
+// DOC
+// FRAMESETS
+// FRAMESET
+// PARAGRAPH
+// TEXT - Text Element
+// FORMATS
+// FORMAT id=1 pos= len=
+// LAYOUT
+// NAME value=
+
+
+// --------------------------------------------------------------------------------
+
+
+static void ProcessOneAttrTag ( TQDomNode myNode,
+ TQString attrName,
+ TQString attrType,
+ void *attrData,
+ KWEFKWordLeader *leader )
+{
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing (attrName, attrType, attrData);
+ ProcessAttributes (myNode, attrProcessingList);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessColorAttrTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader * )
+{
+ TQColor *attrValue = (TQColor *) tagData;
+
+ int red, green, blue;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "red", red );
+ attrProcessingList << AttrProcessing ( "green", green );
+ attrProcessingList << AttrProcessing ( "blue", blue );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ attrValue->setRgb (red, green, blue);
+}
+
+
+static void ProcessBoolIntAttrTag ( TQDomNode myNode,
+ TQString attrName,
+ void *attrData,
+ KWEFKWordLeader *leader )
+{
+ ProcessOneAttrTag (myNode, attrName, "bool", attrData, leader);
+}
+
+
+// --------------------------------------------------------------------------------
+
+
+static void ProcessIntValueTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ProcessOneAttrTag (myNode, "value", "int", tagData, leader);
+}
+
+
+static void ProcessBoolIntValueTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ProcessBoolIntAttrTag (myNode, "value", tagData, leader);
+}
+
+
+static void ProcessStringValueTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ProcessOneAttrTag (myNode, "value", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
+}
+
+static void ProcessStringNameTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ProcessOneAttrTag (myNode, "name", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
+}
+
+
+// --------------------------------------------------------------------------------
+
+
+static void ProcessOldLayoutChildTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/)
+{
+ TQValueList<AttrProcessing> attrProcessingList;
+
+ double* d = (double*) ( tagData );
+ *d = 0.0; // Put a sensible default
+
+ attrProcessingList
+ << AttrProcessing ( "pt", *d )
+ << AttrProcessing ( "inch" )
+ << AttrProcessing ( "mm" )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+}
+
+static void ProcessUnderlineTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
+{
+ TextFormatting* text=(TextFormatting*) tagData;
+ TQString str,style;
+ TQString strColor;
+
+ text->underlineWord = false;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+
+ attrProcessingList
+ << AttrProcessing ( "value", str )
+ << AttrProcessing ( "styleline", style )
+ << AttrProcessing ( "wordbyword", text->underlineWord )
+ << AttrProcessing ( "underlinecolor", strColor )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ str=str.stripWhiteSpace();
+ text->underlineValue=str;
+ if ( (str=="0") || (str.isEmpty()) )
+ {
+ text->underline=false;
+ }
+ else
+ {
+ // We assume that anything else is underlined
+ text->underline=true;
+ text->underlineStyle = style;
+ text->underlineColor.setNamedColor(strColor);
+ }
+}
+
+static void ProcessStrikeoutTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
+{
+ TextFormatting* text=(TextFormatting*) tagData;
+ TQString type, linestyle;
+
+ text->strikeoutWord = false;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ("value" , type );
+ attrProcessingList << AttrProcessing ("styleline" , linestyle );
+ attrProcessingList << AttrProcessing ( "wordbyword", text->strikeoutWord );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ if( type.isEmpty() || ( type == "0" ) )
+ text->strikeout = false;
+ else
+ {
+ text->strikeout = true;
+ text->strikeoutType = type;
+ text->strikeoutLineStyle = linestyle;
+ if( text->strikeoutType == "1" )
+ text->strikeoutType = "single";
+ if( text->strikeoutLineStyle.isEmpty() )
+ text->strikeoutLineStyle = "solid";
+ }
+}
+
+
+void ProcessAnchorTag ( TQDomNode myNode,
+ void *tagData,
+ KWEFKWordLeader *leader )
+{
+ TQString *instance = (TQString *) tagData;
+
+ TQString type;
+ *instance = TQString();
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "type", type )
+ << AttrProcessing ( "instance", TQSTRING_OBJECT_NAME_STRING, instance );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ if ( type != "frameset" )
+ {
+ kdWarning (30508) << "Unknown ANCHOR type " << type << "!" << endl;
+ }
+
+ if ( (*instance).isEmpty () )
+ {
+ kdWarning (30508) << "Bad ANCHOR instance name!" << endl;
+ }
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessLinkTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
+{
+ VariableData *variable = (VariableData *) tagData;
+
+ TQString linkName, hrefName;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList.append ( AttrProcessing ("linkName", linkName) );
+ attrProcessingList.append ( AttrProcessing ("hrefName", hrefName) );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ variable->setLink(linkName, hrefName);
+}
+
+
+static void ProcessPgNumTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
+{
+ VariableData *variable = (VariableData *) tagData;
+
+ TQString subtype, value;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList.append ( AttrProcessing ("subtype", subtype) );
+ attrProcessingList.append ( AttrProcessing ("value", value ) );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ variable->setPgNum(subtype, value);
+}
+
+
+static void ProcessTypeTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
+{
+ VariableData *variable = (VariableData *) tagData;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList.append ( AttrProcessing ("key", variable->m_key ) );
+ attrProcessingList.append ( AttrProcessing ("text", variable->m_text) );
+ attrProcessingList.append ( AttrProcessing ("type", variable->m_type) );
+ ProcessAttributes (myNode, attrProcessingList);
+}
+
+static void ProcessFieldTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *)
+{
+ VariableData *variable = (VariableData *) tagData;
+ int subtype;
+ TQString name, value;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList.append ( AttrProcessing ("subtype", subtype) );
+ attrProcessingList.append ( AttrProcessing ("value", value ) );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ switch( subtype )
+ {
+ case 0: name = "fileName"; break;
+ case 1: name = "dirName"; break;
+ case 2: name = "authorName"; break;
+ case 3: name = "authorEmail"; break;
+ case 4: name = "authorCompany"; break;
+ case 10: name = "docTitle"; break;
+ case 11: name = "docAbstract"; break;
+ case 16: name = "authorInitial"; break;
+ default: break;
+ }
+
+ if(!name.isEmpty())
+ variable->setField(name, value);
+}
+
+static void ProcessFootnoteTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
+{
+ VariableData *variable = (VariableData *) tagData;
+ TQString frameset, value, numberingtype, notetype;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "value", value )
+ << AttrProcessing ( "numberingtype", numberingtype )
+ << AttrProcessing ( "frameset", frameset )
+ << AttrProcessing ( "notetype", notetype )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ // search for frameset in the footnoteList
+ for(unsigned i=0;i<leader->footnoteList.count();i++)
+ {
+ if( leader->footnoteList[i].frameName == frameset )
+ {
+ variable->setFootnote( notetype, numberingtype, value, &leader->footnoteList[i].para );
+ break;
+ }
+ }
+}
+
+static void ProcessNoteTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
+{
+ VariableData *variable = (VariableData *) tagData;
+
+ TQString note;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList
+ << AttrProcessing ( "note", note )
+ ;
+ ProcessAttributes (myNode, attrProcessingList);
+
+ // set it even if note is empty
+ variable->setGenericData( "note", note );
+}
+
+// ### TODO: some files have not a <VARIABLE> tag but its supposed children are directly children of <FORMAT id="4">
+static void ProcessVariableTag (TQDomNode myNode, void* tagData, KWEFKWordLeader* leader)
+{
+ VariableData *variable = (VariableData *) tagData;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ // "TYPE|PGNUM|DATE|TIME|CUSTOM|SERIALLETTER|FIELD|LINK|NOTE"
+ tagProcessingList
+ << TagProcessing ( "TYPE", ProcessTypeTag, variable )
+ << TagProcessing ( "PGNUM", ProcessPgNumTag, variable )
+ << TagProcessing ( "DATE" )
+ << TagProcessing ( "TIME" )
+ << TagProcessing ( "CUSTOM" )
+ << TagProcessing ( "SERIALLETTER" )
+ << TagProcessing ( "FIELD", ProcessFieldTag, variable )
+ << TagProcessing ( "LINK", ProcessLinkTag, variable )
+ << TagProcessing ( "NOTE", ProcessNoteTag, variable )
+ << TagProcessing ( "FOOTNOTE", ProcessFootnoteTag, variable )
+ ;
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+static void AppendTagProcessingFormatOne(TQValueList<TagProcessing>& tagProcessingList, FormatData& formatData)
+{
+ tagProcessingList
+ << TagProcessing ( "COLOR", ProcessColorAttrTag, &formatData.text.fgColor )
+ << TagProcessing ( "FONT", ProcessStringNameTag, &formatData.text.fontName )
+ << TagProcessing ( "SIZE", ProcessIntValueTag, &formatData.text.fontSize )
+ << TagProcessing ( "WEIGHT", ProcessIntValueTag, &formatData.text.weight )
+ << TagProcessing ( "ITALIC", ProcessBoolIntValueTag, &formatData.text.italic )
+ << TagProcessing ( "UNDERLINE", ProcessUnderlineTag, &formatData.text )
+ << TagProcessing ( "STRIKEOUT", ProcessStrikeoutTag, &formatData.text )
+ << TagProcessing ( "VERTALIGN", ProcessIntValueTag, &formatData.text.verticalAlignment )
+ << TagProcessing ( "SHADOW" )
+ << TagProcessing ( "FONTATTRIBUTE", ProcessStringValueTag, &formatData.text.fontAttribute )
+ << TagProcessing ( "LANGUAGE", ProcessStringValueTag, &formatData.text.language )
+ << TagProcessing ( "ANCHOR" )
+ << TagProcessing ( "IMAGE" )
+ << TagProcessing ( "PICTURE" )
+ << TagProcessing ( "VARIABLE" )
+ << TagProcessing ( "TEXTBACKGROUNDCOLOR", ProcessColorAttrTag, &formatData.text.bgColor )
+ << TagProcessing ( "OFFSETFROMBASELINE" )
+ << TagProcessing ( "CHARSET" ) // Old KWord documents or KWord's RTF import filter
+ ;
+
+ if ( formatData.text.language == "xx" )
+ {
+ // The text language should have been named "x-test" or so to follow the specification
+ // As it does not, we need to convert it.
+ formatData.text.language = "en_US";
+ }
+}
+
+
+static void SubProcessFormatOneTag(TQDomNode myNode,
+ ValueListFormatData *formatDataList, int formatPos, int formatLen,
+ KWEFKWordLeader *leader)
+{
+ if ( formatPos == -1 || formatLen == -1 )
+ {
+ // We have no position and no length defined
+ // It can happen in a child of <STYLE>, just put secure values
+ formatPos=0;
+ formatLen=0;
+ kdDebug (30508) << "Missing formatting! Style? "
+ << myNode.nodeName()
+ << " = " << myNode.nodeValue()
+ << endl;
+
+ // In the old syntax (KWord 0.8), the comment would be displayed for each paragraph, so do not show it.
+ if ( ! leader->m_oldSyntax )
+ kdDebug (30508) << "Missing formatting for <FORMAT> (style or syntax version 1 ?)" << endl;
+ }
+
+ FormatData formatData(1, formatPos, formatLen);
+ TQValueList<TagProcessing> tagProcessingList;
+ AppendTagProcessingFormatOne(tagProcessingList,formatData);
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ (*formatDataList) << formatData;
+}
+
+
+static void SubProcessFormatTwoTag(TQDomNode myNode,
+ ValueListFormatData *formatDataList, int formatPos, int formatLen,
+ KWEFKWordLeader *leader)
+{
+ if ( (formatPos == -1) )
+ {
+ // We have no position defined
+ kdWarning(30508) << "Missing text image position!" << endl;
+ return;
+ }
+ // In KWord 0.8, the len attribute was not defined
+ if (formatLen == -1)
+ formatLen = 1;
+
+ FormatData formatData(2, formatPos, formatLen);
+ TQValueList<TagProcessing> tagProcessingList;
+
+ TQString fileName; // KWord 0.8
+ KoPictureKey key; // Re-saved by KWord 1.2 or KWord 1.3
+ tagProcessingList.append(TagProcessing( "FILENAME", ProcessStringValueTag, &fileName));
+ tagProcessingList.append(TagProcessing( "PICTURE", ProcessImageTag, &key ));
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ if ( !fileName.isEmpty() )
+ {
+ kdDebug(30508) << "KWord 0.8 text image: " << fileName << endl;
+ key = KoPictureKey( fileName );
+ }
+ else
+ {
+ kdDebug(30508) << "KWord 1.2/1.3 text image: " << key.toString() << endl;
+ }
+
+ formatData.frameAnchor.key = key;
+ formatData.frameAnchor.picture.key = key;
+
+ (*formatDataList) << formatData;
+}
+
+
+static void SubProcessFormatThreeTag(TQDomNode myNode,
+ ValueListFormatData *formatDataList, int formatPos, int /*formatLen*/,
+ KWEFKWordLeader *leader)
+{
+ if ( (formatPos == -1) ) // formatLen is never there but is 1.
+ {
+ // We have no position and no length defined
+ kdWarning(30508) << "Missing variable formatting!" << endl;
+ return;
+ }
+ AllowNoSubtags (myNode, leader);
+
+ const FormatData formatData(3, formatPos, 1);
+ (*formatDataList) << formatData;
+}
+
+static void SubProcessFormatFourTag(TQDomNode myNode,
+ ValueListFormatData *formatDataList, int formatPos, int formatLen,
+ KWEFKWordLeader *leader)
+{
+ if ( (formatPos == -1) || (formatLen == -1) )
+ {
+ // We have no position and no length defined
+ kdWarning(30508) << "Missing variable formatting!" << endl;
+ return;
+ }
+ FormatData formatData(4, formatPos, formatLen);
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList.append(TagProcessing("VARIABLE", ProcessVariableTag, &formatData.variable));
+ // As variables can have a formating too, we have to process formating
+ AppendTagProcessingFormatOne(tagProcessingList,formatData);
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+ (*formatDataList) << formatData;
+}
+
+
+static void SubProcessFormatSixTag(TQDomNode myNode,
+ ValueListFormatData *formatDataList, int formatPos, int formatLen,
+ KWEFKWordLeader *leader)
+{
+ if ( formatPos != -1 && formatLen != -1 )
+ {
+ TQString instance;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ // TODO: We can have all layout information as in regular texts
+ // They simply apply to the table frames
+ // FONT is just the first that we've come across so far
+ tagProcessingList << TagProcessing ( "FONT" )
+ << TagProcessing ( "ANCHOR", ProcessAnchorTag, &instance );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+#if 0
+ kdDebug (30508) << "DEBUG: Adding frame anchor " << instance << endl;
+#endif
+
+ (*formatDataList) << FormatData ( formatPos, formatLen, FrameAnchor (instance) );
+ }
+ else
+ {
+ kdWarning (30508) << "Missing or bad anchor formatting!" << endl;
+ }
+}
+
+static void ProcessFormatTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
+{
+ ValueListFormatData *formatDataList = (ValueListFormatData *) tagData;
+ int formatId = -1;
+ int formatPos = -1;
+ int formatLen = -1;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "id", formatId );
+ attrProcessingList << AttrProcessing ( "pos", formatPos );
+ attrProcessingList << AttrProcessing ( "len", formatLen );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ if ( ( formatId == -1 ) && ( leader->m_oldSyntax ) )
+ {
+ formatId = 1; // KWord 0.8 did not define it in <LAYOUT>
+ }
+
+ switch ( formatId )
+ {
+ case 1: // regular texts
+ {
+ SubProcessFormatOneTag(myNode, formatDataList, formatPos, formatLen, leader);
+ break;
+ }
+ case 2: // text image (KWord 0.8)
+ {
+ SubProcessFormatTwoTag(myNode, formatDataList, formatPos, formatLen, leader);
+ break;
+ }
+ case 3: // KWord 0.8 tabulator
+ {
+ SubProcessFormatThreeTag(myNode, formatDataList, formatPos, formatLen, leader);
+ break;
+ }
+ case 4: // variables
+ {
+ SubProcessFormatFourTag(myNode, formatDataList, formatPos, formatLen, leader);
+ break;
+ }
+ case 6: // anchors
+ {
+ SubProcessFormatSixTag(myNode, formatDataList, formatPos, formatLen, leader);
+ break;
+ }
+ case -1:
+ {
+ kdWarning (30508) << "FORMAT attribute id value not set!" << endl;
+ AllowNoSubtags (myNode, leader);
+ break;
+ }
+ case 5: // KWord 0.8 footnote
+ default:
+ kdWarning(30508) << "Unexpected FORMAT attribute id value " << formatId << endl;
+ AllowNoSubtags (myNode, leader);
+ }
+
+}
+
+
+void ProcessFormatsTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ValueListFormatData *formatDataList = (ValueListFormatData *) tagData;
+
+ AllowNoAttributes (myNode);
+
+ (*formatDataList).clear ();
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "FORMAT", ProcessFormatTag, formatDataList );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
+
+// --------------------------------------------------------------------------------
+
+
+static void ProcessCounterTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ CounterData *counter = (CounterData *) tagData;
+
+ // Be extra careful with data declared as enum (it could be very different from an int)
+ int counterStyle = counter->style;
+ int counterNumbering = counter->numbering;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "type", counterStyle );
+ attrProcessingList << AttrProcessing ( "depth", counter->depth );
+ attrProcessingList << AttrProcessing ( "bullet", counter->customCharacter );
+ attrProcessingList << AttrProcessing ( "start", counter->start );
+ attrProcessingList << AttrProcessing ( "numberingtype", counterNumbering );
+ attrProcessingList << AttrProcessing ( "lefttext", counter->lefttext );
+ attrProcessingList << AttrProcessing ( "righttext", counter->righttext );
+ attrProcessingList << AttrProcessing ( "bulletfont", counter->customFont );
+ attrProcessingList << AttrProcessing ( "customdef" );
+ attrProcessingList << AttrProcessing ( "text", counter->text );
+ attrProcessingList << AttrProcessing ( "display-levels" );
+ attrProcessingList << AttrProcessing ( "align" );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ counter->style = CounterData::Style( counterStyle );
+ counter->numbering = CounterData::Numbering( counterNumbering );
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessLayoutTabulatorTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ TabulatorList* tabulatorList = (TabulatorList*) tagData;
+
+ TabulatorData tabulator;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+
+ attrProcessingList
+ << AttrProcessing ( "ptpos", tabulator.m_ptpos )
+ << AttrProcessing ( "type", tabulator.m_type )
+ << AttrProcessing ( "filling", tabulator.m_filling )
+ << AttrProcessing ( "width", tabulator.m_width )
+ << AttrProcessing ( "alignchar" )
+ ;
+
+ if ( leader->m_oldSyntax )
+ {
+ // Avoid too many warning
+ attrProcessingList
+ << AttrProcessing ( "mmpos" )
+ << AttrProcessing ( "inchpos" ) // Never ever use it, as this value is mostly wrong (e.g. 1.1009e+15)
+ ;
+ }
+
+ ProcessAttributes (myNode, attrProcessingList);
+ tabulatorList->append(tabulator);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessIndentsTag (TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ LayoutData *layout = (LayoutData *) tagData;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ("first" , layout->indentFirst );
+ attrProcessingList << AttrProcessing ("left" , layout->indentLeft );
+ attrProcessingList << AttrProcessing ("right" , layout->indentRight );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessLayoutOffsetTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ LayoutData *layout = (LayoutData *) tagData;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ("after" , layout->marginBottom );
+ attrProcessingList << AttrProcessing ("before" , layout->marginTop );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessLineBreakingTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ LayoutData *layout = (LayoutData *) tagData;
+
+ TQString strBefore, strAfter;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "linesTogether", layout->keepLinesTogether );
+ attrProcessingList << AttrProcessing ( "hardFrameBreak", layout->pageBreakBefore );
+ attrProcessingList << AttrProcessing ( "hardFrameBreakAfter", layout->pageBreakAfter );
+ attrProcessingList << AttrProcessing ( "keepWithNext" ); // RTF import filter
+ ProcessAttributes (myNode, attrProcessingList);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+
+static void ProcessShadowTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader)
+{
+ LayoutData *layout = (LayoutData *) tagData;
+
+ int red=0;
+ int green=0;
+ int blue=0;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "distance", layout->shadowDistance );
+ attrProcessingList << AttrProcessing ( "direction", layout->shadowDirection );
+ attrProcessingList << AttrProcessing ( "red", red );
+ attrProcessingList << AttrProcessing ( "green", green );
+ attrProcessingList << AttrProcessing ( "blue", blue );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ layout->shadowColor.setRgb(red,green,blue);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+static void ProcessAnyBorderTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ BorderData *border = static_cast <BorderData*> (tagData);
+
+ int red=0;
+ int green=0;
+ int blue=0;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "red", red );
+ attrProcessingList << AttrProcessing ( "green", green );
+ attrProcessingList << AttrProcessing ( "blue", blue );
+ attrProcessingList << AttrProcessing ( "style", border->style );
+ attrProcessingList << AttrProcessing ( "width", border->width );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ border->color.setRgb(red,green,blue);
+
+ AllowNoSubtags (myNode, leader);
+}
+
+static void ProcessFollowingTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ ProcessOneAttrTag (myNode, "name", TQSTRING_OBJECT_NAME_STRING, tagData, leader);
+}
+
+static void ProcessLinespacingTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
+{
+ LayoutData *layout = (LayoutData *) tagData;
+ TQString oldValue, spacingType;
+ double spacingValue;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ("value" , oldValue );
+ attrProcessingList << AttrProcessing ("type" , spacingType );
+ attrProcessingList << AttrProcessing ("spacingvalue" , spacingValue );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ // KWord pre-1.2 uses only the "value" attribute (stored in oldValue)
+ // while 1.2 uses mainly "type" and "spacingvalue", while keeping "value" for compatibility
+
+ if ( spacingType.isEmpty() )
+ {
+ // for old format
+ if( oldValue == "oneandhalf" )
+ layout->lineSpacingType = LayoutData::LS_ONEANDHALF;
+ else if ( oldValue == "double" )
+ layout->lineSpacingType = LayoutData::LS_DOUBLE;
+ else
+ {
+ bool ok = false;
+ const double size = oldValue.toDouble( &ok );
+ if ( ok && ( size >= 0.0 ) ) // 0 is allowed but negative values are not
+ {
+ // We have a valid size
+ layout->lineSpacingType = LayoutData::LS_CUSTOM; // set to custom
+ layout->lineSpacing = size;
+ }
+ else
+ layout->lineSpacingType = LayoutData::LS_SINGLE; // assume single linespace
+ }
+ }
+ else
+ {
+ // for new format
+ if( spacingType == "oneandhalf" )
+ layout->lineSpacingType = LayoutData::LS_ONEANDHALF;
+ else if ( spacingType == "double" )
+ layout->lineSpacingType = LayoutData::LS_DOUBLE;
+ else if ( spacingType == "custom" )
+ layout->lineSpacingType = LayoutData::LS_CUSTOM;
+ else if ( spacingType == "atleast" )
+ layout->lineSpacingType = LayoutData::LS_ATLEAST;
+ else if ( spacingType == "multiple" )
+ layout->lineSpacingType = LayoutData::LS_MULTIPLE;
+ else if ( spacingType == "fixed" )
+ layout->lineSpacingType = LayoutData::LS_FIXED;
+ else
+ layout->lineSpacingType = LayoutData::LS_SINGLE; // assume single linespace
+ layout->lineSpacing = spacingValue;
+ }
+}
+
+static void ProcessLineSpaceTag (TQDomNode myNode, void *tagData, KWEFKWordLeader* /*leader*/ )
+{
+ // <LINESPACE> is an old tag, of before syntax 1
+ LayoutData *layout = (LayoutData *) tagData;
+ double spacingValue = 0.0;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "pt", spacingValue );
+ attrProcessingList << AttrProcessing ( "mm" );
+ attrProcessingList << AttrProcessing ( "inch" );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ layout->lineSpacingType = LayoutData::LS_CUSTOM; // set to custom
+ layout->lineSpacing = spacingValue;
+}
+
+static void ProcessFlowTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+{
+ LayoutData *layout = (LayoutData *) tagData;
+
+ TQString oldAlign, normalAlign;
+
+ TQValueList<AttrProcessing> attrProcessingList;
+ if ( leader->m_oldSyntax )
+ {
+ // KWord 0.8
+ attrProcessingList << AttrProcessing ( "value", oldAlign ); // KWord 0.8
+ }
+ // New syntax and some files from syntax 1
+ attrProcessingList << AttrProcessing ( "align", normalAlign );
+ attrProcessingList << AttrProcessing ( "dir" ); // ### TODO
+ ProcessAttributes (myNode, attrProcessingList);
+
+ if ( leader->m_oldSyntax && normalAlign.isEmpty() )
+ {
+ if ( oldAlign.isEmpty() )
+ {
+ layout->alignment = "left"; // KWord 0.8 did not support right-to-left
+ }
+ else
+ {
+ const int align = oldAlign.toInt();
+ if ( ( align < 0 ) || ( align > 3) )
+ {
+ kdWarning(30508) << "KWord 0.8 flow unknown: " << oldAlign << endl;
+ layout->alignment = "left"; // Unknown, so assume left
+ }
+ else
+ {
+ const char* flows[]={"left", "right", "center", "justify" };
+ layout->alignment = flows[ align ];
+ }
+ }
+ kdDebug(30508) << "KWord 0.8 flow: " << oldAlign << " corrected: " << layout->alignment << endl;
+ }
+ else
+ {
+ layout->alignment = normalAlign;
+ }
+
+}
+
+
+void ProcessLayoutTag ( TQDomNode myNode, void *tagData, KWEFKWordLeader *leader )
+// Processes <LAYOUT> and <STYLE>
+{
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "outline" ); // Only in <STYLE>
+ ProcessAttributes (myNode, attrProcessingList);
+
+ LayoutData *layout = (LayoutData *) tagData;
+
+ ValueListFormatData formatDataList;
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "NAME", ProcessStringValueTag, &layout->styleName );
+ tagProcessingList << TagProcessing ( "FOLLOWING", ProcessFollowingTag, &layout->styleFollowing );
+ tagProcessingList << TagProcessing ( "FLOW", ProcessFlowTag, layout );
+ tagProcessingList << TagProcessing ( "INDENTS", ProcessIndentsTag, layout );
+ tagProcessingList << TagProcessing ( "OFFSETS", ProcessLayoutOffsetTag, layout );
+ tagProcessingList << TagProcessing ( "LINESPACING", ProcessLinespacingTag, layout );
+ tagProcessingList << TagProcessing ( "PAGEBREAKING", ProcessLineBreakingTag, layout );
+ tagProcessingList << TagProcessing ( "LEFTBORDER", ProcessAnyBorderTag, &layout->leftBorder );
+ tagProcessingList << TagProcessing ( "RIGHTBORDER", ProcessAnyBorderTag, &layout->rightBorder );
+ tagProcessingList << TagProcessing ( "TOPBORDER", ProcessAnyBorderTag, &layout->topBorder );
+ tagProcessingList << TagProcessing ( "BOTTOMBORDER", ProcessAnyBorderTag, &layout->bottomBorder );
+ tagProcessingList << TagProcessing ( "COUNTER", ProcessCounterTag, &layout->counter );
+ tagProcessingList << TagProcessing ( "FORMAT", ProcessFormatTag, &formatDataList );
+ tagProcessingList << TagProcessing ( "TABULATOR", ProcessLayoutTabulatorTag, &layout->tabulatorList );
+ tagProcessingList << TagProcessing ( "SHADOW", ProcessShadowTag, layout );
+
+ if ( leader->m_oldSyntax )
+ {
+ layout->indentLeft = 0.0; // ### TODO: needed or not?
+ tagProcessingList
+ << TagProcessing ( "OHEAD", ProcessOldLayoutChildTag, &layout->marginTop )
+ << TagProcessing ( "OFOOT", ProcessOldLayoutChildTag, &layout->marginBottom )
+ << TagProcessing ( "ILEFT", ProcessOldLayoutChildTag, &layout->indentLeft )
+ << TagProcessing ( "IFIRST", ProcessOldLayoutChildTag, &layout->indentFirst )
+ << TagProcessing ( "LINESPACE", ProcessLineSpaceTag, layout )
+ ;
+ }
+
+ ProcessSubtags (myNode, tagProcessingList, leader);
+
+
+ if ( formatDataList.isEmpty () )
+ {
+ kdWarning (30508) << "No FORMAT tag within LAYOUT/STYLE!" << endl;
+ }
+ else
+ {
+ layout->formatData = formatDataList.first ();
+
+ if ( formatDataList.count () > 1 )
+ {
+ kdWarning (30508) << "More than one FORMAT tag within LAYOUT/STYLE!" << endl;
+ }
+ }
+
+ if ( layout->styleName.isEmpty () )
+ {
+ layout->styleName = "Standard";
+ kdWarning (30508) << "Empty layout name!" << endl;
+ }
+
+}
+
+
+static void ProcessImageKeyTag ( TQDomNode myNode,
+ void *tagData, KWEFKWordLeader *)
+{
+ KoPictureKey *key = (KoPictureKey*) tagData;
+
+ // Let KoPicture do the loading
+ key->loadAttributes(myNode.toElement());
+}
+
+void ProcessImageTag ( TQDomNode myNode,
+ void *tagData, KWEFKWordLeader *leader )
+{ // <PICTURE>
+ TQValueList<AttrProcessing> attrProcessingList;
+ attrProcessingList << AttrProcessing ( "keepAspectRatio" );
+ ProcessAttributes (myNode, attrProcessingList);
+
+ TQValueList<TagProcessing> tagProcessingList;
+ tagProcessingList << TagProcessing ( "KEY", ProcessImageKeyTag, tagData );
+ ProcessSubtags (myNode, tagProcessingList, leader);
+}
+
diff --git a/filters/kword/libexport/TagProcessing.cc b/filters/kword/libexport/TagProcessing.cc
deleted file mode 100644
index b70d58d9b..000000000
--- a/filters/kword/libexport/TagProcessing.cc
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- This file is part of the KDE project
- Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
- Copyright (c) 2001 IABG mbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@IABG.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@GMX.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <kdebug.h>
-#include <tqdom.h>
-
-#include "TagProcessing.h"
-
-#define DEBUG_KWORD_TAGS
-// #define DEBUG_KWORD_IGNORED_TAGS
-
-
-void ProcessSubtags ( const TQDomNode &parentNode,
- TQValueList<TagProcessing> &tagProcessingList,
- KWEFKWordLeader *leader)
-{
- //kdDebug(30508) << "Starting ProcessSubtags for node: " << parentNode.nodeName() << endl;
-
- TQDomNode childNode;
-
- for ( childNode = parentNode.firstChild (); !childNode.isNull (); childNode = childNode.nextSibling () )
- {
- if ( childNode.isElement () )
- {
- bool found = false;
-
- TQValueList<TagProcessing>::Iterator tagProcessingIt;
-
- for ( tagProcessingIt = tagProcessingList.begin ();
- tagProcessingIt != tagProcessingList.end ();
- tagProcessingIt++ )
- {
- if ( childNode.nodeName () == (*tagProcessingIt).name )
- {
- found = true;
-
- if ( (*tagProcessingIt).processor != NULL )
- {
- ((*tagProcessingIt).processor) ( childNode, (*tagProcessingIt).data, leader );
- }
-#ifdef DEBUG_KWORD_IGNORED_TAGS
- else
- {
- kdDebug(30508) << "Ignoring " << childNode.nodeName ()
- << " tag in " << parentNode.nodeName () << endl;
- }
-#endif
- break;
- }
- }
-
- if ( !found )
- {
- kdDebug(30508) << "Unexpected tag " << childNode.nodeName ()
- << " in " << parentNode.nodeName () << "!" << endl;
- }
- }
- }
- //kdDebug(30508) << "Ending ProcessSubtags for node: " << parentNode.nodeName() << endl;
-}
-
-void AllowNoSubtags ( const TQDomNode& myNode, KWEFKWordLeader *leader )
-{
-#ifdef DEBUG_KWORD_TAGS
- TQString outputText;
- TQValueList<TagProcessing> tagProcessingList;
- ProcessSubtags (myNode, tagProcessingList, leader);
-#else
- @_UNUSED( leader ):
-#endif
-}
-
-AttrProcessing::AttrProcessing ( const TQString& n, const TQString& t, void *d )
- : name (n), data (d)
-{
- if ( t == "int" )
- type = AttrInt;
- else if ( t == TQSTRING_OBJECT_NAME_STRING )
- type = AttrTQString;
- else if ( t == "double" )
- type = AttrDouble;
- else if ( t == "bool" )
- type = AttrBool;
- else if ( t.isEmpty() )
- type = AttrNull;
- else
- {
- kdWarning(30508) << "Unknown type: " << t << " for element " << n << " assuming NULL" << endl;
- type = AttrNull;
- }
-}
-
-
-void ProcessAttributes ( const TQDomNode &myNode,
- TQValueList<AttrProcessing> &attrProcessingList )
-{
- //kdDebug(30508) << "Starting ProcessAttributes for node: " << myNode.nodeName() << endl;
-
- TQDomNamedNodeMap myAttribs ( myNode.attributes () );
- //kdDebug(30508) << "Attributes = " << myAttribs.length () <<endl;
- for ( uint i = 0; i < myAttribs.length (); i++ )
- {
- TQDomAttr myAttrib ( myAttribs.item (i).toAttr () );
-
- if ( !myAttrib.isNull () )
- {
- bool found = false;
-
- TQValueList<AttrProcessing>::Iterator attrProcessingIt;
-
- for ( attrProcessingIt = attrProcessingList.begin ();
- attrProcessingIt != attrProcessingList.end ();
- attrProcessingIt++ )
- {
- //kdDebug(30508) << "NAME: " << myAttrib.name () << " == " << (*attrProcessingIt).name <<endl;
- if ( myAttrib.name () == (*attrProcessingIt).name )
- {
- found = true;
-
- if ( (*attrProcessingIt).data != NULL )
- {
- switch ( (*attrProcessingIt).type )
- {
- case AttrProcessing::AttrTQString:
- {
- *((TQString *) (*attrProcessingIt).data) = myAttrib.value ();
- break;
- }
- case AttrProcessing::AttrInt:
- {
- *((int *) (*attrProcessingIt).data) = myAttrib.value ().toInt ();
- break;
- }
- case AttrProcessing::AttrDouble:
- {
- *((double *) (*attrProcessingIt).data) = myAttrib.value ().toDouble ();
- break;
- }
- case AttrProcessing::AttrBool:
- {
- const TQString strAttr ( myAttrib.value().simplifyWhiteSpace() );
- bool flag;
- if ((strAttr=="yes")||(strAttr=="1")||(strAttr=="true"))
- {
- flag=true;
- }
- else if ((strAttr=="no")||(strAttr=="0")||(strAttr=="false"))
- {
- flag=false;
- }
- else
- {
- flag=false;
- kdWarning(30508) << "Unknown value for a boolean: " << strAttr
- << " in tag " << myNode.nodeName () << ", attribute "
- << myAttrib.name() << endl;
- }
- *((bool *) (*attrProcessingIt).data) = flag;
- break;
- }
- case AttrProcessing::AttrNull:
- break;
- default:
- {
- kdDebug(30508) << "Unexpected data type " << int( (*attrProcessingIt).type )
- << " in " << myNode.nodeName ()
- << " attribute " << (*attrProcessingIt).name
- << endl;
- break;
- }
- }
- }
-#ifdef DEBUG_KWORD_IGNORED_TAGS
- else
- {
- kdDebug(30508) << "Ignoring " << myNode.nodeName()
- << " attribute " << (*attrProcessingIt).name
- << endl;
- }
-#endif
- break;
- }
- }
-
- if ( !found )
- {
- kdWarning(30508) << "Unexpected attribute " << myAttrib.name ()
- << " in " << myNode.nodeName () << "!" << endl;
- }
- }
- }
- //kdDebug(30508) << "Ending ProcessAttributes for node: " << myNode.nodeName() << endl;
-}
-
-void AllowNoAttributes ( const TQDomNode & myNode )
-{
-#ifdef DEBUG_KWORD_TAGS
- TQValueList<AttrProcessing> attrProcessingList;
- ProcessAttributes (myNode, attrProcessingList);
-#else
- Q_UNUSED( myNode );
-#endif
-}
diff --git a/filters/kword/libexport/TagProcessing.cpp b/filters/kword/libexport/TagProcessing.cpp
new file mode 100644
index 000000000..46a8fb353
--- /dev/null
+++ b/filters/kword/libexport/TagProcessing.cpp
@@ -0,0 +1,235 @@
+/*
+ This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2004 Nicolas GOUTTE <goutte@kde.org>
+ Copyright (c) 2001 IABG mbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@IABG.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@GMX.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <kdebug.h>
+#include <tqdom.h>
+
+#include "TagProcessing.h"
+
+#define DEBUG_KWORD_TAGS
+// #define DEBUG_KWORD_IGNORED_TAGS
+
+
+void ProcessSubtags ( const TQDomNode &parentNode,
+ TQValueList<TagProcessing> &tagProcessingList,
+ KWEFKWordLeader *leader)
+{
+ //kdDebug(30508) << "Starting ProcessSubtags for node: " << parentNode.nodeName() << endl;
+
+ TQDomNode childNode;
+
+ for ( childNode = parentNode.firstChild (); !childNode.isNull (); childNode = childNode.nextSibling () )
+ {
+ if ( childNode.isElement () )
+ {
+ bool found = false;
+
+ TQValueList<TagProcessing>::Iterator tagProcessingIt;
+
+ for ( tagProcessingIt = tagProcessingList.begin ();
+ tagProcessingIt != tagProcessingList.end ();
+ tagProcessingIt++ )
+ {
+ if ( childNode.nodeName () == (*tagProcessingIt).name )
+ {
+ found = true;
+
+ if ( (*tagProcessingIt).processor != NULL )
+ {
+ ((*tagProcessingIt).processor) ( childNode, (*tagProcessingIt).data, leader );
+ }
+#ifdef DEBUG_KWORD_IGNORED_TAGS
+ else
+ {
+ kdDebug(30508) << "Ignoring " << childNode.nodeName ()
+ << " tag in " << parentNode.nodeName () << endl;
+ }
+#endif
+ break;
+ }
+ }
+
+ if ( !found )
+ {
+ kdDebug(30508) << "Unexpected tag " << childNode.nodeName ()
+ << " in " << parentNode.nodeName () << "!" << endl;
+ }
+ }
+ }
+ //kdDebug(30508) << "Ending ProcessSubtags for node: " << parentNode.nodeName() << endl;
+}
+
+void AllowNoSubtags ( const TQDomNode& myNode, KWEFKWordLeader *leader )
+{
+#ifdef DEBUG_KWORD_TAGS
+ TQString outputText;
+ TQValueList<TagProcessing> tagProcessingList;
+ ProcessSubtags (myNode, tagProcessingList, leader);
+#else
+ @_UNUSED( leader ):
+#endif
+}
+
+AttrProcessing::AttrProcessing ( const TQString& n, const TQString& t, void *d )
+ : name (n), data (d)
+{
+ if ( t == "int" )
+ type = AttrInt;
+ else if ( t == TQSTRING_OBJECT_NAME_STRING )
+ type = AttrTQString;
+ else if ( t == "double" )
+ type = AttrDouble;
+ else if ( t == "bool" )
+ type = AttrBool;
+ else if ( t.isEmpty() )
+ type = AttrNull;
+ else
+ {
+ kdWarning(30508) << "Unknown type: " << t << " for element " << n << " assuming NULL" << endl;
+ type = AttrNull;
+ }
+}
+
+
+void ProcessAttributes ( const TQDomNode &myNode,
+ TQValueList<AttrProcessing> &attrProcessingList )
+{
+ //kdDebug(30508) << "Starting ProcessAttributes for node: " << myNode.nodeName() << endl;
+
+ TQDomNamedNodeMap myAttribs ( myNode.attributes () );
+ //kdDebug(30508) << "Attributes = " << myAttribs.length () <<endl;
+ for ( uint i = 0; i < myAttribs.length (); i++ )
+ {
+ TQDomAttr myAttrib ( myAttribs.item (i).toAttr () );
+
+ if ( !myAttrib.isNull () )
+ {
+ bool found = false;
+
+ TQValueList<AttrProcessing>::Iterator attrProcessingIt;
+
+ for ( attrProcessingIt = attrProcessingList.begin ();
+ attrProcessingIt != attrProcessingList.end ();
+ attrProcessingIt++ )
+ {
+ //kdDebug(30508) << "NAME: " << myAttrib.name () << " == " << (*attrProcessingIt).name <<endl;
+ if ( myAttrib.name () == (*attrProcessingIt).name )
+ {
+ found = true;
+
+ if ( (*attrProcessingIt).data != NULL )
+ {
+ switch ( (*attrProcessingIt).type )
+ {
+ case AttrProcessing::AttrTQString:
+ {
+ *((TQString *) (*attrProcessingIt).data) = myAttrib.value ();
+ break;
+ }
+ case AttrProcessing::AttrInt:
+ {
+ *((int *) (*attrProcessingIt).data) = myAttrib.value ().toInt ();
+ break;
+ }
+ case AttrProcessing::AttrDouble:
+ {
+ *((double *) (*attrProcessingIt).data) = myAttrib.value ().toDouble ();
+ break;
+ }
+ case AttrProcessing::AttrBool:
+ {
+ const TQString strAttr ( myAttrib.value().simplifyWhiteSpace() );
+ bool flag;
+ if ((strAttr=="yes")||(strAttr=="1")||(strAttr=="true"))
+ {
+ flag=true;
+ }
+ else if ((strAttr=="no")||(strAttr=="0")||(strAttr=="false"))
+ {
+ flag=false;
+ }
+ else
+ {
+ flag=false;
+ kdWarning(30508) << "Unknown value for a boolean: " << strAttr
+ << " in tag " << myNode.nodeName () << ", attribute "
+ << myAttrib.name() << endl;
+ }
+ *((bool *) (*attrProcessingIt).data) = flag;
+ break;
+ }
+ case AttrProcessing::AttrNull:
+ break;
+ default:
+ {
+ kdDebug(30508) << "Unexpected data type " << int( (*attrProcessingIt).type )
+ << " in " << myNode.nodeName ()
+ << " attribute " << (*attrProcessingIt).name
+ << endl;
+ break;
+ }
+ }
+ }
+#ifdef DEBUG_KWORD_IGNORED_TAGS
+ else
+ {
+ kdDebug(30508) << "Ignoring " << myNode.nodeName()
+ << " attribute " << (*attrProcessingIt).name
+ << endl;
+ }
+#endif
+ break;
+ }
+ }
+
+ if ( !found )
+ {
+ kdWarning(30508) << "Unexpected attribute " << myAttrib.name ()
+ << " in " << myNode.nodeName () << "!" << endl;
+ }
+ }
+ }
+ //kdDebug(30508) << "Ending ProcessAttributes for node: " << myNode.nodeName() << endl;
+}
+
+void AllowNoAttributes ( const TQDomNode & myNode )
+{
+#ifdef DEBUG_KWORD_TAGS
+ TQValueList<AttrProcessing> attrProcessingList;
+ ProcessAttributes (myNode, attrProcessingList);
+#else
+ Q_UNUSED( myNode );
+#endif
+}
diff --git a/filters/kword/libexport/TagProcessing.h b/filters/kword/libexport/TagProcessing.h
index f2bf46652..62176fd36 100644
--- a/filters/kword/libexport/TagProcessing.h
+++ b/filters/kword/libexport/TagProcessing.h
@@ -20,7 +20,7 @@
/*
This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
The old file was copyrighted by
Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
diff --git a/filters/kword/msword/document.cpp b/filters/kword/msword/document.cpp
index 043c1bc24..2e20b999d 100644
--- a/filters/kword/msword/document.cpp
+++ b/filters/kword/msword/document.cpp
@@ -498,9 +498,9 @@ KoStoreDevice* Document::createPictureFrameSet( const KoSize& size )
// The position doesn't matter as long as the picture is inline
// FIXME for non-inline pics ####
- // To determine the size, look at OOo's filter (WW8PicDesc in ww8graf2.cxx, version 1.50, line 406)
+ // To determine the size, look at OOo's filter (WW8PicDesc in ww8graf2.cpp, version 1.50, line 406)
// Hint: #i17200#, a bit of guesswork I'm afraid
- // if (aPic.dxaGoal == 1000 && aPic.mx == 1) //100% hack ? (from ww8graf2.cxx)
+ // if (aPic.dxaGoal == 1000 && aPic.mx == 1) //100% hack ? (from ww8graf2.cpp)
createInitialFrame( framesetElement, 0, size.width(), 0, size.height(), false, NoFollowup );
TQDomElement pictureElem = m_mainDocument.createElement("PICTURE");
diff --git a/filters/kword/msword/texthandler.cpp b/filters/kword/msword/texthandler.cpp
index 775f8bce8..d25408693 100644
--- a/filters/kword/msword/texthandler.cpp
+++ b/filters/kword/msword/texthandler.cpp
@@ -659,7 +659,7 @@ void KWordTextHandler::writeLayout( TQDomElement& parentElement, const wvWare::P
// which kword doesn't support. We map it to 0 with a clever '%4' :)
tabElement.setAttribute( "type", td.tbd.jc % 4 );
int filling = 0;
- double width = 0.5; // default kword value, see koparaglayout.cc
+ double width = 0.5; // default kword value, see koparaglayout.cpp
switch ( td.tbd.tlc ) {
case 1: // dots
case 2: // hyphenated
diff --git a/filters/kword/mswrite/ImportDialog.cc b/filters/kword/mswrite/ImportDialog.cpp
index cb9834913..cb9834913 100644
--- a/filters/kword/mswrite/ImportDialog.cc
+++ b/filters/kword/mswrite/ImportDialog.cpp
diff --git a/filters/kword/mswrite/Makefile.am b/filters/kword/mswrite/Makefile.am
index c94df3fd0..8bb2ea29d 100644
--- a/filters/kword/mswrite/Makefile.am
+++ b/filters/kword/mswrite/Makefile.am
@@ -6,13 +6,13 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) -I$(srcdir)/../libexport $(all_include
kde_module_LTLIBRARIES = libmswriteimport.la libmswriteexport.la
-libmswriteimport_la_SOURCES = mswriteimport.cc \
- libmswrite_defs.cpp structures_generated.cpp structures_private.cpp structures.cpp libmswrite.cpp ImportDialogUI.ui ImportDialog.cc
+libmswriteimport_la_SOURCES = mswriteimport.cpp \
+ libmswrite_defs.cpp structures_generated.cpp structures_private.cpp structures.cpp libmswrite.cpp ImportDialogUI.ui ImportDialog.cpp
libmswriteimport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libmswriteimport_la_LIBADD = $(KOFFICE_LIBS)
-libmswriteexport_la_SOURCES = mswriteexport.cc \
+libmswriteexport_la_SOURCES = mswriteexport.cpp \
libmswrite_defs.cpp structures_generated.cpp structures_private.cpp structures.cpp libmswrite.cpp
libmswriteexport_la_LDFLAGS = -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libmswriteexport_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KOWMF) ../libexport/libkwordexportfilters.la
diff --git a/filters/kword/mswrite/mswriteexport.cc b/filters/kword/mswrite/mswriteexport.cpp
index abf007f88..abf007f88 100644
--- a/filters/kword/mswrite/mswriteexport.cc
+++ b/filters/kword/mswrite/mswriteexport.cpp
diff --git a/filters/kword/mswrite/mswriteimport.cc b/filters/kword/mswrite/mswriteimport.cpp
index 7fd3b63e3..7fd3b63e3 100644
--- a/filters/kword/mswrite/mswriteimport.cc
+++ b/filters/kword/mswrite/mswriteimport.cpp
diff --git a/filters/kword/mswrite/status.html b/filters/kword/mswrite/status.html
index 5a8bddd15..9d70e7b21 100644
--- a/filters/kword/mswrite/status.html
+++ b/filters/kword/mswrite/status.html
@@ -99,7 +99,7 @@
<br>
<b> Version 0.3-1: KOffice 1.2 Beta1 </b> <br>
- - fixed mswritelib.cc crash on files with an unusual font table <br>
+ - fixed mswritelib.cpp crash on files with an unusual font table <br>
- emulates image position from left margin by using paragraph indents <br>
- WMFs now render correctly in KWord (thanks to Lorthiois Thierry); note that only TQWMF code was changed <br>
- gcc 2.95.3 internal error workaround <br>
diff --git a/filters/kword/oowriter/ExportFilter.cc b/filters/kword/oowriter/ExportFilter.cc
deleted file mode 100644
index 216ace492..000000000
--- a/filters/kword/oowriter/ExportFilter.cc
+++ /dev/null
@@ -1,2229 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <tqmap.h>
-#include <tqiodevice.h>
-#include <tqbuffer.h>
-#include <tqtextstream.h>
-#include <tqdom.h>
-
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kzip.h>
-
-#include <KoPageLayout.h>
-#include <KoPictureKey.h>
-#include <KoPicture.h>
-
-#include <KWEFStructures.h>
-#include <KWEFUtil.h>
-#include <KWEFBaseWorker.h>
-#include <KWEFKWordLeader.h>
-
-#include "ExportFilter.h"
-
-OOWriterWorker::OOWriterWorker(void) : m_streamOut(NULL),
- m_paperBorderTop(0.0),m_paperBorderLeft(0.0),
- m_paperBorderBottom(0.0),m_paperBorderRight(0.0), m_zip(NULL), m_pictureNumber(0),
- m_automaticParagraphStyleNumber(0), m_automaticTextStyleNumber(0),
- m_footnoteNumber(0), m_tableNumber(0), m_textBoxNumber( 0 ),
- m_columnspacing( 36.0 ), m_columns( 1 )
-{
-}
-
-TQString OOWriterWorker::escapeOOText(const TQString& strText) const
-{
- // Escape quotes (needed in attributes)
- // Escape apostrophs (allowed by XML)
- return KWEFUtil::EscapeSgmlText(NULL,strText,true,true);
-}
-
-TQString OOWriterWorker::escapeOOSpan(const TQString& strText) const
-// We need not only to escape the classical XML stuff but also to take care of spaces and tabs.
-{
- TQString strReturn;
- TQChar ch;
- int spaceNumber = 0; // How many spaces should be written
-
- for (uint i=0; i<strText.length(); i++)
- {
- ch=strText[i];
-
- if (ch!=' ')
- {
- // The next character is not a space (anymore)
- if ( spaceNumber > 0 )
- {
- strReturn += ' ';
- --spaceNumber;
- if ( spaceNumber > 0 )
- {
- strReturn += "<text:s text:c=\"";
- strReturn += TQString::number( spaceNumber );
- strReturn += "\"/>";
- }
- spaceNumber = 0;
- }
- }
-
- // ### TODO: would be switch/case or if/elseif the best?
- switch (ch.unicode())
- {
- case 9: // Tab
- {
- strReturn+="<text:tab-stop/>";
- break;
- }
- case 10: // Line-feed
- {
- strReturn+="<text:line-break/>";
- break;
- }
- case 32: // Space
- {
- if ( spaceNumber > 0 )
- {
- ++spaceNumber;
- }
- else
- {
- spaceNumber = 1;
- }
- break;
- }
- case 38: // &
- {
- strReturn+="&amp;";
- break;
- }
- case 60: // <
- {
- strReturn+="&lt;";
- break;
- }
- case 62: // >
- {
- strReturn+="&gt;";
- break;
- }
- case 34: // "
- {
- strReturn+="&quot;";
- break;
- }
- case 39: // '
- {
- strReturn+="&apos;";
- break;
- }
- case 1: // (Non-XML-compatible) replacement character from KWord 0.8
- {
- strReturn += '#'; //use KWord 1.[123] replacement character instead
- break;
- }
- // Following characters are not allowed in XML (but some files from KWord 0.8 have some of them.)
- case 0:
- case 2:
- case 3:
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 11:
- case 12:
- case 14:
- case 15:
- case 16:
- case 17:
- case 18:
- case 19:
- case 20:
- case 21:
- case 22:
- case 23:
- case 24:
- case 25:
- case 26:
- case 27:
- case 28:
- case 29:
- case 30:
- case 31:
- {
- kdWarning(30518) << "Not allowed XML character: " << ch.unicode() << endl;
- strReturn += '?';
- break;
- }
- case 13: // ### TODO: what to do with it?
- default:
- {
- strReturn+=ch;
- break;
- }
- }
- }
-
- if ( spaceNumber > 0 )
- {
- // The last characters were spaces
- strReturn += ' ';
- --spaceNumber;
- if ( spaceNumber > 0 )
- {
- strReturn += "<text:s text:c=\"";
- strReturn += TQString::number( spaceNumber );
- strReturn += "\"/>";
- }
- spaceNumber = 0;
- }
-
- return strReturn;
-}
-
-bool OOWriterWorker::doOpenFile(const TQString& filenameOut, const TQString& )
-{
- kdDebug(30518) << "Opening file: " << filenameOut
- << " (in OOWriterWorker::doOpenFile)" << endl;
-
- m_zip=new KZip(filenameOut); // How to check failure?
-
- if (!m_zip->open(IO_WriteOnly))
- {
- kdError(30518) << "Could not open ZIP file for writing! Aborting!" << endl;
- delete m_zip;
- m_zip=NULL;
- return false;
- }
-
- m_zip->setCompression( KZip::NoCompression );
- m_zip->setExtraField( KZip::NoExtraField );
-
- const TQCString appId( "application/vnd.sun.xml.writer" );
-
- m_zip->writeFile( "mimetype", TQString(), TQString(), appId.length(), appId.data() );
-
- m_zip->setCompression( KZip::DeflateCompression );
-
- m_streamOut=new TQTextStream(m_contentBody, IO_WriteOnly);
-
- m_streamOut->setEncoding( TQTextStream::UnicodeUTF8 );
-
- return true;
-}
-
-bool OOWriterWorker::zipPrepareWriting(const TQString& name)
-{
- if (!m_zip)
- return false;
- m_size=0;
- return m_zip->prepareWriting(name, TQString(), TQString(), 0);
-}
-
-bool OOWriterWorker::zipDoneWriting(void)
-{
- if (!m_zip)
- return false;
- return m_zip->doneWriting(m_size);
-}
-
-bool OOWriterWorker::zipWriteData(const char* str)
-{
- if (!m_zip)
- return false;
- const uint size=strlen(str);
- m_size+=size;
- return m_zip->writeData(str,size);
-}
-
-bool OOWriterWorker::zipWriteData(const TQByteArray& array)
-{
- if (!m_zip)
- return false;
- const uint size=array.size();
- m_size+=size;
- return m_zip->writeData(array.data(),size);
-}
-
-bool OOWriterWorker::zipWriteData(const TQCString& cstr)
-{
- if (!m_zip)
- return false;
- const uint size=cstr.length();
- m_size+=size;
- return m_zip->writeData(cstr.data(),size);
-}
-
-bool OOWriterWorker::zipWriteData(const TQString& str)
-{
- return zipWriteData(str.utf8());
-}
-
-void OOWriterWorker::writeStartOfFile(const TQString& type)
-{
- const bool noType=type.isEmpty();
- zipWriteData("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-
- zipWriteData("<!DOCTYPE office:document");
- if (!noType)
- {
- // No type might happen for raw XML documents (which this filter does not support yet.)
- zipWriteData("-");
- zipWriteData(type);
- }
- zipWriteData(" PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\"");
- zipWriteData(" \"office.dtd\"");
- zipWriteData(">\n");
-
- zipWriteData("<office:document");
- if (!noType)
- {
- zipWriteData("-");
- zipWriteData(type);
- }
-
- // The name spaces used by OOWriter (those not used by this filter are commented out)
-
- // General namespaces
- zipWriteData(" xmlns:office=\"http://openoffice.org/2000/office\"");
- zipWriteData(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"");
-
- // Namespaces for context.xml and style.xml
- if ( type == "content" || type == "styles" || type.isEmpty() )
- {
- zipWriteData(" xmlns:style=\"http://openoffice.org/2000/style\"");
- zipWriteData(" xmlns:text=\"http://openoffice.org/2000/text\"");
- zipWriteData(" xmlns:table=\"http://openoffice.org/2000/table\"");
- zipWriteData(" xmlns:draw=\"http://openoffice.org/2000/drawing\"");
- zipWriteData(" xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"");
-
- //zipWriteData(" xmlns:number=\"http://openoffice.org/2000/datastyle\"");
- zipWriteData(" xmlns:svg=\"http://www.w3.org/2000/svg\"");
- //zipWriteData(" xmlns:chart=\"http://openoffice.org/2000/chart\"");
- //zipWriteData(" xmlns:dr3d=\"http://openoffice.org/2000/dr3d\"");
- //zipWriteData(" xmlns:math=\"http://www.w3.org/1998/Math/MathML"");
- //zipWriteData(" xmlns:form=\"http://openoffice.org/2000/form\"");
- //zipWriteData(" xmlns:script=\"http://openoffice.org/2000/script\"");
- }
-
- // Namespaces For meta.xml
- if ( type == "meta" || type.isEmpty() )
- {
- zipWriteData(" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"");
- zipWriteData(" xmlns:meta=\"http://openoffice.org/2000/meta\"");
- }
-
- zipWriteData(" office:class=\"text\"");
-
-
-#ifdef STRICT_OOWRITER_VERSION_1
- zipWriteData(" office:version=\"1.0\"");
-#else
- // We are using an (rejected draft OASIS) extension compared to version 1.0, so we cannot write the version string.
- // (We do not even write it for context.xml and meta.xml, as OOWriter 1.0.1 does not like it in this case.)
-#endif
-
- zipWriteData(">\n");
-}
-
-void OOWriterWorker::writeFontDeclaration(void)
-{
- zipWriteData( " <office:font-decls>\n");
- TQMap<TQString,TQString>::ConstIterator end(m_fontNames.end());
- for (TQMap<TQString,TQString>::ConstIterator it=m_fontNames.begin(); it!=end; ++it)
- {
- const bool space=(it.key().find(' ')>=0); // Does the font has at least a space in its name
- const TQString fontName(escapeOOText(it.key()));
- zipWriteData(" <style:font-decl style:name=\"");
- zipWriteData(fontName);
- zipWriteData("\" fo:font-family=\"");
- if (space)
- { // It has a space, so (simple) quote it
- zipWriteData("&apos;");
- zipWriteData(fontName);
- zipWriteData("&apos;");
- }
- else
- { // The font has no space in its name, so it can be written normally.
- zipWriteData(fontName);
- }
- zipWriteData("\" ");
- zipWriteData(it.data()); // already in XML, so do not escape
- zipWriteData(" />\n");
- }
- zipWriteData(" </office:font-decls>\n");
-}
-
-void OOWriterWorker::writeStylesXml(void)
-{
- if (!m_zip)
- return;
-
- zipPrepareWriting("styles.xml");
-
- writeStartOfFile("styles");
-
- writeFontDeclaration();
-
- zipWriteData(m_styles);
-
- zipWriteData(" <office:automatic-styles>\n");
- zipWriteData(" <style:page-master style:name=\"pm1\">\n"); // ### TODO: verify if style name is unique
-
- zipWriteData(" <style:properties ");
- zipWriteData( " style:page-usage=\"all\"" ); // ### TODO: check
-
- zipWriteData(" fo:page-width=\"");
- zipWriteData(TQString::number(m_paperWidth));
- zipWriteData("pt\" fo:page-height=\"");
- zipWriteData(TQString::number(m_paperHeight));
- zipWriteData("pt\" ");
-
- zipWriteData("style:print-orientation=\"");
- if (1==m_paperOrientation)
- {
- zipWriteData("landscape");
- }
- else
- {
- zipWriteData("portrait");
- }
-
- zipWriteData("\" fo:margin-top=\"");
- zipWriteData(TQString::number(m_paperBorderTop));
- zipWriteData("pt\" fo:margin-bottom=\"");
- zipWriteData(TQString::number(m_paperBorderBottom));
- zipWriteData("pt\" fo:margin-left=\"");
- zipWriteData(TQString::number(m_paperBorderLeft));
- zipWriteData("pt\" fo:margin-right=\"");
- zipWriteData(TQString::number(m_paperBorderRight));
- zipWriteData("pt\" style:first-page-number=\"");
- zipWriteData(TQString::number(m_varSet.startingPageNumber));
- zipWriteData( "\">\n" );
-
- if ( m_columns > 1 )
- {
- zipWriteData( " <style:columns" );
- zipWriteData( " fo:column-count=\"" );
- zipWriteData( TQString::number( m_columns ) );
- zipWriteData( "\" fo:column-gap=\"" );
- zipWriteData( TQString::number( m_columnspacing ) );
- zipWriteData( "pt\">\n" );
-
- for (int i=0; i < m_columns; ++i)
- {
- zipWriteData( " <style:column style:rel-width=\"1*\" fo:margin-left=\"0cm\" fo:margin-right=\"0cm\"/>\n" );
- }
-
- zipWriteData( " </style:columns>\n" );
- }
-
- zipWriteData(" </style:properties>\n");
-
- zipWriteData(" </style:page-master>\n");
- zipWriteData(" </office:automatic-styles>\n");
-
- zipWriteData(" <office:master-styles>\n");
- zipWriteData(" <style:master-page style:name=\"Standard\" style:page-master-name=\"pm1\" />\n");
- zipWriteData(" </office:master-styles>\n");
-
- zipWriteData( "</office:document-styles>\n" );
-
- zipDoneWriting();
-}
-
-void OOWriterWorker::writeContentXml(void)
-{
- if (!m_zip)
- return;
-
- zipPrepareWriting("content.xml");
-
- writeStartOfFile("content");
-
- writeFontDeclaration();
-
- zipWriteData(" <office:automatic-styles>\n");
- zipWriteData(m_contentAutomaticStyles);
- m_contentAutomaticStyles = TQString(); // Release memory
-
- zipWriteData(" </office:automatic-styles>\n");
-
- zipWriteData(m_contentBody);
- m_contentBody.resize( 0 ); // Release memory
-
- zipWriteData( "</office:document-content>\n" );
-
- zipDoneWriting();
-}
-
-void OOWriterWorker::writeMetaXml(void)
-{
- if (!m_zip)
- return;
-
- zipPrepareWriting("meta.xml");
-
- writeStartOfFile("meta");
-
- zipWriteData(" <office:meta>\n");
-
- // Tell who we are in case that we have a bug in our filter output!
- zipWriteData(" <meta:generator>KWord's OOWriter Export Filter");
- zipWriteData(TQString("$Revision: 515673 $").mid(10).remove('$')); // has a leading and a trailing space.
-
- zipWriteData("</meta:generator>\n");
-
- if (!m_docInfo.title.isEmpty())
- {
- zipWriteData(" <dc:title>");
- zipWriteData(escapeOOText(m_docInfo.title));
- zipWriteData("</dc:title>\n");
- }
- if (!m_docInfo.abstract.isEmpty())
- {
- zipWriteData(" <dc:description>");
- zipWriteData(escapeOOText(m_docInfo.abstract));
- zipWriteData("</dc:description>\n");
- }
-
- if (m_varSet.creationTime.isValid())
- {
- zipWriteData(" <meta:creation-date>");
- zipWriteData(escapeOOText(m_varSet.creationTime.toString(Qt::ISODate)));
- zipWriteData("</meta:creation-date>\n");
- }
-
- if (m_varSet.modificationTime.isValid())
- {
- zipWriteData(" <dc:date>");
- zipWriteData(escapeOOText(m_varSet.modificationTime.toString(Qt::ISODate)));
- zipWriteData("</dc:date>\n");
- }
-
- if (m_varSet.printTime.isValid())
- {
- zipWriteData(" <meta:print-date>");
- zipWriteData(escapeOOText(m_varSet.printTime.toString(Qt::ISODate)));
- zipWriteData("</meta:print-date>\n");
- }
-
- zipWriteData( " <meta:document-statistic" );
-
- // KWord files coming from import filters mostly do not have no page count
- if ( m_numPages > 0 )
- {
- zipWriteData( " meta:page-count=\"" );
- zipWriteData( TQString::number ( m_numPages ) );
- zipWriteData( "\"" );
- }
-
- zipWriteData( " meta:image-count=\"" ); // This is not specified in the OO specification section 2.1.19
- zipWriteData( TQString::number ( m_pictureNumber ) );
- zipWriteData( "\"" );
-
- zipWriteData( " meta:table-count=\"" );
- zipWriteData( TQString::number ( m_tableNumber ) );
- zipWriteData( "\"" );
-
- zipWriteData( "/>\n" ); // meta:document-statistic
-
- zipWriteData(" </office:meta>\n");
- zipWriteData("</office:document-meta>\n");
-
- zipDoneWriting();
-}
-
-bool OOWriterWorker::doCloseFile(void)
-{
- kdDebug(30518)<< "OOWriterWorker::doCloseFile" << endl;
- if (m_zip)
- {
- writeContentXml();
- writeMetaXml();
- writeStylesXml();
- m_zip->close();
- }
-
- delete m_zip;
- m_zip=NULL;
- return true;
-}
-
-bool OOWriterWorker::doOpenDocument(void)
-{
- kdDebug(30518)<< "OOWriterWorker::doOpenDocument" << endl;
-
- *m_streamOut << " <office:body>\n";
-
- return true;
-}
-
-bool OOWriterWorker::doCloseDocument(void)
-{
- *m_streamOut << " </office:body>\n";
- return true;
-}
-
-bool OOWriterWorker::doOpenBody(void)
-{
- TQValueList<FrameAnchor>::Iterator it;
-
- // We have to process all non-inline pictures
- kdDebug(30518) << "=== Processing non-inlined pictures ===" << endl;
- for ( it = m_nonInlinedPictureAnchors.begin(); it != m_nonInlinedPictureAnchors.end(); ++it )
- {
- *m_streamOut << " ";
- makePicture( *it, AnchorNonInlined );
- *m_streamOut << "\n";
- }
- kdDebug(30518) << "=== Non-inlined pictures processed ===" << endl;
-
- // We have to process all non-inline tables
- kdDebug(30518) << "=== Processing non-inlined tables ===" << endl;
- for ( it = m_nonInlinedTableAnchors.begin(); it != m_nonInlinedTableAnchors.end(); ++it )
- {
- *m_streamOut << " ";
- makeTable( *it, AnchorNonInlined );
- *m_streamOut << "\n";
- }
- kdDebug(30518) << "=== Non-inlined tables processed ===" << endl;
-
- return true;
-}
-
-TQString OOWriterWorker::textFormatToStyle(const TextFormatting& formatOrigin,
- const TextFormatting& formatData, const bool force, TQString& key)
-{
- // TODO: rename variable formatData
- TQString strElement; // TODO: rename this variable
-
- // Font name
- TQString fontName = formatData.fontName;
- declareFont(fontName);
- if ( !fontName.isEmpty()
- && (force || (formatOrigin.fontName!=formatData.fontName)))
- {
- strElement+="style:font-name=\"";
- strElement+= escapeOOText(fontName);
- strElement+="\" ";
- key += fontName;
- }
-
- key += ",";
-
- if (force || (formatOrigin.italic!=formatData.italic))
- {
- // Font style
- strElement+="fo:font-style=\"";
- if ( formatData.italic )
- {
- strElement+="italic";
- key+='I';
- }
- else
- {
- strElement+="normal";
- key+='N';
- }
- strElement+="\" ";
- }
-
- key += ",";
-
- if (force || ((formatOrigin.weight>=75)!=(formatData.weight>=75)))
- {
- strElement+="fo:font-weight=\"";
- if ( formatData.weight >= 75 )
- {
- strElement+="bold";
- key+='B';
- }
- else
- {
- strElement+="normal";
- key+='N';
- }
- strElement+="\" ";
- }
-
- key += ",";
-
- if (force || (formatOrigin.fontSize!=formatData.fontSize))
- {
- const int size=formatData.fontSize;
- if (size>0)
- {
- strElement+="fo:font-size=\"";
- strElement+=TQString::number(size,10);
- strElement+="pt\" ";
- key+=TQString::number(size,10);
- }
- }
-
- key += ",";
-
- if (force || (formatOrigin.fgColor!=formatData.fgColor))
- {
- if ( formatData.fgColor.isValid() )
- {
- strElement+="fo:color=\"";
- strElement+=formatData.fgColor.name();
- strElement+="\" ";
- key+=formatData.fgColor.name();
- }
- }
-
- key += ",";
-
- if (force || (formatOrigin.bgColor!=formatData.bgColor))
- {
- if ( formatData.bgColor.isValid() )
- {
- strElement+="style:text-background-color=\""; // ### what is fo:background-color ?
- strElement+=formatData.bgColor.name();
- strElement+="\" ";
- key+=formatData.bgColor.name();
- }
- }
-
- key += ';'; // Another separator
-
- if ( force || ( formatOrigin.underline != formatData.underline )
- || ( formatOrigin.underlineColor != formatData.underlineColor )
- || ( formatOrigin.underlineValue != formatData.underlineValue )
- || ( formatOrigin.underlineStyle != formatData.underlineStyle ) )
- {
- strElement+="style:text-underline=\"";
- if ( formatData.underline )
- {
- TQString underlineValue ( formatData.underlineValue );
- TQString underlineStyle ( formatData.underlineStyle );
-
- if ( underlineStyle.isEmpty() )
- underlineStyle = "solid";
- if ( underlineValue == "1" )
- underlineValue = "single";
-
- if ( underlineValue == "single" )
- {
- if ( underlineStyle == "dash" )
- {
- strElement += "dash";
- key += "DA";
- }
- else if ( underlineStyle == "dot" )
- {
- strElement += "dotted";
- key += "DO";
- }
- else if ( underlineStyle == "dashdot" )
- {
- strElement += "dot-dash";
- key += "DDA";
- }
- else if ( underlineStyle == "dashdotdot" )
- {
- strElement += "dot-dot-dash";
- key += "DDDA";
- }
- else
- {
- strElement += "single";
- key += "1";
- }
- }
- else if ( underlineValue == "double" )
- {
- strElement += "double";
- key += "2";
- }
- else if ( underlineValue == "single-bold" )
- {
- strElement += "bold";
- key += "BL";
- }
- else if ( underlineValue == "wave" )
- {
- strElement += "wave";
- key += "WV";
- }
- else
- {
- strElement += "single";
- key += "?";
- }
- }
- else
- {
- strElement+="none";
- key += 'N';
- }
- strElement += "\" ";
-
- if ( formatData.underline && formatData.underlineColor.isValid() )
- {
- const TQString colorName( formatData.underlineColor.name() );
- strElement += "style:text-underline-color=\"";
- strElement += colorName;
- strElement += "\" ";
- key += colorName;
- }
-
- }
-
- key += ',';
-
- if ( force
- || (formatOrigin.strikeout != formatData.strikeout )
- || (formatOrigin.strikeoutType != formatData.strikeoutType ) )
- {
- // OOWriter can only do single, double, thick (and slash and X that KWord cannot do.)
- // So no dash, dot and friends.
-
- strElement+="style:text-crossing-out=\"";
- if ( ( formatData.strikeoutType == "single" ) || ( formatData.strikeoutType == "1" ) )
- {
- strElement+="single-line";
- key += "1";
- }
- else if ( formatData.strikeoutType == "double" )
- {
- strElement+="double-line";
- key += "2";
- }
- else if ( formatData.strikeoutType == "single-bold" )
- {
- strElement+="thick";
- key += "T";
- }
- else
- {
- strElement+="none";
- key += 'N';
- }
- strElement+="\" ";
- }
-
- key += ',';
-
- // It seems that OOWriter 1.1 does have problems with word-by-word (OO Issue #11873, #25187)
- // It is supposed to be fixed in development versions of OO
- if (force || ( formatOrigin.underlineWord != formatData.underlineWord )
- || (formatOrigin.strikeoutWord != formatData.strikeoutWord ) )
- {
- // Strikeout and underline can only have one word-by-word behaviour in OO
- // (OO Issue #????? ; will not be changed.)
- strElement+="fo:score-spaces=\""; // Are space processed?
- if ( formatData.underlineWord || formatData.strikeoutWord )
- {
- strElement += "false";
- key += 'W';
- }
- else
- {
- strElement += "true";
- key += 'N';
- }
- strElement += "\" ";
- }
-
- key += ',';
-
- if ( force || ( formatOrigin.language != formatData.language ) )
- {
- const TQString lang ( formatData.language );
- if ( ! lang.isEmpty() )
- {
- const int res = lang.find( '_' );
-
- if ( res >= 0 )
- {
- kdDebug(30518) << "Language: " << lang << " => " << lang.left( res ) << " - " << lang.mid( res + 1 ) << endl;
- strElement += "fo:language=\"";
- strElement += lang.left( res );
- strElement += "\" ";
- strElement += "fo:country=\"";
- strElement += lang.mid( res + 1 );
- strElement += "\" ";
- }
- else
- {
- kdDebug(30518) << "Language without country: " << lang << endl;
- strElement += "fo:language=\"";
- strElement += lang;
- strElement += "\" ";
- }
-
- key+=formatData.language;
- }
- }
-
- key += ",";
-
- if ( force || ( formatOrigin.fontAttribute != formatData.fontAttribute ) )
- {
- // Note: OOWriter does not like when both fo:text-transform and fo:font-variant exist (except if both are none/normal)
- // (It is documented so, see sections 3.10.1 and 3.10.2)
- if ( formatData.fontAttribute == "uppercase" )
- {
- strElement += "fo:text-transform=\"uppercase\" ";
- key += 'U';
- }
- else if ( formatData.fontAttribute == "lowercase" )
- {
- strElement += "fo:text-transform=\"lowercase\" ";
- key += 'L';
- }
- else if ( formatData.fontAttribute == "smallcaps" )
- {
- strElement += "fo:font-variant=\"small-caps\" ";
- key += 'S';
- }
- else
- {
- strElement += "fo:text-transform=\"none\" ";
- strElement += "fo:font-variant=\"normal\" ";
- key += 'N';
- }
- }
-
- key += ",";
-
- if ( force || ( formatOrigin.verticalAlignment != formatData.verticalAlignment ) )
- {
- if ( 1 == formatData.verticalAlignment )
- {
- //Subscript
- strElement += "style:text-position=\"sub\" ";
- key += 'B';
- }
- else if ( 2 == formatData.verticalAlignment )
- {
- //Superscript
- strElement += "style:text-position=\"super\" ";
- key += 'P';
- }
- // ### TODO: how to reset it? "0pt" ?
- }
-
- return strElement.stripWhiteSpace(); // Remove especially trailing spaces
-}
-
-#define ALLOW_TABLE
-
-TQString OOWriterWorker::cellToProperties( const TableCell& cell, TQString& key) const
-{
-#ifdef ALLOW_TABLE
- const FrameData& frame = cell.frame;
- TQString properties;
-
- key += "!L"; // left border
- key += frame.lColor.name();
- key += ",";
- key += TQString::number( frame.lWidth );
- properties += " fo:border-left=\"";
- if ( frame.lColor.isValid() && frame.lWidth > 0.0 )
- {
- properties += TQString::number( frame.lWidth );
- properties += "pt";
- properties += " solid "; // ### TODO
- properties += frame.lColor.name();
- }
- else
- {
- properties += "0pt none #000000";
- }
- properties += "\"";
-
- key += "!R"; // right border
- key += frame.rColor.name();
- key += ",";
- key += TQString::number( frame.rWidth );
- properties += " fo:border-right=\"";
- if ( frame.rColor.isValid() && frame.rWidth > 0.0 )
- {
- properties += TQString::number( frame.rWidth );
- properties += "pt";
- properties += " solid "; // ### TODO
- properties += frame.rColor.name();
- }
- else
- {
- properties += "0pt none #000000";
- }
- properties += "\"";
-
- key += "!T"; // top border
- key += frame.tColor.name();
- key += ",";
- key += TQString::number( frame.tWidth );
- properties += " fo:border-top=\"";
- if ( frame.tColor.isValid() && frame.tWidth > 0.0 )
- {
- properties += TQString::number( frame.tWidth );
- properties += "pt";
- properties += " solid "; // ### TODO
- properties += frame.tColor.name();
- }
- else
- {
- properties += "0pt none #000000";
- }
- properties += "\"";
-
- key += "!B"; // bottom border
- key += frame.bColor.name();
- key += ",";
- key += TQString::number( frame.bWidth );
- properties += " fo:border-bottom=\"";
- if ( frame.bColor.isValid() && frame.bWidth > 0.0 )
- {
- properties += TQString::number( frame.bWidth );
- properties += "pt";
- properties += " solid "; // ### TODO
- properties += frame.bColor.name();
- }
- else
- {
- properties += "0pt none #000000";
- }
- properties += "\"";
-
- return properties;
-#else
- return TQString();
-#endif
-}
-
-bool OOWriterWorker::makeTableRows( const TQString& tableName, const Table& table, int firstRowNumber )
-{
-#ifdef ALLOW_TABLE
- // ### TODO: rows
- // ### TODO: be careful that covered-cell can be due vertical spanning.
- // ### TODO: One way to find is the difference between the row variables (or against the last known column)
- // ### TODO: be careful that fully-covered rows might exist.
-
- *m_streamOut << "<table:table-row>\n";
- int rowCurrent = firstRowNumber;
-
- ulong cellNumber = 0L;
-
- TQMap<TQString,TQString> mapCellStyleKeys;
-
- for ( TQValueList<TableCell>::ConstIterator itCell ( table.cellList.begin() );
- itCell != table.cellList.end(); ++itCell)
- {
- if ( rowCurrent != (*itCell).row )
- {
- rowCurrent = (*itCell).row;
- *m_streamOut << "</table:table-row>\n";
- *m_streamOut << "<table:table-row>\n";
- }
-
- TQString key;
- const TQString props ( cellToProperties( (*itCell), key ) );
-
- TQString automaticCellStyle;
- TQMap<TQString,TQString>::ConstIterator it ( mapCellStyleKeys.find( key ) );
- if ( it == mapCellStyleKeys.end() )
- {
- automaticCellStyle = makeAutomaticStyleName( tableName + ".Cell", cellNumber );
- mapCellStyleKeys [ key ] = automaticCellStyle;
- kdDebug(30518) << "Creating automatic cell style: " << automaticCellStyle << " key: " << key << endl;
- m_contentAutomaticStyles += " <style:style";
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticCellStyle ) + "\"";
- m_contentAutomaticStyles += " style:family=\"table-cell\"";
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties ";
- m_contentAutomaticStyles += props;
- m_contentAutomaticStyles += "/>\n";
- m_contentAutomaticStyles += " </style:style>\n";
- }
- else
- {
- automaticCellStyle = it.data();
- kdDebug(30518) << "Using automatic cell style: " << automaticCellStyle << " key: " << key << endl;
- }
-
- *m_streamOut << "<table:table-cell table:value-type=\"string\" table:style-name=\""
- << escapeOOText( automaticCellStyle)
- << "\"";
-
- // More than one column width?
- {
- *m_streamOut << " table:number-columns-spanned=\"" << (*itCell).m_cols << "\"";
- }
-
- *m_streamOut << ">\n";
-
- if (!doFullAllParagraphs(*(*itCell).paraList))
- {
- return false;
- }
-
- *m_streamOut << "</table:table-cell>\n";
-
- if ( (*itCell).m_cols > 1 )
- {
- // We need to add some placeholder for the "covered" cells
- for (int i = 1; i < (*itCell).m_cols; ++i)
- {
- *m_streamOut << "<table:covered-table-cell/>";
- }
- }
- }
-
- *m_streamOut << "</table:table-row>\n";
- return true;
-#else
- return false;
-#endif
-}
-
-#ifdef ALLOW_TABLE
-static uint getColumnWidths( const Table& table, TQMemArray<double>& widthArray, int firstRowNumber )
-{
- bool uniqueColumns = true; // We have not found any horizontally spanned cells yet.
- uint currentColumn = 0;
- int tryingRow = firstRowNumber; // We are trying the first row
- TQValueList<TableCell>::ConstIterator itCell;
-
- for ( itCell = table.cellList.begin();
- itCell != table.cellList.end(); ++itCell )
- {
- kdDebug(30518) << "Column: " << (*itCell).col << " (Row: " << (*itCell).row << ")" << endl;
-
- if ( (*itCell).row != tryingRow )
- {
- if ( uniqueColumns )
- {
- // We had a full row without any horizontally spanned cell, so we have the needed data
- return currentColumn;
- }
- else
- {
- // No luck in the previous row, so now try this new one
- tryingRow = (*itCell).row;
- uniqueColumns = true;
- currentColumn = 0;
- }
- }
-
- if ( (*itCell).m_cols > 1 )
- {
- // We have a horizontally spanned cell
- uniqueColumns = false;
- // Do not waste the time to calculate the width
- continue;
- }
-
- const double width = ( (*itCell).frame.right - (*itCell).frame.left );
-
- if ( currentColumn >= widthArray.size() )
- widthArray.resize( currentColumn + 4, TQGArray::SpeedOptim);
-
- widthArray.at( currentColumn ) = width;
- ++currentColumn;
- }
-
- // If we are here, it can be:
- // - the table is either empty or there is not any row without horizontally spanned cells
- // - we have needed the last row for getting something usable
-
- return uniqueColumns ? currentColumn : 0;
-}
-#endif
-
-#ifdef ALLOW_TABLE
-static uint getFirstRowColumnWidths( const Table& table, TQMemArray<double>& widthArray, int firstRowNumber )
-// Get the column widths only by the first row.
-// This is used when all table rows have horizontally spanned cells.
-{
- uint currentColumn = 0;
- TQValueList<TableCell>::ConstIterator itCell;
-
- for ( itCell = table.cellList.begin();
- itCell != table.cellList.end(); ++itCell )
- {
- kdDebug(30518) << "Column: " << (*itCell).col << " (Row: " << (*itCell).row << ")" << endl;
- if ( (*itCell).row != firstRowNumber )
- break; // We have finished the first row
-
- int cols = (*itCell).m_cols;
- if ( cols < 1)
- cols = 1;
-
- // ### FIXME: the columns behind a larger cell do not need to be symmetrical
- const double width = ( (*itCell).frame.right - (*itCell).frame.left ) / cols;
-
- if ( currentColumn + cols > widthArray.size() )
- widthArray.resize( currentColumn + 4, TQGArray::SpeedOptim);
-
- for ( int i = 0; i < cols; ++i )
- {
- widthArray.at( currentColumn ) = width;
- ++currentColumn;
- }
- }
- return currentColumn;
-}
-#endif
-
-bool OOWriterWorker::makeTable( const FrameAnchor& anchor, const AnchorType anchorType )
-{
-#ifdef ALLOW_TABLE
-
- // Be careful that while being similar the following 5 strings have different purposes
- const TQString automaticTableStyle ( makeAutomaticStyleName( "Table", m_tableNumber ) ); // It also increases m_tableNumber
- const TQString tableName( TQString( "Table" ) + TQString::number( m_tableNumber ) ); // m_tableNumber was already increased
- const TQString translatedName( i18n( "Object name", "Table %1").arg( m_tableNumber ) );
- const TQString automaticFrameStyle ( makeAutomaticStyleName( "TableFrame", m_textBoxNumber ) ); // It also increases m_textBoxNumber
- const TQString translatedFrameName( i18n( "Object name", "Table Frame %1").arg( m_textBoxNumber ) );
-
- kdDebug(30518) << "Processing table " << anchor.key.toString() << " => " << tableName << endl;
-
- const TQValueList<TableCell>::ConstIterator firstCell ( anchor.table.cellList.begin() );
-
- if ( firstCell == anchor.table.cellList.end() )
- {
- kdError(30518) << "Table has not any cell!" << endl;
- return false;
- }
-
- const int firstRowNumber = (*firstCell).row;
- kdDebug(30518) << "First row: " << firstRowNumber << endl;
-
- TQMemArray<double> widthArray(4);
-
- uint numberColumns = getColumnWidths( anchor.table, widthArray, firstRowNumber );
-
- if ( numberColumns <= 0 )
- {
- kdDebug(30518) << "Could not get correct column widths, so approximating" << endl;
- // There was a problem, the width array cannot be trusted, so try to do a column width array with the first row
- numberColumns = getFirstRowColumnWidths( anchor.table, widthArray, firstRowNumber );
- if ( numberColumns <= 0 )
- {
- // Still not right? Then it is an error!
- kdError(30518) << "Cannot get column widths of table " << anchor.key.toString() << endl;
- return false;
- }
- }
-
- kdDebug(30518) << "Number of columns: " << numberColumns << endl;
-
-
- double tableWidth = 0.0; // total width of table
- uint i; // We need the loop variable 2 times
- for ( i=0; i < numberColumns; ++i )
- {
- tableWidth += widthArray.at( i );
- }
- kdDebug(30518) << "Table width: " << tableWidth << endl;
-
- // An inlined table, is an "as-char" text-box
- *m_streamOut << "<draw:text-box";
- *m_streamOut << " style:name=\"" << escapeOOText( automaticFrameStyle ) << "\"";
- *m_streamOut << " draw:name=\"" << escapeOOText( translatedFrameName ) << "\"";
- if ( anchorType == AnchorNonInlined )
- {
- // ### TODO: correctly set a OOWriter frame positioned on the page
- *m_streamOut << " text:anchor-type=\"paragraph\"";
- }
- else
- {
- *m_streamOut << " text:anchor-type=\"as-char\"";
- }
- *m_streamOut << " svg:width=\"" << tableWidth << "pt\""; // ### TODO: any supplement to the width?
- //*m_streamOut << " fo:min-height=\"1pt\"";// ### TODO: a better height (can be calulated from the KWord table frames)
- *m_streamOut << ">\n";
-
- *m_streamOut << "<table:table table:name=\""
- << escapeOOText( translatedName )
- << "\" table:style-name=\""
- << escapeOOText( automaticTableStyle )
- << "\" >\n";
-
-
- // Now we have enough information to generate the style for the table and its frame
-
- kdDebug(30518) << "Creating automatic frame style: " << automaticFrameStyle /* << " key: " << styleKey */ << endl;
- m_contentAutomaticStyles += " <style:style"; // for frame
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticFrameStyle ) + "\"";
- m_contentAutomaticStyles += " style:family=\"graphics\"";
- m_contentAutomaticStyles += " style:parent-style-name=\"Frame\""; // ### TODO: parent style needs to be correctly defined
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties "; // ### TODO
- m_contentAutomaticStyles += " text:anchor-type=\"as-char\""; // ### TODO: needed?
- m_contentAutomaticStyles += " fo:padding=\"0pt\" fo:border=\"none\"";
- m_contentAutomaticStyles += " fo:margin-left=\"0pt\"";
- m_contentAutomaticStyles += " fo:margin-top=\"0pt\"";
- m_contentAutomaticStyles += " fo:margin-bottom=\"0pt\"";
- m_contentAutomaticStyles += " fo:margin-right=\"0pt\"";
- m_contentAutomaticStyles += "/>\n";
- m_contentAutomaticStyles += " </style:style>\n";
-
- kdDebug(30518) << "Creating automatic table style: " << automaticTableStyle /* << " key: " << styleKey */ << endl;
- m_contentAutomaticStyles += " <style:style"; // for table
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticTableStyle ) + "\"";
- m_contentAutomaticStyles += " style:family=\"table\"";
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties ";
- m_contentAutomaticStyles += " style:width=\"" + TQString::number( tableWidth ) + "pt\" ";
- m_contentAutomaticStyles += "/>\n";
- m_contentAutomaticStyles += " </style:style>\n";
-
- TQValueList<TableCell>::ConstIterator itCell;
-
- ulong columnNumber = 0L;
-
- for ( i=0; i < numberColumns; ++i )
- {
- const TQString automaticColumnStyle ( makeAutomaticStyleName( tableName + ".Column", columnNumber ) );
- kdDebug(30518) << "Creating automatic column style: " << automaticColumnStyle /* << " key: " << styleKey */ << endl;
-
- m_contentAutomaticStyles += " <style:style";
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticColumnStyle ) + "\"";
- m_contentAutomaticStyles += " style:family=\"table-column\"";
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties ";
- // Despite that some OO specification examples use fo:width, OO specification section 4.19 tells to use style:column-width
- // and/or the relative variant: style:rel-column-width
- m_contentAutomaticStyles += " style:column-width=\"" + TQString::number( widthArray.at( i ) ) + "pt\" ";
- m_contentAutomaticStyles += "/>\n";
- m_contentAutomaticStyles += " </style:style>\n";
-
- // ### TODO: find a way how to use table:number-columns-repeated for more that one cell's column(s)
- *m_streamOut << "<table:table-column table:style-name=\""
- << escapeOOText( automaticColumnStyle )
- << "\" table:number-columns-repeated=\"1\"/>\n";
- }
-
- makeTableRows( tableName, anchor.table, firstRowNumber );
-
- *m_streamOut << "</table:table>\n";
-
- *m_streamOut << "</draw:text-box>"; // End of inline
-
-#endif
- return true;
-}
-
-bool OOWriterWorker::makePicture( const FrameAnchor& anchor, const AnchorType anchorType )
-{
- kdDebug(30518) << "New picture: " << anchor.picture.koStoreName
- << " , " << anchor.picture.key.toString() << endl;
-
- const TQString koStoreName(anchor.picture.koStoreName);
-
- TQByteArray image;
-
- TQString strExtension(koStoreName.lower());
- const int result=koStoreName.findRev(".");
- if (result>=0)
- {
- strExtension=koStoreName.mid(result+1);
- }
-
- bool isImageLoaded=false;
-
- if (strExtension=="png")
- {
- isImageLoaded=loadSubFile(koStoreName,image);
- }
- else if ((strExtension=="jpg") || (strExtension=="jpeg"))
- {
- isImageLoaded=loadSubFile(koStoreName,image);
- strExtension="jpg"; // ### TODO: verify
- }
- else if ((strExtension=="tif") || (strExtension=="tiff"))
- {
- isImageLoaded=loadSubFile(koStoreName,image);
- strExtension="tif"; // ### TODO: verify
- }
- else if ((strExtension=="gif") || (strExtension=="wmf"))
- // ### TODO: Which other image formats does OOWriter support directly?
- {
- isImageLoaded=loadSubFile(koStoreName,image);
- }
- else
- {
- // All other picture types must be converted to PNG
- isImageLoaded=loadAndConvertToImage(koStoreName,strExtension,"PNG",image);
- strExtension="png";
- }
-
- if (!isImageLoaded)
- {
- kdWarning(30518) << "Unable to load picture: " << koStoreName << endl;
- return true;
- }
-
- kdDebug(30518) << "Picture loaded: " << koStoreName << endl;
-
- double height = 0.0;
- double width = 0.0;
-
- if ( anchorType == AnchorTextImage )
- {
- // Text image have no frameset, so the only size information is in the picture itself.
- TQBuffer buffer( image.copy() ); // Be more safe than sorry and do not allow shallow copy
- KoPicture pic;
- buffer.open( IO_ReadOnly );
- if ( pic.load( TQT_TQIODEVICE(&buffer), strExtension ) )
- {
- const TQSize size ( pic.getOriginalSize() );
- height = size.height();
- width = size.width();
- }
- else
- {
- kdWarning(30518) << "Could not load KoPicture: " << koStoreName << endl;
- }
- buffer.close();
- }
- else
- {
- // Use frame size
- height=anchor.frame.bottom - anchor.frame.top;
- width =anchor.frame.right - anchor.frame.left;
- }
-
- if ( height < 1.0 )
- {
- kdWarning(30518) << "Silly height for " << koStoreName << " : " << height << endl;
- height = 72.0;
- }
- if ( width < 1.0 )
- {
- kdWarning(30518) << "Silly width for " << koStoreName << " : " << width << endl;
- width = 72.0;
- }
-
- // We need a 32 digit hex value of the picture number
- // Please note: it is an exact 32 digit value, truncated if the value is more than 512 bits wide. :-)
- TQString number;
- number.fill('0',32);
- number += TQString::number(++m_pictureNumber,16); // in hex
-
- TQString ooName("Pictures/");
- ooName += number.right(32);
- ooName += '.';
- ooName += strExtension;
-
- kdDebug(30518) << "Picture " << koStoreName << " => " << ooName << endl;
-
- // TODO: we are only using the filename, not the rest of the key
- // TODO: (bad if there are two images of the same name, but of a different key)
- *m_streamOut << "<draw:image draw:name=\"" << anchor.picture.key.filename() << "\"";
- *m_streamOut << " draw:style-name=\"Graphics\""; // ### TODO: should be an automatic "graphic" style name instead
- if ( anchorType == AnchorNonInlined )
- {
- // ### TODO: correctly set a OOWriter frame positioned on the page
- *m_streamOut << " text:anchor-type=\"paragraph\"";
- }
- else
- {
- *m_streamOut << " text:anchor-type=\"as-char\"";
- }
- *m_streamOut << " svg:height=\"" << height << "pt\" svg:width=\"" << width << "pt\"";
- *m_streamOut << " draw:z-index=\"0\" xlink:href=\"#" << ooName << "\"";
- *m_streamOut << " xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"";
- *m_streamOut << "/>"; // NO end of line!
-
- if (m_zip)
- {
-#if 0
- // ### FIXME Why is the following line not working (at least with KDE 3.1)? (It makes unzip having problems with meta.xml)
- m_zip->writeFile(ooName,TQString(), TQString(), image.size(), image.data());
-#else
- zipPrepareWriting(ooName);
- zipWriteData( image );
- zipDoneWriting();
-#endif
- }
-
- return true;
-}
-
-void OOWriterWorker::processNormalText ( const TQString &paraText,
- const TextFormatting& formatLayout,
- const FormatData& formatData)
-{
- // Retrieve text and escape it (and necessary space, tabs and line-break tags)
- const TQString partialText( escapeOOSpan( paraText.mid( formatData.pos, formatData.len ) ) );
-
- if (formatData.text.missing)
- {
- // It's just normal text, so we do not need a <text:span> element!
- *m_streamOut << partialText;
- }
- else
- { // Text with properties, so use a <text:span> element!
- *m_streamOut << "<text:span";
-
- TQString styleKey;
- const TQString props ( textFormatToStyle(formatLayout,formatData.text,false,styleKey) );
-
- TQMap<TQString,TQString>::ConstIterator it ( m_mapTextStyleKeys.find(styleKey) );
- kdDebug(30518) << "Searching text key: " << styleKey << endl;
-
- TQString automaticStyle;
- if (it==m_mapTextStyleKeys.end())
- {
- // We have not any match, so we need a new automatic text style
- automaticStyle=makeAutomaticStyleName("T", m_automaticTextStyleNumber);
- kdDebug(30518) << "Creating automatic text style: " << automaticStyle << " key: " << styleKey << endl;
- m_mapTextStyleKeys[styleKey]=automaticStyle;
-
- m_contentAutomaticStyles += " <style:style";
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText(automaticStyle) + "\"";
- m_contentAutomaticStyles += " style:family=\"text\"";
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties ";
- m_contentAutomaticStyles += props;
- m_contentAutomaticStyles += "/>\n";
- m_contentAutomaticStyles += " </style:style>\n";
- }
- else
- {
- // We have a match, so use the already defined automatic text style
- automaticStyle=it.data();
- kdDebug(30518) << "Using automatic text style: " << automaticStyle << " key: " << styleKey << endl;
- }
-
- *m_streamOut << " text:style-name=\"" << escapeOOText(automaticStyle) << "\" ";
-
- *m_streamOut << ">" << partialText << "</text:span>";
- }
-}
-
-void OOWriterWorker::processFootnote( const VariableData& variable )
-{
- // Footnote
- const TQValueList<ParaData> *paraList = variable.getFootnotePara();
- if( paraList )
- {
- const TQString value ( variable.getFootnoteValue() );
- //const bool automatic = formatData.variable.getFootnoteAuto();
- const bool flag = variable.getFootnoteType();
-
- if ( flag )
- {
- *m_streamOut << "<text:footnote text:id=\"ft";
- *m_streamOut << (++m_footnoteNumber);
- *m_streamOut << "\">";
- *m_streamOut << "<text:footnote-citation>" << escapeOOText( value ) << "</text:footnote-citation>";
- *m_streamOut << "<text:footnote-body>\n";
-
- doFullAllParagraphs( *paraList );
-
- *m_streamOut << "\n</text:footnote-body>";
- *m_streamOut << "</text:footnote>";
- }
- else
- {
- *m_streamOut << "<text:endnote text:id=\"ft";
- *m_streamOut << (++m_footnoteNumber);
- *m_streamOut << "\">";
- *m_streamOut << "<text:endnote-citation>" << escapeOOText( value ) << "</text:endnote-citation>";
- *m_streamOut << "<text:endnote-body>\n";
-
- doFullAllParagraphs( *paraList );
-
- *m_streamOut << "\n</text:endnote-body>";
- *m_streamOut << "</text:endnote>";
- }
- }
-}
-
-void OOWriterWorker::processNote( const VariableData& variable )
-{
- // KWord 1.3's annotations are anonymous and undated,
- // however the OO specification tells that author and date are mandatory (even if OOWriter 1.1 consider them optional)
-
- *m_streamOut << "<office:annotation office:create-date=\"";
-
- // We use the document creation date as creation date for the annotation
- // (OOWriter uses only the date part, there is no time part)
- if ( m_varSet.creationTime.isValid() )
- *m_streamOut << escapeOOText( m_varSet.creationTime.date().toString( Qt::ISODate ) );
- else
- *m_streamOut << "1970-01-01";
-
- *m_streamOut << "\" office:author=\"";
-
- // We try to use the document author's name as annotation author
- if ( m_docInfo.fullName.isEmpty() )
- *m_streamOut << escapeOOText( i18n( "Pseudo-author for annotations", "KWord 1.3" ) );
- else
- *m_streamOut << escapeOOText( m_docInfo.fullName );
-
- *m_streamOut << "\">\n";
- *m_streamOut << "<text:p>"
- << escapeOOSpan( variable.getGenericData( "note" ) )
- << "</text:p>\n"
- << "</office:annotation>";
-}
-
-void OOWriterWorker::processVariable ( const TQString&,
- const TextFormatting& /*formatLayout*/,
- const FormatData& formatData)
-{
- if (0==formatData.variable.m_type)
- {
- *m_streamOut << "<text:date/>"; // ### TODO: parameters
- }
- else if (2==formatData.variable.m_type)
- {
- *m_streamOut << "<text:time/>"; // ### TODO: parameters
- }
- else if (4==formatData.variable.m_type)
- {
- // ### TODO: the other under-types, other parameters
- if (formatData.variable.isPageNumber())
- {
- *m_streamOut << "<text:page-number text:select-page=\"current\"/>";
- }
- else if (formatData.variable.isPageCount())
- {
- *m_streamOut << "<text:page-count/>";
- }
- else
- {
- // Unknown subtype, therefore write out the result
- *m_streamOut << formatData.variable.m_text;
- }
- }
- else if (9==formatData.variable.m_type)
- {
- // A link
- *m_streamOut << "<text:a xlink:href=\""
- << escapeOOText(formatData.variable.getHrefName())
- << "\" xlink:type=\"simple\">"
- << escapeOOText(formatData.variable.getLinkName())
- << "</text:a>";
- }
- else if ( 10 == formatData.variable.m_type )
- { // Note (OOWriter: annotation)
- processNote ( formatData.variable );
- }
- else if (11==formatData.variable.m_type)
- {
- // Footnote
- processFootnote ( formatData.variable );
- }
- else
- {
- // Generic variable
- *m_streamOut << formatData.variable.m_text;
- }
-}
-
-void OOWriterWorker::processAnchor ( const TQString&,
- const TextFormatting& /*formatLayout*/, //TODO
- const FormatData& formatData)
-{
- // We have a picture or a table
- if ( (2==formatData.frameAnchor.type) // <IMAGE> or <PICTURE>
- || (5==formatData.frameAnchor.type) ) // <CLIPART>
- {
- makePicture( formatData.frameAnchor, AnchorInlined );
- }
- else if (6==formatData.frameAnchor.type)
- {
- makeTable( formatData.frameAnchor, AnchorInlined );
- }
- else
- {
- kdWarning(30518) << "Unsupported anchor type: "
- << formatData.frameAnchor.type << endl;
- }
-}
-
-void OOWriterWorker::processTextImage ( const TQString&,
- const TextFormatting& /*formatLayout*/,
- const FormatData& formatData)
-{
- kdDebug(30518) << "Text Image: " << formatData.frameAnchor.key.toString() << endl;
- makePicture( formatData.frameAnchor, AnchorTextImage );
-}
-
-void OOWriterWorker::processParagraphData ( const TQString &paraText,
- const TextFormatting& formatLayout,
- const ValueListFormatData &paraFormatDataList)
-{
- if ( paraText.length () > 0 )
- {
- ValueListFormatData::ConstIterator paraFormatDataIt;
-
- for ( paraFormatDataIt = paraFormatDataList.begin ();
- paraFormatDataIt != paraFormatDataList.end ();
- paraFormatDataIt++ )
- {
- if (1==(*paraFormatDataIt).id)
- {
- processNormalText(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if (2==(*paraFormatDataIt).id)
- {
- processTextImage(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if ( 3 == (*paraFormatDataIt).id )
- {
- // Just a (KWord 0.8) tab stop, nothing else to do!
- *m_streamOut << "<text:tab-stop/>";
- }
- else if (4==(*paraFormatDataIt).id)
- {
- processVariable(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if (6==(*paraFormatDataIt).id)
- {
- processAnchor(paraText, formatLayout, (*paraFormatDataIt));
- }
- else if ( 1001 == (*paraFormatDataIt).id ) // Start of bookmark
- {
- *m_streamOut << "<text:bookmark-start text:name=\""
- << escapeOOText( (*paraFormatDataIt).variable.m_text )
- <<"\"/>";
- }
- else if ( 1002 == (*paraFormatDataIt).id ) // End of bookmark
- {
- *m_streamOut << "<text:bookmark-end text:name=\""
- << escapeOOText( (*paraFormatDataIt).variable.m_text )
- <<"\"/>";
- }
- }
- }
-}
-
-TQString OOWriterWorker::layoutToParagraphStyle(const LayoutData& layoutOrigin,
- const LayoutData& layout, const bool force, TQString& styleKey)
-{
- TQString props; // Props has to remain empty, if there is no difference.
-
- styleKey += layout.styleName;
- styleKey += ',';
-
- if (force || (layoutOrigin.alignment!=layout.alignment))
- {
- // NOTE: OO 1.0.x uses start and end like left and right (section 3.11.4)
- // Unfortunately in XSL-FO's text-align, they are really supposed to be the start and the end.
- if (layout.alignment == "left")
- {
- props += "fo:text-align=\"start\" ";
- styleKey += 'L';
- }
- else if (layout.alignment == "right")
- {
- props += "fo:text-align=\"end\" ";
- styleKey += 'R';
- }
- else if (layout.alignment == "center")
- {
- props += "fo:text-align=\"center\" ";
- styleKey += 'C';
- }
- else if (layout.alignment == "justify")
- {
- props += "fo:text-align=\"justify\" ";
- styleKey += 'J';
- }
- else if (layout.alignment == "auto")
- {
- props += "fo:text-align=\"start\" ";
-#ifndef STRICT_OOWRITER_VERSION_1
- props += "style:text-auto-align=\"true\" "; // rejected draft OASIS extension
-#endif
- styleKey += 'A';
- }
- else
- {
- kdWarning(30518) << "Unknown alignment: " << layout.alignment << endl;
- }
- }
-
- styleKey += ',';
-
- if ((layout.indentLeft>=0.0)
- && (force || (layoutOrigin.indentLeft!=layout.indentLeft)))
- {
- props += TQString("fo:margin-left=\"%1pt\" ").arg(layout.indentLeft);
- styleKey += TQString::number(layout.indentLeft);
- }
-
- styleKey += ',';
-
- if ((layout.indentRight>=0.0)
- && (force || (layoutOrigin.indentRight!=layout.indentRight)))
- {
- props += TQString("fo:margin-right=\"%1pt\" ").arg(layout.indentRight);
- styleKey += TQString::number(layout.indentRight);
- }
-
- styleKey += ',';
-
- if (force || (layoutOrigin.indentLeft!=layout.indentLeft))
- {
- props += "fo:text-indent=\"";
- props += TQString::number(layout.indentFirst);
- props += "\" ";
- styleKey += TQString::number(layout.indentFirst);
- }
-
- styleKey += ',';
-
- if ((layout.marginBottom>=0.0)
- && ( force || ( layoutOrigin.marginBottom != layout.marginBottom ) ) )
- {
- props += TQString("fo:margin-bottom=\"%1pt\" ").arg(layout.marginBottom);
- styleKey += TQString::number(layout.marginBottom);
- }
-
- styleKey += ',';
-
- if ((layout.marginTop>=0.0)
- && ( force || ( layoutOrigin.marginTop != layout.marginTop ) ) )
- {
- props += TQString("fo:margin-top=\"%1pt\" ").arg(layout.marginTop);
- styleKey += TQString::number(layout.marginTop);
- }
-
- styleKey += ',';
-
- if (force
- || ( layoutOrigin.lineSpacingType != layout.lineSpacingType )
- || ( layoutOrigin.lineSpacing != layout.lineSpacing ) )
- {
- switch ( layout.lineSpacingType )
- {
- case LayoutData::LS_CUSTOM:
- {
- // We have a custom line spacing (in points)
- const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
- props += "style:line-spacing=\"";
- props += height;
- props += "pt\" ";
- styleKey += height;
- styleKey += 'C';
- break;
- }
- case LayoutData::LS_SINGLE:
- {
- props += "fo:line-height=\"normal\" "; // One
- styleKey += "100%"; // One
- break;
- }
- case LayoutData::LS_ONEANDHALF:
- {
- props += "fo:line-height=\"150%\" "; // One-and-half
- styleKey += "150%";
- break;
- }
- case LayoutData::LS_DOUBLE:
- {
- props += "fo:line-height=\"200%\" "; // Two
- styleKey += "200%";
- break;
- }
- case LayoutData::LS_MULTIPLE:
- {
- // OOWriter 1.1 only allows up to 200%
- const TQString mult ( TQString::number( tqRound( layout.lineSpacing * 100 ) ) );
- props += "fo:line-height=\"";
- props += mult;
- props += "%\" ";
- styleKey += mult;
- styleKey += "%";
- break;
- }
- case LayoutData::LS_FIXED:
- {
- // We have a fixed line height (in points)
- const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
- props += "fo:line-height=\"";
- props += height;
- props += "pt\" ";
- styleKey += height;
- styleKey += 'F';
- break;
- }
- case LayoutData::LS_ATLEAST:
- {
- // We have a at-least line height (in points)
- const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
- props += "style:line-height-at-least=\"";
- props += height;
- props += "pt\" ";
- styleKey += height;
- styleKey += 'A';
- break;
- }
- default:
- {
- kdWarning(30518) << "Unsupported lineSpacingType: " << layout.lineSpacingType << " (Ignoring!)" << endl;
- break;
- }
- }
- }
-
- styleKey += ',';
-
- if ( layout.pageBreakBefore )
- {
- // We have a page break before the paragraph
- props += "fo:page-break-before=\"page\" ";
- styleKey += 'B';
- }
-
- styleKey += ',';
-
- if ( layout.pageBreakAfter )
- {
- // We have a page break after the paragraph
- props += "fo:page-break-after=\"page\" ";
- styleKey += 'A';
- }
-
- styleKey += '@'; // A more visible seperator
-
- props += textFormatToStyle(layoutOrigin.formatData.text,layout.formatData.text,force,styleKey);
-
- props += ">";
-
- styleKey += '@'; // A more visible seperator
-
- // ### TODO/FIXME: what if all tabulators must be erased?
- if (!layout.tabulatorList.isEmpty()
- && (force || (layoutOrigin.tabulatorList!=layout.tabulatorList) ))
- {
- props += "\n <style:tab-stops>\n";
- TabulatorList::ConstIterator it;
- TabulatorList::ConstIterator end(layout.tabulatorList.end());
- for (it=layout.tabulatorList.begin();it!=end;++it)
- {
- props+=" <style:tab-stop style:position=\"";
- props += TQString::number((*it).m_ptpos);
- props += "pt\"";
- styleKey += TQString::number((*it).m_ptpos);
- switch ((*it).m_type)
- {
- case 0: props += " style:type=\"left\""; styleKey += "L"; break;
- case 1: props += " style:type=\"center\""; styleKey += "C"; break;
- case 2: props += " style:type=\"right\""; styleKey += "R"; break;
- case 3: props += " style:type=\"char\" style:char=\".\""; styleKey += "D"; break; // decimal
- default: props += " style:type=\"left\""; styleKey += "L"; break;
- }
- switch ((*it).m_filling) // ### TODO: check if the characters are right
- {
- case TabulatorData::TF_NONE: break;
- case TabulatorData::TF_DOT: props += " style:leader-char=\".\""; break;
- case TabulatorData::TF_LINE: props += " style:leader-char=\"_\""; break;
-
- case TabulatorData::TF_DASH:
- case TabulatorData::TF_DASHDOT:
- case TabulatorData::TF_DASHDOTDOT: props += " style:leader-char=\"-\""; break;
-
- default: break;
- }
- props += "/>\n";
- styleKey +='/';
- }
- props += " </style:tab-stops>\n ";
- }
-
- return props;
-}
-
-bool OOWriterWorker::doFullParagraph(const TQString& paraText, const LayoutData& layout,
- const ValueListFormatData& paraFormatDataList)
-{
- const bool header = ( (layout.counter.numbering == CounterData::NUM_CHAPTER)
- && (layout.counter.depth<10) ); // ### TODO: Does OOWriter really limits to 10?
-
- if (header)
- {
- *m_streamOut << " <text:h text:level=\"";
- *m_streamOut << TQString::number(layout.counter.depth+1,10);
- *m_streamOut << "\" ";
- }
- else
- *m_streamOut << " <text:p ";
-
- const LayoutData& styleLayout=m_styleMap[layout.styleName];
-
- TQString styleKey;
- const TQString props(layoutToParagraphStyle(styleLayout,layout,false,styleKey));
-
- TQString actualStyle(layout.styleName);
- if (!props.isEmpty())
- {
- TQMap<TQString,TQString>::ConstIterator it ( m_mapParaStyleKeys.find(styleKey) );
- kdDebug(30518) << "Searching paragraph key: " << styleKey << endl;
-
- TQString automaticStyle;
-
- if (it==m_mapParaStyleKeys.end())
- {
- // We have additional properties, so we need an automatic style for the paragraph
- automaticStyle = makeAutomaticStyleName("P", m_automaticParagraphStyleNumber);
- kdDebug(30518) << "Creating automatic paragraph style: " << automaticStyle << " key: " << styleKey << endl;
- m_mapParaStyleKeys[styleKey]=automaticStyle;
-
- m_contentAutomaticStyles += " <style:style";
- m_contentAutomaticStyles += " style:name=\"" + escapeOOText(automaticStyle) + "\"";
- m_contentAutomaticStyles += " style:parent-style-name=\"" + escapeOOText(layout.styleName) + "\"";
- m_contentAutomaticStyles += " style:family=\"paragraph\" style:class=\"text\"";
- m_contentAutomaticStyles += ">\n";
- m_contentAutomaticStyles += " <style:properties ";
- m_contentAutomaticStyles += props;
- m_contentAutomaticStyles += "</style:properties>\n";
- m_contentAutomaticStyles += " </style:style>\n";
- }
- else
- {
- // We have a match, so use the already defined automatic paragraph style
- automaticStyle=it.data();
- kdDebug(30518) << "Using automatic paragraph style: " << automaticStyle << " key: " << styleKey << endl;
- }
-
- actualStyle=automaticStyle;
- }
-
- if (!actualStyle.isEmpty())
- {
- *m_streamOut << "text:style-name=\"" << escapeOOText(actualStyle) << "\" ";
- }
- else
- { // SHould not happen
- kdWarning(30518) << "No style for a paragraph!" << endl;
- }
-
- *m_streamOut << ">";
-
- processParagraphData(paraText, layout.formatData.text, paraFormatDataList);
-
- if (header)
- *m_streamOut << "</text:h>\n";
- else
- *m_streamOut << "</text:p>\n";
-
- return true;
-}
-
-bool OOWriterWorker::doOpenStyles(void)
-{
- m_styles += " <office:styles>\n";
- m_styles += " <style:style style:name=\"Graphics\" style:family=\"graphics\">\n"; // ### TODO: what if Graphics is a normal style
- m_styles += " <style:properties text:anchor-type=\"paragraph\" style:wrap=\"none\"/>\n";
- m_styles += " </style:style>\n";
- m_styles += " <style:style style:name=\"Frame\" style:family=\"graphics\">\n"; // ### TODO: what if Frame is a normal style
- m_styles += " <style:properties text:anchor-type=\"paragraph\" style:wrap=\"none\"/>\n";
- m_styles += " </style:style>\n";
- return true;
-}
-
-bool OOWriterWorker::doFullDefineStyle(LayoutData& layout)
-{
- //Register style in the style map
- m_styleMap[layout.styleName]=layout;
-
- m_styles += " <style:style";
-
- m_styles += " style:name=\"" + escapeOOText( layout.styleName ) + "\"";
- m_styles += " style:next-style-name=\"" + escapeOOText( layout.styleFollowing ) + "\"";
- m_styles += " style:family=\"paragraph\" style:class=\"text\"";
- m_styles += ">\n";
- m_styles += " <style:properties ";
-
- TQString debugKey; // Not needed
- m_styles += layoutToParagraphStyle(layout,layout,true,debugKey);
- kdDebug(30518) << "Defining style: " << debugKey << endl;
-
- m_styles += "</style:properties>\n";
- m_styles += " </style:style>\n";
-
- return true;
-}
-
-bool OOWriterWorker::doCloseStyles(void)
-{
- m_styles += " </office:styles>\n";
- return true;
-}
-
-bool OOWriterWorker::doFullPaperFormat(const int format,
- const double width, const double height, const int orientation)
-{
- if ( ( format < 0 ) // Be careful that 0 is ISO A3
- || ( width < 1.0 )
- || ( height < 1.0 ) )
- {
- kdWarning(30518) << "Page size problem: format: " << format << " width: " << width << " height: " << height << endl;
- // Something is wrong with the page size
- KoFormat newFormat = KoFormat ( format );
- if ( ( format < 0 ) || ( format > PG_LAST_FORMAT ) )
- {
- // Bad or unknown format, so assume ISO A4
- newFormat = PG_DIN_A4;
- }
- m_paperWidth = KoPageFormat::width ( newFormat, KoOrientation( orientation ) ) * 72.0 / 25.4 ;
- m_paperHeight = KoPageFormat::height ( newFormat, KoOrientation( orientation ) ) * 72.0 / 25.4 ;
- m_paperFormat = newFormat;
- }
- else
- {
- m_paperFormat=format;
- m_paperWidth=width;
- m_paperHeight=height;
- }
- m_paperOrientation=orientation; // ### TODO: check if OOWriter needs the orignal size (without landscape) or the real size
- return true;
-}
-
-bool OOWriterWorker::doFullPaperBorders (const double top, const double left,
- const double bottom, const double right)
-{
- m_paperBorderTop=top;
- m_paperBorderLeft=left;
- m_paperBorderBottom=bottom;
- m_paperBorderRight=right;
- return true;
-}
-
-bool OOWriterWorker::doFullPaperFormatOther ( const int columns, const double columnspacing, const int numPages )
-{
- m_columns = columns;
- m_columnspacing = columnspacing;
- m_numPages = numPages;
- return true;
-}
-
-bool OOWriterWorker::doFullDocumentInfo(const KWEFDocumentInfo& docInfo)
-{
- m_docInfo=docInfo;
-
- return true;
-}
-
-bool OOWriterWorker::doVariableSettings(const VariableSettingsData& vs)
-{
- m_varSet=vs;
-
- return true;
-}
-
-bool OOWriterWorker::doDeclareNonInlinedFramesets( TQValueList<FrameAnchor>& pictureAnchors, TQValueList<FrameAnchor>& tableAnchors )
-{
- m_nonInlinedPictureAnchors = pictureAnchors;
- m_nonInlinedTableAnchors = tableAnchors;
- return true;
-}
-
-void OOWriterWorker::declareFont(const TQString& fontName)
-{
- if (fontName.isEmpty())
- return;
-
- if (m_fontNames.find(fontName)==m_fontNames.end())
- {
- TQString props;
-
- // Disabled, as TQFontInfo::styleHint() cannot guess
-#if 0
- TQFont font(fontName);
- TQFontInfo info(font);
- props+="style:font-family-generic=\""
- switch (info.styleHint())
- {
- case TQFont::SansSerif:
- default:
- {
- props += "swiss";
- break;
- }
- case TQFont::Serif:
- {
- props += "roman";
- break;
- }
- case TQFont::Courier:
- {
- props += "modern";
- break;
- }
- case TQFont::OldEnglish:
- {
- props += "decorative";
- break;
- }
- }
- props +="\" ";
-#endif
-
- props +="style:font-pitch=\"variable\""; // ### TODO: check if font is variable or fixed
- // New font, so register it
- m_fontNames[fontName]=props;
- }
-}
-
-TQString OOWriterWorker::makeAutomaticStyleName(const TQString& prefix, ulong& counter) const
-{
- const TQString str (prefix + TQString::number(++counter,10));
-
- // Checks if the automatic style has not the same name as a user one.
- // If it is the case, change it!
-
- if (m_styleMap.find(str)==m_styleMap.end())
- return str; // Unique, so let's go!
-
- TQString str2(str+"_bis");
- if (m_styleMap.find(str2)==m_styleMap.end())
- return str2;
-
- str2 = str+"_ter";
- if (m_styleMap.find(str2)==m_styleMap.end())
- return str2;
-
- // If it is still not unique, try a time stamp.
- const TQDateTime dt(TQDateTime::currentDateTime(Qt::UTC));
-
- str2 = str + "_" + TQString::number(dt.toTime_t(),16);
- if (m_styleMap.find(str2)==m_styleMap.end())
- return str2;
-
- kdWarning(30518) << "Could not make an unique style name: " << str2 << endl;
- return str2; // Still return, as we have nothing better
-}
-
diff --git a/filters/kword/oowriter/ExportFilter.cpp b/filters/kword/oowriter/ExportFilter.cpp
new file mode 100644
index 000000000..0894d0443
--- /dev/null
+++ b/filters/kword/oowriter/ExportFilter.cpp
@@ -0,0 +1,2229 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <tqmap.h>
+#include <tqiodevice.h>
+#include <tqbuffer.h>
+#include <tqtextstream.h>
+#include <tqdom.h>
+
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kzip.h>
+
+#include <KoPageLayout.h>
+#include <KoPictureKey.h>
+#include <KoPicture.h>
+
+#include <KWEFStructures.h>
+#include <KWEFUtil.h>
+#include <KWEFBaseWorker.h>
+#include <KWEFKWordLeader.h>
+
+#include "ExportFilter.h"
+
+OOWriterWorker::OOWriterWorker(void) : m_streamOut(NULL),
+ m_paperBorderTop(0.0),m_paperBorderLeft(0.0),
+ m_paperBorderBottom(0.0),m_paperBorderRight(0.0), m_zip(NULL), m_pictureNumber(0),
+ m_automaticParagraphStyleNumber(0), m_automaticTextStyleNumber(0),
+ m_footnoteNumber(0), m_tableNumber(0), m_textBoxNumber( 0 ),
+ m_columnspacing( 36.0 ), m_columns( 1 )
+{
+}
+
+TQString OOWriterWorker::escapeOOText(const TQString& strText) const
+{
+ // Escape quotes (needed in attributes)
+ // Escape apostrophs (allowed by XML)
+ return KWEFUtil::EscapeSgmlText(NULL,strText,true,true);
+}
+
+TQString OOWriterWorker::escapeOOSpan(const TQString& strText) const
+// We need not only to escape the classical XML stuff but also to take care of spaces and tabs.
+{
+ TQString strReturn;
+ TQChar ch;
+ int spaceNumber = 0; // How many spaces should be written
+
+ for (uint i=0; i<strText.length(); i++)
+ {
+ ch=strText[i];
+
+ if (ch!=' ')
+ {
+ // The next character is not a space (anymore)
+ if ( spaceNumber > 0 )
+ {
+ strReturn += ' ';
+ --spaceNumber;
+ if ( spaceNumber > 0 )
+ {
+ strReturn += "<text:s text:c=\"";
+ strReturn += TQString::number( spaceNumber );
+ strReturn += "\"/>";
+ }
+ spaceNumber = 0;
+ }
+ }
+
+ // ### TODO: would be switch/case or if/elseif the best?
+ switch (ch.unicode())
+ {
+ case 9: // Tab
+ {
+ strReturn+="<text:tab-stop/>";
+ break;
+ }
+ case 10: // Line-feed
+ {
+ strReturn+="<text:line-break/>";
+ break;
+ }
+ case 32: // Space
+ {
+ if ( spaceNumber > 0 )
+ {
+ ++spaceNumber;
+ }
+ else
+ {
+ spaceNumber = 1;
+ }
+ break;
+ }
+ case 38: // &
+ {
+ strReturn+="&amp;";
+ break;
+ }
+ case 60: // <
+ {
+ strReturn+="&lt;";
+ break;
+ }
+ case 62: // >
+ {
+ strReturn+="&gt;";
+ break;
+ }
+ case 34: // "
+ {
+ strReturn+="&quot;";
+ break;
+ }
+ case 39: // '
+ {
+ strReturn+="&apos;";
+ break;
+ }
+ case 1: // (Non-XML-compatible) replacement character from KWord 0.8
+ {
+ strReturn += '#'; //use KWord 1.[123] replacement character instead
+ break;
+ }
+ // Following characters are not allowed in XML (but some files from KWord 0.8 have some of them.)
+ case 0:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ case 11:
+ case 12:
+ case 14:
+ case 15:
+ case 16:
+ case 17:
+ case 18:
+ case 19:
+ case 20:
+ case 21:
+ case 22:
+ case 23:
+ case 24:
+ case 25:
+ case 26:
+ case 27:
+ case 28:
+ case 29:
+ case 30:
+ case 31:
+ {
+ kdWarning(30518) << "Not allowed XML character: " << ch.unicode() << endl;
+ strReturn += '?';
+ break;
+ }
+ case 13: // ### TODO: what to do with it?
+ default:
+ {
+ strReturn+=ch;
+ break;
+ }
+ }
+ }
+
+ if ( spaceNumber > 0 )
+ {
+ // The last characters were spaces
+ strReturn += ' ';
+ --spaceNumber;
+ if ( spaceNumber > 0 )
+ {
+ strReturn += "<text:s text:c=\"";
+ strReturn += TQString::number( spaceNumber );
+ strReturn += "\"/>";
+ }
+ spaceNumber = 0;
+ }
+
+ return strReturn;
+}
+
+bool OOWriterWorker::doOpenFile(const TQString& filenameOut, const TQString& )
+{
+ kdDebug(30518) << "Opening file: " << filenameOut
+ << " (in OOWriterWorker::doOpenFile)" << endl;
+
+ m_zip=new KZip(filenameOut); // How to check failure?
+
+ if (!m_zip->open(IO_WriteOnly))
+ {
+ kdError(30518) << "Could not open ZIP file for writing! Aborting!" << endl;
+ delete m_zip;
+ m_zip=NULL;
+ return false;
+ }
+
+ m_zip->setCompression( KZip::NoCompression );
+ m_zip->setExtraField( KZip::NoExtraField );
+
+ const TQCString appId( "application/vnd.sun.xml.writer" );
+
+ m_zip->writeFile( "mimetype", TQString(), TQString(), appId.length(), appId.data() );
+
+ m_zip->setCompression( KZip::DeflateCompression );
+
+ m_streamOut=new TQTextStream(m_contentBody, IO_WriteOnly);
+
+ m_streamOut->setEncoding( TQTextStream::UnicodeUTF8 );
+
+ return true;
+}
+
+bool OOWriterWorker::zipPrepareWriting(const TQString& name)
+{
+ if (!m_zip)
+ return false;
+ m_size=0;
+ return m_zip->prepareWriting(name, TQString(), TQString(), 0);
+}
+
+bool OOWriterWorker::zipDoneWriting(void)
+{
+ if (!m_zip)
+ return false;
+ return m_zip->doneWriting(m_size);
+}
+
+bool OOWriterWorker::zipWriteData(const char* str)
+{
+ if (!m_zip)
+ return false;
+ const uint size=strlen(str);
+ m_size+=size;
+ return m_zip->writeData(str,size);
+}
+
+bool OOWriterWorker::zipWriteData(const TQByteArray& array)
+{
+ if (!m_zip)
+ return false;
+ const uint size=array.size();
+ m_size+=size;
+ return m_zip->writeData(array.data(),size);
+}
+
+bool OOWriterWorker::zipWriteData(const TQCString& cstr)
+{
+ if (!m_zip)
+ return false;
+ const uint size=cstr.length();
+ m_size+=size;
+ return m_zip->writeData(cstr.data(),size);
+}
+
+bool OOWriterWorker::zipWriteData(const TQString& str)
+{
+ return zipWriteData(str.utf8());
+}
+
+void OOWriterWorker::writeStartOfFile(const TQString& type)
+{
+ const bool noType=type.isEmpty();
+ zipWriteData("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+
+ zipWriteData("<!DOCTYPE office:document");
+ if (!noType)
+ {
+ // No type might happen for raw XML documents (which this filter does not support yet.)
+ zipWriteData("-");
+ zipWriteData(type);
+ }
+ zipWriteData(" PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\"");
+ zipWriteData(" \"office.dtd\"");
+ zipWriteData(">\n");
+
+ zipWriteData("<office:document");
+ if (!noType)
+ {
+ zipWriteData("-");
+ zipWriteData(type);
+ }
+
+ // The name spaces used by OOWriter (those not used by this filter are commented out)
+
+ // General namespaces
+ zipWriteData(" xmlns:office=\"http://openoffice.org/2000/office\"");
+ zipWriteData(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"");
+
+ // Namespaces for context.xml and style.xml
+ if ( type == "content" || type == "styles" || type.isEmpty() )
+ {
+ zipWriteData(" xmlns:style=\"http://openoffice.org/2000/style\"");
+ zipWriteData(" xmlns:text=\"http://openoffice.org/2000/text\"");
+ zipWriteData(" xmlns:table=\"http://openoffice.org/2000/table\"");
+ zipWriteData(" xmlns:draw=\"http://openoffice.org/2000/drawing\"");
+ zipWriteData(" xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"");
+
+ //zipWriteData(" xmlns:number=\"http://openoffice.org/2000/datastyle\"");
+ zipWriteData(" xmlns:svg=\"http://www.w3.org/2000/svg\"");
+ //zipWriteData(" xmlns:chart=\"http://openoffice.org/2000/chart\"");
+ //zipWriteData(" xmlns:dr3d=\"http://openoffice.org/2000/dr3d\"");
+ //zipWriteData(" xmlns:math=\"http://www.w3.org/1998/Math/MathML"");
+ //zipWriteData(" xmlns:form=\"http://openoffice.org/2000/form\"");
+ //zipWriteData(" xmlns:script=\"http://openoffice.org/2000/script\"");
+ }
+
+ // Namespaces For meta.xml
+ if ( type == "meta" || type.isEmpty() )
+ {
+ zipWriteData(" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"");
+ zipWriteData(" xmlns:meta=\"http://openoffice.org/2000/meta\"");
+ }
+
+ zipWriteData(" office:class=\"text\"");
+
+
+#ifdef STRICT_OOWRITER_VERSION_1
+ zipWriteData(" office:version=\"1.0\"");
+#else
+ // We are using an (rejected draft OASIS) extension compared to version 1.0, so we cannot write the version string.
+ // (We do not even write it for context.xml and meta.xml, as OOWriter 1.0.1 does not like it in this case.)
+#endif
+
+ zipWriteData(">\n");
+}
+
+void OOWriterWorker::writeFontDeclaration(void)
+{
+ zipWriteData( " <office:font-decls>\n");
+ TQMap<TQString,TQString>::ConstIterator end(m_fontNames.end());
+ for (TQMap<TQString,TQString>::ConstIterator it=m_fontNames.begin(); it!=end; ++it)
+ {
+ const bool space=(it.key().find(' ')>=0); // Does the font has at least a space in its name
+ const TQString fontName(escapeOOText(it.key()));
+ zipWriteData(" <style:font-decl style:name=\"");
+ zipWriteData(fontName);
+ zipWriteData("\" fo:font-family=\"");
+ if (space)
+ { // It has a space, so (simple) quote it
+ zipWriteData("&apos;");
+ zipWriteData(fontName);
+ zipWriteData("&apos;");
+ }
+ else
+ { // The font has no space in its name, so it can be written normally.
+ zipWriteData(fontName);
+ }
+ zipWriteData("\" ");
+ zipWriteData(it.data()); // already in XML, so do not escape
+ zipWriteData(" />\n");
+ }
+ zipWriteData(" </office:font-decls>\n");
+}
+
+void OOWriterWorker::writeStylesXml(void)
+{
+ if (!m_zip)
+ return;
+
+ zipPrepareWriting("styles.xml");
+
+ writeStartOfFile("styles");
+
+ writeFontDeclaration();
+
+ zipWriteData(m_styles);
+
+ zipWriteData(" <office:automatic-styles>\n");
+ zipWriteData(" <style:page-master style:name=\"pm1\">\n"); // ### TODO: verify if style name is unique
+
+ zipWriteData(" <style:properties ");
+ zipWriteData( " style:page-usage=\"all\"" ); // ### TODO: check
+
+ zipWriteData(" fo:page-width=\"");
+ zipWriteData(TQString::number(m_paperWidth));
+ zipWriteData("pt\" fo:page-height=\"");
+ zipWriteData(TQString::number(m_paperHeight));
+ zipWriteData("pt\" ");
+
+ zipWriteData("style:print-orientation=\"");
+ if (1==m_paperOrientation)
+ {
+ zipWriteData("landscape");
+ }
+ else
+ {
+ zipWriteData("portrait");
+ }
+
+ zipWriteData("\" fo:margin-top=\"");
+ zipWriteData(TQString::number(m_paperBorderTop));
+ zipWriteData("pt\" fo:margin-bottom=\"");
+ zipWriteData(TQString::number(m_paperBorderBottom));
+ zipWriteData("pt\" fo:margin-left=\"");
+ zipWriteData(TQString::number(m_paperBorderLeft));
+ zipWriteData("pt\" fo:margin-right=\"");
+ zipWriteData(TQString::number(m_paperBorderRight));
+ zipWriteData("pt\" style:first-page-number=\"");
+ zipWriteData(TQString::number(m_varSet.startingPageNumber));
+ zipWriteData( "\">\n" );
+
+ if ( m_columns > 1 )
+ {
+ zipWriteData( " <style:columns" );
+ zipWriteData( " fo:column-count=\"" );
+ zipWriteData( TQString::number( m_columns ) );
+ zipWriteData( "\" fo:column-gap=\"" );
+ zipWriteData( TQString::number( m_columnspacing ) );
+ zipWriteData( "pt\">\n" );
+
+ for (int i=0; i < m_columns; ++i)
+ {
+ zipWriteData( " <style:column style:rel-width=\"1*\" fo:margin-left=\"0cm\" fo:margin-right=\"0cm\"/>\n" );
+ }
+
+ zipWriteData( " </style:columns>\n" );
+ }
+
+ zipWriteData(" </style:properties>\n");
+
+ zipWriteData(" </style:page-master>\n");
+ zipWriteData(" </office:automatic-styles>\n");
+
+ zipWriteData(" <office:master-styles>\n");
+ zipWriteData(" <style:master-page style:name=\"Standard\" style:page-master-name=\"pm1\" />\n");
+ zipWriteData(" </office:master-styles>\n");
+
+ zipWriteData( "</office:document-styles>\n" );
+
+ zipDoneWriting();
+}
+
+void OOWriterWorker::writeContentXml(void)
+{
+ if (!m_zip)
+ return;
+
+ zipPrepareWriting("content.xml");
+
+ writeStartOfFile("content");
+
+ writeFontDeclaration();
+
+ zipWriteData(" <office:automatic-styles>\n");
+ zipWriteData(m_contentAutomaticStyles);
+ m_contentAutomaticStyles = TQString(); // Release memory
+
+ zipWriteData(" </office:automatic-styles>\n");
+
+ zipWriteData(m_contentBody);
+ m_contentBody.resize( 0 ); // Release memory
+
+ zipWriteData( "</office:document-content>\n" );
+
+ zipDoneWriting();
+}
+
+void OOWriterWorker::writeMetaXml(void)
+{
+ if (!m_zip)
+ return;
+
+ zipPrepareWriting("meta.xml");
+
+ writeStartOfFile("meta");
+
+ zipWriteData(" <office:meta>\n");
+
+ // Tell who we are in case that we have a bug in our filter output!
+ zipWriteData(" <meta:generator>KWord's OOWriter Export Filter");
+ zipWriteData(TQString("$Revision: 515673 $").mid(10).remove('$')); // has a leading and a trailing space.
+
+ zipWriteData("</meta:generator>\n");
+
+ if (!m_docInfo.title.isEmpty())
+ {
+ zipWriteData(" <dc:title>");
+ zipWriteData(escapeOOText(m_docInfo.title));
+ zipWriteData("</dc:title>\n");
+ }
+ if (!m_docInfo.abstract.isEmpty())
+ {
+ zipWriteData(" <dc:description>");
+ zipWriteData(escapeOOText(m_docInfo.abstract));
+ zipWriteData("</dc:description>\n");
+ }
+
+ if (m_varSet.creationTime.isValid())
+ {
+ zipWriteData(" <meta:creation-date>");
+ zipWriteData(escapeOOText(m_varSet.creationTime.toString(Qt::ISODate)));
+ zipWriteData("</meta:creation-date>\n");
+ }
+
+ if (m_varSet.modificationTime.isValid())
+ {
+ zipWriteData(" <dc:date>");
+ zipWriteData(escapeOOText(m_varSet.modificationTime.toString(Qt::ISODate)));
+ zipWriteData("</dc:date>\n");
+ }
+
+ if (m_varSet.printTime.isValid())
+ {
+ zipWriteData(" <meta:print-date>");
+ zipWriteData(escapeOOText(m_varSet.printTime.toString(Qt::ISODate)));
+ zipWriteData("</meta:print-date>\n");
+ }
+
+ zipWriteData( " <meta:document-statistic" );
+
+ // KWord files coming from import filters mostly do not have no page count
+ if ( m_numPages > 0 )
+ {
+ zipWriteData( " meta:page-count=\"" );
+ zipWriteData( TQString::number ( m_numPages ) );
+ zipWriteData( "\"" );
+ }
+
+ zipWriteData( " meta:image-count=\"" ); // This is not specified in the OO specification section 2.1.19
+ zipWriteData( TQString::number ( m_pictureNumber ) );
+ zipWriteData( "\"" );
+
+ zipWriteData( " meta:table-count=\"" );
+ zipWriteData( TQString::number ( m_tableNumber ) );
+ zipWriteData( "\"" );
+
+ zipWriteData( "/>\n" ); // meta:document-statistic
+
+ zipWriteData(" </office:meta>\n");
+ zipWriteData("</office:document-meta>\n");
+
+ zipDoneWriting();
+}
+
+bool OOWriterWorker::doCloseFile(void)
+{
+ kdDebug(30518)<< "OOWriterWorker::doCloseFile" << endl;
+ if (m_zip)
+ {
+ writeContentXml();
+ writeMetaXml();
+ writeStylesXml();
+ m_zip->close();
+ }
+
+ delete m_zip;
+ m_zip=NULL;
+ return true;
+}
+
+bool OOWriterWorker::doOpenDocument(void)
+{
+ kdDebug(30518)<< "OOWriterWorker::doOpenDocument" << endl;
+
+ *m_streamOut << " <office:body>\n";
+
+ return true;
+}
+
+bool OOWriterWorker::doCloseDocument(void)
+{
+ *m_streamOut << " </office:body>\n";
+ return true;
+}
+
+bool OOWriterWorker::doOpenBody(void)
+{
+ TQValueList<FrameAnchor>::Iterator it;
+
+ // We have to process all non-inline pictures
+ kdDebug(30518) << "=== Processing non-inlined pictures ===" << endl;
+ for ( it = m_nonInlinedPictureAnchors.begin(); it != m_nonInlinedPictureAnchors.end(); ++it )
+ {
+ *m_streamOut << " ";
+ makePicture( *it, AnchorNonInlined );
+ *m_streamOut << "\n";
+ }
+ kdDebug(30518) << "=== Non-inlined pictures processed ===" << endl;
+
+ // We have to process all non-inline tables
+ kdDebug(30518) << "=== Processing non-inlined tables ===" << endl;
+ for ( it = m_nonInlinedTableAnchors.begin(); it != m_nonInlinedTableAnchors.end(); ++it )
+ {
+ *m_streamOut << " ";
+ makeTable( *it, AnchorNonInlined );
+ *m_streamOut << "\n";
+ }
+ kdDebug(30518) << "=== Non-inlined tables processed ===" << endl;
+
+ return true;
+}
+
+TQString OOWriterWorker::textFormatToStyle(const TextFormatting& formatOrigin,
+ const TextFormatting& formatData, const bool force, TQString& key)
+{
+ // TODO: rename variable formatData
+ TQString strElement; // TODO: rename this variable
+
+ // Font name
+ TQString fontName = formatData.fontName;
+ declareFont(fontName);
+ if ( !fontName.isEmpty()
+ && (force || (formatOrigin.fontName!=formatData.fontName)))
+ {
+ strElement+="style:font-name=\"";
+ strElement+= escapeOOText(fontName);
+ strElement+="\" ";
+ key += fontName;
+ }
+
+ key += ",";
+
+ if (force || (formatOrigin.italic!=formatData.italic))
+ {
+ // Font style
+ strElement+="fo:font-style=\"";
+ if ( formatData.italic )
+ {
+ strElement+="italic";
+ key+='I';
+ }
+ else
+ {
+ strElement+="normal";
+ key+='N';
+ }
+ strElement+="\" ";
+ }
+
+ key += ",";
+
+ if (force || ((formatOrigin.weight>=75)!=(formatData.weight>=75)))
+ {
+ strElement+="fo:font-weight=\"";
+ if ( formatData.weight >= 75 )
+ {
+ strElement+="bold";
+ key+='B';
+ }
+ else
+ {
+ strElement+="normal";
+ key+='N';
+ }
+ strElement+="\" ";
+ }
+
+ key += ",";
+
+ if (force || (formatOrigin.fontSize!=formatData.fontSize))
+ {
+ const int size=formatData.fontSize;
+ if (size>0)
+ {
+ strElement+="fo:font-size=\"";
+ strElement+=TQString::number(size,10);
+ strElement+="pt\" ";
+ key+=TQString::number(size,10);
+ }
+ }
+
+ key += ",";
+
+ if (force || (formatOrigin.fgColor!=formatData.fgColor))
+ {
+ if ( formatData.fgColor.isValid() )
+ {
+ strElement+="fo:color=\"";
+ strElement+=formatData.fgColor.name();
+ strElement+="\" ";
+ key+=formatData.fgColor.name();
+ }
+ }
+
+ key += ",";
+
+ if (force || (formatOrigin.bgColor!=formatData.bgColor))
+ {
+ if ( formatData.bgColor.isValid() )
+ {
+ strElement+="style:text-background-color=\""; // ### what is fo:background-color ?
+ strElement+=formatData.bgColor.name();
+ strElement+="\" ";
+ key+=formatData.bgColor.name();
+ }
+ }
+
+ key += ';'; // Another separator
+
+ if ( force || ( formatOrigin.underline != formatData.underline )
+ || ( formatOrigin.underlineColor != formatData.underlineColor )
+ || ( formatOrigin.underlineValue != formatData.underlineValue )
+ || ( formatOrigin.underlineStyle != formatData.underlineStyle ) )
+ {
+ strElement+="style:text-underline=\"";
+ if ( formatData.underline )
+ {
+ TQString underlineValue ( formatData.underlineValue );
+ TQString underlineStyle ( formatData.underlineStyle );
+
+ if ( underlineStyle.isEmpty() )
+ underlineStyle = "solid";
+ if ( underlineValue == "1" )
+ underlineValue = "single";
+
+ if ( underlineValue == "single" )
+ {
+ if ( underlineStyle == "dash" )
+ {
+ strElement += "dash";
+ key += "DA";
+ }
+ else if ( underlineStyle == "dot" )
+ {
+ strElement += "dotted";
+ key += "DO";
+ }
+ else if ( underlineStyle == "dashdot" )
+ {
+ strElement += "dot-dash";
+ key += "DDA";
+ }
+ else if ( underlineStyle == "dashdotdot" )
+ {
+ strElement += "dot-dot-dash";
+ key += "DDDA";
+ }
+ else
+ {
+ strElement += "single";
+ key += "1";
+ }
+ }
+ else if ( underlineValue == "double" )
+ {
+ strElement += "double";
+ key += "2";
+ }
+ else if ( underlineValue == "single-bold" )
+ {
+ strElement += "bold";
+ key += "BL";
+ }
+ else if ( underlineValue == "wave" )
+ {
+ strElement += "wave";
+ key += "WV";
+ }
+ else
+ {
+ strElement += "single";
+ key += "?";
+ }
+ }
+ else
+ {
+ strElement+="none";
+ key += 'N';
+ }
+ strElement += "\" ";
+
+ if ( formatData.underline && formatData.underlineColor.isValid() )
+ {
+ const TQString colorName( formatData.underlineColor.name() );
+ strElement += "style:text-underline-color=\"";
+ strElement += colorName;
+ strElement += "\" ";
+ key += colorName;
+ }
+
+ }
+
+ key += ',';
+
+ if ( force
+ || (formatOrigin.strikeout != formatData.strikeout )
+ || (formatOrigin.strikeoutType != formatData.strikeoutType ) )
+ {
+ // OOWriter can only do single, double, thick (and slash and X that KWord cannot do.)
+ // So no dash, dot and friends.
+
+ strElement+="style:text-crossing-out=\"";
+ if ( ( formatData.strikeoutType == "single" ) || ( formatData.strikeoutType == "1" ) )
+ {
+ strElement+="single-line";
+ key += "1";
+ }
+ else if ( formatData.strikeoutType == "double" )
+ {
+ strElement+="double-line";
+ key += "2";
+ }
+ else if ( formatData.strikeoutType == "single-bold" )
+ {
+ strElement+="thick";
+ key += "T";
+ }
+ else
+ {
+ strElement+="none";
+ key += 'N';
+ }
+ strElement+="\" ";
+ }
+
+ key += ',';
+
+ // It seems that OOWriter 1.1 does have problems with word-by-word (OO Issue #11873, #25187)
+ // It is supposed to be fixed in development versions of OO
+ if (force || ( formatOrigin.underlineWord != formatData.underlineWord )
+ || (formatOrigin.strikeoutWord != formatData.strikeoutWord ) )
+ {
+ // Strikeout and underline can only have one word-by-word behaviour in OO
+ // (OO Issue #????? ; will not be changed.)
+ strElement+="fo:score-spaces=\""; // Are space processed?
+ if ( formatData.underlineWord || formatData.strikeoutWord )
+ {
+ strElement += "false";
+ key += 'W';
+ }
+ else
+ {
+ strElement += "true";
+ key += 'N';
+ }
+ strElement += "\" ";
+ }
+
+ key += ',';
+
+ if ( force || ( formatOrigin.language != formatData.language ) )
+ {
+ const TQString lang ( formatData.language );
+ if ( ! lang.isEmpty() )
+ {
+ const int res = lang.find( '_' );
+
+ if ( res >= 0 )
+ {
+ kdDebug(30518) << "Language: " << lang << " => " << lang.left( res ) << " - " << lang.mid( res + 1 ) << endl;
+ strElement += "fo:language=\"";
+ strElement += lang.left( res );
+ strElement += "\" ";
+ strElement += "fo:country=\"";
+ strElement += lang.mid( res + 1 );
+ strElement += "\" ";
+ }
+ else
+ {
+ kdDebug(30518) << "Language without country: " << lang << endl;
+ strElement += "fo:language=\"";
+ strElement += lang;
+ strElement += "\" ";
+ }
+
+ key+=formatData.language;
+ }
+ }
+
+ key += ",";
+
+ if ( force || ( formatOrigin.fontAttribute != formatData.fontAttribute ) )
+ {
+ // Note: OOWriter does not like when both fo:text-transform and fo:font-variant exist (except if both are none/normal)
+ // (It is documented so, see sections 3.10.1 and 3.10.2)
+ if ( formatData.fontAttribute == "uppercase" )
+ {
+ strElement += "fo:text-transform=\"uppercase\" ";
+ key += 'U';
+ }
+ else if ( formatData.fontAttribute == "lowercase" )
+ {
+ strElement += "fo:text-transform=\"lowercase\" ";
+ key += 'L';
+ }
+ else if ( formatData.fontAttribute == "smallcaps" )
+ {
+ strElement += "fo:font-variant=\"small-caps\" ";
+ key += 'S';
+ }
+ else
+ {
+ strElement += "fo:text-transform=\"none\" ";
+ strElement += "fo:font-variant=\"normal\" ";
+ key += 'N';
+ }
+ }
+
+ key += ",";
+
+ if ( force || ( formatOrigin.verticalAlignment != formatData.verticalAlignment ) )
+ {
+ if ( 1 == formatData.verticalAlignment )
+ {
+ //Subscript
+ strElement += "style:text-position=\"sub\" ";
+ key += 'B';
+ }
+ else if ( 2 == formatData.verticalAlignment )
+ {
+ //Superscript
+ strElement += "style:text-position=\"super\" ";
+ key += 'P';
+ }
+ // ### TODO: how to reset it? "0pt" ?
+ }
+
+ return strElement.stripWhiteSpace(); // Remove especially trailing spaces
+}
+
+#define ALLOW_TABLE
+
+TQString OOWriterWorker::cellToProperties( const TableCell& cell, TQString& key) const
+{
+#ifdef ALLOW_TABLE
+ const FrameData& frame = cell.frame;
+ TQString properties;
+
+ key += "!L"; // left border
+ key += frame.lColor.name();
+ key += ",";
+ key += TQString::number( frame.lWidth );
+ properties += " fo:border-left=\"";
+ if ( frame.lColor.isValid() && frame.lWidth > 0.0 )
+ {
+ properties += TQString::number( frame.lWidth );
+ properties += "pt";
+ properties += " solid "; // ### TODO
+ properties += frame.lColor.name();
+ }
+ else
+ {
+ properties += "0pt none #000000";
+ }
+ properties += "\"";
+
+ key += "!R"; // right border
+ key += frame.rColor.name();
+ key += ",";
+ key += TQString::number( frame.rWidth );
+ properties += " fo:border-right=\"";
+ if ( frame.rColor.isValid() && frame.rWidth > 0.0 )
+ {
+ properties += TQString::number( frame.rWidth );
+ properties += "pt";
+ properties += " solid "; // ### TODO
+ properties += frame.rColor.name();
+ }
+ else
+ {
+ properties += "0pt none #000000";
+ }
+ properties += "\"";
+
+ key += "!T"; // top border
+ key += frame.tColor.name();
+ key += ",";
+ key += TQString::number( frame.tWidth );
+ properties += " fo:border-top=\"";
+ if ( frame.tColor.isValid() && frame.tWidth > 0.0 )
+ {
+ properties += TQString::number( frame.tWidth );
+ properties += "pt";
+ properties += " solid "; // ### TODO
+ properties += frame.tColor.name();
+ }
+ else
+ {
+ properties += "0pt none #000000";
+ }
+ properties += "\"";
+
+ key += "!B"; // bottom border
+ key += frame.bColor.name();
+ key += ",";
+ key += TQString::number( frame.bWidth );
+ properties += " fo:border-bottom=\"";
+ if ( frame.bColor.isValid() && frame.bWidth > 0.0 )
+ {
+ properties += TQString::number( frame.bWidth );
+ properties += "pt";
+ properties += " solid "; // ### TODO
+ properties += frame.bColor.name();
+ }
+ else
+ {
+ properties += "0pt none #000000";
+ }
+ properties += "\"";
+
+ return properties;
+#else
+ return TQString();
+#endif
+}
+
+bool OOWriterWorker::makeTableRows( const TQString& tableName, const Table& table, int firstRowNumber )
+{
+#ifdef ALLOW_TABLE
+ // ### TODO: rows
+ // ### TODO: be careful that covered-cell can be due vertical spanning.
+ // ### TODO: One way to find is the difference between the row variables (or against the last known column)
+ // ### TODO: be careful that fully-covered rows might exist.
+
+ *m_streamOut << "<table:table-row>\n";
+ int rowCurrent = firstRowNumber;
+
+ ulong cellNumber = 0L;
+
+ TQMap<TQString,TQString> mapCellStyleKeys;
+
+ for ( TQValueList<TableCell>::ConstIterator itCell ( table.cellList.begin() );
+ itCell != table.cellList.end(); ++itCell)
+ {
+ if ( rowCurrent != (*itCell).row )
+ {
+ rowCurrent = (*itCell).row;
+ *m_streamOut << "</table:table-row>\n";
+ *m_streamOut << "<table:table-row>\n";
+ }
+
+ TQString key;
+ const TQString props ( cellToProperties( (*itCell), key ) );
+
+ TQString automaticCellStyle;
+ TQMap<TQString,TQString>::ConstIterator it ( mapCellStyleKeys.find( key ) );
+ if ( it == mapCellStyleKeys.end() )
+ {
+ automaticCellStyle = makeAutomaticStyleName( tableName + ".Cell", cellNumber );
+ mapCellStyleKeys [ key ] = automaticCellStyle;
+ kdDebug(30518) << "Creating automatic cell style: " << automaticCellStyle << " key: " << key << endl;
+ m_contentAutomaticStyles += " <style:style";
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticCellStyle ) + "\"";
+ m_contentAutomaticStyles += " style:family=\"table-cell\"";
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties ";
+ m_contentAutomaticStyles += props;
+ m_contentAutomaticStyles += "/>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+ }
+ else
+ {
+ automaticCellStyle = it.data();
+ kdDebug(30518) << "Using automatic cell style: " << automaticCellStyle << " key: " << key << endl;
+ }
+
+ *m_streamOut << "<table:table-cell table:value-type=\"string\" table:style-name=\""
+ << escapeOOText( automaticCellStyle)
+ << "\"";
+
+ // More than one column width?
+ {
+ *m_streamOut << " table:number-columns-spanned=\"" << (*itCell).m_cols << "\"";
+ }
+
+ *m_streamOut << ">\n";
+
+ if (!doFullAllParagraphs(*(*itCell).paraList))
+ {
+ return false;
+ }
+
+ *m_streamOut << "</table:table-cell>\n";
+
+ if ( (*itCell).m_cols > 1 )
+ {
+ // We need to add some placeholder for the "covered" cells
+ for (int i = 1; i < (*itCell).m_cols; ++i)
+ {
+ *m_streamOut << "<table:covered-table-cell/>";
+ }
+ }
+ }
+
+ *m_streamOut << "</table:table-row>\n";
+ return true;
+#else
+ return false;
+#endif
+}
+
+#ifdef ALLOW_TABLE
+static uint getColumnWidths( const Table& table, TQMemArray<double>& widthArray, int firstRowNumber )
+{
+ bool uniqueColumns = true; // We have not found any horizontally spanned cells yet.
+ uint currentColumn = 0;
+ int tryingRow = firstRowNumber; // We are trying the first row
+ TQValueList<TableCell>::ConstIterator itCell;
+
+ for ( itCell = table.cellList.begin();
+ itCell != table.cellList.end(); ++itCell )
+ {
+ kdDebug(30518) << "Column: " << (*itCell).col << " (Row: " << (*itCell).row << ")" << endl;
+
+ if ( (*itCell).row != tryingRow )
+ {
+ if ( uniqueColumns )
+ {
+ // We had a full row without any horizontally spanned cell, so we have the needed data
+ return currentColumn;
+ }
+ else
+ {
+ // No luck in the previous row, so now try this new one
+ tryingRow = (*itCell).row;
+ uniqueColumns = true;
+ currentColumn = 0;
+ }
+ }
+
+ if ( (*itCell).m_cols > 1 )
+ {
+ // We have a horizontally spanned cell
+ uniqueColumns = false;
+ // Do not waste the time to calculate the width
+ continue;
+ }
+
+ const double width = ( (*itCell).frame.right - (*itCell).frame.left );
+
+ if ( currentColumn >= widthArray.size() )
+ widthArray.resize( currentColumn + 4, TQGArray::SpeedOptim);
+
+ widthArray.at( currentColumn ) = width;
+ ++currentColumn;
+ }
+
+ // If we are here, it can be:
+ // - the table is either empty or there is not any row without horizontally spanned cells
+ // - we have needed the last row for getting something usable
+
+ return uniqueColumns ? currentColumn : 0;
+}
+#endif
+
+#ifdef ALLOW_TABLE
+static uint getFirstRowColumnWidths( const Table& table, TQMemArray<double>& widthArray, int firstRowNumber )
+// Get the column widths only by the first row.
+// This is used when all table rows have horizontally spanned cells.
+{
+ uint currentColumn = 0;
+ TQValueList<TableCell>::ConstIterator itCell;
+
+ for ( itCell = table.cellList.begin();
+ itCell != table.cellList.end(); ++itCell )
+ {
+ kdDebug(30518) << "Column: " << (*itCell).col << " (Row: " << (*itCell).row << ")" << endl;
+ if ( (*itCell).row != firstRowNumber )
+ break; // We have finished the first row
+
+ int cols = (*itCell).m_cols;
+ if ( cols < 1)
+ cols = 1;
+
+ // ### FIXME: the columns behind a larger cell do not need to be symmetrical
+ const double width = ( (*itCell).frame.right - (*itCell).frame.left ) / cols;
+
+ if ( currentColumn + cols > widthArray.size() )
+ widthArray.resize( currentColumn + 4, TQGArray::SpeedOptim);
+
+ for ( int i = 0; i < cols; ++i )
+ {
+ widthArray.at( currentColumn ) = width;
+ ++currentColumn;
+ }
+ }
+ return currentColumn;
+}
+#endif
+
+bool OOWriterWorker::makeTable( const FrameAnchor& anchor, const AnchorType anchorType )
+{
+#ifdef ALLOW_TABLE
+
+ // Be careful that while being similar the following 5 strings have different purposes
+ const TQString automaticTableStyle ( makeAutomaticStyleName( "Table", m_tableNumber ) ); // It also increases m_tableNumber
+ const TQString tableName( TQString( "Table" ) + TQString::number( m_tableNumber ) ); // m_tableNumber was already increased
+ const TQString translatedName( i18n( "Object name", "Table %1").arg( m_tableNumber ) );
+ const TQString automaticFrameStyle ( makeAutomaticStyleName( "TableFrame", m_textBoxNumber ) ); // It also increases m_textBoxNumber
+ const TQString translatedFrameName( i18n( "Object name", "Table Frame %1").arg( m_textBoxNumber ) );
+
+ kdDebug(30518) << "Processing table " << anchor.key.toString() << " => " << tableName << endl;
+
+ const TQValueList<TableCell>::ConstIterator firstCell ( anchor.table.cellList.begin() );
+
+ if ( firstCell == anchor.table.cellList.end() )
+ {
+ kdError(30518) << "Table has not any cell!" << endl;
+ return false;
+ }
+
+ const int firstRowNumber = (*firstCell).row;
+ kdDebug(30518) << "First row: " << firstRowNumber << endl;
+
+ TQMemArray<double> widthArray(4);
+
+ uint numberColumns = getColumnWidths( anchor.table, widthArray, firstRowNumber );
+
+ if ( numberColumns <= 0 )
+ {
+ kdDebug(30518) << "Could not get correct column widths, so approximating" << endl;
+ // There was a problem, the width array cannot be trusted, so try to do a column width array with the first row
+ numberColumns = getFirstRowColumnWidths( anchor.table, widthArray, firstRowNumber );
+ if ( numberColumns <= 0 )
+ {
+ // Still not right? Then it is an error!
+ kdError(30518) << "Cannot get column widths of table " << anchor.key.toString() << endl;
+ return false;
+ }
+ }
+
+ kdDebug(30518) << "Number of columns: " << numberColumns << endl;
+
+
+ double tableWidth = 0.0; // total width of table
+ uint i; // We need the loop variable 2 times
+ for ( i=0; i < numberColumns; ++i )
+ {
+ tableWidth += widthArray.at( i );
+ }
+ kdDebug(30518) << "Table width: " << tableWidth << endl;
+
+ // An inlined table, is an "as-char" text-box
+ *m_streamOut << "<draw:text-box";
+ *m_streamOut << " style:name=\"" << escapeOOText( automaticFrameStyle ) << "\"";
+ *m_streamOut << " draw:name=\"" << escapeOOText( translatedFrameName ) << "\"";
+ if ( anchorType == AnchorNonInlined )
+ {
+ // ### TODO: correctly set a OOWriter frame positioned on the page
+ *m_streamOut << " text:anchor-type=\"paragraph\"";
+ }
+ else
+ {
+ *m_streamOut << " text:anchor-type=\"as-char\"";
+ }
+ *m_streamOut << " svg:width=\"" << tableWidth << "pt\""; // ### TODO: any supplement to the width?
+ //*m_streamOut << " fo:min-height=\"1pt\"";// ### TODO: a better height (can be calulated from the KWord table frames)
+ *m_streamOut << ">\n";
+
+ *m_streamOut << "<table:table table:name=\""
+ << escapeOOText( translatedName )
+ << "\" table:style-name=\""
+ << escapeOOText( automaticTableStyle )
+ << "\" >\n";
+
+
+ // Now we have enough information to generate the style for the table and its frame
+
+ kdDebug(30518) << "Creating automatic frame style: " << automaticFrameStyle /* << " key: " << styleKey */ << endl;
+ m_contentAutomaticStyles += " <style:style"; // for frame
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticFrameStyle ) + "\"";
+ m_contentAutomaticStyles += " style:family=\"graphics\"";
+ m_contentAutomaticStyles += " style:parent-style-name=\"Frame\""; // ### TODO: parent style needs to be correctly defined
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties "; // ### TODO
+ m_contentAutomaticStyles += " text:anchor-type=\"as-char\""; // ### TODO: needed?
+ m_contentAutomaticStyles += " fo:padding=\"0pt\" fo:border=\"none\"";
+ m_contentAutomaticStyles += " fo:margin-left=\"0pt\"";
+ m_contentAutomaticStyles += " fo:margin-top=\"0pt\"";
+ m_contentAutomaticStyles += " fo:margin-bottom=\"0pt\"";
+ m_contentAutomaticStyles += " fo:margin-right=\"0pt\"";
+ m_contentAutomaticStyles += "/>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+
+ kdDebug(30518) << "Creating automatic table style: " << automaticTableStyle /* << " key: " << styleKey */ << endl;
+ m_contentAutomaticStyles += " <style:style"; // for table
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticTableStyle ) + "\"";
+ m_contentAutomaticStyles += " style:family=\"table\"";
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties ";
+ m_contentAutomaticStyles += " style:width=\"" + TQString::number( tableWidth ) + "pt\" ";
+ m_contentAutomaticStyles += "/>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+
+ TQValueList<TableCell>::ConstIterator itCell;
+
+ ulong columnNumber = 0L;
+
+ for ( i=0; i < numberColumns; ++i )
+ {
+ const TQString automaticColumnStyle ( makeAutomaticStyleName( tableName + ".Column", columnNumber ) );
+ kdDebug(30518) << "Creating automatic column style: " << automaticColumnStyle /* << " key: " << styleKey */ << endl;
+
+ m_contentAutomaticStyles += " <style:style";
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText( automaticColumnStyle ) + "\"";
+ m_contentAutomaticStyles += " style:family=\"table-column\"";
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties ";
+ // Despite that some OO specification examples use fo:width, OO specification section 4.19 tells to use style:column-width
+ // and/or the relative variant: style:rel-column-width
+ m_contentAutomaticStyles += " style:column-width=\"" + TQString::number( widthArray.at( i ) ) + "pt\" ";
+ m_contentAutomaticStyles += "/>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+
+ // ### TODO: find a way how to use table:number-columns-repeated for more that one cell's column(s)
+ *m_streamOut << "<table:table-column table:style-name=\""
+ << escapeOOText( automaticColumnStyle )
+ << "\" table:number-columns-repeated=\"1\"/>\n";
+ }
+
+ makeTableRows( tableName, anchor.table, firstRowNumber );
+
+ *m_streamOut << "</table:table>\n";
+
+ *m_streamOut << "</draw:text-box>"; // End of inline
+
+#endif
+ return true;
+}
+
+bool OOWriterWorker::makePicture( const FrameAnchor& anchor, const AnchorType anchorType )
+{
+ kdDebug(30518) << "New picture: " << anchor.picture.koStoreName
+ << " , " << anchor.picture.key.toString() << endl;
+
+ const TQString koStoreName(anchor.picture.koStoreName);
+
+ TQByteArray image;
+
+ TQString strExtension(koStoreName.lower());
+ const int result=koStoreName.findRev(".");
+ if (result>=0)
+ {
+ strExtension=koStoreName.mid(result+1);
+ }
+
+ bool isImageLoaded=false;
+
+ if (strExtension=="png")
+ {
+ isImageLoaded=loadSubFile(koStoreName,image);
+ }
+ else if ((strExtension=="jpg") || (strExtension=="jpeg"))
+ {
+ isImageLoaded=loadSubFile(koStoreName,image);
+ strExtension="jpg"; // ### TODO: verify
+ }
+ else if ((strExtension=="tif") || (strExtension=="tiff"))
+ {
+ isImageLoaded=loadSubFile(koStoreName,image);
+ strExtension="tif"; // ### TODO: verify
+ }
+ else if ((strExtension=="gif") || (strExtension=="wmf"))
+ // ### TODO: Which other image formats does OOWriter support directly?
+ {
+ isImageLoaded=loadSubFile(koStoreName,image);
+ }
+ else
+ {
+ // All other picture types must be converted to PNG
+ isImageLoaded=loadAndConvertToImage(koStoreName,strExtension,"PNG",image);
+ strExtension="png";
+ }
+
+ if (!isImageLoaded)
+ {
+ kdWarning(30518) << "Unable to load picture: " << koStoreName << endl;
+ return true;
+ }
+
+ kdDebug(30518) << "Picture loaded: " << koStoreName << endl;
+
+ double height = 0.0;
+ double width = 0.0;
+
+ if ( anchorType == AnchorTextImage )
+ {
+ // Text image have no frameset, so the only size information is in the picture itself.
+ TQBuffer buffer( image.copy() ); // Be more safe than sorry and do not allow shallow copy
+ KoPicture pic;
+ buffer.open( IO_ReadOnly );
+ if ( pic.load( TQT_TQIODEVICE(&buffer), strExtension ) )
+ {
+ const TQSize size ( pic.getOriginalSize() );
+ height = size.height();
+ width = size.width();
+ }
+ else
+ {
+ kdWarning(30518) << "Could not load KoPicture: " << koStoreName << endl;
+ }
+ buffer.close();
+ }
+ else
+ {
+ // Use frame size
+ height=anchor.frame.bottom - anchor.frame.top;
+ width =anchor.frame.right - anchor.frame.left;
+ }
+
+ if ( height < 1.0 )
+ {
+ kdWarning(30518) << "Silly height for " << koStoreName << " : " << height << endl;
+ height = 72.0;
+ }
+ if ( width < 1.0 )
+ {
+ kdWarning(30518) << "Silly width for " << koStoreName << " : " << width << endl;
+ width = 72.0;
+ }
+
+ // We need a 32 digit hex value of the picture number
+ // Please note: it is an exact 32 digit value, truncated if the value is more than 512 bits wide. :-)
+ TQString number;
+ number.fill('0',32);
+ number += TQString::number(++m_pictureNumber,16); // in hex
+
+ TQString ooName("Pictures/");
+ ooName += number.right(32);
+ ooName += '.';
+ ooName += strExtension;
+
+ kdDebug(30518) << "Picture " << koStoreName << " => " << ooName << endl;
+
+ // TODO: we are only using the filename, not the rest of the key
+ // TODO: (bad if there are two images of the same name, but of a different key)
+ *m_streamOut << "<draw:image draw:name=\"" << anchor.picture.key.filename() << "\"";
+ *m_streamOut << " draw:style-name=\"Graphics\""; // ### TODO: should be an automatic "graphic" style name instead
+ if ( anchorType == AnchorNonInlined )
+ {
+ // ### TODO: correctly set a OOWriter frame positioned on the page
+ *m_streamOut << " text:anchor-type=\"paragraph\"";
+ }
+ else
+ {
+ *m_streamOut << " text:anchor-type=\"as-char\"";
+ }
+ *m_streamOut << " svg:height=\"" << height << "pt\" svg:width=\"" << width << "pt\"";
+ *m_streamOut << " draw:z-index=\"0\" xlink:href=\"#" << ooName << "\"";
+ *m_streamOut << " xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"";
+ *m_streamOut << "/>"; // NO end of line!
+
+ if (m_zip)
+ {
+#if 0
+ // ### FIXME Why is the following line not working (at least with KDE 3.1)? (It makes unzip having problems with meta.xml)
+ m_zip->writeFile(ooName,TQString(), TQString(), image.size(), image.data());
+#else
+ zipPrepareWriting(ooName);
+ zipWriteData( image );
+ zipDoneWriting();
+#endif
+ }
+
+ return true;
+}
+
+void OOWriterWorker::processNormalText ( const TQString &paraText,
+ const TextFormatting& formatLayout,
+ const FormatData& formatData)
+{
+ // Retrieve text and escape it (and necessary space, tabs and line-break tags)
+ const TQString partialText( escapeOOSpan( paraText.mid( formatData.pos, formatData.len ) ) );
+
+ if (formatData.text.missing)
+ {
+ // It's just normal text, so we do not need a <text:span> element!
+ *m_streamOut << partialText;
+ }
+ else
+ { // Text with properties, so use a <text:span> element!
+ *m_streamOut << "<text:span";
+
+ TQString styleKey;
+ const TQString props ( textFormatToStyle(formatLayout,formatData.text,false,styleKey) );
+
+ TQMap<TQString,TQString>::ConstIterator it ( m_mapTextStyleKeys.find(styleKey) );
+ kdDebug(30518) << "Searching text key: " << styleKey << endl;
+
+ TQString automaticStyle;
+ if (it==m_mapTextStyleKeys.end())
+ {
+ // We have not any match, so we need a new automatic text style
+ automaticStyle=makeAutomaticStyleName("T", m_automaticTextStyleNumber);
+ kdDebug(30518) << "Creating automatic text style: " << automaticStyle << " key: " << styleKey << endl;
+ m_mapTextStyleKeys[styleKey]=automaticStyle;
+
+ m_contentAutomaticStyles += " <style:style";
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText(automaticStyle) + "\"";
+ m_contentAutomaticStyles += " style:family=\"text\"";
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties ";
+ m_contentAutomaticStyles += props;
+ m_contentAutomaticStyles += "/>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+ }
+ else
+ {
+ // We have a match, so use the already defined automatic text style
+ automaticStyle=it.data();
+ kdDebug(30518) << "Using automatic text style: " << automaticStyle << " key: " << styleKey << endl;
+ }
+
+ *m_streamOut << " text:style-name=\"" << escapeOOText(automaticStyle) << "\" ";
+
+ *m_streamOut << ">" << partialText << "</text:span>";
+ }
+}
+
+void OOWriterWorker::processFootnote( const VariableData& variable )
+{
+ // Footnote
+ const TQValueList<ParaData> *paraList = variable.getFootnotePara();
+ if( paraList )
+ {
+ const TQString value ( variable.getFootnoteValue() );
+ //const bool automatic = formatData.variable.getFootnoteAuto();
+ const bool flag = variable.getFootnoteType();
+
+ if ( flag )
+ {
+ *m_streamOut << "<text:footnote text:id=\"ft";
+ *m_streamOut << (++m_footnoteNumber);
+ *m_streamOut << "\">";
+ *m_streamOut << "<text:footnote-citation>" << escapeOOText( value ) << "</text:footnote-citation>";
+ *m_streamOut << "<text:footnote-body>\n";
+
+ doFullAllParagraphs( *paraList );
+
+ *m_streamOut << "\n</text:footnote-body>";
+ *m_streamOut << "</text:footnote>";
+ }
+ else
+ {
+ *m_streamOut << "<text:endnote text:id=\"ft";
+ *m_streamOut << (++m_footnoteNumber);
+ *m_streamOut << "\">";
+ *m_streamOut << "<text:endnote-citation>" << escapeOOText( value ) << "</text:endnote-citation>";
+ *m_streamOut << "<text:endnote-body>\n";
+
+ doFullAllParagraphs( *paraList );
+
+ *m_streamOut << "\n</text:endnote-body>";
+ *m_streamOut << "</text:endnote>";
+ }
+ }
+}
+
+void OOWriterWorker::processNote( const VariableData& variable )
+{
+ // KWord 1.3's annotations are anonymous and undated,
+ // however the OO specification tells that author and date are mandatory (even if OOWriter 1.1 consider them optional)
+
+ *m_streamOut << "<office:annotation office:create-date=\"";
+
+ // We use the document creation date as creation date for the annotation
+ // (OOWriter uses only the date part, there is no time part)
+ if ( m_varSet.creationTime.isValid() )
+ *m_streamOut << escapeOOText( m_varSet.creationTime.date().toString( Qt::ISODate ) );
+ else
+ *m_streamOut << "1970-01-01";
+
+ *m_streamOut << "\" office:author=\"";
+
+ // We try to use the document author's name as annotation author
+ if ( m_docInfo.fullName.isEmpty() )
+ *m_streamOut << escapeOOText( i18n( "Pseudo-author for annotations", "KWord 1.3" ) );
+ else
+ *m_streamOut << escapeOOText( m_docInfo.fullName );
+
+ *m_streamOut << "\">\n";
+ *m_streamOut << "<text:p>"
+ << escapeOOSpan( variable.getGenericData( "note" ) )
+ << "</text:p>\n"
+ << "</office:annotation>";
+}
+
+void OOWriterWorker::processVariable ( const TQString&,
+ const TextFormatting& /*formatLayout*/,
+ const FormatData& formatData)
+{
+ if (0==formatData.variable.m_type)
+ {
+ *m_streamOut << "<text:date/>"; // ### TODO: parameters
+ }
+ else if (2==formatData.variable.m_type)
+ {
+ *m_streamOut << "<text:time/>"; // ### TODO: parameters
+ }
+ else if (4==formatData.variable.m_type)
+ {
+ // ### TODO: the other under-types, other parameters
+ if (formatData.variable.isPageNumber())
+ {
+ *m_streamOut << "<text:page-number text:select-page=\"current\"/>";
+ }
+ else if (formatData.variable.isPageCount())
+ {
+ *m_streamOut << "<text:page-count/>";
+ }
+ else
+ {
+ // Unknown subtype, therefore write out the result
+ *m_streamOut << formatData.variable.m_text;
+ }
+ }
+ else if (9==formatData.variable.m_type)
+ {
+ // A link
+ *m_streamOut << "<text:a xlink:href=\""
+ << escapeOOText(formatData.variable.getHrefName())
+ << "\" xlink:type=\"simple\">"
+ << escapeOOText(formatData.variable.getLinkName())
+ << "</text:a>";
+ }
+ else if ( 10 == formatData.variable.m_type )
+ { // Note (OOWriter: annotation)
+ processNote ( formatData.variable );
+ }
+ else if (11==formatData.variable.m_type)
+ {
+ // Footnote
+ processFootnote ( formatData.variable );
+ }
+ else
+ {
+ // Generic variable
+ *m_streamOut << formatData.variable.m_text;
+ }
+}
+
+void OOWriterWorker::processAnchor ( const TQString&,
+ const TextFormatting& /*formatLayout*/, //TODO
+ const FormatData& formatData)
+{
+ // We have a picture or a table
+ if ( (2==formatData.frameAnchor.type) // <IMAGE> or <PICTURE>
+ || (5==formatData.frameAnchor.type) ) // <CLIPART>
+ {
+ makePicture( formatData.frameAnchor, AnchorInlined );
+ }
+ else if (6==formatData.frameAnchor.type)
+ {
+ makeTable( formatData.frameAnchor, AnchorInlined );
+ }
+ else
+ {
+ kdWarning(30518) << "Unsupported anchor type: "
+ << formatData.frameAnchor.type << endl;
+ }
+}
+
+void OOWriterWorker::processTextImage ( const TQString&,
+ const TextFormatting& /*formatLayout*/,
+ const FormatData& formatData)
+{
+ kdDebug(30518) << "Text Image: " << formatData.frameAnchor.key.toString() << endl;
+ makePicture( formatData.frameAnchor, AnchorTextImage );
+}
+
+void OOWriterWorker::processParagraphData ( const TQString &paraText,
+ const TextFormatting& formatLayout,
+ const ValueListFormatData &paraFormatDataList)
+{
+ if ( paraText.length () > 0 )
+ {
+ ValueListFormatData::ConstIterator paraFormatDataIt;
+
+ for ( paraFormatDataIt = paraFormatDataList.begin ();
+ paraFormatDataIt != paraFormatDataList.end ();
+ paraFormatDataIt++ )
+ {
+ if (1==(*paraFormatDataIt).id)
+ {
+ processNormalText(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if (2==(*paraFormatDataIt).id)
+ {
+ processTextImage(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if ( 3 == (*paraFormatDataIt).id )
+ {
+ // Just a (KWord 0.8) tab stop, nothing else to do!
+ *m_streamOut << "<text:tab-stop/>";
+ }
+ else if (4==(*paraFormatDataIt).id)
+ {
+ processVariable(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if (6==(*paraFormatDataIt).id)
+ {
+ processAnchor(paraText, formatLayout, (*paraFormatDataIt));
+ }
+ else if ( 1001 == (*paraFormatDataIt).id ) // Start of bookmark
+ {
+ *m_streamOut << "<text:bookmark-start text:name=\""
+ << escapeOOText( (*paraFormatDataIt).variable.m_text )
+ <<"\"/>";
+ }
+ else if ( 1002 == (*paraFormatDataIt).id ) // End of bookmark
+ {
+ *m_streamOut << "<text:bookmark-end text:name=\""
+ << escapeOOText( (*paraFormatDataIt).variable.m_text )
+ <<"\"/>";
+ }
+ }
+ }
+}
+
+TQString OOWriterWorker::layoutToParagraphStyle(const LayoutData& layoutOrigin,
+ const LayoutData& layout, const bool force, TQString& styleKey)
+{
+ TQString props; // Props has to remain empty, if there is no difference.
+
+ styleKey += layout.styleName;
+ styleKey += ',';
+
+ if (force || (layoutOrigin.alignment!=layout.alignment))
+ {
+ // NOTE: OO 1.0.x uses start and end like left and right (section 3.11.4)
+ // Unfortunately in XSL-FO's text-align, they are really supposed to be the start and the end.
+ if (layout.alignment == "left")
+ {
+ props += "fo:text-align=\"start\" ";
+ styleKey += 'L';
+ }
+ else if (layout.alignment == "right")
+ {
+ props += "fo:text-align=\"end\" ";
+ styleKey += 'R';
+ }
+ else if (layout.alignment == "center")
+ {
+ props += "fo:text-align=\"center\" ";
+ styleKey += 'C';
+ }
+ else if (layout.alignment == "justify")
+ {
+ props += "fo:text-align=\"justify\" ";
+ styleKey += 'J';
+ }
+ else if (layout.alignment == "auto")
+ {
+ props += "fo:text-align=\"start\" ";
+#ifndef STRICT_OOWRITER_VERSION_1
+ props += "style:text-auto-align=\"true\" "; // rejected draft OASIS extension
+#endif
+ styleKey += 'A';
+ }
+ else
+ {
+ kdWarning(30518) << "Unknown alignment: " << layout.alignment << endl;
+ }
+ }
+
+ styleKey += ',';
+
+ if ((layout.indentLeft>=0.0)
+ && (force || (layoutOrigin.indentLeft!=layout.indentLeft)))
+ {
+ props += TQString("fo:margin-left=\"%1pt\" ").arg(layout.indentLeft);
+ styleKey += TQString::number(layout.indentLeft);
+ }
+
+ styleKey += ',';
+
+ if ((layout.indentRight>=0.0)
+ && (force || (layoutOrigin.indentRight!=layout.indentRight)))
+ {
+ props += TQString("fo:margin-right=\"%1pt\" ").arg(layout.indentRight);
+ styleKey += TQString::number(layout.indentRight);
+ }
+
+ styleKey += ',';
+
+ if (force || (layoutOrigin.indentLeft!=layout.indentLeft))
+ {
+ props += "fo:text-indent=\"";
+ props += TQString::number(layout.indentFirst);
+ props += "\" ";
+ styleKey += TQString::number(layout.indentFirst);
+ }
+
+ styleKey += ',';
+
+ if ((layout.marginBottom>=0.0)
+ && ( force || ( layoutOrigin.marginBottom != layout.marginBottom ) ) )
+ {
+ props += TQString("fo:margin-bottom=\"%1pt\" ").arg(layout.marginBottom);
+ styleKey += TQString::number(layout.marginBottom);
+ }
+
+ styleKey += ',';
+
+ if ((layout.marginTop>=0.0)
+ && ( force || ( layoutOrigin.marginTop != layout.marginTop ) ) )
+ {
+ props += TQString("fo:margin-top=\"%1pt\" ").arg(layout.marginTop);
+ styleKey += TQString::number(layout.marginTop);
+ }
+
+ styleKey += ',';
+
+ if (force
+ || ( layoutOrigin.lineSpacingType != layout.lineSpacingType )
+ || ( layoutOrigin.lineSpacing != layout.lineSpacing ) )
+ {
+ switch ( layout.lineSpacingType )
+ {
+ case LayoutData::LS_CUSTOM:
+ {
+ // We have a custom line spacing (in points)
+ const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
+ props += "style:line-spacing=\"";
+ props += height;
+ props += "pt\" ";
+ styleKey += height;
+ styleKey += 'C';
+ break;
+ }
+ case LayoutData::LS_SINGLE:
+ {
+ props += "fo:line-height=\"normal\" "; // One
+ styleKey += "100%"; // One
+ break;
+ }
+ case LayoutData::LS_ONEANDHALF:
+ {
+ props += "fo:line-height=\"150%\" "; // One-and-half
+ styleKey += "150%";
+ break;
+ }
+ case LayoutData::LS_DOUBLE:
+ {
+ props += "fo:line-height=\"200%\" "; // Two
+ styleKey += "200%";
+ break;
+ }
+ case LayoutData::LS_MULTIPLE:
+ {
+ // OOWriter 1.1 only allows up to 200%
+ const TQString mult ( TQString::number( tqRound( layout.lineSpacing * 100 ) ) );
+ props += "fo:line-height=\"";
+ props += mult;
+ props += "%\" ";
+ styleKey += mult;
+ styleKey += "%";
+ break;
+ }
+ case LayoutData::LS_FIXED:
+ {
+ // We have a fixed line height (in points)
+ const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
+ props += "fo:line-height=\"";
+ props += height;
+ props += "pt\" ";
+ styleKey += height;
+ styleKey += 'F';
+ break;
+ }
+ case LayoutData::LS_ATLEAST:
+ {
+ // We have a at-least line height (in points)
+ const TQString height ( TQString::number(layout.lineSpacing) ); // ### TODO: rounding?
+ props += "style:line-height-at-least=\"";
+ props += height;
+ props += "pt\" ";
+ styleKey += height;
+ styleKey += 'A';
+ break;
+ }
+ default:
+ {
+ kdWarning(30518) << "Unsupported lineSpacingType: " << layout.lineSpacingType << " (Ignoring!)" << endl;
+ break;
+ }
+ }
+ }
+
+ styleKey += ',';
+
+ if ( layout.pageBreakBefore )
+ {
+ // We have a page break before the paragraph
+ props += "fo:page-break-before=\"page\" ";
+ styleKey += 'B';
+ }
+
+ styleKey += ',';
+
+ if ( layout.pageBreakAfter )
+ {
+ // We have a page break after the paragraph
+ props += "fo:page-break-after=\"page\" ";
+ styleKey += 'A';
+ }
+
+ styleKey += '@'; // A more visible seperator
+
+ props += textFormatToStyle(layoutOrigin.formatData.text,layout.formatData.text,force,styleKey);
+
+ props += ">";
+
+ styleKey += '@'; // A more visible seperator
+
+ // ### TODO/FIXME: what if all tabulators must be erased?
+ if (!layout.tabulatorList.isEmpty()
+ && (force || (layoutOrigin.tabulatorList!=layout.tabulatorList) ))
+ {
+ props += "\n <style:tab-stops>\n";
+ TabulatorList::ConstIterator it;
+ TabulatorList::ConstIterator end(layout.tabulatorList.end());
+ for (it=layout.tabulatorList.begin();it!=end;++it)
+ {
+ props+=" <style:tab-stop style:position=\"";
+ props += TQString::number((*it).m_ptpos);
+ props += "pt\"";
+ styleKey += TQString::number((*it).m_ptpos);
+ switch ((*it).m_type)
+ {
+ case 0: props += " style:type=\"left\""; styleKey += "L"; break;
+ case 1: props += " style:type=\"center\""; styleKey += "C"; break;
+ case 2: props += " style:type=\"right\""; styleKey += "R"; break;
+ case 3: props += " style:type=\"char\" style:char=\".\""; styleKey += "D"; break; // decimal
+ default: props += " style:type=\"left\""; styleKey += "L"; break;
+ }
+ switch ((*it).m_filling) // ### TODO: check if the characters are right
+ {
+ case TabulatorData::TF_NONE: break;
+ case TabulatorData::TF_DOT: props += " style:leader-char=\".\""; break;
+ case TabulatorData::TF_LINE: props += " style:leader-char=\"_\""; break;
+
+ case TabulatorData::TF_DASH:
+ case TabulatorData::TF_DASHDOT:
+ case TabulatorData::TF_DASHDOTDOT: props += " style:leader-char=\"-\""; break;
+
+ default: break;
+ }
+ props += "/>\n";
+ styleKey +='/';
+ }
+ props += " </style:tab-stops>\n ";
+ }
+
+ return props;
+}
+
+bool OOWriterWorker::doFullParagraph(const TQString& paraText, const LayoutData& layout,
+ const ValueListFormatData& paraFormatDataList)
+{
+ const bool header = ( (layout.counter.numbering == CounterData::NUM_CHAPTER)
+ && (layout.counter.depth<10) ); // ### TODO: Does OOWriter really limits to 10?
+
+ if (header)
+ {
+ *m_streamOut << " <text:h text:level=\"";
+ *m_streamOut << TQString::number(layout.counter.depth+1,10);
+ *m_streamOut << "\" ";
+ }
+ else
+ *m_streamOut << " <text:p ";
+
+ const LayoutData& styleLayout=m_styleMap[layout.styleName];
+
+ TQString styleKey;
+ const TQString props(layoutToParagraphStyle(styleLayout,layout,false,styleKey));
+
+ TQString actualStyle(layout.styleName);
+ if (!props.isEmpty())
+ {
+ TQMap<TQString,TQString>::ConstIterator it ( m_mapParaStyleKeys.find(styleKey) );
+ kdDebug(30518) << "Searching paragraph key: " << styleKey << endl;
+
+ TQString automaticStyle;
+
+ if (it==m_mapParaStyleKeys.end())
+ {
+ // We have additional properties, so we need an automatic style for the paragraph
+ automaticStyle = makeAutomaticStyleName("P", m_automaticParagraphStyleNumber);
+ kdDebug(30518) << "Creating automatic paragraph style: " << automaticStyle << " key: " << styleKey << endl;
+ m_mapParaStyleKeys[styleKey]=automaticStyle;
+
+ m_contentAutomaticStyles += " <style:style";
+ m_contentAutomaticStyles += " style:name=\"" + escapeOOText(automaticStyle) + "\"";
+ m_contentAutomaticStyles += " style:parent-style-name=\"" + escapeOOText(layout.styleName) + "\"";
+ m_contentAutomaticStyles += " style:family=\"paragraph\" style:class=\"text\"";
+ m_contentAutomaticStyles += ">\n";
+ m_contentAutomaticStyles += " <style:properties ";
+ m_contentAutomaticStyles += props;
+ m_contentAutomaticStyles += "</style:properties>\n";
+ m_contentAutomaticStyles += " </style:style>\n";
+ }
+ else
+ {
+ // We have a match, so use the already defined automatic paragraph style
+ automaticStyle=it.data();
+ kdDebug(30518) << "Using automatic paragraph style: " << automaticStyle << " key: " << styleKey << endl;
+ }
+
+ actualStyle=automaticStyle;
+ }
+
+ if (!actualStyle.isEmpty())
+ {
+ *m_streamOut << "text:style-name=\"" << escapeOOText(actualStyle) << "\" ";
+ }
+ else
+ { // SHould not happen
+ kdWarning(30518) << "No style for a paragraph!" << endl;
+ }
+
+ *m_streamOut << ">";
+
+ processParagraphData(paraText, layout.formatData.text, paraFormatDataList);
+
+ if (header)
+ *m_streamOut << "</text:h>\n";
+ else
+ *m_streamOut << "</text:p>\n";
+
+ return true;
+}
+
+bool OOWriterWorker::doOpenStyles(void)
+{
+ m_styles += " <office:styles>\n";
+ m_styles += " <style:style style:name=\"Graphics\" style:family=\"graphics\">\n"; // ### TODO: what if Graphics is a normal style
+ m_styles += " <style:properties text:anchor-type=\"paragraph\" style:wrap=\"none\"/>\n";
+ m_styles += " </style:style>\n";
+ m_styles += " <style:style style:name=\"Frame\" style:family=\"graphics\">\n"; // ### TODO: what if Frame is a normal style
+ m_styles += " <style:properties text:anchor-type=\"paragraph\" style:wrap=\"none\"/>\n";
+ m_styles += " </style:style>\n";
+ return true;
+}
+
+bool OOWriterWorker::doFullDefineStyle(LayoutData& layout)
+{
+ //Register style in the style map
+ m_styleMap[layout.styleName]=layout;
+
+ m_styles += " <style:style";
+
+ m_styles += " style:name=\"" + escapeOOText( layout.styleName ) + "\"";
+ m_styles += " style:next-style-name=\"" + escapeOOText( layout.styleFollowing ) + "\"";
+ m_styles += " style:family=\"paragraph\" style:class=\"text\"";
+ m_styles += ">\n";
+ m_styles += " <style:properties ";
+
+ TQString debugKey; // Not needed
+ m_styles += layoutToParagraphStyle(layout,layout,true,debugKey);
+ kdDebug(30518) << "Defining style: " << debugKey << endl;
+
+ m_styles += "</style:properties>\n";
+ m_styles += " </style:style>\n";
+
+ return true;
+}
+
+bool OOWriterWorker::doCloseStyles(void)
+{
+ m_styles += " </office:styles>\n";
+ return true;
+}
+
+bool OOWriterWorker::doFullPaperFormat(const int format,
+ const double width, const double height, const int orientation)
+{
+ if ( ( format < 0 ) // Be careful that 0 is ISO A3
+ || ( width < 1.0 )
+ || ( height < 1.0 ) )
+ {
+ kdWarning(30518) << "Page size problem: format: " << format << " width: " << width << " height: " << height << endl;
+ // Something is wrong with the page size
+ KoFormat newFormat = KoFormat ( format );
+ if ( ( format < 0 ) || ( format > PG_LAST_FORMAT ) )
+ {
+ // Bad or unknown format, so assume ISO A4
+ newFormat = PG_DIN_A4;
+ }
+ m_paperWidth = KoPageFormat::width ( newFormat, KoOrientation( orientation ) ) * 72.0 / 25.4 ;
+ m_paperHeight = KoPageFormat::height ( newFormat, KoOrientation( orientation ) ) * 72.0 / 25.4 ;
+ m_paperFormat = newFormat;
+ }
+ else
+ {
+ m_paperFormat=format;
+ m_paperWidth=width;
+ m_paperHeight=height;
+ }
+ m_paperOrientation=orientation; // ### TODO: check if OOWriter needs the orignal size (without landscape) or the real size
+ return true;
+}
+
+bool OOWriterWorker::doFullPaperBorders (const double top, const double left,
+ const double bottom, const double right)
+{
+ m_paperBorderTop=top;
+ m_paperBorderLeft=left;
+ m_paperBorderBottom=bottom;
+ m_paperBorderRight=right;
+ return true;
+}
+
+bool OOWriterWorker::doFullPaperFormatOther ( const int columns, const double columnspacing, const int numPages )
+{
+ m_columns = columns;
+ m_columnspacing = columnspacing;
+ m_numPages = numPages;
+ return true;
+}
+
+bool OOWriterWorker::doFullDocumentInfo(const KWEFDocumentInfo& docInfo)
+{
+ m_docInfo=docInfo;
+
+ return true;
+}
+
+bool OOWriterWorker::doVariableSettings(const VariableSettingsData& vs)
+{
+ m_varSet=vs;
+
+ return true;
+}
+
+bool OOWriterWorker::doDeclareNonInlinedFramesets( TQValueList<FrameAnchor>& pictureAnchors, TQValueList<FrameAnchor>& tableAnchors )
+{
+ m_nonInlinedPictureAnchors = pictureAnchors;
+ m_nonInlinedTableAnchors = tableAnchors;
+ return true;
+}
+
+void OOWriterWorker::declareFont(const TQString& fontName)
+{
+ if (fontName.isEmpty())
+ return;
+
+ if (m_fontNames.find(fontName)==m_fontNames.end())
+ {
+ TQString props;
+
+ // Disabled, as TQFontInfo::styleHint() cannot guess
+#if 0
+ TQFont font(fontName);
+ TQFontInfo info(font);
+ props+="style:font-family-generic=\""
+ switch (info.styleHint())
+ {
+ case TQFont::SansSerif:
+ default:
+ {
+ props += "swiss";
+ break;
+ }
+ case TQFont::Serif:
+ {
+ props += "roman";
+ break;
+ }
+ case TQFont::Courier:
+ {
+ props += "modern";
+ break;
+ }
+ case TQFont::OldEnglish:
+ {
+ props += "decorative";
+ break;
+ }
+ }
+ props +="\" ";
+#endif
+
+ props +="style:font-pitch=\"variable\""; // ### TODO: check if font is variable or fixed
+ // New font, so register it
+ m_fontNames[fontName]=props;
+ }
+}
+
+TQString OOWriterWorker::makeAutomaticStyleName(const TQString& prefix, ulong& counter) const
+{
+ const TQString str (prefix + TQString::number(++counter,10));
+
+ // Checks if the automatic style has not the same name as a user one.
+ // If it is the case, change it!
+
+ if (m_styleMap.find(str)==m_styleMap.end())
+ return str; // Unique, so let's go!
+
+ TQString str2(str+"_bis");
+ if (m_styleMap.find(str2)==m_styleMap.end())
+ return str2;
+
+ str2 = str+"_ter";
+ if (m_styleMap.find(str2)==m_styleMap.end())
+ return str2;
+
+ // If it is still not unique, try a time stamp.
+ const TQDateTime dt(TQDateTime::currentDateTime(Qt::UTC));
+
+ str2 = str + "_" + TQString::number(dt.toTime_t(),16);
+ if (m_styleMap.find(str2)==m_styleMap.end())
+ return str2;
+
+ kdWarning(30518) << "Could not make an unique style name: " << str2 << endl;
+ return str2; // Still return, as we have nothing better
+}
+
diff --git a/filters/kword/oowriter/ExportFilter.h b/filters/kword/oowriter/ExportFilter.h
index c89e15acb..d4fa9db2e 100644
--- a/filters/kword/oowriter/ExportFilter.h
+++ b/filters/kword/oowriter/ExportFilter.h
@@ -19,7 +19,7 @@
/*
This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
The old file was copyrighted by
Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
diff --git a/filters/kword/oowriter/Makefile.am b/filters/kword/oowriter/Makefile.am
index 63b37bbfc..775b2beb6 100644
--- a/filters/kword/oowriter/Makefile.am
+++ b/filters/kword/oowriter/Makefile.am
@@ -7,13 +7,13 @@ $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = liboowriterimport.la liboowriterexport.la
noinst_LTLIBRARIES = libcommon.la
-libcommon_la_SOURCES = conversion.cc
+libcommon_la_SOURCES = conversion.cpp
-liboowriterimport_la_SOURCES = oowriterimport.cc
+liboowriterimport_la_SOURCES = oowriterimport.cpp
liboowriterimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
liboowriterimport_la_LIBADD = ../../liboofilter/liboofilter.la libcommon.la $(KOFFICE_LIBS)
-liboowriterexport_la_SOURCES = oowriterexport.cc ExportFilter.cc
+liboowriterexport_la_SOURCES = oowriterexport.cpp ExportFilter.cpp
liboowriterexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
liboowriterexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.la libcommon.la
diff --git a/filters/kword/oowriter/conversion.cc b/filters/kword/oowriter/conversion.cpp
index 259d97b5b..259d97b5b 100644
--- a/filters/kword/oowriter/conversion.cc
+++ b/filters/kword/oowriter/conversion.cpp
diff --git a/filters/kword/oowriter/oowriterexport.cc b/filters/kword/oowriter/oowriterexport.cc
deleted file mode 100644
index aba0ee9fd..000000000
--- a/filters/kword/oowriter/oowriterexport.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <kimageio.h>
-
-#include <KoFilterChain.h>
-
-#include "ExportFilter.h"
-#include "oowriterexport.h"
-
-class OOWRITERExportFactory : KGenericFactory<OOWRITERExport, KoFilter>
-{
-public:
- OOWRITERExportFactory(void) : KGenericFactory<OOWRITERExport, KoFilter> ("kwordoowriterexport")
- {}
-};
-
-K_EXPORT_COMPONENT_FACTORY( liboowriterexport, OOWRITERExportFactory() )
-
-OOWRITERExport::OOWRITERExport(KoFilter */*parent*/, const char */*name*/, const TQStringList &) :
- KoFilter() {
-}
-
-KoFilter::ConversionStatus OOWRITERExport::convert( const TQCString& from, const TQCString& to )
-{
- if ( to != "application/vnd.sun.xml.writer" || from != "application/x-kword" )
- {
- return KoFilter::NotImplemented;
- }
-
- // We need KimageIO's help in OOWriterWorker::convertUnknownImage
- KImageIO::registerFormats();
-
- OOWriterWorker* worker=new OOWriterWorker();
-
- if (!worker)
- {
- kdError(30506) << "Cannot create Worker! Aborting!" << endl;
- return KoFilter::StupidError;
- }
-
- KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
-
- if (!leader)
- {
- kdError(30506) << "Cannot create Worker! Aborting!" << endl;
- delete worker;
- return KoFilter::StupidError;
- }
-
- KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
-
- delete leader;
- delete worker;
-
- return result;
-}
-
-#include "oowriterexport.moc"
diff --git a/filters/kword/oowriter/oowriterexport.cpp b/filters/kword/oowriter/oowriterexport.cpp
new file mode 100644
index 000000000..5c974084e
--- /dev/null
+++ b/filters/kword/oowriter/oowriterexport.cpp
@@ -0,0 +1,90 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001, 2002, 2003, 2004 Nicolas GOUTTE <goutte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kimageio.h>
+
+#include <KoFilterChain.h>
+
+#include "ExportFilter.h"
+#include "oowriterexport.h"
+
+class OOWRITERExportFactory : KGenericFactory<OOWRITERExport, KoFilter>
+{
+public:
+ OOWRITERExportFactory(void) : KGenericFactory<OOWRITERExport, KoFilter> ("kwordoowriterexport")
+ {}
+};
+
+K_EXPORT_COMPONENT_FACTORY( liboowriterexport, OOWRITERExportFactory() )
+
+OOWRITERExport::OOWRITERExport(KoFilter */*parent*/, const char */*name*/, const TQStringList &) :
+ KoFilter() {
+}
+
+KoFilter::ConversionStatus OOWRITERExport::convert( const TQCString& from, const TQCString& to )
+{
+ if ( to != "application/vnd.sun.xml.writer" || from != "application/x-kword" )
+ {
+ return KoFilter::NotImplemented;
+ }
+
+ // We need KimageIO's help in OOWriterWorker::convertUnknownImage
+ KImageIO::registerFormats();
+
+ OOWriterWorker* worker=new OOWriterWorker();
+
+ if (!worker)
+ {
+ kdError(30506) << "Cannot create Worker! Aborting!" << endl;
+ return KoFilter::StupidError;
+ }
+
+ KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
+
+ if (!leader)
+ {
+ kdError(30506) << "Cannot create Worker! Aborting!" << endl;
+ delete worker;
+ return KoFilter::StupidError;
+ }
+
+ KoFilter::ConversionStatus result=leader->convert(m_chain,from,to);
+
+ delete leader;
+ delete worker;
+
+ return result;
+}
+
+#include "oowriterexport.moc"
diff --git a/filters/kword/oowriter/oowriterimport.cc b/filters/kword/oowriter/oowriterimport.cpp
index 5e54ce06f..5e54ce06f 100644
--- a/filters/kword/oowriter/oowriterimport.cc
+++ b/filters/kword/oowriter/oowriterimport.cpp
diff --git a/filters/kword/palmdoc/Makefile.am b/filters/kword/palmdoc/Makefile.am
index 1e0e7d9ec..6f1b64e47 100644
--- a/filters/kword/palmdoc/Makefile.am
+++ b/filters/kword/palmdoc/Makefile.am
@@ -10,8 +10,8 @@ libpalmdocexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.
kde_module_LTLIBRARIES = libpalmdocimport.la libpalmdocexport.la
-libpalmdocimport_la_SOURCES = palmdocimport.cc palmdb.cpp palmdoc.cpp
-libpalmdocexport_la_SOURCES = palmdocexport.cc palmdb.cpp palmdoc.cpp
+libpalmdocimport_la_SOURCES = palmdocimport.cpp palmdb.cpp palmdoc.cpp
+libpalmdocexport_la_SOURCES = palmdocexport.cpp palmdb.cpp palmdoc.cpp
noinst_HEADERS = palmdocimport.h palmdb.h palmdoc.h
diff --git a/filters/kword/palmdoc/palmdocexport.cc b/filters/kword/palmdoc/palmdocexport.cpp
index 37f8d9cf2..37f8d9cf2 100644
--- a/filters/kword/palmdoc/palmdocexport.cc
+++ b/filters/kword/palmdoc/palmdocexport.cpp
diff --git a/filters/kword/palmdoc/palmdocimport.cc b/filters/kword/palmdoc/palmdocimport.cpp
index a1e8107bc..a1e8107bc 100644
--- a/filters/kword/palmdoc/palmdocimport.cc
+++ b/filters/kword/palmdoc/palmdocimport.cpp
diff --git a/filters/kword/pdf/diffs/goo_enable-final.diff b/filters/kword/pdf/diffs/goo_enable-final.diff
index b3d137ad7..7993ce58e 100644
--- a/filters/kword/pdf/diffs/goo_enable-final.diff
+++ b/filters/kword/pdf/diffs/goo_enable-final.diff
@@ -1,11 +1,11 @@
-Index: GHash.cc
+Index: GHash.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GHash.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GHash.cpp,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -p -r1.2 -r1.3
---- GHash.cc 13 Jan 2003 14:51:16 -0000 1.2
-+++ GHash.cc 10 Oct 2004 21:37:09 -0000 1.3
+--- GHash.cpp 13 Jan 2003 14:51:16 -0000 1.2
++++ GHash.cpp 10 Oct 2004 21:37:09 -0000 1.3
@@ -8,9 +8,6 @@
#include <aconf.h>
@@ -34,14 +34,14 @@ diff -u -p -r1.2 -r1.3
#include "gtypes.h"
-Index: GList.cc
+Index: GList.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GList.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GList.cpp,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -p -r1.1 -r1.2
---- GList.cc 23 Nov 2002 14:15:14 -0000 1.1
-+++ GList.cc 10 Oct 2004 21:37:09 -0000 1.2
+--- GList.cpp 23 Nov 2002 14:15:14 -0000 1.1
++++ GList.cpp 10 Oct 2004 21:37:09 -0000 1.2
@@ -8,9 +8,6 @@
#include <aconf.h>
@@ -70,14 +70,14 @@ diff -u -p -r1.1 -r1.2
#include "gtypes.h"
-Index: GString.cc
+Index: GString.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GString.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GString.cpp,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -p -r1.1 -r1.2
---- GString.cc 23 Nov 2002 14:15:14 -0000 1.1
-+++ GString.cc 10 Oct 2004 21:37:09 -0000 1.2
+--- GString.cpp 23 Nov 2002 14:15:14 -0000 1.1
++++ GString.cpp 10 Oct 2004 21:37:09 -0000 1.2
@@ -10,9 +10,6 @@
#include <aconf.h>
diff --git a/filters/kword/pdf/diffs/goo_gfile.diff b/filters/kword/pdf/diffs/goo_gfile.diff
index 6aac2487c..2e9cdd537 100644
--- a/filters/kword/pdf/diffs/goo_gfile.diff
+++ b/filters/kword/pdf/diffs/goo_gfile.diff
@@ -1,6 +1,6 @@
-diff -u /home/azhyd/xpdf-2.00/goo/gfile.cc goo/gfile.cc
---- /home/azhyd/xpdf-2.00/goo/gfile.cc Sun Nov 3 23:15:36 2002
-+++ goo/gfile.cc Wed Nov 20 06:43:32 2002
+diff -u /home/azhyd/xpdf-2.00/goo/gfile.cpp goo/gfile.cpp
+--- /home/azhyd/xpdf-2.00/goo/gfile.cpp Sun Nov 3 23:15:36 2002
++++ goo/gfile.cpp Wed Nov 20 06:43:32 2002
@@ -443,7 +443,7 @@
#endif
}
diff --git a/filters/kword/pdf/diffs/xpdf_TextOutputDev.diff b/filters/kword/pdf/diffs/xpdf_TextOutputDev.diff
index ec981364b..693ecb556 100644
--- a/filters/kword/pdf/diffs/xpdf_TextOutputDev.diff
+++ b/filters/kword/pdf/diffs/xpdf_TextOutputDev.diff
@@ -1,6 +1,6 @@
-diff -u /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cc xpdf/TextOutputDev.cc
---- /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cc Thu Nov 14 04:41:00 2002
-+++ xpdf/TextOutputDev.cc Sat Nov 23 21:01:14 2002
+diff -u /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cpp xpdf/TextOutputDev.cpp
+--- /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cpp Thu Nov 14 04:41:00 2002
++++ xpdf/TextOutputDev.cpp Sat Nov 23 21:01:14 2002
@@ -46,26 +46,6 @@
// TextBlock
//------------------------------------------------------------------------
diff --git a/filters/kword/pdf/diffs/xpdf_includes.diff b/filters/kword/pdf/diffs/xpdf_includes.diff
index 33fbea601..c9eeb465d 100644
--- a/filters/kword/pdf/diffs/xpdf_includes.diff
+++ b/filters/kword/pdf/diffs/xpdf_includes.diff
@@ -10,9 +10,9 @@ diff -u /home/azhyd/xpdf-2.00/xpdf/Error.h xpdf/Error.h
extern void CDECL error(int pos, char *msg, ...);
-diff -u /home/azhyd/xpdf-2.00/xpdf/PDFDoc.cc xpdf/PDFDoc.cc
---- /home/azhyd/xpdf-2.00/xpdf/PDFDoc.cc Sun Nov 3 23:15:36 2002
-+++ xpdf/PDFDoc.cc Wed Nov 20 07:30:55 2002
+diff -u /home/azhyd/xpdf-2.00/xpdf/PDFDoc.cpp xpdf/PDFDoc.cpp
+--- /home/azhyd/xpdf-2.00/xpdf/PDFDoc.cpp Sun Nov 3 23:15:36 2002
++++ xpdf/PDFDoc.cpp Wed Nov 20 07:30:55 2002
@@ -17,7 +17,7 @@
#include <stddef.h>
#include <string.h>
@@ -22,9 +22,9 @@ diff -u /home/azhyd/xpdf-2.00/xpdf/PDFDoc.cc xpdf/PDFDoc.cc
#include "GlobalParams.h"
#include "Page.h"
#include "Catalog.h"
-diff -u /home/azhyd/xpdf-2.00/xpdf/Stream.cc xpdf/Stream.cc
---- /home/azhyd/xpdf-2.00/xpdf/Stream.cc Sun Nov 3 23:15:37 2002
-+++ xpdf/Stream.cc Wed Nov 20 07:31:33 2002
+diff -u /home/azhyd/xpdf-2.00/xpdf/Stream.cpp xpdf/Stream.cpp
+--- /home/azhyd/xpdf-2.00/xpdf/Stream.cpp Sun Nov 3 23:15:37 2002
++++ xpdf/Stream.cpp Wed Nov 20 07:31:33 2002
@@ -22,7 +22,7 @@
#include <ctype.h>
#include "gmem.h"
@@ -34,9 +34,9 @@ diff -u /home/azhyd/xpdf-2.00/xpdf/Stream.cc xpdf/Stream.cc
#include "Error.h"
#include "Object.h"
#ifndef NO_DECRYPTION
-diff -u /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cc xpdf/TextOutputDev.cc
---- /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cc Thu Nov 14 04:41:00 2002
-+++ xpdf/TextOutputDev.cc Wed Nov 20 07:31:41 2002
+diff -u /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cpp xpdf/TextOutputDev.cpp
+--- /home/azhyd/xpdf-2.00/xpdf/TextOutputDev.cpp Thu Nov 14 04:41:00 2002
++++ xpdf/TextOutputDev.cpp Wed Nov 20 07:31:41 2002
@@ -19,7 +19,7 @@
#include <ctype.h>
#include "GString.h"
diff --git a/filters/kword/pdf/diffs/xpdf_security_integer_overflow.diff b/filters/kword/pdf/diffs/xpdf_security_integer_overflow.diff
index 1b3872083..d5261ba68 100644
--- a/filters/kword/pdf/diffs/xpdf_security_integer_overflow.diff
+++ b/filters/kword/pdf/diffs/xpdf_security_integer_overflow.diff
@@ -1,10 +1,10 @@
-Index: Catalog.cc
+Index: Catalog.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/Catalog.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/Catalog.cpp,v
retrieving revision 1.1
-diff -u -p -r1.1 Catalog.cc
---- Catalog.cc 23 Nov 2002 14:15:14 -0000 1.1
-+++ Catalog.cc 30 Oct 2004 16:34:49 -0000
+diff -u -p -r1.1 Catalog.cpp
+--- Catalog.cpp 23 Nov 2002 14:15:14 -0000 1.1
++++ Catalog.cpp 30 Oct 2004 16:34:49 -0000
@@ -12,6 +12,7 @@
#pragma implementation
#endif
@@ -38,13 +38,13 @@ diff -u -p -r1.1 Catalog.cc
pages = (Page **)grealloc(pages, pagesSize * sizeof(Page *));
pageRefs = (Ref *)grealloc(pageRefs, pagesSize * sizeof(Ref));
for (j = pagesSize - 32; j < pagesSize; ++j) {
-Index: XRef.cc
+Index: XRef.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/XRef.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/XRef.cpp,v
retrieving revision 1.1
-diff -u -p -r1.1 XRef.cc
---- XRef.cc 23 Nov 2002 14:15:14 -0000 1.1
-+++ XRef.cc 30 Oct 2004 16:34:53 -0000
+diff -u -p -r1.1 XRef.cpp
+--- XRef.cpp 23 Nov 2002 14:15:14 -0000 1.1
++++ XRef.cpp 30 Oct 2004 16:34:53 -0000
@@ -12,6 +12,7 @@
#pragma implementation
#endif
diff --git a/filters/kword/pdf/diffs/xpdf_security_integer_overflow_2.diff b/filters/kword/pdf/diffs/xpdf_security_integer_overflow_2.diff
index e64646128..38bb723ec 100644
--- a/filters/kword/pdf/diffs/xpdf_security_integer_overflow_2.diff
+++ b/filters/kword/pdf/diffs/xpdf_security_integer_overflow_2.diff
@@ -1,11 +1,11 @@
-Index: goo/GHash.cc
+Index: goo/GHash.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GHash.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GHash.cpp,v
retrieving revision 1.3
retrieving revision 1.2.2.1
diff -u -p -r1.3 -r1.2.2.1
---- goo/GHash.cc 10 Oct 2004 21:37:09 -0000 1.3
-+++ goo/GHash.cc 21 Oct 2004 20:32:51 -0000 1.2.2.1
+--- goo/GHash.cpp 10 Oct 2004 21:37:09 -0000 1.3
++++ goo/GHash.cpp 21 Oct 2004 20:32:51 -0000 1.2.2.1
@@ -8,7 +8,6 @@
#include <aconf.h>
@@ -30,14 +30,14 @@ diff -u -p -r1.3 -r1.2.2.1
#include "gtypes.h"
class GString;
-Index: goo/GList.cc
+Index: goo/GList.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GList.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GList.cpp,v
retrieving revision 1.2
retrieving revision 1.1.2.1
diff -u -p -r1.2 -r1.1.2.1
---- goo/GList.cc 10 Oct 2004 21:37:09 -0000 1.2
-+++ goo/GList.cc 21 Oct 2004 20:32:51 -0000 1.1.2.1
+--- goo/GList.cpp 10 Oct 2004 21:37:09 -0000 1.2
++++ goo/GList.cpp 21 Oct 2004 20:32:51 -0000 1.1.2.1
@@ -8,7 +8,6 @@
#include <aconf.h>
@@ -62,14 +62,14 @@ diff -u -p -r1.2 -r1.1.2.1
#include "gtypes.h"
//------------------------------------------------------------------------
-Index: goo/GString.cc
+Index: goo/GString.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GString.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/goo/GString.cpp,v
retrieving revision 1.2
retrieving revision 1.1.2.1
diff -u -p -r1.2 -r1.1.2.1
---- goo/GString.cc 10 Oct 2004 21:37:09 -0000 1.2
-+++ goo/GString.cc 21 Oct 2004 20:32:51 -0000 1.1.2.1
+--- goo/GString.cpp 10 Oct 2004 21:37:09 -0000 1.2
++++ goo/GString.cpp 21 Oct 2004 20:32:51 -0000 1.1.2.1
@@ -10,7 +10,6 @@
#include <aconf.h>
@@ -94,14 +94,14 @@ diff -u -p -r1.3 -r1.2.2.1
#include <string.h>
class GString {
-Index: xpdf/Gfx.cc
+Index: xpdf/Gfx.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/Gfx.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/Gfx.cpp,v
retrieving revision 1.3
retrieving revision 1.3.2.1
diff -u -p -r1.3 -r1.3.2.1
---- xpdf/Gfx.cc 25 Jan 2003 23:17:44 -0000 1.3
-+++ xpdf/Gfx.cc 22 Dec 2004 12:07:12 -0000 1.3.2.1
+--- xpdf/Gfx.cpp 25 Jan 2003 23:17:44 -0000 1.3
++++ xpdf/Gfx.cpp 22 Dec 2004 12:07:12 -0000 1.3.2.1
@@ -2379,7 +2379,9 @@ void Gfx::doImage(Object *ref, Stream *s
haveMask = gFalse;
dict->lookup("Mask", &maskObj);
@@ -113,14 +113,14 @@ diff -u -p -r1.3 -r1.3.2.1
maskObj.arrayGet(i, &obj1);
maskColors[i] = obj1.getInt();
obj1.free();
-Index: xpdf/GfxState.cc
+Index: xpdf/GfxState.cpp
===================================================================
-RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/GfxState.cc,v
+RCS file: /home/kde/koffice/filters/kword/pdf/xpdf/xpdf/GfxState.cpp,v
retrieving revision 1.3
retrieving revision 1.3.2.2
diff -u -p -r1.3 -r1.3.2.2
---- xpdf/GfxState.cc 25 Jan 2003 23:17:44 -0000 1.3
-+++ xpdf/GfxState.cc 22 Dec 2004 13:50:53 -0000 1.3.2.2
+--- xpdf/GfxState.cpp 25 Jan 2003 23:17:44 -0000 1.3
++++ xpdf/GfxState.cpp 22 Dec 2004 13:50:53 -0000 1.3.2.2
@@ -682,6 +682,11 @@ GfxColorSpace *GfxICCBasedColorSpace::pa
}
nCompsA = obj2.getInt();
diff --git a/filters/kword/pdf/xpdf/CHANGES b/filters/kword/pdf/xpdf/CHANGES
index 7a09620d2..6cf5c8ef1 100644
--- a/filters/kword/pdf/xpdf/CHANGES
+++ b/filters/kword/pdf/xpdf/CHANGES
@@ -44,7 +44,7 @@ Changed several things to ease porting:
- changed '__inline' to 'inline' (to adhere to the ANSI standard)
- surrounded interface/implementation pragmas with #ifdef _GNUC__
- got rid of empty array initializer lists
- - moved Operator type definition from Gfx.cc to Gfx.h
+ - moved Operator type definition from Gfx.cpp to Gfx.h
- renamed String, uint, etc.
- ability to uncompress to file (NO_POPEN and USE_GZIP flags)
- added definitions of XK_Page_Up/Down and XPointer for old versions
@@ -75,7 +75,7 @@ Fixed PostScript output:
- if page is larger than paper size, scale it down.
Set default MediaBox to 8.5" x 11" to deal with non-compliant PDF
files which don't specify a MediaBox.
-Added DEBUG_MEM stuff in gmem.c and gmempp.cc.
+Added DEBUG_MEM stuff in gmem.c and gmempp.cpp.
Fixed memory leaks:
- LTKWindow didn't delete the LTKBox.
- LinkAction needs a virtual destructor.
@@ -149,7 +149,7 @@ Added file name to window title.
Implemented RunLength filter.
Implemented forms.
Convert ObjType to an enum.
-Changed isDict("Pages") to isDict() (in Catalog.cc) to deal with
+Changed isDict("Pages") to isDict() (in Catalog.cpp) to deal with
incorrect PDF files.
Changed color selection so that very pale colors don't map to white.
Fixed bug in CCITTFax filter (multiple make-up codes).
@@ -292,10 +292,10 @@ ASCII85Stream, ASCIIHexStream, and DCTStream didn't check for EOF and
could run past the end of the stream in damaged files.
Handle hex escapes (#xx) in names. Still allow the name /# for
backward-compatibility.
-Check for NULL characters in encoding array in GfxFont.cc (was calling
+Check for NULL characters in encoding array in GfxFont.cpp (was calling
strcmp() with NULL which crashed under Solaris).
PageAttrs::PageAttrs() didn't initialize crop box boundaries.
-Changed uses of lookup() to lookupNF() in XRef.cc.
+Changed uses of lookup() to lookupNF() in XRef.cpp.
Fixed type checking of operators which take a variable number of
args.
Gfx::buildImageStream() doesn't need to check for parser (since I got
@@ -311,7 +311,7 @@ Throw away zero-length strings in TextOutputDev -- they don't have
valid xMin/xMax values.
Swapped order of XLIBS and XPMLIB in xpdf/Makefile.
Deleted 'LTKApp::' in function declaration in LTKApp.h.
-Changed '(XKeyEvent *)&event' to '&event.xkey' in LTKApp.cc.
+Changed '(XKeyEvent *)&event' to '&event.xkey' in LTKApp.cpp.
Check that the link rectangle coordinates are in the correct order,
and swap if necessary.
TextOutputDev didn't set text to NULL, which caused pdftotext to
@@ -346,7 +346,7 @@ Rewrote XRef::readXRef() to avoid using a parser to read the xref
entries.
Added NO_TEXT_SELECT option.
Ignore APPn/COM/etc. markers in DCT streams.
-Replaced select() with XMultiplexInput() in LTKApp.cc for VMS.
+Replaced select() with XMultiplexInput() in LTKApp.cpp for VMS.
Handle WM_DELETE_WINDOW protocol -- if you ask the window manager to
delete the xpdf window, xpdf will exit cleanly; other
windows/dialogs are simply closed.
@@ -359,7 +359,7 @@ Added "normal" SETWIDTH parameter to all font descriptors in
Added FOPEN_READ_BIN and FOPEN_WRITE_BIN to support Win32.
Added a hack which allows better font substitution for some Type 3
fonts. Also allow character names of the form /nn and /nnn.
-Added <strings.h> and <bstring.h> to LTKApp.cc (needed by AIX and IRIX
+Added <strings.h> and <bstring.h> to LTKApp.cpp (needed by AIX and IRIX
for bzero() declaration for FD_ZERO).
0.80 (98-nov-27)
@@ -404,7 +404,7 @@ Changes to configure script and Makefiles:
- Get rid of AC_C_INLINE -- this is meant for C, not C++.
- Changed -USE_GZIP to -DUSE_GZIP.
- Added ability to compile ouside of the source tree.
- - Added .cc.o rule to {goo,ltk,xpdf}/Makefile.in.
+ - Added .cpp.o rule to {goo,ltk,xpdf}/Makefile.in.
- Added @LIBS@ to XLIBS in xpdf/Makefile.in.
- In top-level Makefile.in: added '-' to clean commands; added
distclean rule.
@@ -529,7 +529,7 @@ Do a better job with anti-aliased Type 1 fonts on non-white
Handle Lab color spaces.
Handle non-null user passwords.
Avoid security hole with tmpnam()/fopen() -- added openTempFile() in
- goo/gfile.cc. [Thanks to Joseph S. Myers for pointing this out.]
+ goo/gfile.cpp. [Thanks to Joseph S. Myers for pointing this out.]
Filter out quote marks (' and ") in URLs before running urlCommand to
avoid a potential security hole. [Thanks to Frank Doepper for
pointing this out.]
@@ -582,7 +582,7 @@ Fixed a memory (malloc size) bug in CCITTFaxStream.
Fixed two bugs in FontEncoding::hash() -- handle zero-length character
names (which were found in a (buggy?) PDF file), and handle
character names with high-bit-set characters (use unsigned ints).
-Added PDFDoc::isLinearized() and corresponding code in pdfinfo.cc.
+Added PDFDoc::isLinearized() and corresponding code in pdfinfo.cpp.
Handle files with an incorrect page count in the Pages dictionary
(FOP, from the Apache project produces a page count of 0).
Handle TrueType equivalents to the Base14 fonts (Arial, TimesNewRoman,
@@ -602,7 +602,7 @@ Configure script switches to C++ for the strings.h/bstring.h test.
Gfx::opRestore() calls clearPath() to handle (apparently) buggy PDF
files produced by FreeHand.
The /Type field in most dictionaries is optional (PDF 1.3 change).
-Move printCommands variable definition into Gfx.cc.
+Move printCommands variable definition into Gfx.cpp.
If page is smaller than paper, center the PostScript output.
Fix a minor bug in the SELECT_TAKES_INT detection in the configure
script.
@@ -661,7 +661,7 @@ Rearranged the GfxResources class.
Clean up white space handling in Lexer.
Make the dpi parameter to PDFDoc::displayPage etc. a double - this
avoids margin gaps with fit-page and fit-width.
-Fix a rounding problem in xpdf.cc that was causing the window to
+Fix a rounding problem in xpdf.cpp that was causing the window to
sometimes be one pixel too small.
Fixed a minor bug in dealing with Base-14 TrueType font names.
Fixed Lab -> RGB color space conversion.
@@ -998,7 +998,7 @@ Added psASCIIHex parameter.
Added the GBK Unicode map to the simplified Chinese language pack.
Pdftotext now opens the text file in binary mode to avoid Microsoft's
annoying automatic end-of-line translation stuff.
-Added an executeCommand function in goo/gfile.cc. [Thanks to Mikhail
+Added an executeCommand function in goo/gfile.cpp. [Thanks to Mikhail
Kruk.]
The %ALDImagePosition OPI comment was wrong if the page was scaled to
a different paper size.
diff --git a/filters/kword/pdf/xpdf/goo/GHash.cc b/filters/kword/pdf/xpdf/goo/GHash.cc
deleted file mode 100644
index d336f88e3..000000000
--- a/filters/kword/pdf/xpdf/goo/GHash.cc
+++ /dev/null
@@ -1,238 +0,0 @@
-//========================================================================
-//
-// GHash.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-
-#include "gmem.h"
-#include "GString.h"
-#include "GHash.h"
-
-//------------------------------------------------------------------------
-
-struct GHashBucket {
- GString *key;
- void *val;
- GHashBucket *next;
-};
-
-struct GHashIter {
- int h;
- GHashBucket *p;
-};
-
-//------------------------------------------------------------------------
-
-GHash::GHash(GBool deleteKeysA) {
- int h;
-
- deleteKeys = deleteKeysA;
- size = 7;
- tab = (GHashBucket **)gmalloc(size * sizeof(GHashBucket *));
- for (h = 0; h < size; ++h) {
- tab[h] = NULL;
- }
- len = 0;
-}
-
-GHash::~GHash() {
- GHashBucket *p;
- int h;
-
- for (h = 0; h < size; ++h) {
- while (tab[h]) {
- p = tab[h];
- tab[h] = p->next;
- if (deleteKeys) {
- delete p->key;
- }
- delete p;
- }
- }
- gfree(tab);
-}
-
-void GHash::add(GString *key, void *val) {
- GHashBucket **oldTab;
- GHashBucket *p;
- int oldSize, i, h;
-
- // expand the table if necessary
- if (len >= size) {
- oldSize = size;
- oldTab = tab;
- size = 2*size + 1;
- tab = (GHashBucket **)gmalloc(size * sizeof(GHashBucket *));
- for (h = 0; h < size; ++h) {
- tab[h] = NULL;
- }
- for (i = 0; i < oldSize; ++i) {
- while (oldTab[i]) {
- p = oldTab[i];
- oldTab[i] = oldTab[i]->next;
- h = hash(p->key);
- p->next = tab[h];
- tab[h] = p;
- }
- }
- gfree(oldTab);
- }
-
- // add the new symbol
- p = new GHashBucket;
- p->key = key;
- p->val = val;
- h = hash(key);
- p->next = tab[h];
- tab[h] = p;
- ++len;
-}
-
-void *GHash::lookup(const GString *key) {
- GHashBucket *p;
- int h;
-
- if (!(p = find(key, &h))) {
- return NULL;
- }
- return p->val;
-}
-
-void *GHash::lookup(const char *key) {
- GHashBucket *p;
- int h;
-
- if (!(p = find(key, &h))) {
- return NULL;
- }
- return p->val;
-}
-
-void *GHash::remove(const GString *key) {
- GHashBucket *p;
- GHashBucket **q;
- void *val;
- int h;
-
- if (!(p = find(key, &h))) {
- return NULL;
- }
- q = &tab[h];
- while (*q != p) {
- q = &((*q)->next);
- }
- *q = p->next;
- if (deleteKeys) {
- delete p->key;
- }
- val = p->val;
- delete p;
- --len;
- return val;
-}
-
-void *GHash::remove(const char *key) {
- GHashBucket *p;
- GHashBucket **q;
- void *val;
- int h;
-
- if (!(p = find(key, &h))) {
- return NULL;
- }
- q = &tab[h];
- while (*q != p) {
- q = &((*q)->next);
- }
- *q = p->next;
- if (deleteKeys) {
- delete p->key;
- }
- val = p->val;
- delete p;
- --len;
- return val;
-}
-
-void GHash::startIter(GHashIter **iter) {
- *iter = new GHashIter;
- (*iter)->h = -1;
- (*iter)->p = NULL;
-}
-
-GBool GHash::getNext(GHashIter **iter, GString **key, void **val) {
- if (!*iter) {
- return gFalse;
- }
- if ((*iter)->p) {
- (*iter)->p = (*iter)->p->next;
- }
- while (!(*iter)->p) {
- if (++(*iter)->h == size) {
- delete *iter;
- *iter = NULL;
- return gFalse;
- }
- (*iter)->p = tab[(*iter)->h];
- }
- *key = (*iter)->p->key;
- *val = (*iter)->p->val;
- return gTrue;
-}
-
-void GHash::killIter(GHashIter **iter) {
- delete *iter;
- *iter = NULL;
-}
-
-GHashBucket *GHash::find(const GString *key, int *h) {
- GHashBucket *p;
-
- *h = hash(key);
- for (p = tab[*h]; p; p = p->next) {
- if (!p->key->cmp(key)) {
- return p;
- }
- }
- return NULL;
-}
-
-GHashBucket *GHash::find(const char *key, int *h) {
- GHashBucket *p;
-
- *h = hash(key);
- for (p = tab[*h]; p; p = p->next) {
- if (!p->key->cmp(key)) {
- return p;
- }
- }
- return NULL;
-}
-
-int GHash::hash(const GString *key) {
- const char *p;
- unsigned int h;
- int i;
-
- h = 0;
- for (p = key->getCString(), i = 0; i < key->getLength(); ++p, ++i) {
- h = 17 * h + (int)(*p & 0xff);
- }
- return (int)(h % size);
-}
-
-int GHash::hash(const char *key) {
- const char *p;
- unsigned int h;
-
- h = 0;
- for (p = key; *p; ++p) {
- h = 17 * h + (int)(*p & 0xff);
- }
- return (int)(h % size);
-}
diff --git a/filters/kword/pdf/xpdf/goo/GHash.cpp b/filters/kword/pdf/xpdf/goo/GHash.cpp
new file mode 100644
index 000000000..94b327766
--- /dev/null
+++ b/filters/kword/pdf/xpdf/goo/GHash.cpp
@@ -0,0 +1,238 @@
+//========================================================================
+//
+// GHash.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+
+#include "gmem.h"
+#include "GString.h"
+#include "GHash.h"
+
+//------------------------------------------------------------------------
+
+struct GHashBucket {
+ GString *key;
+ void *val;
+ GHashBucket *next;
+};
+
+struct GHashIter {
+ int h;
+ GHashBucket *p;
+};
+
+//------------------------------------------------------------------------
+
+GHash::GHash(GBool deleteKeysA) {
+ int h;
+
+ deleteKeys = deleteKeysA;
+ size = 7;
+ tab = (GHashBucket **)gmalloc(size * sizeof(GHashBucket *));
+ for (h = 0; h < size; ++h) {
+ tab[h] = NULL;
+ }
+ len = 0;
+}
+
+GHash::~GHash() {
+ GHashBucket *p;
+ int h;
+
+ for (h = 0; h < size; ++h) {
+ while (tab[h]) {
+ p = tab[h];
+ tab[h] = p->next;
+ if (deleteKeys) {
+ delete p->key;
+ }
+ delete p;
+ }
+ }
+ gfree(tab);
+}
+
+void GHash::add(GString *key, void *val) {
+ GHashBucket **oldTab;
+ GHashBucket *p;
+ int oldSize, i, h;
+
+ // expand the table if necessary
+ if (len >= size) {
+ oldSize = size;
+ oldTab = tab;
+ size = 2*size + 1;
+ tab = (GHashBucket **)gmalloc(size * sizeof(GHashBucket *));
+ for (h = 0; h < size; ++h) {
+ tab[h] = NULL;
+ }
+ for (i = 0; i < oldSize; ++i) {
+ while (oldTab[i]) {
+ p = oldTab[i];
+ oldTab[i] = oldTab[i]->next;
+ h = hash(p->key);
+ p->next = tab[h];
+ tab[h] = p;
+ }
+ }
+ gfree(oldTab);
+ }
+
+ // add the new symbol
+ p = new GHashBucket;
+ p->key = key;
+ p->val = val;
+ h = hash(key);
+ p->next = tab[h];
+ tab[h] = p;
+ ++len;
+}
+
+void *GHash::lookup(const GString *key) {
+ GHashBucket *p;
+ int h;
+
+ if (!(p = find(key, &h))) {
+ return NULL;
+ }
+ return p->val;
+}
+
+void *GHash::lookup(const char *key) {
+ GHashBucket *p;
+ int h;
+
+ if (!(p = find(key, &h))) {
+ return NULL;
+ }
+ return p->val;
+}
+
+void *GHash::remove(const GString *key) {
+ GHashBucket *p;
+ GHashBucket **q;
+ void *val;
+ int h;
+
+ if (!(p = find(key, &h))) {
+ return NULL;
+ }
+ q = &tab[h];
+ while (*q != p) {
+ q = &((*q)->next);
+ }
+ *q = p->next;
+ if (deleteKeys) {
+ delete p->key;
+ }
+ val = p->val;
+ delete p;
+ --len;
+ return val;
+}
+
+void *GHash::remove(const char *key) {
+ GHashBucket *p;
+ GHashBucket **q;
+ void *val;
+ int h;
+
+ if (!(p = find(key, &h))) {
+ return NULL;
+ }
+ q = &tab[h];
+ while (*q != p) {
+ q = &((*q)->next);
+ }
+ *q = p->next;
+ if (deleteKeys) {
+ delete p->key;
+ }
+ val = p->val;
+ delete p;
+ --len;
+ return val;
+}
+
+void GHash::startIter(GHashIter **iter) {
+ *iter = new GHashIter;
+ (*iter)->h = -1;
+ (*iter)->p = NULL;
+}
+
+GBool GHash::getNext(GHashIter **iter, GString **key, void **val) {
+ if (!*iter) {
+ return gFalse;
+ }
+ if ((*iter)->p) {
+ (*iter)->p = (*iter)->p->next;
+ }
+ while (!(*iter)->p) {
+ if (++(*iter)->h == size) {
+ delete *iter;
+ *iter = NULL;
+ return gFalse;
+ }
+ (*iter)->p = tab[(*iter)->h];
+ }
+ *key = (*iter)->p->key;
+ *val = (*iter)->p->val;
+ return gTrue;
+}
+
+void GHash::killIter(GHashIter **iter) {
+ delete *iter;
+ *iter = NULL;
+}
+
+GHashBucket *GHash::find(const GString *key, int *h) {
+ GHashBucket *p;
+
+ *h = hash(key);
+ for (p = tab[*h]; p; p = p->next) {
+ if (!p->key->cmp(key)) {
+ return p;
+ }
+ }
+ return NULL;
+}
+
+GHashBucket *GHash::find(const char *key, int *h) {
+ GHashBucket *p;
+
+ *h = hash(key);
+ for (p = tab[*h]; p; p = p->next) {
+ if (!p->key->cmp(key)) {
+ return p;
+ }
+ }
+ return NULL;
+}
+
+int GHash::hash(const GString *key) {
+ const char *p;
+ unsigned int h;
+ int i;
+
+ h = 0;
+ for (p = key->getCString(), i = 0; i < key->getLength(); ++p, ++i) {
+ h = 17 * h + (int)(*p & 0xff);
+ }
+ return (int)(h % size);
+}
+
+int GHash::hash(const char *key) {
+ const char *p;
+ unsigned int h;
+
+ h = 0;
+ for (p = key; *p; ++p) {
+ h = 17 * h + (int)(*p & 0xff);
+ }
+ return (int)(h % size);
+}
diff --git a/filters/kword/pdf/xpdf/goo/GList.cc b/filters/kword/pdf/xpdf/goo/GList.cc
deleted file mode 100644
index 3754cc713..000000000
--- a/filters/kword/pdf/xpdf/goo/GList.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-//========================================================================
-//
-// GList.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-
-#include <string.h>
-#include "gmem.h"
-#include "GList.h"
-
-//------------------------------------------------------------------------
-// GList
-//------------------------------------------------------------------------
-
-GList::GList() {
- size = 8;
- data = (void **)gmalloc(size * sizeof(void*));
- length = 0;
- inc = 0;
-}
-
-GList::GList(int sizeA) {
- size = sizeA;
- data = (void **)gmalloc(size * sizeof(void*));
- length = 0;
- inc = 0;
-}
-
-GList::~GList() {
- gfree(data);
-}
-
-void GList::append(void *p) {
- if (length >= size) {
- expand();
- }
- data[length++] = p;
-}
-
-void GList::append(GList *list) {
- int i;
-
- while (length + list->length > size) {
- expand();
- }
- for (i = 0; i < list->length; ++i) {
- data[length++] = list->data[i];
- }
-}
-
-void GList::insert(int i, void *p) {
- if (length >= size) {
- expand();
- }
- if (i < length) {
- memmove(data+i+1, data+i, (length - i) * sizeof(void *));
- }
- data[i] = p;
- ++length;
-}
-
-void *GList::del(int i) {
- void *p;
-
- p = data[i];
- if (i < length - 1) {
- memmove(data+i, data+i+1, (length - i - 1) * sizeof(void *));
- }
- --length;
- if (size - length >= ((inc > 0) ? inc : size/2)) {
- shrink();
- }
- return p;
-}
-
-void GList::expand() {
- size += (inc > 0) ? inc : size;
- data = (void **)grealloc(data, size * sizeof(void*));
-}
-
-void GList::shrink() {
- size -= (inc > 0) ? inc : size/2;
- data = (void **)grealloc(data, size * sizeof(void*));
-}
diff --git a/filters/kword/pdf/xpdf/goo/GList.cpp b/filters/kword/pdf/xpdf/goo/GList.cpp
new file mode 100644
index 000000000..5d2a76467
--- /dev/null
+++ b/filters/kword/pdf/xpdf/goo/GList.cpp
@@ -0,0 +1,89 @@
+//========================================================================
+//
+// GList.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+
+#include <string.h>
+#include "gmem.h"
+#include "GList.h"
+
+//------------------------------------------------------------------------
+// GList
+//------------------------------------------------------------------------
+
+GList::GList() {
+ size = 8;
+ data = (void **)gmalloc(size * sizeof(void*));
+ length = 0;
+ inc = 0;
+}
+
+GList::GList(int sizeA) {
+ size = sizeA;
+ data = (void **)gmalloc(size * sizeof(void*));
+ length = 0;
+ inc = 0;
+}
+
+GList::~GList() {
+ gfree(data);
+}
+
+void GList::append(void *p) {
+ if (length >= size) {
+ expand();
+ }
+ data[length++] = p;
+}
+
+void GList::append(GList *list) {
+ int i;
+
+ while (length + list->length > size) {
+ expand();
+ }
+ for (i = 0; i < list->length; ++i) {
+ data[length++] = list->data[i];
+ }
+}
+
+void GList::insert(int i, void *p) {
+ if (length >= size) {
+ expand();
+ }
+ if (i < length) {
+ memmove(data+i+1, data+i, (length - i) * sizeof(void *));
+ }
+ data[i] = p;
+ ++length;
+}
+
+void *GList::del(int i) {
+ void *p;
+
+ p = data[i];
+ if (i < length - 1) {
+ memmove(data+i, data+i+1, (length - i - 1) * sizeof(void *));
+ }
+ --length;
+ if (size - length >= ((inc > 0) ? inc : size/2)) {
+ shrink();
+ }
+ return p;
+}
+
+void GList::expand() {
+ size += (inc > 0) ? inc : size;
+ data = (void **)grealloc(data, size * sizeof(void*));
+}
+
+void GList::shrink() {
+ size -= (inc > 0) ? inc : size/2;
+ data = (void **)grealloc(data, size * sizeof(void*));
+}
diff --git a/filters/kword/pdf/xpdf/goo/GString.cc b/filters/kword/pdf/xpdf/goo/GString.cc
deleted file mode 100644
index 6a556fab8..000000000
--- a/filters/kword/pdf/xpdf/goo/GString.cc
+++ /dev/null
@@ -1,233 +0,0 @@
-//========================================================================
-//
-// GString.cc
-//
-// Simple variable-length string type.
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <ctype.h>
-#include "gtypes.h"
-#include "GString.h"
-
-static inline int size(int len) {
- int delta;
-
- delta = len < 256 ? 7 : 255;
- return ((len + 1) + delta) & ~delta;
-}
-
-inline void GString::resize(int length1) {
- char *s1;
-
- if (!s) {
- s = new char[size(length1)];
- } else if (size(length1) != size(length)) {
- s1 = new char[size(length1)];
- memcpy(s1, s, length + 1);
- delete[] s;
- s = s1;
- }
-}
-
-GString::GString() {
- s = NULL;
- resize(length = 0);
- s[0] = '\0';
-}
-
-GString::GString(const char *sA) {
- int n = strlen(sA);
-
- s = NULL;
- resize(length = n);
- memcpy(s, sA, n + 1);
-}
-
-GString::GString(const char *sA, int lengthA) {
- s = NULL;
- resize(length = lengthA);
- memcpy(s, sA, length * sizeof(char));
- s[length] = '\0';
-}
-
-GString::GString(GString *str, int idx, int lengthA) {
- s = NULL;
- resize(length = lengthA);
- memcpy(s, str->getCString() + idx, length);
- s[length] = '\0';
-}
-
-GString::GString(GString *str) {
- s = NULL;
- resize(length = str->getLength());
- memcpy(s, str->getCString(), length + 1);
-}
-
-GString::GString(GString *str1, GString *str2) {
- int n1 = str1->getLength();
- int n2 = str2->getLength();
-
- s = NULL;
- resize(length = n1 + n2);
- memcpy(s, str1->getCString(), n1);
- memcpy(s + n1, str2->getCString(), n2 + 1);
-}
-
-GString *GString::fromInt(int x) {
- char buf[24]; // enough space for 64-bit ints plus a little extra
- GBool neg;
- Guint y;
- int i;
-
- i = 24;
- if (x == 0) {
- buf[--i] = '0';
- } else {
- if ((neg = x < 0)) {
- y = (Guint)-x;
- } else {
- y = (Guint)x;
- }
- while (i > 0 && y > 0) {
- buf[--i] = '0' + y % 10;
- y /= 10;
- }
- if (neg && i > 0) {
- buf[--i] = '-';
- }
- }
- return new GString(buf + i, 24 - i);
-}
-
-GString::~GString() {
- delete[] s;
-}
-
-GString *GString::clear() {
- s[length = 0] = '\0';
- resize(0);
- return this;
-}
-
-GString *GString::append(char c) {
- resize(length + 1);
- s[length++] = c;
- s[length] = '\0';
- return this;
-}
-
-GString *GString::append(GString *str) {
- int n = str->getLength();
-
- resize(length + n);
- memcpy(s + length, str->getCString(), n + 1);
- length += n;
- return this;
-}
-
-GString *GString::append(const char *str) {
- int n = strlen(str);
-
- resize(length + n);
- memcpy(s + length, str, n + 1);
- length += n;
- return this;
-}
-
-GString *GString::append(const char *str, int lengthA) {
- resize(length + lengthA);
- memcpy(s + length, str, lengthA);
- length += lengthA;
- s[length] = '\0';
- return this;
-}
-
-GString *GString::insert(int i, char c) {
- int j;
-
- resize(length + 1);
- for (j = length + 1; j > i; --j)
- s[j] = s[j-1];
- s[i] = c;
- ++length;
- return this;
-}
-
-GString *GString::insert(int i, GString *str) {
- int n = str->getLength();
- int j;
-
- resize(length + n);
- for (j = length; j >= i; --j)
- s[j+n] = s[j];
- memcpy(s+i, str->getCString(), n);
- length += n;
- return this;
-}
-
-GString *GString::insert(int i, const char *str) {
- int n = strlen(str);
- int j;
-
- resize(length + n);
- for (j = length; j >= i; --j)
- s[j+n] = s[j];
- memcpy(s+i, str, n);
- length += n;
- return this;
-}
-
-GString *GString::insert(int i, const char *str, int lengthA) {
- int j;
-
- resize(length + lengthA);
- for (j = length; j >= i; --j)
- s[j+lengthA] = s[j];
- memcpy(s+i, str, lengthA);
- length += lengthA;
- return this;
-}
-
-GString *GString::del(int i, int n) {
- int j;
-
- if (n > 0) {
- if (i + n > length) {
- n = length - i;
- }
- for (j = i; j <= length - n; ++j) {
- s[j] = s[j + n];
- }
- resize(length -= n);
- }
- return this;
-}
-
-GString *GString::upperCase() {
- int i;
-
- for (i = 0; i < length; ++i) {
- if (islower(s[i]))
- s[i] = toupper(s[i]);
- }
- return this;
-}
-
-GString *GString::lowerCase() {
- int i;
-
- for (i = 0; i < length; ++i) {
- if (isupper(s[i]))
- s[i] = tolower(s[i]);
- }
- return this;
-}
diff --git a/filters/kword/pdf/xpdf/goo/GString.cpp b/filters/kword/pdf/xpdf/goo/GString.cpp
new file mode 100644
index 000000000..ef792adba
--- /dev/null
+++ b/filters/kword/pdf/xpdf/goo/GString.cpp
@@ -0,0 +1,233 @@
+//========================================================================
+//
+// GString.cpp
+//
+// Simple variable-length string type.
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <ctype.h>
+#include "gtypes.h"
+#include "GString.h"
+
+static inline int size(int len) {
+ int delta;
+
+ delta = len < 256 ? 7 : 255;
+ return ((len + 1) + delta) & ~delta;
+}
+
+inline void GString::resize(int length1) {
+ char *s1;
+
+ if (!s) {
+ s = new char[size(length1)];
+ } else if (size(length1) != size(length)) {
+ s1 = new char[size(length1)];
+ memcpy(s1, s, length + 1);
+ delete[] s;
+ s = s1;
+ }
+}
+
+GString::GString() {
+ s = NULL;
+ resize(length = 0);
+ s[0] = '\0';
+}
+
+GString::GString(const char *sA) {
+ int n = strlen(sA);
+
+ s = NULL;
+ resize(length = n);
+ memcpy(s, sA, n + 1);
+}
+
+GString::GString(const char *sA, int lengthA) {
+ s = NULL;
+ resize(length = lengthA);
+ memcpy(s, sA, length * sizeof(char));
+ s[length] = '\0';
+}
+
+GString::GString(GString *str, int idx, int lengthA) {
+ s = NULL;
+ resize(length = lengthA);
+ memcpy(s, str->getCString() + idx, length);
+ s[length] = '\0';
+}
+
+GString::GString(GString *str) {
+ s = NULL;
+ resize(length = str->getLength());
+ memcpy(s, str->getCString(), length + 1);
+}
+
+GString::GString(GString *str1, GString *str2) {
+ int n1 = str1->getLength();
+ int n2 = str2->getLength();
+
+ s = NULL;
+ resize(length = n1 + n2);
+ memcpy(s, str1->getCString(), n1);
+ memcpy(s + n1, str2->getCString(), n2 + 1);
+}
+
+GString *GString::fromInt(int x) {
+ char buf[24]; // enough space for 64-bit ints plus a little extra
+ GBool neg;
+ Guint y;
+ int i;
+
+ i = 24;
+ if (x == 0) {
+ buf[--i] = '0';
+ } else {
+ if ((neg = x < 0)) {
+ y = (Guint)-x;
+ } else {
+ y = (Guint)x;
+ }
+ while (i > 0 && y > 0) {
+ buf[--i] = '0' + y % 10;
+ y /= 10;
+ }
+ if (neg && i > 0) {
+ buf[--i] = '-';
+ }
+ }
+ return new GString(buf + i, 24 - i);
+}
+
+GString::~GString() {
+ delete[] s;
+}
+
+GString *GString::clear() {
+ s[length = 0] = '\0';
+ resize(0);
+ return this;
+}
+
+GString *GString::append(char c) {
+ resize(length + 1);
+ s[length++] = c;
+ s[length] = '\0';
+ return this;
+}
+
+GString *GString::append(GString *str) {
+ int n = str->getLength();
+
+ resize(length + n);
+ memcpy(s + length, str->getCString(), n + 1);
+ length += n;
+ return this;
+}
+
+GString *GString::append(const char *str) {
+ int n = strlen(str);
+
+ resize(length + n);
+ memcpy(s + length, str, n + 1);
+ length += n;
+ return this;
+}
+
+GString *GString::append(const char *str, int lengthA) {
+ resize(length + lengthA);
+ memcpy(s + length, str, lengthA);
+ length += lengthA;
+ s[length] = '\0';
+ return this;
+}
+
+GString *GString::insert(int i, char c) {
+ int j;
+
+ resize(length + 1);
+ for (j = length + 1; j > i; --j)
+ s[j] = s[j-1];
+ s[i] = c;
+ ++length;
+ return this;
+}
+
+GString *GString::insert(int i, GString *str) {
+ int n = str->getLength();
+ int j;
+
+ resize(length + n);
+ for (j = length; j >= i; --j)
+ s[j+n] = s[j];
+ memcpy(s+i, str->getCString(), n);
+ length += n;
+ return this;
+}
+
+GString *GString::insert(int i, const char *str) {
+ int n = strlen(str);
+ int j;
+
+ resize(length + n);
+ for (j = length; j >= i; --j)
+ s[j+n] = s[j];
+ memcpy(s+i, str, n);
+ length += n;
+ return this;
+}
+
+GString *GString::insert(int i, const char *str, int lengthA) {
+ int j;
+
+ resize(length + lengthA);
+ for (j = length; j >= i; --j)
+ s[j+lengthA] = s[j];
+ memcpy(s+i, str, lengthA);
+ length += lengthA;
+ return this;
+}
+
+GString *GString::del(int i, int n) {
+ int j;
+
+ if (n > 0) {
+ if (i + n > length) {
+ n = length - i;
+ }
+ for (j = i; j <= length - n; ++j) {
+ s[j] = s[j + n];
+ }
+ resize(length -= n);
+ }
+ return this;
+}
+
+GString *GString::upperCase() {
+ int i;
+
+ for (i = 0; i < length; ++i) {
+ if (islower(s[i]))
+ s[i] = toupper(s[i]);
+ }
+ return this;
+}
+
+GString *GString::lowerCase() {
+ int i;
+
+ for (i = 0; i < length; ++i) {
+ if (isupper(s[i]))
+ s[i] = tolower(s[i]);
+ }
+ return this;
+}
diff --git a/filters/kword/pdf/xpdf/goo/Makefile.am b/filters/kword/pdf/xpdf/goo/Makefile.am
index 186aa0db3..3a5700d7b 100644
--- a/filters/kword/pdf/xpdf/goo/Makefile.am
+++ b/filters/kword/pdf/xpdf/goo/Makefile.am
@@ -3,5 +3,5 @@ INCLUDES= -I$(srcdir)
noinst_LTLIBRARIES = libgoo.la
-libgoo_la_SOURCES = GHash.cc GList.cc GString.cc gmempp.cc gfile.cc \
+libgoo_la_SOURCES = GHash.cpp GList.cpp GString.cpp gmempp.cpp gfile.cpp \
gmem.c parseargs.c
diff --git a/filters/kword/pdf/xpdf/goo/gfile.cc b/filters/kword/pdf/xpdf/goo/gfile.cc
deleted file mode 100644
index 55fb2f837..000000000
--- a/filters/kword/pdf/xpdf/goo/gfile.cc
+++ /dev/null
@@ -1,700 +0,0 @@
-//========================================================================
-//
-// gfile.cc
-//
-// Miscellaneous file and directory name manipulation.
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef WIN32
- extern "C" {
-# ifndef _MSC_VER
-# include <kpathsea/win32lib.h>
-# endif
- }
-#else // !WIN32
-# if defined(MACOS)
-# include <sys/stat.h>
-# elif !defined(ACORN)
-# include <sys/types.h>
-# include <sys/stat.h>
-# include <fcntl.h>
-# endif
-# include <limits.h>
-# include <string.h>
-# if !defined(VMS) && !defined(ACORN) && !defined(MACOS)
-# include <pwd.h>
-# endif
-# if defined(VMS) && (__DECCXX_VER < 50200000)
-# include <unixlib.h>
-# endif
-#endif // WIN32
-#include "GString.h"
-#include "gfile.h"
-
-// Some systems don't define this, so just make it something reasonably
-// large.
-#ifndef PATH_MAX
-#define PATH_MAX 1024
-#endif
-
-//------------------------------------------------------------------------
-
-GString *getHomeDir() {
-#ifdef VMS
- //---------- VMS ----------
- return new GString("SYS$LOGIN:");
-
-#elif defined(__EMX__) || defined(WIN32)
- //---------- OS/2+EMX and Win32 ----------
- char *s;
- GString *ret;
-
- if ((s = getenv("HOME")))
- ret = new GString(s);
- else
- ret = new GString(".");
- return ret;
-
-#elif defined(ACORN)
- //---------- RISCOS ----------
- return new GString("@");
-
-#elif defined(MACOS)
- //---------- MacOS ----------
- return new GString(":");
-
-#else
- //---------- Unix ----------
- char *s;
- struct passwd *pw;
- GString *ret;
-
- if ((s = getenv("HOME"))) {
- ret = new GString(s);
- } else {
- if ((s = getenv("USER")))
- pw = getpwnam(s);
- else
- pw = getpwuid(getuid());
- if (pw)
- ret = new GString(pw->pw_dir);
- else
- ret = new GString(".");
- }
- return ret;
-#endif
-}
-
-GString *getCurrentDir() {
- char buf[PATH_MAX+1];
-
-#if defined(__EMX__)
- if (_getcwd2(buf, sizeof(buf)))
-#elif defined(WIN32)
- if (GetCurrentDirectory(sizeof(buf), buf))
-#elif defined(ACORN)
- if (strcpy(buf, "@"))
-#elif defined(MACOS)
- if (strcpy(buf, ":"))
-#else
- if (getcwd(buf, sizeof(buf)))
-#endif
- return new GString(buf);
- return new GString();
-}
-
-GString *appendToPath(GString *path, const char *fileName) {
-#if defined(VMS)
- //---------- VMS ----------
- //~ this should handle everything necessary for file
- //~ requesters, but it's certainly not complete
- char *p0, *p1, *p2;
- char *q1;
-
- p0 = path->getCString();
- p1 = p0 + path->getLength() - 1;
- if (!strcmp(fileName, "-")) {
- if (*p1 == ']') {
- for (p2 = p1; p2 > p0 && *p2 != '.' && *p2 != '['; --p2) ;
- if (*p2 == '[')
- ++p2;
- path->del(p2 - p0, p1 - p2);
- } else if (*p1 == ':') {
- path->append("[-]");
- } else {
- path->clear();
- path->append("[-]");
- }
- } else if ((q1 = strrchr(fileName, '.')) && !strncmp(q1, ".DIR;", 5)) {
- if (*p1 == ']') {
- path->insert(p1 - p0, '.');
- path->insert(p1 - p0 + 1, fileName, q1 - fileName);
- } else if (*p1 == ':') {
- path->append('[');
- path->append(']');
- path->append(fileName, q1 - fileName);
- } else {
- path->clear();
- path->append(fileName, q1 - fileName);
- }
- } else {
- if (*p1 != ']' && *p1 != ':')
- path->clear();
- path->append(fileName);
- }
- return path;
-
-#elif defined(WIN32)
- //---------- Win32 ----------
- GString *tmp;
- char buf[256];
- char *fp;
-
- tmp = new GString(path);
- tmp->append('/');
- tmp->append(fileName);
- GetFullPathName(tmp->getCString(), sizeof(buf), buf, &fp);
- delete tmp;
- path->clear();
- path->append(buf);
- return path;
-
-#elif defined(ACORN)
- //---------- RISCOS ----------
- char *p;
- int i;
-
- path->append(".");
- i = path->getLength();
- path->append(fileName);
- for (p = path->getCString() + i; *p; ++p) {
- if (*p == '/') {
- *p = '.';
- } else if (*p == '.') {
- *p = '/';
- }
- }
- return path;
-
-#elif defined(MACOS)
- //---------- MacOS ----------
- char *p;
- int i;
-
- path->append(":");
- i = path->getLength();
- path->append(fileName);
- for (p = path->getCString() + i; *p; ++p) {
- if (*p == '/') {
- *p = ':';
- } else if (*p == '.') {
- *p = ':';
- }
- }
- return path;
-
-#elif defined(__EMX__)
- //---------- OS/2+EMX ----------
- int i;
-
- // appending "." does nothing
- if (!strcmp(fileName, "."))
- return path;
-
- // appending ".." goes up one directory
- if (!strcmp(fileName, "..")) {
- for (i = path->getLength() - 2; i >= 0; --i) {
- if (path->getChar(i) == '/' || path->getChar(i) == '\\' ||
- path->getChar(i) == ':')
- break;
- }
- if (i <= 0) {
- if (path->getChar(0) == '/' || path->getChar(0) == '\\') {
- path->del(1, path->getLength() - 1);
- } else if (path->getLength() >= 2 && path->getChar(1) == ':') {
- path->del(2, path->getLength() - 2);
- } else {
- path->clear();
- path->append("..");
- }
- } else {
- if (path->getChar(i-1) == ':')
- ++i;
- path->del(i, path->getLength() - i);
- }
- return path;
- }
-
- // otherwise, append "/" and new path component
- if (path->getLength() > 0 &&
- path->getChar(path->getLength() - 1) != '/' &&
- path->getChar(path->getLength() - 1) != '\\')
- path->append('/');
- path->append(fileName);
- return path;
-
-#else
- //---------- Unix ----------
- int i;
-
- // appending "." does nothing
- if (!strcmp(fileName, "."))
- return path;
-
- // appending ".." goes up one directory
- if (!strcmp(fileName, "..")) {
- for (i = path->getLength() - 2; i >= 0; --i) {
- if (path->getChar(i) == '/')
- break;
- }
- if (i <= 0) {
- if (path->getChar(0) == '/') {
- path->del(1, path->getLength() - 1);
- } else {
- path->clear();
- path->append("..");
- }
- } else {
- path->del(i, path->getLength() - i);
- }
- return path;
- }
-
- // otherwise, append "/" and new path component
- if (path->getLength() > 0 &&
- path->getChar(path->getLength() - 1) != '/')
- path->append('/');
- path->append(fileName);
- return path;
-#endif
-}
-
-GString *grabPath(const char *fileName) {
-#ifdef VMS
- //---------- VMS ----------
- char *p;
-
- if ((p = strrchr(fileName, ']')))
- return new GString(fileName, p + 1 - fileName);
- if ((p = strrchr(fileName, ':')))
- return new GString(fileName, p + 1 - fileName);
- return new GString();
-
-#elif defined(__EMX__) || defined(WIN32)
- //---------- OS/2+EMX and Win32 ----------
- char *p;
-
- if ((p = strrchr(fileName, '/')))
- return new GString(fileName, p - fileName);
- if ((p = strrchr(fileName, '\\')))
- return new GString(fileName, p - fileName);
- if ((p = strrchr(fileName, ':')))
- return new GString(fileName, p + 1 - fileName);
- return new GString();
-
-#elif defined(ACORN)
- //---------- RISCOS ----------
- char *p;
-
- if ((p = strrchr(fileName, '.')))
- return new GString(fileName, p - fileName);
- return new GString();
-
-#elif defined(MACOS)
- //---------- MacOS ----------
- char *p;
-
- if ((p = strrchr(fileName, ':')))
- return new GString(fileName, p - fileName);
- return new GString();
-
-#else
- //---------- Unix ----------
- const char *p;
-
- if ((p = strrchr(fileName, '/')))
- return new GString(fileName, p - fileName);
- return new GString();
-#endif
-}
-
-GBool isAbsolutePath(const char *path) {
-#ifdef VMS
- //---------- VMS ----------
- return strchr(path, ':') ||
- (path[0] == '[' && path[1] != '.' && path[1] != '-');
-
-#elif defined(__EMX__) || defined(WIN32)
- //---------- OS/2+EMX and Win32 ----------
- return path[0] == '/' || path[0] == '\\' || path[1] == ':';
-
-#elif defined(ACORN)
- //---------- RISCOS ----------
- return path[0] == '$';
-
-#elif defined(MACOS)
- //---------- MacOS ----------
- return path[0] != ':';
-
-#else
- //---------- Unix ----------
- return path[0] == '/';
-#endif
-}
-
-GString *makePathAbsolute(GString *path) {
-#ifdef VMS
- //---------- VMS ----------
- char buf[PATH_MAX+1];
-
- if (!isAbsolutePath(path->getCString())) {
- if (getcwd(buf, sizeof(buf))) {
- path->insert(0, buf);
- }
- }
- return path;
-
-#elif defined(WIN32)
- //---------- Win32 ----------
- char buf[_MAX_PATH];
- char *fp;
-
- buf[0] = '\0';
- if (!GetFullPathName(path->getCString(), _MAX_PATH, buf, &fp)) {
- path->clear();
- return path;
- }
- path->clear();
- path->append(buf);
- return path;
-
-#elif defined(ACORN)
- //---------- RISCOS ----------
- path->insert(0, '@');
- return path;
-
-#elif defined(MACOS)
- //---------- MacOS ----------
- path->del(0, 1);
- return path;
-
-#else
- //---------- Unix and OS/2+EMX ----------
- struct passwd *pw;
- char buf[PATH_MAX+1];
- GString *s;
- char *p1, *p2;
- int n;
-
- if (path->getChar(0) == '~') {
- if (path->getChar(1) == '/' ||
-#ifdef __EMX__
- path->getChar(1) == '\\' ||
-#endif
- path->getLength() == 1) {
- path->del(0, 1);
- s = getHomeDir();
- path->insert(0, s);
- delete s;
- } else {
- p1 = path->getCString() + 1;
-#ifdef __EMX__
- for (p2 = p1; *p2 && *p2 != '/' && *p2 != '\\'; ++p2) ;
-#else
- for (p2 = p1; *p2 && *p2 != '/'; ++p2) ;
-#endif
- if ((n = p2 - p1) > PATH_MAX)
- n = PATH_MAX;
- strncpy(buf, p1, n);
- buf[n] = '\0';
- if ((pw = getpwnam(buf))) {
- path->del(0, p2 - p1 + 1);
- path->insert(0, pw->pw_dir);
- }
- }
- } else if (!isAbsolutePath(path->getCString())) {
- if (getcwd(buf, sizeof(buf))) {
-#ifndef __EMX__
- path->insert(0, '/');
-#endif
- path->insert(0, buf);
- }
- }
- return path;
-#endif
-}
-
-time_t getModTime(const char *fileName) {
-#ifdef WIN32
- //~ should implement this, but it's (currently) only used in xpdf
- return 0;
-#else
- struct stat statBuf;
-
- if (stat(fileName, &statBuf)) {
- return 0;
- }
- return statBuf.st_mtime;
-#endif
-}
-
-GBool openTempFile(GString **name, FILE **f, const char *mode/*, char *ext*/) {
-#if defined(WIN32)
- //---------- Win32 ----------
- char *s;
- char buf[_MAX_PATH];
- char *fp;
-
- if (!(s = _tempnam(getenv("TEMP"), NULL))) {
- return gFalse;
- }
- *name = new GString(s);
- free(s);
- if (ext) {
- (*name)->append(ext);
- }
- if (!(*f = fopen((*name)->getCString(), mode))) {
- delete (*name);
- return gFalse;
- }
- return gTrue;
-#elif defined(VMS) || defined(__EMX__) || defined(ACORN) || defined(MACOS)
- //---------- non-Unix ----------
- char *s;
-
- // There is a security hole here: an attacker can create a symlink
- // with this file name after the tmpnam call and before the fopen
- // call. I will happily accept fixes to this function for non-Unix
- // OSs.
- if (!(s = tmpnam(NULL))) {
- return gFalse;
- }
- *name = new GString(s);
- if (ext) {
- (*name)->append(ext);
- }
- if (!(*f = fopen((*name)->getCString(), mode))) {
- delete (*name);
- return gFalse;
- }
- return gTrue;
-#else
- //---------- Unix ----------
- char *s;
- int fd;
-
-// if (ext) {
-//#if HAVE_MKSTEMPS
-// if ((s = getenv("TMPDIR"))) {
-// *name = new GString(s);
-// } else {
-// *name = new GString("/tmp");
-// }
-// (*name)->append("/XXXXXX")->append(ext);
-// fd = mkstemps((*name)->getCString(), strlen(ext));
-//#else
-// if (!(s = tmpnam(NULL))) {
-// return gFalse;
-//}
-// *name = new GString(s);
-// (*name)->append(ext);
-// fd = open((*name)->getCString(), O_WRONLY | O_CREAT | O_EXCL, 0600);
-//#endif
-//} else {
-#if HAVE_MKSTEMP
- if ((s = getenv("TMPDIR"))) {
- *name = new GString(s);
- } else {
- *name = new GString("/tmp");
- }
- (*name)->append("/XXXXXX");
- fd = mkstemp((*name)->getCString());
-#else // HAVE_MKSTEMP
- if (!(s = tmpnam(NULL))) {
- return gFalse;
- }
- *name = new GString(s);
- fd = open((*name)->getCString(), O_WRONLY | O_CREAT | O_EXCL, 0600);
-#endif // HAVE_MKSTEMP
-// }
- if (fd < 0 || !(*f = fdopen(fd, mode))) {
- delete *name;
- return gFalse;
- }
- return gTrue;
-#endif
-}
-
-GBool executeCommand(const char *cmd) {
-#ifdef VMS
- return system(cmd) ? gTrue : gFalse;
-#else
- return system(cmd) ? gFalse : gTrue;
-#endif
-}
-
-char *getLine(char *buf, int size, FILE *f) {
- int c, i;
-
- i = 0;
- while (i < size - 1) {
- if ((c = fgetc(f)) == EOF) {
- break;
- }
- buf[i++] = (char)c;
- if (c == '\x0a') {
- break;
- }
- if (c == '\x0d') {
- c = fgetc(f);
- if (c == '\x0a' && i < size - 1) {
- buf[i++] = (char)c;
- } else if (c != EOF) {
- ungetc(c, f);
- }
- break;
- }
- }
- buf[i] = '\0';
- if (i == 0) {
- return NULL;
- }
- return buf;
-}
-
-//------------------------------------------------------------------------
-// GDir and GDirEntry
-//------------------------------------------------------------------------
-
-GDirEntry::GDirEntry(const char *dirPath, const char *nameA, GBool doStat) {
-#ifdef VMS
- char *p;
-#elif defined(WIN32)
- int fa;
- GString *s;
-#elif defined(ACORN)
-#else
- struct stat st;
- GString *s;
-#endif
-
- name = new GString(nameA);
- dir = gFalse;
- if (doStat) {
-#ifdef VMS
- if (!strcmp(nameA, "-") ||
- ((p = strrchr(nameA, '.')) && !strncmp(p, ".DIR;", 5)))
- dir = gTrue;
-#elif defined(ACORN)
-#else
- s = new GString(dirPath);
- appendToPath(s, nameA);
-#ifdef WIN32
- fa = GetFileAttributes(s->getCString());
- dir = (fa != 0xFFFFFFFF && (fa & FILE_ATTRIBUTE_DIRECTORY));
-#else
- if (stat(s->getCString(), &st) == 0)
- dir = S_ISDIR(st.st_mode);
-#endif
- delete s;
-#endif
- }
-}
-
-GDirEntry::~GDirEntry() {
- delete name;
-}
-
-GDir::GDir(const char *name, GBool doStatA) {
- path = new GString(name);
- doStat = doStatA;
-#if defined(WIN32)
- GString *tmp;
-
- tmp = path->copy();
- tmp->append("/*.*");
- hnd = FindFirstFile(tmp->getCString(), &ffd);
- delete tmp;
-#elif defined(ACORN)
-#elif defined(MACOS)
-#else
- dir = opendir(name);
-#ifdef VMS
- needParent = strchr(name, '[') != NULL;
-#endif
-#endif
-}
-
-GDir::~GDir() {
- delete path;
-#if defined(WIN32)
- if (hnd) {
- FindClose(hnd);
- hnd = NULL;
- }
-#elif defined(ACORN)
-#elif defined(MACOS)
-#else
- if (dir)
- closedir(dir);
-#endif
-}
-
-GDirEntry *GDir::getNextEntry() {
- struct dirent *ent;
- GDirEntry *e;
-
- e = NULL;
-#if defined(WIN32)
- e = new GDirEntry(path->getCString(), ffd.cFileName, doStat);
- if (hnd && !FindNextFile(hnd, &ffd)) {
- FindClose(hnd);
- hnd = NULL;
- }
-#elif defined(ACORN)
-#elif defined(MACOS)
-#else
- if (dir) {
-#ifdef VMS
- if (needParent) {
- e = new GDirEntry(path->getCString(), "-", doStat);
- needParent = gFalse;
- return e;
- }
-#endif
- ent = readdir(dir);
-#ifndef VMS
- if (ent && !strcmp(ent->d_name, "."))
- ent = readdir(dir);
-#endif
- if (ent)
- e = new GDirEntry(path->getCString(), ent->d_name, doStat);
- }
-#endif
- return e;
-}
-
-void GDir::rewind() {
-#ifdef WIN32
- GString *tmp;
-
- if (hnd)
- FindClose(hnd);
- tmp = path->copy();
- tmp->append("/*.*");
- hnd = FindFirstFile(tmp->getCString(), &ffd);
-#elif defined(ACORN)
-#elif defined(MACOS)
-#else
- if (dir)
- rewinddir(dir);
-#ifdef VMS
- needParent = strchr(path->getCString(), '[') != NULL;
-#endif
-#endif
-}
diff --git a/filters/kword/pdf/xpdf/goo/gfile.cpp b/filters/kword/pdf/xpdf/goo/gfile.cpp
new file mode 100644
index 000000000..7fb7aaefb
--- /dev/null
+++ b/filters/kword/pdf/xpdf/goo/gfile.cpp
@@ -0,0 +1,700 @@
+//========================================================================
+//
+// gfile.cpp
+//
+// Miscellaneous file and directory name manipulation.
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef WIN32
+ extern "C" {
+# ifndef _MSC_VER
+# include <kpathsea/win32lib.h>
+# endif
+ }
+#else // !WIN32
+# if defined(MACOS)
+# include <sys/stat.h>
+# elif !defined(ACORN)
+# include <sys/types.h>
+# include <sys/stat.h>
+# include <fcntl.h>
+# endif
+# include <limits.h>
+# include <string.h>
+# if !defined(VMS) && !defined(ACORN) && !defined(MACOS)
+# include <pwd.h>
+# endif
+# if defined(VMS) && (__DECCXX_VER < 50200000)
+# include <unixlib.h>
+# endif
+#endif // WIN32
+#include "GString.h"
+#include "gfile.h"
+
+// Some systems don't define this, so just make it something reasonably
+// large.
+#ifndef PATH_MAX
+#define PATH_MAX 1024
+#endif
+
+//------------------------------------------------------------------------
+
+GString *getHomeDir() {
+#ifdef VMS
+ //---------- VMS ----------
+ return new GString("SYS$LOGIN:");
+
+#elif defined(__EMX__) || defined(WIN32)
+ //---------- OS/2+EMX and Win32 ----------
+ char *s;
+ GString *ret;
+
+ if ((s = getenv("HOME")))
+ ret = new GString(s);
+ else
+ ret = new GString(".");
+ return ret;
+
+#elif defined(ACORN)
+ //---------- RISCOS ----------
+ return new GString("@");
+
+#elif defined(MACOS)
+ //---------- MacOS ----------
+ return new GString(":");
+
+#else
+ //---------- Unix ----------
+ char *s;
+ struct passwd *pw;
+ GString *ret;
+
+ if ((s = getenv("HOME"))) {
+ ret = new GString(s);
+ } else {
+ if ((s = getenv("USER")))
+ pw = getpwnam(s);
+ else
+ pw = getpwuid(getuid());
+ if (pw)
+ ret = new GString(pw->pw_dir);
+ else
+ ret = new GString(".");
+ }
+ return ret;
+#endif
+}
+
+GString *getCurrentDir() {
+ char buf[PATH_MAX+1];
+
+#if defined(__EMX__)
+ if (_getcwd2(buf, sizeof(buf)))
+#elif defined(WIN32)
+ if (GetCurrentDirectory(sizeof(buf), buf))
+#elif defined(ACORN)
+ if (strcpy(buf, "@"))
+#elif defined(MACOS)
+ if (strcpy(buf, ":"))
+#else
+ if (getcwd(buf, sizeof(buf)))
+#endif
+ return new GString(buf);
+ return new GString();
+}
+
+GString *appendToPath(GString *path, const char *fileName) {
+#if defined(VMS)
+ //---------- VMS ----------
+ //~ this should handle everything necessary for file
+ //~ requesters, but it's certainly not complete
+ char *p0, *p1, *p2;
+ char *q1;
+
+ p0 = path->getCString();
+ p1 = p0 + path->getLength() - 1;
+ if (!strcmp(fileName, "-")) {
+ if (*p1 == ']') {
+ for (p2 = p1; p2 > p0 && *p2 != '.' && *p2 != '['; --p2) ;
+ if (*p2 == '[')
+ ++p2;
+ path->del(p2 - p0, p1 - p2);
+ } else if (*p1 == ':') {
+ path->append("[-]");
+ } else {
+ path->clear();
+ path->append("[-]");
+ }
+ } else if ((q1 = strrchr(fileName, '.')) && !strncmp(q1, ".DIR;", 5)) {
+ if (*p1 == ']') {
+ path->insert(p1 - p0, '.');
+ path->insert(p1 - p0 + 1, fileName, q1 - fileName);
+ } else if (*p1 == ':') {
+ path->append('[');
+ path->append(']');
+ path->append(fileName, q1 - fileName);
+ } else {
+ path->clear();
+ path->append(fileName, q1 - fileName);
+ }
+ } else {
+ if (*p1 != ']' && *p1 != ':')
+ path->clear();
+ path->append(fileName);
+ }
+ return path;
+
+#elif defined(WIN32)
+ //---------- Win32 ----------
+ GString *tmp;
+ char buf[256];
+ char *fp;
+
+ tmp = new GString(path);
+ tmp->append('/');
+ tmp->append(fileName);
+ GetFullPathName(tmp->getCString(), sizeof(buf), buf, &fp);
+ delete tmp;
+ path->clear();
+ path->append(buf);
+ return path;
+
+#elif defined(ACORN)
+ //---------- RISCOS ----------
+ char *p;
+ int i;
+
+ path->append(".");
+ i = path->getLength();
+ path->append(fileName);
+ for (p = path->getCString() + i; *p; ++p) {
+ if (*p == '/') {
+ *p = '.';
+ } else if (*p == '.') {
+ *p = '/';
+ }
+ }
+ return path;
+
+#elif defined(MACOS)
+ //---------- MacOS ----------
+ char *p;
+ int i;
+
+ path->append(":");
+ i = path->getLength();
+ path->append(fileName);
+ for (p = path->getCString() + i; *p; ++p) {
+ if (*p == '/') {
+ *p = ':';
+ } else if (*p == '.') {
+ *p = ':';
+ }
+ }
+ return path;
+
+#elif defined(__EMX__)
+ //---------- OS/2+EMX ----------
+ int i;
+
+ // appending "." does nothing
+ if (!strcmp(fileName, "."))
+ return path;
+
+ // appending ".." goes up one directory
+ if (!strcmp(fileName, "..")) {
+ for (i = path->getLength() - 2; i >= 0; --i) {
+ if (path->getChar(i) == '/' || path->getChar(i) == '\\' ||
+ path->getChar(i) == ':')
+ break;
+ }
+ if (i <= 0) {
+ if (path->getChar(0) == '/' || path->getChar(0) == '\\') {
+ path->del(1, path->getLength() - 1);
+ } else if (path->getLength() >= 2 && path->getChar(1) == ':') {
+ path->del(2, path->getLength() - 2);
+ } else {
+ path->clear();
+ path->append("..");
+ }
+ } else {
+ if (path->getChar(i-1) == ':')
+ ++i;
+ path->del(i, path->getLength() - i);
+ }
+ return path;
+ }
+
+ // otherwise, append "/" and new path component
+ if (path->getLength() > 0 &&
+ path->getChar(path->getLength() - 1) != '/' &&
+ path->getChar(path->getLength() - 1) != '\\')
+ path->append('/');
+ path->append(fileName);
+ return path;
+
+#else
+ //---------- Unix ----------
+ int i;
+
+ // appending "." does nothing
+ if (!strcmp(fileName, "."))
+ return path;
+
+ // appending ".." goes up one directory
+ if (!strcmp(fileName, "..")) {
+ for (i = path->getLength() - 2; i >= 0; --i) {
+ if (path->getChar(i) == '/')
+ break;
+ }
+ if (i <= 0) {
+ if (path->getChar(0) == '/') {
+ path->del(1, path->getLength() - 1);
+ } else {
+ path->clear();
+ path->append("..");
+ }
+ } else {
+ path->del(i, path->getLength() - i);
+ }
+ return path;
+ }
+
+ // otherwise, append "/" and new path component
+ if (path->getLength() > 0 &&
+ path->getChar(path->getLength() - 1) != '/')
+ path->append('/');
+ path->append(fileName);
+ return path;
+#endif
+}
+
+GString *grabPath(const char *fileName) {
+#ifdef VMS
+ //---------- VMS ----------
+ char *p;
+
+ if ((p = strrchr(fileName, ']')))
+ return new GString(fileName, p + 1 - fileName);
+ if ((p = strrchr(fileName, ':')))
+ return new GString(fileName, p + 1 - fileName);
+ return new GString();
+
+#elif defined(__EMX__) || defined(WIN32)
+ //---------- OS/2+EMX and Win32 ----------
+ char *p;
+
+ if ((p = strrchr(fileName, '/')))
+ return new GString(fileName, p - fileName);
+ if ((p = strrchr(fileName, '\\')))
+ return new GString(fileName, p - fileName);
+ if ((p = strrchr(fileName, ':')))
+ return new GString(fileName, p + 1 - fileName);
+ return new GString();
+
+#elif defined(ACORN)
+ //---------- RISCOS ----------
+ char *p;
+
+ if ((p = strrchr(fileName, '.')))
+ return new GString(fileName, p - fileName);
+ return new GString();
+
+#elif defined(MACOS)
+ //---------- MacOS ----------
+ char *p;
+
+ if ((p = strrchr(fileName, ':')))
+ return new GString(fileName, p - fileName);
+ return new GString();
+
+#else
+ //---------- Unix ----------
+ const char *p;
+
+ if ((p = strrchr(fileName, '/')))
+ return new GString(fileName, p - fileName);
+ return new GString();
+#endif
+}
+
+GBool isAbsolutePath(const char *path) {
+#ifdef VMS
+ //---------- VMS ----------
+ return strchr(path, ':') ||
+ (path[0] == '[' && path[1] != '.' && path[1] != '-');
+
+#elif defined(__EMX__) || defined(WIN32)
+ //---------- OS/2+EMX and Win32 ----------
+ return path[0] == '/' || path[0] == '\\' || path[1] == ':';
+
+#elif defined(ACORN)
+ //---------- RISCOS ----------
+ return path[0] == '$';
+
+#elif defined(MACOS)
+ //---------- MacOS ----------
+ return path[0] != ':';
+
+#else
+ //---------- Unix ----------
+ return path[0] == '/';
+#endif
+}
+
+GString *makePathAbsolute(GString *path) {
+#ifdef VMS
+ //---------- VMS ----------
+ char buf[PATH_MAX+1];
+
+ if (!isAbsolutePath(path->getCString())) {
+ if (getcwd(buf, sizeof(buf))) {
+ path->insert(0, buf);
+ }
+ }
+ return path;
+
+#elif defined(WIN32)
+ //---------- Win32 ----------
+ char buf[_MAX_PATH];
+ char *fp;
+
+ buf[0] = '\0';
+ if (!GetFullPathName(path->getCString(), _MAX_PATH, buf, &fp)) {
+ path->clear();
+ return path;
+ }
+ path->clear();
+ path->append(buf);
+ return path;
+
+#elif defined(ACORN)
+ //---------- RISCOS ----------
+ path->insert(0, '@');
+ return path;
+
+#elif defined(MACOS)
+ //---------- MacOS ----------
+ path->del(0, 1);
+ return path;
+
+#else
+ //---------- Unix and OS/2+EMX ----------
+ struct passwd *pw;
+ char buf[PATH_MAX+1];
+ GString *s;
+ char *p1, *p2;
+ int n;
+
+ if (path->getChar(0) == '~') {
+ if (path->getChar(1) == '/' ||
+#ifdef __EMX__
+ path->getChar(1) == '\\' ||
+#endif
+ path->getLength() == 1) {
+ path->del(0, 1);
+ s = getHomeDir();
+ path->insert(0, s);
+ delete s;
+ } else {
+ p1 = path->getCString() + 1;
+#ifdef __EMX__
+ for (p2 = p1; *p2 && *p2 != '/' && *p2 != '\\'; ++p2) ;
+#else
+ for (p2 = p1; *p2 && *p2 != '/'; ++p2) ;
+#endif
+ if ((n = p2 - p1) > PATH_MAX)
+ n = PATH_MAX;
+ strncpy(buf, p1, n);
+ buf[n] = '\0';
+ if ((pw = getpwnam(buf))) {
+ path->del(0, p2 - p1 + 1);
+ path->insert(0, pw->pw_dir);
+ }
+ }
+ } else if (!isAbsolutePath(path->getCString())) {
+ if (getcwd(buf, sizeof(buf))) {
+#ifndef __EMX__
+ path->insert(0, '/');
+#endif
+ path->insert(0, buf);
+ }
+ }
+ return path;
+#endif
+}
+
+time_t getModTime(const char *fileName) {
+#ifdef WIN32
+ //~ should implement this, but it's (currently) only used in xpdf
+ return 0;
+#else
+ struct stat statBuf;
+
+ if (stat(fileName, &statBuf)) {
+ return 0;
+ }
+ return statBuf.st_mtime;
+#endif
+}
+
+GBool openTempFile(GString **name, FILE **f, const char *mode/*, char *ext*/) {
+#if defined(WIN32)
+ //---------- Win32 ----------
+ char *s;
+ char buf[_MAX_PATH];
+ char *fp;
+
+ if (!(s = _tempnam(getenv("TEMP"), NULL))) {
+ return gFalse;
+ }
+ *name = new GString(s);
+ free(s);
+ if (ext) {
+ (*name)->append(ext);
+ }
+ if (!(*f = fopen((*name)->getCString(), mode))) {
+ delete (*name);
+ return gFalse;
+ }
+ return gTrue;
+#elif defined(VMS) || defined(__EMX__) || defined(ACORN) || defined(MACOS)
+ //---------- non-Unix ----------
+ char *s;
+
+ // There is a security hole here: an attacker can create a symlink
+ // with this file name after the tmpnam call and before the fopen
+ // call. I will happily accept fixes to this function for non-Unix
+ // OSs.
+ if (!(s = tmpnam(NULL))) {
+ return gFalse;
+ }
+ *name = new GString(s);
+ if (ext) {
+ (*name)->append(ext);
+ }
+ if (!(*f = fopen((*name)->getCString(), mode))) {
+ delete (*name);
+ return gFalse;
+ }
+ return gTrue;
+#else
+ //---------- Unix ----------
+ char *s;
+ int fd;
+
+// if (ext) {
+//#if HAVE_MKSTEMPS
+// if ((s = getenv("TMPDIR"))) {
+// *name = new GString(s);
+// } else {
+// *name = new GString("/tmp");
+// }
+// (*name)->append("/XXXXXX")->append(ext);
+// fd = mkstemps((*name)->getCString(), strlen(ext));
+//#else
+// if (!(s = tmpnam(NULL))) {
+// return gFalse;
+//}
+// *name = new GString(s);
+// (*name)->append(ext);
+// fd = open((*name)->getCString(), O_WRONLY | O_CREAT | O_EXCL, 0600);
+//#endif
+//} else {
+#if HAVE_MKSTEMP
+ if ((s = getenv("TMPDIR"))) {
+ *name = new GString(s);
+ } else {
+ *name = new GString("/tmp");
+ }
+ (*name)->append("/XXXXXX");
+ fd = mkstemp((*name)->getCString());
+#else // HAVE_MKSTEMP
+ if (!(s = tmpnam(NULL))) {
+ return gFalse;
+ }
+ *name = new GString(s);
+ fd = open((*name)->getCString(), O_WRONLY | O_CREAT | O_EXCL, 0600);
+#endif // HAVE_MKSTEMP
+// }
+ if (fd < 0 || !(*f = fdopen(fd, mode))) {
+ delete *name;
+ return gFalse;
+ }
+ return gTrue;
+#endif
+}
+
+GBool executeCommand(const char *cmd) {
+#ifdef VMS
+ return system(cmd) ? gTrue : gFalse;
+#else
+ return system(cmd) ? gFalse : gTrue;
+#endif
+}
+
+char *getLine(char *buf, int size, FILE *f) {
+ int c, i;
+
+ i = 0;
+ while (i < size - 1) {
+ if ((c = fgetc(f)) == EOF) {
+ break;
+ }
+ buf[i++] = (char)c;
+ if (c == '\x0a') {
+ break;
+ }
+ if (c == '\x0d') {
+ c = fgetc(f);
+ if (c == '\x0a' && i < size - 1) {
+ buf[i++] = (char)c;
+ } else if (c != EOF) {
+ ungetc(c, f);
+ }
+ break;
+ }
+ }
+ buf[i] = '\0';
+ if (i == 0) {
+ return NULL;
+ }
+ return buf;
+}
+
+//------------------------------------------------------------------------
+// GDir and GDirEntry
+//------------------------------------------------------------------------
+
+GDirEntry::GDirEntry(const char *dirPath, const char *nameA, GBool doStat) {
+#ifdef VMS
+ char *p;
+#elif defined(WIN32)
+ int fa;
+ GString *s;
+#elif defined(ACORN)
+#else
+ struct stat st;
+ GString *s;
+#endif
+
+ name = new GString(nameA);
+ dir = gFalse;
+ if (doStat) {
+#ifdef VMS
+ if (!strcmp(nameA, "-") ||
+ ((p = strrchr(nameA, '.')) && !strncmp(p, ".DIR;", 5)))
+ dir = gTrue;
+#elif defined(ACORN)
+#else
+ s = new GString(dirPath);
+ appendToPath(s, nameA);
+#ifdef WIN32
+ fa = GetFileAttributes(s->getCString());
+ dir = (fa != 0xFFFFFFFF && (fa & FILE_ATTRIBUTE_DIRECTORY));
+#else
+ if (stat(s->getCString(), &st) == 0)
+ dir = S_ISDIR(st.st_mode);
+#endif
+ delete s;
+#endif
+ }
+}
+
+GDirEntry::~GDirEntry() {
+ delete name;
+}
+
+GDir::GDir(const char *name, GBool doStatA) {
+ path = new GString(name);
+ doStat = doStatA;
+#if defined(WIN32)
+ GString *tmp;
+
+ tmp = path->copy();
+ tmp->append("/*.*");
+ hnd = FindFirstFile(tmp->getCString(), &ffd);
+ delete tmp;
+#elif defined(ACORN)
+#elif defined(MACOS)
+#else
+ dir = opendir(name);
+#ifdef VMS
+ needParent = strchr(name, '[') != NULL;
+#endif
+#endif
+}
+
+GDir::~GDir() {
+ delete path;
+#if defined(WIN32)
+ if (hnd) {
+ FindClose(hnd);
+ hnd = NULL;
+ }
+#elif defined(ACORN)
+#elif defined(MACOS)
+#else
+ if (dir)
+ closedir(dir);
+#endif
+}
+
+GDirEntry *GDir::getNextEntry() {
+ struct dirent *ent;
+ GDirEntry *e;
+
+ e = NULL;
+#if defined(WIN32)
+ e = new GDirEntry(path->getCString(), ffd.cFileName, doStat);
+ if (hnd && !FindNextFile(hnd, &ffd)) {
+ FindClose(hnd);
+ hnd = NULL;
+ }
+#elif defined(ACORN)
+#elif defined(MACOS)
+#else
+ if (dir) {
+#ifdef VMS
+ if (needParent) {
+ e = new GDirEntry(path->getCString(), "-", doStat);
+ needParent = gFalse;
+ return e;
+ }
+#endif
+ ent = readdir(dir);
+#ifndef VMS
+ if (ent && !strcmp(ent->d_name, "."))
+ ent = readdir(dir);
+#endif
+ if (ent)
+ e = new GDirEntry(path->getCString(), ent->d_name, doStat);
+ }
+#endif
+ return e;
+}
+
+void GDir::rewind() {
+#ifdef WIN32
+ GString *tmp;
+
+ if (hnd)
+ FindClose(hnd);
+ tmp = path->copy();
+ tmp->append("/*.*");
+ hnd = FindFirstFile(tmp->getCString(), &ffd);
+#elif defined(ACORN)
+#elif defined(MACOS)
+#else
+ if (dir)
+ rewinddir(dir);
+#ifdef VMS
+ needParent = strchr(path->getCString(), '[') != NULL;
+#endif
+#endif
+}
diff --git a/filters/kword/pdf/xpdf/goo/gmempp.cc b/filters/kword/pdf/xpdf/goo/gmempp.cc
deleted file mode 100644
index ed94f7a1d..000000000
--- a/filters/kword/pdf/xpdf/goo/gmempp.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-//========================================================================
-//
-// gmempp.cc
-//
-// Use gmalloc/gfree for C++ new/delete operators.
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include "gmem.h"
-
-#ifdef DEBUG_MEM
-
-void *operator new(size_t size) {
- return gmalloc((int)size);
-}
-
-void *operator new[](size_t size) {
- return gmalloc((int)size);
-}
-
-void operator delete(void *p) {
- gfree(p);
-}
-
-void operator delete[](void *p) {
- gfree(p);
-}
-
-#endif
diff --git a/filters/kword/pdf/xpdf/goo/gmempp.cpp b/filters/kword/pdf/xpdf/goo/gmempp.cpp
new file mode 100644
index 000000000..6339f2e8f
--- /dev/null
+++ b/filters/kword/pdf/xpdf/goo/gmempp.cpp
@@ -0,0 +1,32 @@
+//========================================================================
+//
+// gmempp.cpp
+//
+// Use gmalloc/gfree for C++ new/delete operators.
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include "gmem.h"
+
+#ifdef DEBUG_MEM
+
+void *operator new(size_t size) {
+ return gmalloc((int)size);
+}
+
+void *operator new[](size_t size) {
+ return gmalloc((int)size);
+}
+
+void operator delete(void *p) {
+ gfree(p);
+}
+
+void operator delete[](void *p) {
+ gfree(p);
+}
+
+#endif
diff --git a/filters/kword/pdf/xpdf/xpdf/Annot.cc b/filters/kword/pdf/xpdf/xpdf/Annot.cc
deleted file mode 100644
index 8ebf6a0c0..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Annot.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-//========================================================================
-//
-// Annot.cc
-//
-// Copyright 2000-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "gmem.h"
-#include "Object.h"
-#include "Gfx.h"
-#include "Annot.h"
-
-//------------------------------------------------------------------------
-// Annot
-//------------------------------------------------------------------------
-
-Annot::Annot(XRef *xrefA, Dict *dict) {
- Object apObj, asObj, obj1, obj2;
- double t;
-
- ok = gFalse;
- xref = xrefA;
-
- if (dict->lookup("AP", &apObj)->isDict()) {
- if (dict->lookup("AS", &asObj)->isName()) {
- if (apObj.dictLookup("N", &obj1)->isDict()) {
- if (obj1.dictLookupNF(asObj.getName(), &obj2)->isRef()) {
- obj2.copy(&appearance);
- ok = gTrue;
- }
- obj2.free();
- }
- obj1.free();
- } else {
- if (apObj.dictLookupNF("N", &obj1)->isRef()) {
- obj1.copy(&appearance);
- ok = gTrue;
- }
- obj1.free();
- }
- asObj.free();
- }
- apObj.free();
-
- if (dict->lookup("Rect", &obj1)->isArray() &&
- obj1.arrayGetLength() == 4) {
- //~ should check object types here
- obj1.arrayGet(0, &obj2);
- xMin = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- yMin = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- xMax = obj2.getNum();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- yMax = obj2.getNum();
- obj2.free();
- if (xMin > xMax) {
- t = xMin; xMin = xMax; xMax = t;
- }
- if (yMin > yMax) {
- t = yMin; yMin = yMax; yMax = t;
- }
- } else {
- //~ this should return an error
- xMin = yMin = 0;
- xMax = yMax = 1;
- }
- obj1.free();
-}
-
-Annot::~Annot() {
- appearance.free();
-}
-
-void Annot::draw(Gfx *gfx) {
- Object obj;
-
- if (appearance.fetch(xref, &obj)->isStream()) {
- gfx->doAnnot(&obj, xMin, yMin, xMax, yMax);
- }
- obj.free();
-}
-
-//------------------------------------------------------------------------
-// Annots
-//------------------------------------------------------------------------
-
-Annots::Annots(XRef *xref, Object *annotsObj) {
- Annot *annot;
- Object obj1, obj2;
- int size;
- int i;
-
- annots = NULL;
- size = 0;
- nAnnots = 0;
-
- if (annotsObj->isArray()) {
- for (i = 0; i < annotsObj->arrayGetLength(); ++i) {
- if (annotsObj->arrayGet(i, &obj1)->isDict()) {
- obj1.dictLookup("Subtype", &obj2);
- if (obj2.isName("Widget") ||
- obj2.isName("Stamp")) {
- annot = new Annot(xref, obj1.getDict());
- if (annot->isOk()) {
- if (nAnnots >= size) {
- size += 16;
- annots = (Annot **)grealloc(annots, size * sizeof(Annot *));
- }
- annots[nAnnots++] = annot;
- } else {
- delete annot;
- }
- }
- obj2.free();
- }
- obj1.free();
- }
- }
-}
-
-Annots::~Annots() {
- int i;
-
- for (i = 0; i < nAnnots; ++i) {
- delete annots[i];
- }
- gfree(annots);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Annot.cpp b/filters/kword/pdf/xpdf/xpdf/Annot.cpp
new file mode 100644
index 000000000..c3a161190
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Annot.cpp
@@ -0,0 +1,139 @@
+//========================================================================
+//
+// Annot.cpp
+//
+// Copyright 2000-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "gmem.h"
+#include "Object.h"
+#include "Gfx.h"
+#include "Annot.h"
+
+//------------------------------------------------------------------------
+// Annot
+//------------------------------------------------------------------------
+
+Annot::Annot(XRef *xrefA, Dict *dict) {
+ Object apObj, asObj, obj1, obj2;
+ double t;
+
+ ok = gFalse;
+ xref = xrefA;
+
+ if (dict->lookup("AP", &apObj)->isDict()) {
+ if (dict->lookup("AS", &asObj)->isName()) {
+ if (apObj.dictLookup("N", &obj1)->isDict()) {
+ if (obj1.dictLookupNF(asObj.getName(), &obj2)->isRef()) {
+ obj2.copy(&appearance);
+ ok = gTrue;
+ }
+ obj2.free();
+ }
+ obj1.free();
+ } else {
+ if (apObj.dictLookupNF("N", &obj1)->isRef()) {
+ obj1.copy(&appearance);
+ ok = gTrue;
+ }
+ obj1.free();
+ }
+ asObj.free();
+ }
+ apObj.free();
+
+ if (dict->lookup("Rect", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 4) {
+ //~ should check object types here
+ obj1.arrayGet(0, &obj2);
+ xMin = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ yMin = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ xMax = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ yMax = obj2.getNum();
+ obj2.free();
+ if (xMin > xMax) {
+ t = xMin; xMin = xMax; xMax = t;
+ }
+ if (yMin > yMax) {
+ t = yMin; yMin = yMax; yMax = t;
+ }
+ } else {
+ //~ this should return an error
+ xMin = yMin = 0;
+ xMax = yMax = 1;
+ }
+ obj1.free();
+}
+
+Annot::~Annot() {
+ appearance.free();
+}
+
+void Annot::draw(Gfx *gfx) {
+ Object obj;
+
+ if (appearance.fetch(xref, &obj)->isStream()) {
+ gfx->doAnnot(&obj, xMin, yMin, xMax, yMax);
+ }
+ obj.free();
+}
+
+//------------------------------------------------------------------------
+// Annots
+//------------------------------------------------------------------------
+
+Annots::Annots(XRef *xref, Object *annotsObj) {
+ Annot *annot;
+ Object obj1, obj2;
+ int size;
+ int i;
+
+ annots = NULL;
+ size = 0;
+ nAnnots = 0;
+
+ if (annotsObj->isArray()) {
+ for (i = 0; i < annotsObj->arrayGetLength(); ++i) {
+ if (annotsObj->arrayGet(i, &obj1)->isDict()) {
+ obj1.dictLookup("Subtype", &obj2);
+ if (obj2.isName("Widget") ||
+ obj2.isName("Stamp")) {
+ annot = new Annot(xref, obj1.getDict());
+ if (annot->isOk()) {
+ if (nAnnots >= size) {
+ size += 16;
+ annots = (Annot **)grealloc(annots, size * sizeof(Annot *));
+ }
+ annots[nAnnots++] = annot;
+ } else {
+ delete annot;
+ }
+ }
+ obj2.free();
+ }
+ obj1.free();
+ }
+ }
+}
+
+Annots::~Annots() {
+ int i;
+
+ for (i = 0; i < nAnnots; ++i) {
+ delete annots[i];
+ }
+ gfree(annots);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Array.cc b/filters/kword/pdf/xpdf/xpdf/Array.cc
deleted file mode 100644
index 9c6cb3415..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Array.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-//========================================================================
-//
-// Array.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include "gmem.h"
-#include "Object.h"
-#include "Array.h"
-
-//------------------------------------------------------------------------
-// Array
-//------------------------------------------------------------------------
-
-Array::Array(XRef *xrefA) {
- xref = xrefA;
- elems = NULL;
- size = length = 0;
- ref = 1;
-}
-
-Array::~Array() {
- int i;
-
- for (i = 0; i < length; ++i)
- elems[i].free();
- gfree(elems);
-}
-
-void Array::add(Object *elem) {
- if (length + 1 > size) {
- size += 8;
- elems = (Object *)grealloc(elems, size * sizeof(Object));
- }
- elems[length] = *elem;
- ++length;
-}
-
-Object *Array::get(int i, Object *obj) {
- return elems[i].fetch(xref, obj);
-}
-
-Object *Array::getNF(int i, Object *obj) {
- return elems[i].copy(obj);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Array.cpp b/filters/kword/pdf/xpdf/xpdf/Array.cpp
new file mode 100644
index 000000000..758dbfd0b
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Array.cpp
@@ -0,0 +1,54 @@
+//========================================================================
+//
+// Array.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include "gmem.h"
+#include "Object.h"
+#include "Array.h"
+
+//------------------------------------------------------------------------
+// Array
+//------------------------------------------------------------------------
+
+Array::Array(XRef *xrefA) {
+ xref = xrefA;
+ elems = NULL;
+ size = length = 0;
+ ref = 1;
+}
+
+Array::~Array() {
+ int i;
+
+ for (i = 0; i < length; ++i)
+ elems[i].free();
+ gfree(elems);
+}
+
+void Array::add(Object *elem) {
+ if (length + 1 > size) {
+ size += 8;
+ elems = (Object *)grealloc(elems, size * sizeof(Object));
+ }
+ elems[length] = *elem;
+ ++length;
+}
+
+Object *Array::get(int i, Object *obj) {
+ return elems[i].fetch(xref, obj);
+}
+
+Object *Array::getNF(int i, Object *obj) {
+ return elems[i].copy(obj);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cc b/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cc
deleted file mode 100644
index 72b845792..000000000
--- a/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-//========================================================================
-//
-// BuiltinFont.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#include "gmem.h"
-#include "FontEncodingTables.h"
-#include "BuiltinFont.h"
-
-//------------------------------------------------------------------------
-
-BuiltinFontWidths::BuiltinFontWidths(BuiltinFontWidth *widths, int sizeA) {
- int i, h;
-
- size = sizeA;
- tab = (BuiltinFontWidth **)gmalloc(size * sizeof(BuiltinFontWidth *));
- for (i = 0; i < size; ++i) {
- tab[i] = NULL;
- }
- for (i = 0; i < sizeA; ++i) {
- h = hash(widths[i].name);
- widths[i].next = tab[h];
- tab[h] = &widths[i];
- }
-}
-
-BuiltinFontWidths::~BuiltinFontWidths() {
- gfree(tab);
-}
-
-GBool BuiltinFontWidths::getWidth(const char *name, Gushort *width) {
- int h;
- BuiltinFontWidth *p;
-
- h = hash(name);
- for (p = tab[h]; p; p = p->next) {
- if (!strcmp(p->name, name)) {
- *width = p->width;
- return gTrue;
- }
- }
- return gFalse;
-}
-
-int BuiltinFontWidths::hash(const char *name) {
- const char *p;
- unsigned int h;
-
- h = 0;
- for (p = name; *p; ++p) {
- h = 17 * h + (int)(*p & 0xff);
- }
- return (int)(h % size);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cpp b/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cpp
new file mode 100644
index 000000000..3f1effb5e
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/BuiltinFont.cpp
@@ -0,0 +1,65 @@
+//========================================================================
+//
+// BuiltinFont.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include "gmem.h"
+#include "FontEncodingTables.h"
+#include "BuiltinFont.h"
+
+//------------------------------------------------------------------------
+
+BuiltinFontWidths::BuiltinFontWidths(BuiltinFontWidth *widths, int sizeA) {
+ int i, h;
+
+ size = sizeA;
+ tab = (BuiltinFontWidth **)gmalloc(size * sizeof(BuiltinFontWidth *));
+ for (i = 0; i < size; ++i) {
+ tab[i] = NULL;
+ }
+ for (i = 0; i < sizeA; ++i) {
+ h = hash(widths[i].name);
+ widths[i].next = tab[h];
+ tab[h] = &widths[i];
+ }
+}
+
+BuiltinFontWidths::~BuiltinFontWidths() {
+ gfree(tab);
+}
+
+GBool BuiltinFontWidths::getWidth(const char *name, Gushort *width) {
+ int h;
+ BuiltinFontWidth *p;
+
+ h = hash(name);
+ for (p = tab[h]; p; p = p->next) {
+ if (!strcmp(p->name, name)) {
+ *width = p->width;
+ return gTrue;
+ }
+ }
+ return gFalse;
+}
+
+int BuiltinFontWidths::hash(const char *name) {
+ const char *p;
+ unsigned int h;
+
+ h = 0;
+ for (p = name; *p; ++p) {
+ h = 17 * h + (int)(*p & 0xff);
+ }
+ return (int)(h % size);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cc b/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cc
deleted file mode 100644
index e2acfef8a..000000000
--- a/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cc
+++ /dev/null
@@ -1,3367 +0,0 @@
-//========================================================================
-//
-// BuiltinFontTables.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdlib.h>
-#include "FontEncodingTables.h"
-#include "BuiltinFontTables.h"
-
-static BuiltinFontWidth courierWidthsTab[] = {
- { "Ntilde", 600, NULL },
- { "comma", 600, NULL },
- { "cedilla", 600, NULL },
- { "plusminus", 600, NULL },
- { "arrowup", 600, NULL },
- { "circumflex", 600, NULL },
- { "dotaccent", 600, NULL },
- { "LL", 600, NULL },
- { "asciitilde", 600, NULL },
- { "colon", 600, NULL },
- { "onehalf", 600, NULL },
- { "dollar", 600, NULL },
- { "ntilde", 600, NULL },
- { "left", 600, NULL },
- { "minus", 600, NULL },
- { "yen", 600, NULL },
- { "space", 600, NULL },
- { "questiondown", 600, NULL },
- { "emdash", 600, NULL },
- { "Agrave", 600, NULL },
- { "three", 600, NULL },
- { "numbersign", 600, NULL },
- { "A", 600, NULL },
- { "B", 600, NULL },
- { "C", 600, NULL },
- { "D", 600, NULL },
- { "E", 600, NULL },
- { "onequarter", 600, NULL },
- { "F", 600, NULL },
- { "G", 600, NULL },
- { "H", 600, NULL },
- { "I", 600, NULL },
- { "J", 600, NULL },
- { "K", 600, NULL },
- { "L", 600, NULL },
- { "backslash", 600, NULL },
- { "periodcentered", 600, NULL },
- { "M", 600, NULL },
- { "N", 600, NULL },
- { "O", 600, NULL },
- { "P", 600, NULL },
- { "Q", 600, NULL },
- { "R", 600, NULL },
- { "Aacute", 600, NULL },
- { "caron", 600, NULL },
- { "S", 600, NULL },
- { "T", 600, NULL },
- { "U", 600, NULL },
- { "agrave", 600, NULL },
- { "V", 600, NULL },
- { "tab", 600, NULL },
- { "W", 600, NULL },
- { "ll", 600, NULL },
- { "equal", 600, NULL },
- { "question", 600, NULL },
- { "X", 600, NULL },
- { "Y", 600, NULL },
- { "Z", 600, NULL },
- { "four", 600, NULL },
- { "a", 600, NULL },
- { "b", 600, NULL },
- { "c", 600, NULL },
- { "d", 600, NULL },
- { "e", 600, NULL },
- { "f", 600, NULL },
- { "g", 600, NULL },
- { "bullet", 600, NULL },
- { "h", 600, NULL },
- { "i", 600, NULL },
- { "Oslash", 600, NULL },
- { "dagger", 600, NULL },
- { "j", 600, NULL },
- { "k", 600, NULL },
- { "l", 600, NULL },
- { "m", 600, NULL },
- { "n", 600, NULL },
- { "o", 600, NULL },
- { "ordfeminine", 600, NULL },
- { "ring", 600, NULL },
- { "p", 600, NULL },
- { "q", 600, NULL },
- { "r", 600, NULL },
- { "twosuperior", 600, NULL },
- { "largebullet", 600, NULL },
- { "aacute", 600, NULL },
- { "s", 600, NULL },
- { "OE", 600, NULL },
- { "t", 600, NULL },
- { "divide", 600, NULL },
- { "u", 600, NULL },
- { "v", 600, NULL },
- { "w", 600, NULL },
- { "x", 600, NULL },
- { "y", 600, NULL },
- { "z", 600, NULL },
- { "hungarumlaut", 600, NULL },
- { "quotedbl", 600, NULL },
- { "mu", 600, NULL },
- { "Scaron", 600, NULL },
- { "Lslash", 600, NULL },
- { "semicolon", 600, NULL },
- { "oslash", 600, NULL },
- { "parenright", 600, NULL },
- { "Ecircumflex", 600, NULL },
- { "trademark", 600, NULL },
- { "daggerdbl", 600, NULL },
- { "macron", 600, NULL },
- { "Otilde", 600, NULL },
- { "ellipsis", 600, NULL },
- { "scaron", 600, NULL },
- { "AE", 600, NULL },
- { "Ucircumflex", 600, NULL },
- { "lslash", 600, NULL },
- { "lira", 600, NULL },
- { "quotedblleft", 600, NULL },
- { "hyphen", 600, NULL },
- { "guilsinglright", 600, NULL },
- { "quotesingle", 600, NULL },
- { "eight", 600, NULL },
- { "exclamdown", 600, NULL },
- { "endash", 600, NULL },
- { "oe", 600, NULL },
- { "ecircumflex", 600, NULL },
- { "copyright", 600, NULL },
- { "Adieresis", 600, NULL },
- { "Egrave", 600, NULL },
- { "slash", 600, NULL },
- { "Edieresis", 600, NULL },
- { "otilde", 600, NULL },
- { "Idieresis", 600, NULL },
- { "parenleft", 600, NULL },
- { "one", 600, NULL },
- { "ucircumflex", 600, NULL },
- { "Odieresis", 600, NULL },
- { "bracketleft", 600, NULL },
- { "Ugrave", 600, NULL },
- { "quoteright", 600, NULL },
- { "Udieresis", 600, NULL },
- { "perthousand", 600, NULL },
- { "Ydieresis", 600, NULL },
- { "Eacute", 600, NULL },
- { "adieresis", 600, NULL },
- { "egrave", 600, NULL },
- { "edieresis", 600, NULL },
- { "idieresis", 600, NULL },
- { "Eth", 600, NULL },
- { "ae", 600, NULL },
- { "asterisk", 600, NULL },
- { "odieresis", 600, NULL },
- { "Uacute", 600, NULL },
- { "ugrave", 600, NULL },
- { "five", 600, NULL },
- { "nine", 600, NULL },
- { "udieresis", 600, NULL },
- { "Zcaron", 600, NULL },
- { "threequarters", 600, NULL },
- { "guillemotright", 600, NULL },
- { "ydieresis", 600, NULL },
- { "Ccedilla", 600, NULL },
- { "tilde", 600, NULL },
- { "at", 600, NULL },
- { "eacute", 600, NULL },
- { "Gcaron", 600, NULL },
- { "underscore", 600, NULL },
- { "zero", 600, NULL },
- { "multiply", 600, NULL },
- { "Scedilla", 600, NULL },
- { "eth", 600, NULL },
- { "Ograve", 600, NULL },
- { "uacute", 600, NULL },
- { "braceleft", 600, NULL },
- { "Thorn", 600, NULL },
- { "zcaron", 600, NULL },
- { "ccedilla", 600, NULL },
- { "gcaron", 600, NULL },
- { "Oacute", 600, NULL },
- { "Ocircumflex", 600, NULL },
- { "scedilla", 600, NULL },
- { "ogonek", 600, NULL },
- { "arrowdown", 600, NULL },
- { "ograve", 600, NULL },
- { "thorn", 600, NULL },
- { "degree", 600, NULL },
- { "registered", 600, NULL },
- { "percent", 600, NULL },
- { "Aring", 600, NULL },
- { "six", 600, NULL },
- { "paragraph", 600, NULL },
- { "two", 600, NULL },
- { "Igrave", 600, NULL },
- { "oacute", 600, NULL },
- { "ocircumflex", 600, NULL },
- { "asciicircum", 600, NULL },
- { "aring", 600, NULL },
- { "square", 600, NULL },
- { "grave", 600, NULL },
- { "bracketright", 600, NULL },
- { "ampersand", 600, NULL },
- { "Iacute", 600, NULL },
- { "igrave", 600, NULL },
- { "return", 600, NULL },
- { "plus", 600, NULL },
- { "quotesinglbase", 600, NULL },
- { "Yacute", 600, NULL },
- { "threesuperior", 600, NULL },
- { "acute", 600, NULL },
- { "notegraphic", 600, NULL },
- { "section", 600, NULL },
- { "arrowleft", 600, NULL },
- { "dieresis", 600, NULL },
- { "quotedblbase", 600, NULL },
- { "iacute", 600, NULL },
- { "up", 600, NULL },
- { "florin", 600, NULL },
- { "yacute", 600, NULL },
- { "fi", 600, NULL },
- { "fl", 600, NULL },
- { "Acircumflex", 600, NULL },
- { "Icircumflex", 600, NULL },
- { "guillemotleft", 600, NULL },
- { "germandbls", 600, NULL },
- { "seven", 600, NULL },
- { "indent", 600, NULL },
- { "prescription", 600, NULL },
- { "dectab", 600, NULL },
- { "ordmasculine", 600, NULL },
- { "dotlessi", 600, NULL },
- { "sterling", 600, NULL },
- { "IJ", 600, NULL },
- { "acircumflex", 600, NULL },
- { "overscore", 600, NULL },
- { "braceright", 600, NULL },
- { "icircumflex", 600, NULL },
- { "graybox", 600, NULL },
- { "quotedblright", 600, NULL },
- { "center", 600, NULL },
- { "stop", 600, NULL },
- { "cent", 600, NULL },
- { "currency", 600, NULL },
- { "logicalnot", 600, NULL },
- { "Idot", 600, NULL },
- { "merge", 600, NULL },
- { "Atilde", 600, NULL },
- { "breve", 600, NULL },
- { "bar", 600, NULL },
- { "fraction", 600, NULL },
- { "less", 600, NULL },
- { "down", 600, NULL },
- { "guilsinglleft", 600, NULL },
- { "exclam", 600, NULL },
- { "period", 600, NULL },
- { "arrowright", 600, NULL },
- { "format", 600, NULL },
- { "greater", 600, NULL },
- { "atilde", 600, NULL },
- { "ij", 600, NULL },
- { "brokenbar", 600, NULL },
- { "arrowboth", 600, NULL },
- { "quoteleft", 600, NULL },
- { "onesuperior", 600, NULL }
-};
-
-static BuiltinFontWidth courierBoldWidthsTab[] = {
- { "Ntilde", 600, NULL },
- { "comma", 600, NULL },
- { "cedilla", 600, NULL },
- { "plusminus", 600, NULL },
- { "arrowup", 600, NULL },
- { "circumflex", 600, NULL },
- { "dotaccent", 600, NULL },
- { "LL", 600, NULL },
- { "asciitilde", 600, NULL },
- { "colon", 600, NULL },
- { "onehalf", 600, NULL },
- { "dollar", 600, NULL },
- { "ntilde", 600, NULL },
- { "left", 600, NULL },
- { "minus", 600, NULL },
- { "yen", 600, NULL },
- { "space", 600, NULL },
- { "questiondown", 600, NULL },
- { "emdash", 600, NULL },
- { "Agrave", 600, NULL },
- { "three", 600, NULL },
- { "numbersign", 600, NULL },
- { "A", 600, NULL },
- { "B", 600, NULL },
- { "C", 600, NULL },
- { "D", 600, NULL },
- { "E", 600, NULL },
- { "onequarter", 600, NULL },
- { "F", 600, NULL },
- { "G", 600, NULL },
- { "H", 600, NULL },
- { "I", 600, NULL },
- { "J", 600, NULL },
- { "K", 600, NULL },
- { "backslash", 600, NULL },
- { "L", 600, NULL },
- { "periodcentered", 600, NULL },
- { "M", 600, NULL },
- { "N", 600, NULL },
- { "O", 600, NULL },
- { "P", 600, NULL },
- { "Q", 600, NULL },
- { "R", 600, NULL },
- { "Aacute", 600, NULL },
- { "caron", 600, NULL },
- { "S", 600, NULL },
- { "T", 600, NULL },
- { "U", 600, NULL },
- { "agrave", 600, NULL },
- { "V", 600, NULL },
- { "tab", 600, NULL },
- { "W", 600, NULL },
- { "ll", 600, NULL },
- { "X", 600, NULL },
- { "question", 600, NULL },
- { "equal", 600, NULL },
- { "Y", 600, NULL },
- { "Z", 600, NULL },
- { "four", 600, NULL },
- { "a", 600, NULL },
- { "b", 600, NULL },
- { "c", 600, NULL },
- { "d", 600, NULL },
- { "e", 600, NULL },
- { "f", 600, NULL },
- { "g", 600, NULL },
- { "bullet", 600, NULL },
- { "h", 600, NULL },
- { "i", 600, NULL },
- { "Oslash", 600, NULL },
- { "dagger", 600, NULL },
- { "j", 600, NULL },
- { "k", 600, NULL },
- { "l", 600, NULL },
- { "m", 600, NULL },
- { "n", 600, NULL },
- { "o", 600, NULL },
- { "ordfeminine", 600, NULL },
- { "ring", 600, NULL },
- { "p", 600, NULL },
- { "q", 600, NULL },
- { "r", 600, NULL },
- { "twosuperior", 600, NULL },
- { "largebullet", 600, NULL },
- { "aacute", 600, NULL },
- { "s", 600, NULL },
- { "OE", 600, NULL },
- { "t", 600, NULL },
- { "divide", 600, NULL },
- { "u", 600, NULL },
- { "v", 600, NULL },
- { "w", 600, NULL },
- { "x", 600, NULL },
- { "y", 600, NULL },
- { "z", 600, NULL },
- { "hungarumlaut", 600, NULL },
- { "quotedbl", 600, NULL },
- { "mu", 600, NULL },
- { "Scaron", 600, NULL },
- { "Lslash", 600, NULL },
- { "semicolon", 600, NULL },
- { "oslash", 600, NULL },
- { "parenright", 600, NULL },
- { "Ecircumflex", 600, NULL },
- { "trademark", 600, NULL },
- { "daggerdbl", 600, NULL },
- { "macron", 600, NULL },
- { "Otilde", 600, NULL },
- { "ellipsis", 600, NULL },
- { "scaron", 600, NULL },
- { "AE", 600, NULL },
- { "Ucircumflex", 600, NULL },
- { "lslash", 600, NULL },
- { "lira", 600, NULL },
- { "quotedblleft", 600, NULL },
- { "guilsinglright", 600, NULL },
- { "hyphen", 600, NULL },
- { "quotesingle", 600, NULL },
- { "eight", 600, NULL },
- { "exclamdown", 600, NULL },
- { "endash", 600, NULL },
- { "oe", 600, NULL },
- { "ecircumflex", 600, NULL },
- { "copyright", 600, NULL },
- { "Adieresis", 600, NULL },
- { "Egrave", 600, NULL },
- { "slash", 600, NULL },
- { "Edieresis", 600, NULL },
- { "otilde", 600, NULL },
- { "Idieresis", 600, NULL },
- { "parenleft", 600, NULL },
- { "one", 600, NULL },
- { "ucircumflex", 600, NULL },
- { "Odieresis", 600, NULL },
- { "bracketleft", 600, NULL },
- { "Ugrave", 600, NULL },
- { "quoteright", 600, NULL },
- { "Udieresis", 600, NULL },
- { "perthousand", 600, NULL },
- { "Ydieresis", 600, NULL },
- { "Eacute", 600, NULL },
- { "adieresis", 600, NULL },
- { "egrave", 600, NULL },
- { "edieresis", 600, NULL },
- { "idieresis", 600, NULL },
- { "Eth", 600, NULL },
- { "ae", 600, NULL },
- { "asterisk", 600, NULL },
- { "odieresis", 600, NULL },
- { "Uacute", 600, NULL },
- { "ugrave", 600, NULL },
- { "nine", 600, NULL },
- { "five", 600, NULL },
- { "udieresis", 600, NULL },
- { "Zcaron", 600, NULL },
- { "threequarters", 600, NULL },
- { "guillemotright", 600, NULL },
- { "ydieresis", 600, NULL },
- { "Ccedilla", 600, NULL },
- { "tilde", 600, NULL },
- { "at", 600, NULL },
- { "eacute", 600, NULL },
- { "Gcaron", 600, NULL },
- { "underscore", 600, NULL },
- { "multiply", 600, NULL },
- { "zero", 600, NULL },
- { "eth", 600, NULL },
- { "Scedilla", 600, NULL },
- { "Ograve", 600, NULL },
- { "uacute", 600, NULL },
- { "braceleft", 600, NULL },
- { "Thorn", 600, NULL },
- { "zcaron", 600, NULL },
- { "ccedilla", 600, NULL },
- { "gcaron", 600, NULL },
- { "scedilla", 600, NULL },
- { "Ocircumflex", 600, NULL },
- { "Oacute", 600, NULL },
- { "arrowdown", 600, NULL },
- { "ogonek", 600, NULL },
- { "ograve", 600, NULL },
- { "thorn", 600, NULL },
- { "degree", 600, NULL },
- { "registered", 600, NULL },
- { "Aring", 600, NULL },
- { "percent", 600, NULL },
- { "six", 600, NULL },
- { "paragraph", 600, NULL },
- { "two", 600, NULL },
- { "Igrave", 600, NULL },
- { "ocircumflex", 600, NULL },
- { "oacute", 600, NULL },
- { "asciicircum", 600, NULL },
- { "square", 600, NULL },
- { "aring", 600, NULL },
- { "grave", 600, NULL },
- { "bracketright", 600, NULL },
- { "Iacute", 600, NULL },
- { "ampersand", 600, NULL },
- { "igrave", 600, NULL },
- { "return", 600, NULL },
- { "plus", 600, NULL },
- { "quotesinglbase", 600, NULL },
- { "Yacute", 600, NULL },
- { "threesuperior", 600, NULL },
- { "acute", 600, NULL },
- { "notegraphic", 600, NULL },
- { "section", 600, NULL },
- { "arrowleft", 600, NULL },
- { "dieresis", 600, NULL },
- { "iacute", 600, NULL },
- { "quotedblbase", 600, NULL },
- { "up", 600, NULL },
- { "florin", 600, NULL },
- { "yacute", 600, NULL },
- { "fi", 600, NULL },
- { "fl", 600, NULL },
- { "Acircumflex", 600, NULL },
- { "Icircumflex", 600, NULL },
- { "guillemotleft", 600, NULL },
- { "germandbls", 600, NULL },
- { "seven", 600, NULL },
- { "prescription", 600, NULL },
- { "indent", 600, NULL },
- { "dectab", 600, NULL },
- { "ordmasculine", 600, NULL },
- { "dotlessi", 600, NULL },
- { "sterling", 600, NULL },
- { "acircumflex", 600, NULL },
- { "IJ", 600, NULL },
- { "overscore", 600, NULL },
- { "icircumflex", 600, NULL },
- { "braceright", 600, NULL },
- { "graybox", 600, NULL },
- { "quotedblright", 600, NULL },
- { "center", 600, NULL },
- { "stop", 600, NULL },
- { "cent", 600, NULL },
- { "currency", 600, NULL },
- { "logicalnot", 600, NULL },
- { "merge", 600, NULL },
- { "Idot", 600, NULL },
- { "Atilde", 600, NULL },
- { "breve", 600, NULL },
- { "bar", 600, NULL },
- { "fraction", 600, NULL },
- { "less", 600, NULL },
- { "down", 600, NULL },
- { "guilsinglleft", 600, NULL },
- { "exclam", 600, NULL },
- { "period", 600, NULL },
- { "format", 600, NULL },
- { "arrowright", 600, NULL },
- { "greater", 600, NULL },
- { "ij", 600, NULL },
- { "atilde", 600, NULL },
- { "brokenbar", 600, NULL },
- { "arrowboth", 600, NULL },
- { "quoteleft", 600, NULL },
- { "onesuperior", 600, NULL }
-};
-
-static BuiltinFontWidth courierBoldObliqueWidthsTab[] = {
- { "Ntilde", 600, NULL },
- { "comma", 600, NULL },
- { "cedilla", 600, NULL },
- { "plusminus", 600, NULL },
- { "arrowup", 600, NULL },
- { "circumflex", 600, NULL },
- { "dotaccent", 600, NULL },
- { "LL", 600, NULL },
- { "asciitilde", 600, NULL },
- { "colon", 600, NULL },
- { "onehalf", 600, NULL },
- { "dollar", 600, NULL },
- { "ntilde", 600, NULL },
- { "left", 600, NULL },
- { "minus", 600, NULL },
- { "yen", 600, NULL },
- { "space", 600, NULL },
- { "questiondown", 600, NULL },
- { "emdash", 600, NULL },
- { "Agrave", 600, NULL },
- { "three", 600, NULL },
- { "numbersign", 600, NULL },
- { "A", 600, NULL },
- { "B", 600, NULL },
- { "C", 600, NULL },
- { "D", 600, NULL },
- { "E", 600, NULL },
- { "onequarter", 600, NULL },
- { "F", 600, NULL },
- { "G", 600, NULL },
- { "H", 600, NULL },
- { "I", 600, NULL },
- { "J", 600, NULL },
- { "K", 600, NULL },
- { "backslash", 600, NULL },
- { "L", 600, NULL },
- { "periodcentered", 600, NULL },
- { "M", 600, NULL },
- { "N", 600, NULL },
- { "O", 600, NULL },
- { "P", 600, NULL },
- { "Q", 600, NULL },
- { "R", 600, NULL },
- { "Aacute", 600, NULL },
- { "caron", 600, NULL },
- { "S", 600, NULL },
- { "T", 600, NULL },
- { "U", 600, NULL },
- { "agrave", 600, NULL },
- { "V", 600, NULL },
- { "tab", 600, NULL },
- { "W", 600, NULL },
- { "ll", 600, NULL },
- { "X", 600, NULL },
- { "question", 600, NULL },
- { "equal", 600, NULL },
- { "Y", 600, NULL },
- { "Z", 600, NULL },
- { "four", 600, NULL },
- { "a", 600, NULL },
- { "b", 600, NULL },
- { "c", 600, NULL },
- { "d", 600, NULL },
- { "e", 600, NULL },
- { "f", 600, NULL },
- { "g", 600, NULL },
- { "bullet", 600, NULL },
- { "h", 600, NULL },
- { "i", 600, NULL },
- { "Oslash", 600, NULL },
- { "dagger", 600, NULL },
- { "j", 600, NULL },
- { "k", 600, NULL },
- { "l", 600, NULL },
- { "m", 600, NULL },
- { "n", 600, NULL },
- { "o", 600, NULL },
- { "ordfeminine", 600, NULL },
- { "ring", 600, NULL },
- { "p", 600, NULL },
- { "q", 600, NULL },
- { "r", 600, NULL },
- { "twosuperior", 600, NULL },
- { "largebullet", 600, NULL },
- { "aacute", 600, NULL },
- { "s", 600, NULL },
- { "OE", 600, NULL },
- { "t", 600, NULL },
- { "divide", 600, NULL },
- { "u", 600, NULL },
- { "v", 600, NULL },
- { "w", 600, NULL },
- { "x", 600, NULL },
- { "y", 600, NULL },
- { "z", 600, NULL },
- { "hungarumlaut", 600, NULL },
- { "quotedbl", 600, NULL },
- { "mu", 600, NULL },
- { "Scaron", 600, NULL },
- { "Lslash", 600, NULL },
- { "semicolon", 600, NULL },
- { "oslash", 600, NULL },
- { "parenright", 600, NULL },
- { "Ecircumflex", 600, NULL },
- { "trademark", 600, NULL },
- { "daggerdbl", 600, NULL },
- { "macron", 600, NULL },
- { "Otilde", 600, NULL },
- { "ellipsis", 600, NULL },
- { "scaron", 600, NULL },
- { "AE", 600, NULL },
- { "Ucircumflex", 600, NULL },
- { "lslash", 600, NULL },
- { "lira", 600, NULL },
- { "quotedblleft", 600, NULL },
- { "guilsinglright", 600, NULL },
- { "hyphen", 600, NULL },
- { "quotesingle", 600, NULL },
- { "eight", 600, NULL },
- { "exclamdown", 600, NULL },
- { "endash", 600, NULL },
- { "oe", 600, NULL },
- { "ecircumflex", 600, NULL },
- { "copyright", 600, NULL },
- { "Adieresis", 600, NULL },
- { "Egrave", 600, NULL },
- { "slash", 600, NULL },
- { "Edieresis", 600, NULL },
- { "otilde", 600, NULL },
- { "Idieresis", 600, NULL },
- { "parenleft", 600, NULL },
- { "one", 600, NULL },
- { "ucircumflex", 600, NULL },
- { "Odieresis", 600, NULL },
- { "bracketleft", 600, NULL },
- { "Ugrave", 600, NULL },
- { "quoteright", 600, NULL },
- { "Udieresis", 600, NULL },
- { "perthousand", 600, NULL },
- { "Ydieresis", 600, NULL },
- { "Eacute", 600, NULL },
- { "adieresis", 600, NULL },
- { "egrave", 600, NULL },
- { "edieresis", 600, NULL },
- { "idieresis", 600, NULL },
- { "Eth", 600, NULL },
- { "ae", 600, NULL },
- { "asterisk", 600, NULL },
- { "odieresis", 600, NULL },
- { "Uacute", 600, NULL },
- { "ugrave", 600, NULL },
- { "nine", 600, NULL },
- { "five", 600, NULL },
- { "udieresis", 600, NULL },
- { "Zcaron", 600, NULL },
- { "threequarters", 600, NULL },
- { "guillemotright", 600, NULL },
- { "ydieresis", 600, NULL },
- { "Ccedilla", 600, NULL },
- { "tilde", 600, NULL },
- { "at", 600, NULL },
- { "eacute", 600, NULL },
- { "Gcaron", 600, NULL },
- { "underscore", 600, NULL },
- { "multiply", 600, NULL },
- { "zero", 600, NULL },
- { "eth", 600, NULL },
- { "Scedilla", 600, NULL },
- { "Ograve", 600, NULL },
- { "uacute", 600, NULL },
- { "braceleft", 600, NULL },
- { "Thorn", 600, NULL },
- { "zcaron", 600, NULL },
- { "ccedilla", 600, NULL },
- { "gcaron", 600, NULL },
- { "scedilla", 600, NULL },
- { "Ocircumflex", 600, NULL },
- { "Oacute", 600, NULL },
- { "arrowdown", 600, NULL },
- { "ogonek", 600, NULL },
- { "ograve", 600, NULL },
- { "thorn", 600, NULL },
- { "degree", 600, NULL },
- { "registered", 600, NULL },
- { "Aring", 600, NULL },
- { "percent", 600, NULL },
- { "six", 600, NULL },
- { "paragraph", 600, NULL },
- { "two", 600, NULL },
- { "Igrave", 600, NULL },
- { "ocircumflex", 600, NULL },
- { "oacute", 600, NULL },
- { "asciicircum", 600, NULL },
- { "square", 600, NULL },
- { "aring", 600, NULL },
- { "grave", 600, NULL },
- { "bracketright", 600, NULL },
- { "Iacute", 600, NULL },
- { "ampersand", 600, NULL },
- { "igrave", 600, NULL },
- { "return", 600, NULL },
- { "plus", 600, NULL },
- { "quotesinglbase", 600, NULL },
- { "Yacute", 600, NULL },
- { "threesuperior", 600, NULL },
- { "acute", 600, NULL },
- { "notegraphic", 600, NULL },
- { "section", 600, NULL },
- { "arrowleft", 600, NULL },
- { "dieresis", 600, NULL },
- { "iacute", 600, NULL },
- { "quotedblbase", 600, NULL },
- { "up", 600, NULL },
- { "florin", 600, NULL },
- { "yacute", 600, NULL },
- { "fi", 600, NULL },
- { "fl", 600, NULL },
- { "Acircumflex", 600, NULL },
- { "Icircumflex", 600, NULL },
- { "guillemotleft", 600, NULL },
- { "germandbls", 600, NULL },
- { "seven", 600, NULL },
- { "prescription", 600, NULL },
- { "indent", 600, NULL },
- { "dectab", 600, NULL },
- { "ordmasculine", 600, NULL },
- { "dotlessi", 600, NULL },
- { "sterling", 600, NULL },
- { "acircumflex", 600, NULL },
- { "IJ", 600, NULL },
- { "overscore", 600, NULL },
- { "icircumflex", 600, NULL },
- { "braceright", 600, NULL },
- { "graybox", 600, NULL },
- { "quotedblright", 600, NULL },
- { "center", 600, NULL },
- { "stop", 600, NULL },
- { "cent", 600, NULL },
- { "currency", 600, NULL },
- { "logicalnot", 600, NULL },
- { "merge", 600, NULL },
- { "Idot", 600, NULL },
- { "Atilde", 600, NULL },
- { "breve", 600, NULL },
- { "bar", 600, NULL },
- { "fraction", 600, NULL },
- { "less", 600, NULL },
- { "down", 600, NULL },
- { "guilsinglleft", 600, NULL },
- { "exclam", 600, NULL },
- { "period", 600, NULL },
- { "format", 600, NULL },
- { "arrowright", 600, NULL },
- { "greater", 600, NULL },
- { "ij", 600, NULL },
- { "atilde", 600, NULL },
- { "brokenbar", 600, NULL },
- { "arrowboth", 600, NULL },
- { "quoteleft", 600, NULL },
- { "onesuperior", 600, NULL }
-};
-
-static BuiltinFontWidth courierObliqueWidthsTab[] = {
- { "Ntilde", 600, NULL },
- { "comma", 600, NULL },
- { "cedilla", 600, NULL },
- { "plusminus", 600, NULL },
- { "arrowup", 600, NULL },
- { "circumflex", 600, NULL },
- { "dotaccent", 600, NULL },
- { "LL", 600, NULL },
- { "asciitilde", 600, NULL },
- { "colon", 600, NULL },
- { "onehalf", 600, NULL },
- { "dollar", 600, NULL },
- { "ntilde", 600, NULL },
- { "left", 600, NULL },
- { "minus", 600, NULL },
- { "yen", 600, NULL },
- { "space", 600, NULL },
- { "questiondown", 600, NULL },
- { "emdash", 600, NULL },
- { "Agrave", 600, NULL },
- { "three", 600, NULL },
- { "numbersign", 600, NULL },
- { "A", 600, NULL },
- { "B", 600, NULL },
- { "C", 600, NULL },
- { "D", 600, NULL },
- { "E", 600, NULL },
- { "onequarter", 600, NULL },
- { "F", 600, NULL },
- { "G", 600, NULL },
- { "H", 600, NULL },
- { "I", 600, NULL },
- { "J", 600, NULL },
- { "K", 600, NULL },
- { "backslash", 600, NULL },
- { "L", 600, NULL },
- { "periodcentered", 600, NULL },
- { "M", 600, NULL },
- { "N", 600, NULL },
- { "O", 600, NULL },
- { "P", 600, NULL },
- { "Q", 600, NULL },
- { "R", 600, NULL },
- { "Aacute", 600, NULL },
- { "caron", 600, NULL },
- { "S", 600, NULL },
- { "T", 600, NULL },
- { "U", 600, NULL },
- { "agrave", 600, NULL },
- { "V", 600, NULL },
- { "tab", 600, NULL },
- { "W", 600, NULL },
- { "ll", 600, NULL },
- { "X", 600, NULL },
- { "question", 600, NULL },
- { "equal", 600, NULL },
- { "Y", 600, NULL },
- { "Z", 600, NULL },
- { "four", 600, NULL },
- { "a", 600, NULL },
- { "b", 600, NULL },
- { "c", 600, NULL },
- { "d", 600, NULL },
- { "e", 600, NULL },
- { "f", 600, NULL },
- { "g", 600, NULL },
- { "bullet", 600, NULL },
- { "h", 600, NULL },
- { "i", 600, NULL },
- { "Oslash", 600, NULL },
- { "dagger", 600, NULL },
- { "j", 600, NULL },
- { "k", 600, NULL },
- { "l", 600, NULL },
- { "m", 600, NULL },
- { "n", 600, NULL },
- { "o", 600, NULL },
- { "ordfeminine", 600, NULL },
- { "ring", 600, NULL },
- { "p", 600, NULL },
- { "q", 600, NULL },
- { "r", 600, NULL },
- { "twosuperior", 600, NULL },
- { "largebullet", 600, NULL },
- { "aacute", 600, NULL },
- { "s", 600, NULL },
- { "OE", 600, NULL },
- { "t", 600, NULL },
- { "divide", 600, NULL },
- { "u", 600, NULL },
- { "v", 600, NULL },
- { "w", 600, NULL },
- { "x", 600, NULL },
- { "y", 600, NULL },
- { "z", 600, NULL },
- { "hungarumlaut", 600, NULL },
- { "quotedbl", 600, NULL },
- { "mu", 600, NULL },
- { "Scaron", 600, NULL },
- { "Lslash", 600, NULL },
- { "semicolon", 600, NULL },
- { "oslash", 600, NULL },
- { "parenright", 600, NULL },
- { "Ecircumflex", 600, NULL },
- { "trademark", 600, NULL },
- { "daggerdbl", 600, NULL },
- { "macron", 600, NULL },
- { "Otilde", 600, NULL },
- { "ellipsis", 600, NULL },
- { "scaron", 600, NULL },
- { "AE", 600, NULL },
- { "Ucircumflex", 600, NULL },
- { "lslash", 600, NULL },
- { "lira", 600, NULL },
- { "quotedblleft", 600, NULL },
- { "guilsinglright", 600, NULL },
- { "hyphen", 600, NULL },
- { "quotesingle", 600, NULL },
- { "eight", 600, NULL },
- { "exclamdown", 600, NULL },
- { "endash", 600, NULL },
- { "oe", 600, NULL },
- { "ecircumflex", 600, NULL },
- { "copyright", 600, NULL },
- { "Adieresis", 600, NULL },
- { "Egrave", 600, NULL },
- { "slash", 600, NULL },
- { "Edieresis", 600, NULL },
- { "otilde", 600, NULL },
- { "Idieresis", 600, NULL },
- { "parenleft", 600, NULL },
- { "one", 600, NULL },
- { "ucircumflex", 600, NULL },
- { "Odieresis", 600, NULL },
- { "bracketleft", 600, NULL },
- { "Ugrave", 600, NULL },
- { "quoteright", 600, NULL },
- { "Udieresis", 600, NULL },
- { "perthousand", 600, NULL },
- { "Ydieresis", 600, NULL },
- { "Eacute", 600, NULL },
- { "adieresis", 600, NULL },
- { "egrave", 600, NULL },
- { "edieresis", 600, NULL },
- { "idieresis", 600, NULL },
- { "Eth", 600, NULL },
- { "ae", 600, NULL },
- { "asterisk", 600, NULL },
- { "odieresis", 600, NULL },
- { "Uacute", 600, NULL },
- { "ugrave", 600, NULL },
- { "nine", 600, NULL },
- { "five", 600, NULL },
- { "udieresis", 600, NULL },
- { "Zcaron", 600, NULL },
- { "threequarters", 600, NULL },
- { "guillemotright", 600, NULL },
- { "ydieresis", 600, NULL },
- { "Ccedilla", 600, NULL },
- { "tilde", 600, NULL },
- { "at", 600, NULL },
- { "eacute", 600, NULL },
- { "Gcaron", 600, NULL },
- { "underscore", 600, NULL },
- { "multiply", 600, NULL },
- { "zero", 600, NULL },
- { "eth", 600, NULL },
- { "Scedilla", 600, NULL },
- { "Ograve", 600, NULL },
- { "uacute", 600, NULL },
- { "braceleft", 600, NULL },
- { "Thorn", 600, NULL },
- { "zcaron", 600, NULL },
- { "ccedilla", 600, NULL },
- { "gcaron", 600, NULL },
- { "scedilla", 600, NULL },
- { "Ocircumflex", 600, NULL },
- { "Oacute", 600, NULL },
- { "arrowdown", 600, NULL },
- { "ogonek", 600, NULL },
- { "ograve", 600, NULL },
- { "thorn", 600, NULL },
- { "degree", 600, NULL },
- { "registered", 600, NULL },
- { "Aring", 600, NULL },
- { "percent", 600, NULL },
- { "six", 600, NULL },
- { "paragraph", 600, NULL },
- { "two", 600, NULL },
- { "Igrave", 600, NULL },
- { "ocircumflex", 600, NULL },
- { "oacute", 600, NULL },
- { "asciicircum", 600, NULL },
- { "square", 600, NULL },
- { "aring", 600, NULL },
- { "grave", 600, NULL },
- { "bracketright", 600, NULL },
- { "Iacute", 600, NULL },
- { "ampersand", 600, NULL },
- { "igrave", 600, NULL },
- { "return", 600, NULL },
- { "plus", 600, NULL },
- { "quotesinglbase", 600, NULL },
- { "Yacute", 600, NULL },
- { "threesuperior", 600, NULL },
- { "acute", 600, NULL },
- { "notegraphic", 600, NULL },
- { "section", 600, NULL },
- { "arrowleft", 600, NULL },
- { "dieresis", 600, NULL },
- { "iacute", 600, NULL },
- { "quotedblbase", 600, NULL },
- { "up", 600, NULL },
- { "florin", 600, NULL },
- { "yacute", 600, NULL },
- { "fi", 600, NULL },
- { "fl", 600, NULL },
- { "Acircumflex", 600, NULL },
- { "Icircumflex", 600, NULL },
- { "guillemotleft", 600, NULL },
- { "germandbls", 600, NULL },
- { "seven", 600, NULL },
- { "prescription", 600, NULL },
- { "indent", 600, NULL },
- { "dectab", 600, NULL },
- { "ordmasculine", 600, NULL },
- { "dotlessi", 600, NULL },
- { "sterling", 600, NULL },
- { "acircumflex", 600, NULL },
- { "IJ", 600, NULL },
- { "overscore", 600, NULL },
- { "icircumflex", 600, NULL },
- { "braceright", 600, NULL },
- { "graybox", 600, NULL },
- { "quotedblright", 600, NULL },
- { "center", 600, NULL },
- { "stop", 600, NULL },
- { "cent", 600, NULL },
- { "currency", 600, NULL },
- { "logicalnot", 600, NULL },
- { "merge", 600, NULL },
- { "Idot", 600, NULL },
- { "Atilde", 600, NULL },
- { "breve", 600, NULL },
- { "bar", 600, NULL },
- { "fraction", 600, NULL },
- { "less", 600, NULL },
- { "down", 600, NULL },
- { "guilsinglleft", 600, NULL },
- { "exclam", 600, NULL },
- { "period", 600, NULL },
- { "format", 600, NULL },
- { "arrowright", 600, NULL },
- { "greater", 600, NULL },
- { "ij", 600, NULL },
- { "atilde", 600, NULL },
- { "brokenbar", 600, NULL },
- { "arrowboth", 600, NULL },
- { "quoteleft", 600, NULL },
- { "onesuperior", 600, NULL }
-};
-
-static BuiltinFontWidth helveticaWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 278, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 584, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 584, NULL },
- { "colon", 278, NULL },
- { "onehalf", 834, NULL },
- { "dollar", 556, NULL },
- { "ntilde", 556, NULL },
- { "minus", 584, NULL },
- { "yen", 556, NULL },
- { "space", 278, NULL },
- { "questiondown", 611, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 667, NULL },
- { "three", 556, NULL },
- { "numbersign", 556, NULL },
- { "A", 667, NULL },
- { "B", 667, NULL },
- { "C", 722, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 834, NULL },
- { "F", 611, NULL },
- { "G", 778, NULL },
- { "H", 722, NULL },
- { "I", 278, NULL },
- { "J", 500, NULL },
- { "K", 667, NULL },
- { "backslash", 278, NULL },
- { "L", 556, NULL },
- { "periodcentered", 278, NULL },
- { "M", 833, NULL },
- { "N", 722, NULL },
- { "O", 778, NULL },
- { "P", 667, NULL },
- { "Q", 778, NULL },
- { "R", 722, NULL },
- { "Aacute", 667, NULL },
- { "caron", 333, NULL },
- { "S", 667, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 556, NULL },
- { "V", 667, NULL },
- { "W", 944, NULL },
- { "X", 667, NULL },
- { "question", 556, NULL },
- { "equal", 584, NULL },
- { "Y", 667, NULL },
- { "Z", 611, NULL },
- { "four", 556, NULL },
- { "a", 556, NULL },
- { "b", 556, NULL },
- { "c", 500, NULL },
- { "d", 556, NULL },
- { "e", 556, NULL },
- { "f", 278, NULL },
- { "g", 556, NULL },
- { "bullet", 350, NULL },
- { "h", 556, NULL },
- { "i", 222, NULL },
- { "Oslash", 778, NULL },
- { "dagger", 556, NULL },
- { "j", 222, NULL },
- { "k", 500, NULL },
- { "l", 222, NULL },
- { "m", 833, NULL },
- { "n", 556, NULL },
- { "o", 556, NULL },
- { "ordfeminine", 370, NULL },
- { "ring", 333, NULL },
- { "p", 556, NULL },
- { "q", 556, NULL },
- { "r", 333, NULL },
- { "twosuperior", 333, NULL },
- { "aacute", 556, NULL },
- { "s", 500, NULL },
- { "OE", 1000, NULL },
- { "t", 278, NULL },
- { "divide", 584, NULL },
- { "u", 556, NULL },
- { "v", 500, NULL },
- { "w", 722, NULL },
- { "x", 500, NULL },
- { "y", 500, NULL },
- { "z", 500, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 355, NULL },
- { "mu", 556, NULL },
- { "Scaron", 667, NULL },
- { "Lslash", 556, NULL },
- { "semicolon", 278, NULL },
- { "oslash", 611, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 556, NULL },
- { "macron", 333, NULL },
- { "Otilde", 778, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 500, NULL },
- { "AE", 1000, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 222, NULL },
- { "quotedblleft", 333, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 191, NULL },
- { "eight", 556, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 556, NULL },
- { "oe", 944, NULL },
- { "ecircumflex", 556, NULL },
- { "copyright", 737, NULL },
- { "Adieresis", 667, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 556, NULL },
- { "Idieresis", 278, NULL },
- { "parenleft", 333, NULL },
- { "one", 556, NULL },
- { "ucircumflex", 556, NULL },
- { "Odieresis", 778, NULL },
- { "bracketleft", 278, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 222, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 667, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 556, NULL },
- { "egrave", 556, NULL },
- { "edieresis", 556, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 889, NULL },
- { "asterisk", 389, NULL },
- { "odieresis", 556, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 556, NULL },
- { "nine", 556, NULL },
- { "five", 556, NULL },
- { "udieresis", 556, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 834, NULL },
- { "guillemotright", 556, NULL },
- { "ydieresis", 500, NULL },
- { "Ccedilla", 722, NULL },
- { "tilde", 333, NULL },
- { "at", 1015, NULL },
- { "eacute", 556, NULL },
- { "underscore", 556, NULL },
- { "multiply", 584, NULL },
- { "zero", 556, NULL },
- { "eth", 556, NULL },
- { "Ograve", 778, NULL },
- { "uacute", 556, NULL },
- { "braceleft", 334, NULL },
- { "Thorn", 667, NULL },
- { "zcaron", 500, NULL },
- { "ccedilla", 500, NULL },
- { "Ocircumflex", 778, NULL },
- { "Oacute", 778, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 556, NULL },
- { "thorn", 556, NULL },
- { "degree", 400, NULL },
- { "registered", 737, NULL },
- { "Aring", 667, NULL },
- { "percent", 889, NULL },
- { "six", 556, NULL },
- { "paragraph", 537, NULL },
- { "two", 556, NULL },
- { "Igrave", 278, NULL },
- { "ocircumflex", 556, NULL },
- { "oacute", 556, NULL },
- { "asciicircum", 469, NULL },
- { "aring", 556, NULL },
- { "grave", 333, NULL },
- { "bracketright", 278, NULL },
- { "Iacute", 278, NULL },
- { "ampersand", 667, NULL },
- { "igrave", 278, NULL },
- { "plus", 584, NULL },
- { "quotesinglbase", 222, NULL },
- { "Yacute", 667, NULL },
- { "threesuperior", 333, NULL },
- { "acute", 333, NULL },
- { "section", 556, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 333, NULL },
- { "florin", 556, NULL },
- { "yacute", 500, NULL },
- { "fi", 500, NULL },
- { "fl", 500, NULL },
- { "Acircumflex", 667, NULL },
- { "Icircumflex", 278, NULL },
- { "guillemotleft", 556, NULL },
- { "germandbls", 611, NULL },
- { "seven", 556, NULL },
- { "ordmasculine", 365, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 556, NULL },
- { "acircumflex", 556, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 334, NULL },
- { "quotedblright", 333, NULL },
- { "cent", 556, NULL },
- { "currency", 556, NULL },
- { "logicalnot", 584, NULL },
- { "Atilde", 667, NULL },
- { "breve", 333, NULL },
- { "bar", 260, NULL },
- { "fraction", 167, NULL },
- { "less", 584, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 278, NULL },
- { "period", 278, NULL },
- { "greater", 584, NULL },
- { "atilde", 556, NULL },
- { "brokenbar", 260, NULL },
- { "quoteleft", 222, NULL },
- { "onesuperior", 333, NULL }
-};
-
-static BuiltinFontWidth helveticaBoldWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 278, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 584, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 584, NULL },
- { "colon", 333, NULL },
- { "onehalf", 834, NULL },
- { "dollar", 556, NULL },
- { "ntilde", 611, NULL },
- { "minus", 584, NULL },
- { "yen", 556, NULL },
- { "space", 278, NULL },
- { "questiondown", 611, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 722, NULL },
- { "three", 556, NULL },
- { "numbersign", 556, NULL },
- { "A", 722, NULL },
- { "B", 722, NULL },
- { "C", 722, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 834, NULL },
- { "F", 611, NULL },
- { "G", 778, NULL },
- { "H", 722, NULL },
- { "I", 278, NULL },
- { "J", 556, NULL },
- { "K", 722, NULL },
- { "backslash", 278, NULL },
- { "L", 611, NULL },
- { "periodcentered", 278, NULL },
- { "M", 833, NULL },
- { "N", 722, NULL },
- { "O", 778, NULL },
- { "P", 667, NULL },
- { "Q", 778, NULL },
- { "R", 722, NULL },
- { "Aacute", 722, NULL },
- { "caron", 333, NULL },
- { "S", 667, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 556, NULL },
- { "V", 667, NULL },
- { "W", 944, NULL },
- { "X", 667, NULL },
- { "question", 611, NULL },
- { "equal", 584, NULL },
- { "Y", 667, NULL },
- { "Z", 611, NULL },
- { "four", 556, NULL },
- { "a", 556, NULL },
- { "b", 611, NULL },
- { "c", 556, NULL },
- { "d", 611, NULL },
- { "e", 556, NULL },
- { "f", 333, NULL },
- { "g", 611, NULL },
- { "bullet", 350, NULL },
- { "h", 611, NULL },
- { "i", 278, NULL },
- { "Oslash", 778, NULL },
- { "dagger", 556, NULL },
- { "j", 278, NULL },
- { "k", 556, NULL },
- { "l", 278, NULL },
- { "m", 889, NULL },
- { "n", 611, NULL },
- { "o", 611, NULL },
- { "ordfeminine", 370, NULL },
- { "ring", 333, NULL },
- { "p", 611, NULL },
- { "q", 611, NULL },
- { "r", 389, NULL },
- { "twosuperior", 333, NULL },
- { "aacute", 556, NULL },
- { "s", 556, NULL },
- { "OE", 1000, NULL },
- { "t", 333, NULL },
- { "divide", 584, NULL },
- { "u", 611, NULL },
- { "v", 556, NULL },
- { "w", 778, NULL },
- { "x", 556, NULL },
- { "y", 556, NULL },
- { "z", 500, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 474, NULL },
- { "mu", 611, NULL },
- { "Scaron", 667, NULL },
- { "Lslash", 611, NULL },
- { "semicolon", 333, NULL },
- { "oslash", 611, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 556, NULL },
- { "macron", 333, NULL },
- { "Otilde", 778, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 556, NULL },
- { "AE", 1000, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 500, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 238, NULL },
- { "eight", 556, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 556, NULL },
- { "oe", 944, NULL },
- { "ecircumflex", 556, NULL },
- { "copyright", 737, NULL },
- { "Adieresis", 722, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 611, NULL },
- { "Idieresis", 278, NULL },
- { "parenleft", 333, NULL },
- { "one", 556, NULL },
- { "ucircumflex", 611, NULL },
- { "Odieresis", 778, NULL },
- { "bracketleft", 333, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 278, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 667, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 556, NULL },
- { "egrave", 556, NULL },
- { "edieresis", 556, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 889, NULL },
- { "asterisk", 389, NULL },
- { "odieresis", 611, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 611, NULL },
- { "nine", 556, NULL },
- { "five", 556, NULL },
- { "udieresis", 611, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 834, NULL },
- { "guillemotright", 556, NULL },
- { "ydieresis", 556, NULL },
- { "Ccedilla", 722, NULL },
- { "tilde", 333, NULL },
- { "dbldaggerumlaut", 556, NULL },
- { "at", 975, NULL },
- { "eacute", 556, NULL },
- { "underscore", 556, NULL },
- { "multiply", 584, NULL },
- { "zero", 556, NULL },
- { "eth", 611, NULL },
- { "Ograve", 778, NULL },
- { "uacute", 611, NULL },
- { "braceleft", 389, NULL },
- { "Thorn", 667, NULL },
- { "zcaron", 500, NULL },
- { "ccedilla", 556, NULL },
- { "Ocircumflex", 778, NULL },
- { "Oacute", 778, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 611, NULL },
- { "thorn", 611, NULL },
- { "degree", 400, NULL },
- { "registered", 737, NULL },
- { "Aring", 722, NULL },
- { "percent", 889, NULL },
- { "six", 556, NULL },
- { "paragraph", 556, NULL },
- { "two", 556, NULL },
- { "Igrave", 278, NULL },
- { "ocircumflex", 611, NULL },
- { "oacute", 611, NULL },
- { "asciicircum", 584, NULL },
- { "aring", 556, NULL },
- { "grave", 333, NULL },
- { "bracketright", 333, NULL },
- { "Iacute", 278, NULL },
- { "ampersand", 722, NULL },
- { "igrave", 278, NULL },
- { "plus", 584, NULL },
- { "quotesinglbase", 278, NULL },
- { "Yacute", 667, NULL },
- { "threesuperior", 333, NULL },
- { "acute", 333, NULL },
- { "section", 556, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 500, NULL },
- { "florin", 556, NULL },
- { "yacute", 556, NULL },
- { "fi", 611, NULL },
- { "fl", 611, NULL },
- { "Acircumflex", 722, NULL },
- { "Icircumflex", 278, NULL },
- { "guillemotleft", 556, NULL },
- { "germandbls", 611, NULL },
- { "seven", 556, NULL },
- { "ordmasculine", 365, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 556, NULL },
- { "acircumflex", 556, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 389, NULL },
- { "quotedblright", 500, NULL },
- { "cent", 556, NULL },
- { "currency", 556, NULL },
- { "logicalnot", 584, NULL },
- { "Atilde", 722, NULL },
- { "breve", 333, NULL },
- { "bar", 280, NULL },
- { "fraction", 167, NULL },
- { "less", 584, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 333, NULL },
- { "period", 278, NULL },
- { "greater", 584, NULL },
- { "atilde", 556, NULL },
- { "brokenbar", 280, NULL },
- { "quoteleft", 278, NULL },
- { "onesuperior", 333, NULL }
-};
-
-static BuiltinFontWidth helveticaBoldObliqueWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 278, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 584, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 584, NULL },
- { "colon", 333, NULL },
- { "onehalf", 834, NULL },
- { "dollar", 556, NULL },
- { "ntilde", 611, NULL },
- { "minus", 584, NULL },
- { "yen", 556, NULL },
- { "space", 278, NULL },
- { "questiondown", 611, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 722, NULL },
- { "three", 556, NULL },
- { "numbersign", 556, NULL },
- { "A", 722, NULL },
- { "B", 722, NULL },
- { "C", 722, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 834, NULL },
- { "F", 611, NULL },
- { "G", 778, NULL },
- { "H", 722, NULL },
- { "I", 278, NULL },
- { "J", 556, NULL },
- { "K", 722, NULL },
- { "backslash", 278, NULL },
- { "L", 611, NULL },
- { "periodcentered", 278, NULL },
- { "M", 833, NULL },
- { "N", 722, NULL },
- { "O", 778, NULL },
- { "P", 667, NULL },
- { "Q", 778, NULL },
- { "R", 722, NULL },
- { "Aacute", 722, NULL },
- { "caron", 333, NULL },
- { "S", 667, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 556, NULL },
- { "V", 667, NULL },
- { "W", 944, NULL },
- { "X", 667, NULL },
- { "question", 611, NULL },
- { "equal", 584, NULL },
- { "Y", 667, NULL },
- { "Z", 611, NULL },
- { "four", 556, NULL },
- { "a", 556, NULL },
- { "b", 611, NULL },
- { "c", 556, NULL },
- { "d", 611, NULL },
- { "e", 556, NULL },
- { "f", 333, NULL },
- { "g", 611, NULL },
- { "bullet", 350, NULL },
- { "h", 611, NULL },
- { "i", 278, NULL },
- { "Oslash", 778, NULL },
- { "dagger", 556, NULL },
- { "j", 278, NULL },
- { "k", 556, NULL },
- { "l", 278, NULL },
- { "m", 889, NULL },
- { "n", 611, NULL },
- { "o", 611, NULL },
- { "ordfeminine", 370, NULL },
- { "ring", 333, NULL },
- { "p", 611, NULL },
- { "q", 611, NULL },
- { "r", 389, NULL },
- { "twosuperior", 333, NULL },
- { "aacute", 556, NULL },
- { "s", 556, NULL },
- { "OE", 1000, NULL },
- { "t", 333, NULL },
- { "divide", 584, NULL },
- { "u", 611, NULL },
- { "v", 556, NULL },
- { "w", 778, NULL },
- { "x", 556, NULL },
- { "y", 556, NULL },
- { "z", 500, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 474, NULL },
- { "mu", 611, NULL },
- { "Scaron", 667, NULL },
- { "Lslash", 611, NULL },
- { "semicolon", 333, NULL },
- { "oslash", 611, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 556, NULL },
- { "macron", 333, NULL },
- { "Otilde", 778, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 556, NULL },
- { "AE", 1000, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 500, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 238, NULL },
- { "eight", 556, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 556, NULL },
- { "oe", 944, NULL },
- { "ecircumflex", 556, NULL },
- { "copyright", 737, NULL },
- { "Adieresis", 722, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 611, NULL },
- { "Idieresis", 278, NULL },
- { "parenleft", 333, NULL },
- { "one", 556, NULL },
- { "ucircumflex", 611, NULL },
- { "Odieresis", 778, NULL },
- { "bracketleft", 333, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 278, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 667, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 556, NULL },
- { "egrave", 556, NULL },
- { "edieresis", 556, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 889, NULL },
- { "asterisk", 389, NULL },
- { "odieresis", 611, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 611, NULL },
- { "nine", 556, NULL },
- { "five", 556, NULL },
- { "udieresis", 611, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 834, NULL },
- { "guillemotright", 556, NULL },
- { "ydieresis", 556, NULL },
- { "Ccedilla", 722, NULL },
- { "tilde", 333, NULL },
- { "at", 975, NULL },
- { "eacute", 556, NULL },
- { "underscore", 556, NULL },
- { "multiply", 584, NULL },
- { "zero", 556, NULL },
- { "eth", 611, NULL },
- { "Ograve", 778, NULL },
- { "uacute", 611, NULL },
- { "braceleft", 389, NULL },
- { "Thorn", 667, NULL },
- { "zcaron", 500, NULL },
- { "ccedilla", 556, NULL },
- { "Ocircumflex", 778, NULL },
- { "Oacute", 778, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 611, NULL },
- { "thorn", 611, NULL },
- { "degree", 400, NULL },
- { "registered", 737, NULL },
- { "Aring", 722, NULL },
- { "percent", 889, NULL },
- { "six", 556, NULL },
- { "paragraph", 556, NULL },
- { "two", 556, NULL },
- { "Igrave", 278, NULL },
- { "ocircumflex", 611, NULL },
- { "oacute", 611, NULL },
- { "asciicircum", 584, NULL },
- { "aring", 556, NULL },
- { "grave", 333, NULL },
- { "bracketright", 333, NULL },
- { "Iacute", 278, NULL },
- { "ampersand", 722, NULL },
- { "igrave", 278, NULL },
- { "plus", 584, NULL },
- { "quotesinglbase", 278, NULL },
- { "Yacute", 667, NULL },
- { "threesuperior", 333, NULL },
- { "acute", 333, NULL },
- { "section", 556, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 500, NULL },
- { "florin", 556, NULL },
- { "yacute", 556, NULL },
- { "fi", 611, NULL },
- { "fl", 611, NULL },
- { "Acircumflex", 722, NULL },
- { "Icircumflex", 278, NULL },
- { "guillemotleft", 556, NULL },
- { "germandbls", 611, NULL },
- { "seven", 556, NULL },
- { "ordmasculine", 365, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 556, NULL },
- { "acircumflex", 556, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 389, NULL },
- { "quotedblright", 500, NULL },
- { "cent", 556, NULL },
- { "currency", 556, NULL },
- { "logicalnot", 584, NULL },
- { "Atilde", 722, NULL },
- { "breve", 333, NULL },
- { "bar", 280, NULL },
- { "fraction", 167, NULL },
- { "less", 584, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 333, NULL },
- { "period", 278, NULL },
- { "greater", 584, NULL },
- { "atilde", 556, NULL },
- { "brokenbar", 280, NULL },
- { "quoteleft", 278, NULL },
- { "onesuperior", 333, NULL }
-};
-
-static BuiltinFontWidth helveticaObliqueWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 278, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 584, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 584, NULL },
- { "colon", 278, NULL },
- { "onehalf", 834, NULL },
- { "dollar", 556, NULL },
- { "ntilde", 556, NULL },
- { "minus", 584, NULL },
- { "yen", 556, NULL },
- { "space", 278, NULL },
- { "questiondown", 611, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 667, NULL },
- { "three", 556, NULL },
- { "numbersign", 556, NULL },
- { "A", 667, NULL },
- { "B", 667, NULL },
- { "C", 722, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 834, NULL },
- { "F", 611, NULL },
- { "G", 778, NULL },
- { "H", 722, NULL },
- { "I", 278, NULL },
- { "J", 500, NULL },
- { "K", 667, NULL },
- { "backslash", 278, NULL },
- { "L", 556, NULL },
- { "periodcentered", 278, NULL },
- { "M", 833, NULL },
- { "N", 722, NULL },
- { "O", 778, NULL },
- { "P", 667, NULL },
- { "Q", 778, NULL },
- { "R", 722, NULL },
- { "Aacute", 667, NULL },
- { "caron", 333, NULL },
- { "S", 667, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 556, NULL },
- { "V", 667, NULL },
- { "W", 944, NULL },
- { "X", 667, NULL },
- { "question", 556, NULL },
- { "equal", 584, NULL },
- { "Y", 667, NULL },
- { "Z", 611, NULL },
- { "four", 556, NULL },
- { "a", 556, NULL },
- { "b", 556, NULL },
- { "c", 500, NULL },
- { "d", 556, NULL },
- { "e", 556, NULL },
- { "f", 278, NULL },
- { "g", 556, NULL },
- { "bullet", 350, NULL },
- { "h", 556, NULL },
- { "i", 222, NULL },
- { "Oslash", 778, NULL },
- { "dagger", 556, NULL },
- { "j", 222, NULL },
- { "k", 500, NULL },
- { "l", 222, NULL },
- { "m", 833, NULL },
- { "n", 556, NULL },
- { "o", 556, NULL },
- { "ordfeminine", 370, NULL },
- { "ring", 333, NULL },
- { "p", 556, NULL },
- { "q", 556, NULL },
- { "r", 333, NULL },
- { "twosuperior", 333, NULL },
- { "aacute", 556, NULL },
- { "s", 500, NULL },
- { "OE", 1000, NULL },
- { "t", 278, NULL },
- { "divide", 584, NULL },
- { "u", 556, NULL },
- { "v", 500, NULL },
- { "w", 722, NULL },
- { "x", 500, NULL },
- { "y", 500, NULL },
- { "z", 500, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 355, NULL },
- { "mu", 556, NULL },
- { "Scaron", 667, NULL },
- { "Lslash", 556, NULL },
- { "semicolon", 278, NULL },
- { "oslash", 611, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 556, NULL },
- { "macron", 333, NULL },
- { "Otilde", 778, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 500, NULL },
- { "AE", 1000, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 222, NULL },
- { "quotedblleft", 333, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 191, NULL },
- { "eight", 556, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 556, NULL },
- { "oe", 944, NULL },
- { "ecircumflex", 556, NULL },
- { "copyright", 737, NULL },
- { "Adieresis", 667, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 556, NULL },
- { "Idieresis", 278, NULL },
- { "parenleft", 333, NULL },
- { "one", 556, NULL },
- { "ucircumflex", 556, NULL },
- { "Odieresis", 778, NULL },
- { "bracketleft", 278, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 222, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 667, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 556, NULL },
- { "egrave", 556, NULL },
- { "edieresis", 556, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 889, NULL },
- { "asterisk", 389, NULL },
- { "odieresis", 556, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 556, NULL },
- { "nine", 556, NULL },
- { "five", 556, NULL },
- { "udieresis", 556, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 834, NULL },
- { "guillemotright", 556, NULL },
- { "ydieresis", 500, NULL },
- { "Ccedilla", 722, NULL },
- { "tilde", 333, NULL },
- { "at", 1015, NULL },
- { "eacute", 556, NULL },
- { "underscore", 556, NULL },
- { "multiply", 584, NULL },
- { "zero", 556, NULL },
- { "eth", 556, NULL },
- { "Ograve", 778, NULL },
- { "uacute", 556, NULL },
- { "braceleft", 334, NULL },
- { "Thorn", 667, NULL },
- { "zcaron", 500, NULL },
- { "ccedilla", 500, NULL },
- { "Ocircumflex", 778, NULL },
- { "Oacute", 778, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 556, NULL },
- { "thorn", 556, NULL },
- { "degree", 400, NULL },
- { "registered", 737, NULL },
- { "Aring", 667, NULL },
- { "percent", 889, NULL },
- { "six", 556, NULL },
- { "paragraph", 537, NULL },
- { "two", 556, NULL },
- { "Igrave", 278, NULL },
- { "ocircumflex", 556, NULL },
- { "oacute", 556, NULL },
- { "asciicircum", 469, NULL },
- { "aring", 556, NULL },
- { "grave", 333, NULL },
- { "bracketright", 278, NULL },
- { "Iacute", 278, NULL },
- { "ampersand", 667, NULL },
- { "igrave", 278, NULL },
- { "plus", 584, NULL },
- { "quotesinglbase", 222, NULL },
- { "Yacute", 667, NULL },
- { "threesuperior", 333, NULL },
- { "acute", 333, NULL },
- { "section", 556, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 333, NULL },
- { "florin", 556, NULL },
- { "yacute", 500, NULL },
- { "fi", 500, NULL },
- { "fl", 500, NULL },
- { "Acircumflex", 667, NULL },
- { "Icircumflex", 278, NULL },
- { "guillemotleft", 556, NULL },
- { "germandbls", 611, NULL },
- { "seven", 556, NULL },
- { "ordmasculine", 365, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 556, NULL },
- { "acircumflex", 556, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 334, NULL },
- { "quotedblright", 333, NULL },
- { "cent", 556, NULL },
- { "currency", 556, NULL },
- { "logicalnot", 584, NULL },
- { "Atilde", 667, NULL },
- { "breve", 333, NULL },
- { "bar", 260, NULL },
- { "fraction", 167, NULL },
- { "less", 584, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 278, NULL },
- { "period", 278, NULL },
- { "greater", 584, NULL },
- { "atilde", 556, NULL },
- { "brokenbar", 260, NULL },
- { "quoteleft", 222, NULL },
- { "onesuperior", 333, NULL }
-};
-
-static BuiltinFontWidth symbolWidthsTab[] = {
- { "bracketleftex", 384, NULL },
- { "alpha", 631, NULL },
- { "union", 768, NULL },
- { "infinity", 713, NULL },
- { "comma", 250, NULL },
- { "copyrightsans", 790, NULL },
- { "plusminus", 549, NULL },
- { "arrowup", 603, NULL },
- { "apple", 790, NULL },
- { "parenleftbt", 384, NULL },
- { "notelement", 713, NULL },
- { "colon", 278, NULL },
- { "beta", 549, NULL },
- { "braceleftbt", 494, NULL },
- { "Lambda", 686, NULL },
- { "Phi", 763, NULL },
- { "minus", 549, NULL },
- { "space", 250, NULL },
- { "Sigma", 592, NULL },
- { "approxequal", 549, NULL },
- { "minute", 247, NULL },
- { "circleplus", 768, NULL },
- { "Omicron", 722, NULL },
- { "three", 500, NULL },
- { "numbersign", 500, NULL },
- { "lambda", 549, NULL },
- { "phi", 521, NULL },
- { "aleph", 823, NULL },
- { "Tau", 611, NULL },
- { "spade", 753, NULL },
- { "logicaland", 603, NULL },
- { "sigma", 603, NULL },
- { "propersuperset", 713, NULL },
- { "omicron", 549, NULL },
- { "question", 444, NULL },
- { "equal", 549, NULL },
- { "Epsilon", 611, NULL },
- { "emptyset", 823, NULL },
- { "diamond", 753, NULL },
- { "four", 500, NULL },
- { "Mu", 889, NULL },
- { "parenlefttp", 384, NULL },
- { "club", 753, NULL },
- { "bullet", 460, NULL },
- { "Omega", 768, NULL },
- { "tau", 439, NULL },
- { "Upsilon", 690, NULL },
- { "bracelefttp", 494, NULL },
- { "heart", 753, NULL },
- { "divide", 549, NULL },
- { "epsilon", 439, NULL },
- { "logicalor", 603, NULL },
- { "parenleftex", 384, NULL },
- { "greaterequal", 549, NULL },
- { "mu", 576, NULL },
- { "Nu", 722, NULL },
- { "therefore", 863, NULL },
- { "notsubset", 713, NULL },
- { "omega", 686, NULL },
- { "semicolon", 278, NULL },
- { "element", 713, NULL },
- { "upsilon", 576, NULL },
- { "existential", 549, NULL },
- { "integralbt", 686, NULL },
- { "lessequal", 549, NULL },
- { "phi1", 603, NULL },
- { "lozenge", 494, NULL },
- { "trademarkserif", 890, NULL },
- { "parenright", 333, NULL },
- { "reflexsuperset", 713, NULL },
- { "sigma1", 439, NULL },
- { "nu", 521, NULL },
- { "Gamma", 603, NULL },
- { "angleright", 329, NULL },
- { "ellipsis", 1000, NULL },
- { "Rho", 556, NULL },
- { "parenrightbt", 384, NULL },
- { "radicalex", 500, NULL },
- { "eight", 500, NULL },
- { "angleleft", 329, NULL },
- { "arrowdbldown", 603, NULL },
- { "congruent", 549, NULL },
- { "Theta", 741, NULL },
- { "intersection", 768, NULL },
- { "Pi", 768, NULL },
- { "slash", 278, NULL },
- { "registerserif", 790, NULL },
- { "parenleft", 333, NULL },
- { "one", 500, NULL },
- { "gamma", 411, NULL },
- { "bracketleft", 333, NULL },
- { "rho", 549, NULL },
- { "circlemultiply", 768, NULL },
- { "Chi", 722, NULL },
- { "theta", 521, NULL },
- { "pi", 549, NULL },
- { "integraltp", 686, NULL },
- { "Eta", 722, NULL },
- { "product", 823, NULL },
- { "nine", 500, NULL },
- { "five", 500, NULL },
- { "propersubset", 713, NULL },
- { "bracketrightbt", 384, NULL },
- { "trademarksans", 786, NULL },
- { "dotmath", 250, NULL },
- { "integralex", 686, NULL },
- { "chi", 549, NULL },
- { "parenrighttp", 384, NULL },
- { "eta", 603, NULL },
- { "underscore", 500, NULL },
- { "multiply", 549, NULL },
- { "zero", 500, NULL },
- { "partialdiff", 494, NULL },
- { "angle", 768, NULL },
- { "arrowdblleft", 987, NULL },
- { "braceleft", 480, NULL },
- { "parenrightex", 384, NULL },
- { "Rfraktur", 795, NULL },
- { "Zeta", 611, NULL },
- { "braceex", 494, NULL },
- { "arrowdblup", 603, NULL },
- { "arrowdown", 603, NULL },
- { "Ifraktur", 686, NULL },
- { "degree", 400, NULL },
- { "Iota", 333, NULL },
- { "perpendicular", 658, NULL },
- { "radical", 549, NULL },
- { "asteriskmath", 500, NULL },
- { "percent", 833, NULL },
- { "zeta", 494, NULL },
- { "six", 500, NULL },
- { "two", 500, NULL },
- { "weierstrass", 987, NULL },
- { "summation", 713, NULL },
- { "bracketrighttp", 384, NULL },
- { "carriagereturn", 658, NULL },
- { "suchthat", 439, NULL },
- { "arrowvertex", 603, NULL },
- { "Delta", 612, NULL },
- { "iota", 329, NULL },
- { "arrowhorizex", 1000, NULL },
- { "bracketrightex", 384, NULL },
- { "bracketright", 333, NULL },
- { "ampersand", 778, NULL },
- { "plus", 549, NULL },
- { "proportional", 713, NULL },
- { "delta", 494, NULL },
- { "copyrightserif", 790, NULL },
- { "bracerightmid", 494, NULL },
- { "arrowleft", 987, NULL },
- { "second", 411, NULL },
- { "arrowdblboth", 1042, NULL },
- { "florin", 500, NULL },
- { "Psi", 795, NULL },
- { "bracerightbt", 494, NULL },
- { "bracketleftbt", 384, NULL },
- { "seven", 500, NULL },
- { "braceleftmid", 494, NULL },
- { "notequal", 549, NULL },
- { "psi", 686, NULL },
- { "equivalence", 549, NULL },
- { "universal", 713, NULL },
- { "arrowdblright", 987, NULL },
- { "braceright", 480, NULL },
- { "reflexsubset", 713, NULL },
- { "Xi", 645, NULL },
- { "theta1", 631, NULL },
- { "logicalnot", 713, NULL },
- { "Kappa", 722, NULL },
- { "similar", 549, NULL },
- { "bar", 200, NULL },
- { "fraction", 167, NULL },
- { "less", 549, NULL },
- { "registersans", 790, NULL },
- { "omega1", 713, NULL },
- { "exclam", 333, NULL },
- { "Upsilon1", 620, NULL },
- { "bracerighttp", 494, NULL },
- { "xi", 493, NULL },
- { "period", 250, NULL },
- { "Alpha", 722, NULL },
- { "arrowright", 987, NULL },
- { "greater", 549, NULL },
- { "bracketlefttp", 384, NULL },
- { "kappa", 549, NULL },
- { "gradient", 713, NULL },
- { "integral", 274, NULL },
- { "arrowboth", 1042, NULL },
- { "Beta", 667, NULL }
-};
-
-static BuiltinFontWidth timesBoldWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 250, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 570, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 520, NULL },
- { "colon", 333, NULL },
- { "onehalf", 750, NULL },
- { "dollar", 500, NULL },
- { "ntilde", 556, NULL },
- { "minus", 570, NULL },
- { "yen", 500, NULL },
- { "space", 250, NULL },
- { "questiondown", 500, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 722, NULL },
- { "three", 500, NULL },
- { "numbersign", 500, NULL },
- { "A", 722, NULL },
- { "B", 667, NULL },
- { "C", 722, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 750, NULL },
- { "F", 611, NULL },
- { "G", 778, NULL },
- { "H", 778, NULL },
- { "I", 389, NULL },
- { "J", 500, NULL },
- { "K", 778, NULL },
- { "backslash", 278, NULL },
- { "L", 667, NULL },
- { "periodcentered", 250, NULL },
- { "M", 944, NULL },
- { "N", 722, NULL },
- { "O", 778, NULL },
- { "P", 611, NULL },
- { "Q", 778, NULL },
- { "R", 722, NULL },
- { "Aacute", 722, NULL },
- { "caron", 333, NULL },
- { "S", 556, NULL },
- { "T", 667, NULL },
- { "U", 722, NULL },
- { "agrave", 500, NULL },
- { "V", 722, NULL },
- { "W", 1000, NULL },
- { "X", 722, NULL },
- { "question", 500, NULL },
- { "equal", 570, NULL },
- { "Y", 722, NULL },
- { "Z", 667, NULL },
- { "four", 500, NULL },
- { "a", 500, NULL },
- { "b", 556, NULL },
- { "c", 444, NULL },
- { "d", 556, NULL },
- { "e", 444, NULL },
- { "f", 333, NULL },
- { "g", 500, NULL },
- { "bullet", 350, NULL },
- { "h", 556, NULL },
- { "i", 278, NULL },
- { "Oslash", 778, NULL },
- { "dagger", 500, NULL },
- { "j", 333, NULL },
- { "k", 556, NULL },
- { "l", 278, NULL },
- { "m", 833, NULL },
- { "n", 556, NULL },
- { "o", 500, NULL },
- { "ordfeminine", 300, NULL },
- { "ring", 333, NULL },
- { "p", 556, NULL },
- { "q", 556, NULL },
- { "r", 444, NULL },
- { "twosuperior", 300, NULL },
- { "aacute", 500, NULL },
- { "s", 389, NULL },
- { "OE", 1000, NULL },
- { "t", 333, NULL },
- { "divide", 570, NULL },
- { "u", 556, NULL },
- { "v", 500, NULL },
- { "w", 722, NULL },
- { "x", 500, NULL },
- { "y", 500, NULL },
- { "z", 444, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 555, NULL },
- { "mu", 556, NULL },
- { "Scaron", 556, NULL },
- { "Lslash", 667, NULL },
- { "semicolon", 333, NULL },
- { "oslash", 500, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 500, NULL },
- { "macron", 333, NULL },
- { "Otilde", 778, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 389, NULL },
- { "AE", 1000, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 500, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 278, NULL },
- { "eight", 500, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 500, NULL },
- { "oe", 722, NULL },
- { "ecircumflex", 444, NULL },
- { "copyright", 747, NULL },
- { "Adieresis", 722, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 500, NULL },
- { "Idieresis", 389, NULL },
- { "parenleft", 333, NULL },
- { "one", 500, NULL },
- { "ucircumflex", 556, NULL },
- { "Odieresis", 778, NULL },
- { "bracketleft", 333, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 333, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 722, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 500, NULL },
- { "egrave", 444, NULL },
- { "edieresis", 444, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 722, NULL },
- { "asterisk", 500, NULL },
- { "odieresis", 500, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 556, NULL },
- { "nine", 500, NULL },
- { "five", 500, NULL },
- { "udieresis", 556, NULL },
- { "Zcaron", 667, NULL },
- { "threequarters", 750, NULL },
- { "guillemotright", 500, NULL },
- { "ydieresis", 500, NULL },
- { "Ccedilla", 722, NULL },
- { "tilde", 333, NULL },
- { "at", 930, NULL },
- { "eacute", 444, NULL },
- { "underscore", 500, NULL },
- { "multiply", 570, NULL },
- { "zero", 500, NULL },
- { "eth", 500, NULL },
- { "Ograve", 778, NULL },
- { "uacute", 556, NULL },
- { "braceleft", 394, NULL },
- { "Thorn", 611, NULL },
- { "zcaron", 444, NULL },
- { "ccedilla", 444, NULL },
- { "Ocircumflex", 778, NULL },
- { "Oacute", 778, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 500, NULL },
- { "thorn", 556, NULL },
- { "degree", 400, NULL },
- { "registered", 747, NULL },
- { "Aring", 722, NULL },
- { "percent", 1000, NULL },
- { "six", 500, NULL },
- { "paragraph", 540, NULL },
- { "two", 500, NULL },
- { "Igrave", 389, NULL },
- { "ocircumflex", 500, NULL },
- { "oacute", 500, NULL },
- { "asciicircum", 581, NULL },
- { "aring", 500, NULL },
- { "grave", 333, NULL },
- { "bracketright", 333, NULL },
- { "Iacute", 389, NULL },
- { "ampersand", 833, NULL },
- { "igrave", 278, NULL },
- { "plus", 570, NULL },
- { "quotesinglbase", 333, NULL },
- { "Yacute", 722, NULL },
- { "threesuperior", 300, NULL },
- { "acute", 333, NULL },
- { "section", 500, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 500, NULL },
- { "florin", 500, NULL },
- { "yacute", 500, NULL },
- { "fi", 556, NULL },
- { "fl", 556, NULL },
- { "Acircumflex", 722, NULL },
- { "Icircumflex", 389, NULL },
- { "guillemotleft", 500, NULL },
- { "germandbls", 556, NULL },
- { "seven", 500, NULL },
- { "ordmasculine", 330, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 500, NULL },
- { "acircumflex", 500, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 394, NULL },
- { "quotedblright", 500, NULL },
- { "cent", 500, NULL },
- { "currency", 500, NULL },
- { "logicalnot", 570, NULL },
- { "Atilde", 722, NULL },
- { "breve", 333, NULL },
- { "bar", 220, NULL },
- { "fraction", 167, NULL },
- { "less", 570, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 333, NULL },
- { "period", 250, NULL },
- { "greater", 570, NULL },
- { "atilde", 500, NULL },
- { "brokenbar", 220, NULL },
- { "quoteleft", 333, NULL },
- { "onesuperior", 300, NULL }
-};
-
-static BuiltinFontWidth timesBoldItalicWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 250, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 570, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 570, NULL },
- { "colon", 333, NULL },
- { "onehalf", 750, NULL },
- { "dollar", 500, NULL },
- { "ntilde", 556, NULL },
- { "minus", 606, NULL },
- { "yen", 500, NULL },
- { "space", 250, NULL },
- { "questiondown", 500, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 667, NULL },
- { "three", 500, NULL },
- { "numbersign", 500, NULL },
- { "A", 667, NULL },
- { "B", 667, NULL },
- { "C", 667, NULL },
- { "D", 722, NULL },
- { "E", 667, NULL },
- { "onequarter", 750, NULL },
- { "F", 667, NULL },
- { "G", 722, NULL },
- { "H", 778, NULL },
- { "I", 389, NULL },
- { "J", 500, NULL },
- { "K", 667, NULL },
- { "backslash", 278, NULL },
- { "L", 611, NULL },
- { "periodcentered", 250, NULL },
- { "M", 889, NULL },
- { "N", 722, NULL },
- { "O", 722, NULL },
- { "P", 611, NULL },
- { "Q", 722, NULL },
- { "R", 667, NULL },
- { "Aacute", 667, NULL },
- { "caron", 333, NULL },
- { "S", 556, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 500, NULL },
- { "V", 667, NULL },
- { "W", 889, NULL },
- { "X", 667, NULL },
- { "question", 500, NULL },
- { "equal", 570, NULL },
- { "Y", 611, NULL },
- { "Z", 611, NULL },
- { "four", 500, NULL },
- { "a", 500, NULL },
- { "b", 500, NULL },
- { "c", 444, NULL },
- { "d", 500, NULL },
- { "e", 444, NULL },
- { "f", 333, NULL },
- { "g", 500, NULL },
- { "bullet", 350, NULL },
- { "h", 556, NULL },
- { "i", 278, NULL },
- { "Oslash", 722, NULL },
- { "dagger", 500, NULL },
- { "j", 278, NULL },
- { "k", 500, NULL },
- { "l", 278, NULL },
- { "m", 778, NULL },
- { "n", 556, NULL },
- { "o", 500, NULL },
- { "ordfeminine", 266, NULL },
- { "ring", 333, NULL },
- { "p", 500, NULL },
- { "q", 500, NULL },
- { "r", 389, NULL },
- { "twosuperior", 300, NULL },
- { "aacute", 500, NULL },
- { "s", 389, NULL },
- { "OE", 944, NULL },
- { "t", 278, NULL },
- { "divide", 570, NULL },
- { "u", 556, NULL },
- { "v", 444, NULL },
- { "w", 667, NULL },
- { "x", 500, NULL },
- { "y", 444, NULL },
- { "z", 389, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 555, NULL },
- { "mu", 576, NULL },
- { "Scaron", 556, NULL },
- { "Lslash", 611, NULL },
- { "semicolon", 333, NULL },
- { "oslash", 500, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 667, NULL },
- { "trademark", 1000, NULL },
- { "daggerdbl", 500, NULL },
- { "macron", 333, NULL },
- { "Otilde", 722, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 389, NULL },
- { "AE", 944, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 500, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 278, NULL },
- { "eight", 500, NULL },
- { "exclamdown", 389, NULL },
- { "endash", 500, NULL },
- { "oe", 722, NULL },
- { "ecircumflex", 444, NULL },
- { "copyright", 747, NULL },
- { "Adieresis", 667, NULL },
- { "Egrave", 667, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 667, NULL },
- { "otilde", 500, NULL },
- { "Idieresis", 389, NULL },
- { "parenleft", 333, NULL },
- { "one", 500, NULL },
- { "ucircumflex", 556, NULL },
- { "Odieresis", 722, NULL },
- { "bracketleft", 333, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 333, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 611, NULL },
- { "Eacute", 667, NULL },
- { "adieresis", 500, NULL },
- { "egrave", 444, NULL },
- { "edieresis", 444, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 722, NULL },
- { "asterisk", 500, NULL },
- { "odieresis", 500, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 556, NULL },
- { "nine", 500, NULL },
- { "five", 500, NULL },
- { "udieresis", 556, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 750, NULL },
- { "guillemotright", 500, NULL },
- { "ydieresis", 444, NULL },
- { "Ccedilla", 667, NULL },
- { "tilde", 333, NULL },
- { "at", 832, NULL },
- { "eacute", 444, NULL },
- { "underscore", 500, NULL },
- { "multiply", 570, NULL },
- { "zero", 500, NULL },
- { "eth", 500, NULL },
- { "Ograve", 722, NULL },
- { "uacute", 556, NULL },
- { "braceleft", 348, NULL },
- { "Thorn", 611, NULL },
- { "zcaron", 389, NULL },
- { "ccedilla", 444, NULL },
- { "Ocircumflex", 722, NULL },
- { "Oacute", 722, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 500, NULL },
- { "thorn", 500, NULL },
- { "degree", 400, NULL },
- { "registered", 747, NULL },
- { "Aring", 667, NULL },
- { "percent", 833, NULL },
- { "six", 500, NULL },
- { "paragraph", 500, NULL },
- { "two", 500, NULL },
- { "Igrave", 389, NULL },
- { "ocircumflex", 500, NULL },
- { "oacute", 500, NULL },
- { "asciicircum", 570, NULL },
- { "aring", 500, NULL },
- { "grave", 333, NULL },
- { "bracketright", 333, NULL },
- { "Iacute", 389, NULL },
- { "ampersand", 778, NULL },
- { "igrave", 278, NULL },
- { "plus", 570, NULL },
- { "quotesinglbase", 333, NULL },
- { "Yacute", 611, NULL },
- { "threesuperior", 300, NULL },
- { "acute", 333, NULL },
- { "section", 500, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 500, NULL },
- { "florin", 500, NULL },
- { "yacute", 444, NULL },
- { "fi", 556, NULL },
- { "fl", 556, NULL },
- { "Acircumflex", 667, NULL },
- { "Icircumflex", 389, NULL },
- { "guillemotleft", 500, NULL },
- { "germandbls", 500, NULL },
- { "seven", 500, NULL },
- { "ordmasculine", 300, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 500, NULL },
- { "acircumflex", 500, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 348, NULL },
- { "quotedblright", 500, NULL },
- { "cent", 500, NULL },
- { "currency", 500, NULL },
- { "logicalnot", 606, NULL },
- { "Atilde", 667, NULL },
- { "breve", 333, NULL },
- { "bar", 220, NULL },
- { "fraction", 167, NULL },
- { "less", 570, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 389, NULL },
- { "period", 250, NULL },
- { "greater", 570, NULL },
- { "atilde", 500, NULL },
- { "brokenbar", 220, NULL },
- { "quoteleft", 333, NULL },
- { "onesuperior", 300, NULL }
-};
-
-static BuiltinFontWidth timesItalicWidthsTab[] = {
- { "Ntilde", 667, NULL },
- { "comma", 250, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 675, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 541, NULL },
- { "colon", 333, NULL },
- { "onehalf", 750, NULL },
- { "dollar", 500, NULL },
- { "ntilde", 500, NULL },
- { "minus", 675, NULL },
- { "yen", 500, NULL },
- { "space", 250, NULL },
- { "questiondown", 500, NULL },
- { "emdash", 889, NULL },
- { "Agrave", 611, NULL },
- { "three", 500, NULL },
- { "numbersign", 500, NULL },
- { "A", 611, NULL },
- { "B", 611, NULL },
- { "C", 667, NULL },
- { "D", 722, NULL },
- { "E", 611, NULL },
- { "onequarter", 750, NULL },
- { "F", 611, NULL },
- { "G", 722, NULL },
- { "H", 722, NULL },
- { "I", 333, NULL },
- { "J", 444, NULL },
- { "K", 667, NULL },
- { "backslash", 278, NULL },
- { "L", 556, NULL },
- { "periodcentered", 250, NULL },
- { "M", 833, NULL },
- { "N", 667, NULL },
- { "O", 722, NULL },
- { "P", 611, NULL },
- { "Q", 722, NULL },
- { "R", 611, NULL },
- { "Aacute", 611, NULL },
- { "caron", 333, NULL },
- { "S", 500, NULL },
- { "T", 556, NULL },
- { "U", 722, NULL },
- { "agrave", 500, NULL },
- { "V", 611, NULL },
- { "W", 833, NULL },
- { "X", 611, NULL },
- { "question", 500, NULL },
- { "equal", 675, NULL },
- { "Y", 556, NULL },
- { "Z", 556, NULL },
- { "four", 500, NULL },
- { "a", 500, NULL },
- { "b", 500, NULL },
- { "c", 444, NULL },
- { "d", 500, NULL },
- { "e", 444, NULL },
- { "f", 278, NULL },
- { "g", 500, NULL },
- { "bullet", 350, NULL },
- { "h", 500, NULL },
- { "i", 278, NULL },
- { "Oslash", 722, NULL },
- { "dagger", 500, NULL },
- { "j", 278, NULL },
- { "k", 444, NULL },
- { "l", 278, NULL },
- { "m", 722, NULL },
- { "n", 500, NULL },
- { "o", 500, NULL },
- { "ordfeminine", 276, NULL },
- { "ring", 333, NULL },
- { "p", 500, NULL },
- { "q", 500, NULL },
- { "r", 389, NULL },
- { "twosuperior", 300, NULL },
- { "aacute", 500, NULL },
- { "s", 389, NULL },
- { "OE", 944, NULL },
- { "t", 278, NULL },
- { "divide", 675, NULL },
- { "u", 500, NULL },
- { "v", 444, NULL },
- { "w", 667, NULL },
- { "x", 444, NULL },
- { "y", 444, NULL },
- { "z", 389, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 420, NULL },
- { "mu", 500, NULL },
- { "Scaron", 500, NULL },
- { "Lslash", 556, NULL },
- { "semicolon", 333, NULL },
- { "oslash", 500, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 611, NULL },
- { "trademark", 980, NULL },
- { "daggerdbl", 500, NULL },
- { "macron", 333, NULL },
- { "Otilde", 722, NULL },
- { "ellipsis", 889, NULL },
- { "scaron", 389, NULL },
- { "AE", 889, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 556, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 214, NULL },
- { "eight", 500, NULL },
- { "exclamdown", 389, NULL },
- { "endash", 500, NULL },
- { "oe", 667, NULL },
- { "ecircumflex", 444, NULL },
- { "copyright", 760, NULL },
- { "Adieresis", 611, NULL },
- { "Egrave", 611, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 611, NULL },
- { "otilde", 500, NULL },
- { "Idieresis", 333, NULL },
- { "parenleft", 333, NULL },
- { "one", 500, NULL },
- { "ucircumflex", 500, NULL },
- { "Odieresis", 722, NULL },
- { "bracketleft", 389, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 333, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 556, NULL },
- { "Eacute", 611, NULL },
- { "adieresis", 500, NULL },
- { "egrave", 444, NULL },
- { "edieresis", 444, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 667, NULL },
- { "asterisk", 500, NULL },
- { "odieresis", 500, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 500, NULL },
- { "nine", 500, NULL },
- { "five", 500, NULL },
- { "udieresis", 500, NULL },
- { "Zcaron", 556, NULL },
- { "threequarters", 750, NULL },
- { "guillemotright", 500, NULL },
- { "ydieresis", 444, NULL },
- { "Ccedilla", 667, NULL },
- { "tilde", 333, NULL },
- { "at", 920, NULL },
- { "eacute", 444, NULL },
- { "underscore", 500, NULL },
- { "multiply", 675, NULL },
- { "zero", 500, NULL },
- { "eth", 500, NULL },
- { "Ograve", 722, NULL },
- { "uacute", 500, NULL },
- { "braceleft", 400, NULL },
- { "Thorn", 611, NULL },
- { "zcaron", 389, NULL },
- { "ccedilla", 444, NULL },
- { "Ocircumflex", 722, NULL },
- { "Oacute", 722, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 500, NULL },
- { "thorn", 500, NULL },
- { "degree", 400, NULL },
- { "registered", 760, NULL },
- { "Aring", 611, NULL },
- { "percent", 833, NULL },
- { "six", 500, NULL },
- { "paragraph", 523, NULL },
- { "two", 500, NULL },
- { "Igrave", 333, NULL },
- { "ocircumflex", 500, NULL },
- { "oacute", 500, NULL },
- { "asciicircum", 422, NULL },
- { "aring", 500, NULL },
- { "grave", 333, NULL },
- { "bracketright", 389, NULL },
- { "Iacute", 333, NULL },
- { "ampersand", 778, NULL },
- { "igrave", 278, NULL },
- { "plus", 675, NULL },
- { "quotesinglbase", 333, NULL },
- { "Yacute", 556, NULL },
- { "threesuperior", 300, NULL },
- { "acute", 333, NULL },
- { "section", 500, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 556, NULL },
- { "florin", 500, NULL },
- { "yacute", 444, NULL },
- { "fi", 500, NULL },
- { "fl", 500, NULL },
- { "Acircumflex", 611, NULL },
- { "Icircumflex", 333, NULL },
- { "guillemotleft", 500, NULL },
- { "germandbls", 500, NULL },
- { "seven", 500, NULL },
- { "ordmasculine", 310, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 500, NULL },
- { "acircumflex", 500, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 400, NULL },
- { "quotedblright", 556, NULL },
- { "cent", 500, NULL },
- { "currency", 500, NULL },
- { "logicalnot", 675, NULL },
- { "Atilde", 611, NULL },
- { "breve", 333, NULL },
- { "bar", 275, NULL },
- { "fraction", 167, NULL },
- { "less", 675, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 333, NULL },
- { "period", 250, NULL },
- { "greater", 675, NULL },
- { "atilde", 500, NULL },
- { "brokenbar", 275, NULL },
- { "quoteleft", 333, NULL },
- { "onesuperior", 300, NULL }
-};
-
-static BuiltinFontWidth timesRomanWidthsTab[] = {
- { "Ntilde", 722, NULL },
- { "comma", 250, NULL },
- { "cedilla", 333, NULL },
- { "plusminus", 564, NULL },
- { "circumflex", 333, NULL },
- { "dotaccent", 333, NULL },
- { "asciitilde", 541, NULL },
- { "colon", 278, NULL },
- { "onehalf", 750, NULL },
- { "dollar", 500, NULL },
- { "ntilde", 500, NULL },
- { "minus", 564, NULL },
- { "yen", 500, NULL },
- { "space", 250, NULL },
- { "questiondown", 444, NULL },
- { "emdash", 1000, NULL },
- { "Agrave", 722, NULL },
- { "three", 500, NULL },
- { "numbersign", 500, NULL },
- { "A", 722, NULL },
- { "B", 667, NULL },
- { "C", 667, NULL },
- { "D", 722, NULL },
- { "E", 611, NULL },
- { "onequarter", 750, NULL },
- { "F", 556, NULL },
- { "G", 722, NULL },
- { "H", 722, NULL },
- { "I", 333, NULL },
- { "J", 389, NULL },
- { "K", 722, NULL },
- { "backslash", 278, NULL },
- { "L", 611, NULL },
- { "periodcentered", 250, NULL },
- { "M", 889, NULL },
- { "N", 722, NULL },
- { "O", 722, NULL },
- { "P", 556, NULL },
- { "Q", 722, NULL },
- { "R", 667, NULL },
- { "Aacute", 722, NULL },
- { "caron", 333, NULL },
- { "S", 556, NULL },
- { "T", 611, NULL },
- { "U", 722, NULL },
- { "agrave", 444, NULL },
- { "V", 722, NULL },
- { "W", 944, NULL },
- { "X", 722, NULL },
- { "question", 444, NULL },
- { "equal", 564, NULL },
- { "Y", 722, NULL },
- { "Z", 611, NULL },
- { "four", 500, NULL },
- { "a", 444, NULL },
- { "b", 500, NULL },
- { "c", 444, NULL },
- { "d", 500, NULL },
- { "e", 444, NULL },
- { "f", 333, NULL },
- { "g", 500, NULL },
- { "bullet", 350, NULL },
- { "h", 500, NULL },
- { "i", 278, NULL },
- { "Oslash", 722, NULL },
- { "dagger", 500, NULL },
- { "j", 278, NULL },
- { "k", 500, NULL },
- { "l", 278, NULL },
- { "m", 778, NULL },
- { "n", 500, NULL },
- { "o", 500, NULL },
- { "ordfeminine", 276, NULL },
- { "ring", 333, NULL },
- { "p", 500, NULL },
- { "q", 500, NULL },
- { "r", 333, NULL },
- { "twosuperior", 300, NULL },
- { "aacute", 444, NULL },
- { "s", 389, NULL },
- { "OE", 889, NULL },
- { "t", 278, NULL },
- { "divide", 564, NULL },
- { "u", 500, NULL },
- { "v", 500, NULL },
- { "w", 722, NULL },
- { "x", 500, NULL },
- { "y", 500, NULL },
- { "z", 444, NULL },
- { "hungarumlaut", 333, NULL },
- { "quotedbl", 408, NULL },
- { "mu", 500, NULL },
- { "Scaron", 556, NULL },
- { "Lslash", 611, NULL },
- { "semicolon", 278, NULL },
- { "oslash", 500, NULL },
- { "parenright", 333, NULL },
- { "Ecircumflex", 611, NULL },
- { "trademark", 980, NULL },
- { "daggerdbl", 500, NULL },
- { "macron", 333, NULL },
- { "Otilde", 722, NULL },
- { "ellipsis", 1000, NULL },
- { "scaron", 389, NULL },
- { "AE", 889, NULL },
- { "Ucircumflex", 722, NULL },
- { "lslash", 278, NULL },
- { "quotedblleft", 444, NULL },
- { "guilsinglright", 333, NULL },
- { "hyphen", 333, NULL },
- { "quotesingle", 180, NULL },
- { "eight", 500, NULL },
- { "exclamdown", 333, NULL },
- { "endash", 500, NULL },
- { "oe", 722, NULL },
- { "ecircumflex", 444, NULL },
- { "copyright", 760, NULL },
- { "Adieresis", 722, NULL },
- { "Egrave", 611, NULL },
- { "slash", 278, NULL },
- { "Edieresis", 611, NULL },
- { "otilde", 500, NULL },
- { "Idieresis", 333, NULL },
- { "parenleft", 333, NULL },
- { "one", 500, NULL },
- { "ucircumflex", 500, NULL },
- { "Odieresis", 722, NULL },
- { "bracketleft", 333, NULL },
- { "Ugrave", 722, NULL },
- { "quoteright", 333, NULL },
- { "Udieresis", 722, NULL },
- { "perthousand", 1000, NULL },
- { "Ydieresis", 722, NULL },
- { "Eacute", 611, NULL },
- { "adieresis", 444, NULL },
- { "egrave", 444, NULL },
- { "edieresis", 444, NULL },
- { "idieresis", 278, NULL },
- { "Eth", 722, NULL },
- { "ae", 667, NULL },
- { "asterisk", 500, NULL },
- { "odieresis", 500, NULL },
- { "Uacute", 722, NULL },
- { "ugrave", 500, NULL },
- { "nine", 500, NULL },
- { "five", 500, NULL },
- { "udieresis", 500, NULL },
- { "Zcaron", 611, NULL },
- { "threequarters", 750, NULL },
- { "guillemotright", 500, NULL },
- { "ydieresis", 500, NULL },
- { "Ccedilla", 667, NULL },
- { "tilde", 333, NULL },
- { "at", 921, NULL },
- { "eacute", 444, NULL },
- { "underscore", 500, NULL },
- { "multiply", 564, NULL },
- { "zero", 500, NULL },
- { "eth", 500, NULL },
- { "Ograve", 722, NULL },
- { "uacute", 500, NULL },
- { "braceleft", 480, NULL },
- { "Thorn", 556, NULL },
- { "zcaron", 444, NULL },
- { "ccedilla", 444, NULL },
- { "Ocircumflex", 722, NULL },
- { "Oacute", 722, NULL },
- { "ogonek", 333, NULL },
- { "ograve", 500, NULL },
- { "thorn", 500, NULL },
- { "degree", 400, NULL },
- { "registered", 760, NULL },
- { "Aring", 722, NULL },
- { "percent", 833, NULL },
- { "six", 500, NULL },
- { "paragraph", 453, NULL },
- { "two", 500, NULL },
- { "Igrave", 333, NULL },
- { "ocircumflex", 500, NULL },
- { "oacute", 500, NULL },
- { "asciicircum", 469, NULL },
- { "aring", 444, NULL },
- { "grave", 333, NULL },
- { "bracketright", 333, NULL },
- { "Iacute", 333, NULL },
- { "ampersand", 778, NULL },
- { "igrave", 278, NULL },
- { "plus", 564, NULL },
- { "quotesinglbase", 333, NULL },
- { "Yacute", 722, NULL },
- { "threesuperior", 300, NULL },
- { "acute", 333, NULL },
- { "section", 500, NULL },
- { "dieresis", 333, NULL },
- { "iacute", 278, NULL },
- { "quotedblbase", 444, NULL },
- { "florin", 500, NULL },
- { "yacute", 500, NULL },
- { "fi", 556, NULL },
- { "fl", 556, NULL },
- { "Acircumflex", 722, NULL },
- { "Icircumflex", 333, NULL },
- { "guillemotleft", 500, NULL },
- { "germandbls", 500, NULL },
- { "seven", 500, NULL },
- { "ordmasculine", 310, NULL },
- { "dotlessi", 278, NULL },
- { "sterling", 500, NULL },
- { "acircumflex", 444, NULL },
- { "icircumflex", 278, NULL },
- { "braceright", 480, NULL },
- { "quotedblright", 444, NULL },
- { "cent", 500, NULL },
- { "currency", 500, NULL },
- { "logicalnot", 564, NULL },
- { "Atilde", 722, NULL },
- { "breve", 333, NULL },
- { "bar", 200, NULL },
- { "fraction", 167, NULL },
- { "less", 564, NULL },
- { "guilsinglleft", 333, NULL },
- { "exclam", 333, NULL },
- { "period", 250, NULL },
- { "greater", 564, NULL },
- { "atilde", 444, NULL },
- { "brokenbar", 200, NULL },
- { "quoteleft", 333, NULL },
- { "onesuperior", 300, NULL }
-};
-
-static BuiltinFontWidth zapfDingbatsWidthsTab[] = {
- { "a81", 438, NULL },
- { "a82", 138, NULL },
- { "a83", 277, NULL },
- { "a84", 415, NULL },
- { "a85", 509, NULL },
- { "a86", 410, NULL },
- { "a87", 234, NULL },
- { "a88", 234, NULL },
- { "a89", 390, NULL },
- { "a140", 788, NULL },
- { "a141", 788, NULL },
- { "a142", 788, NULL },
- { "a143", 788, NULL },
- { "a144", 788, NULL },
- { "a145", 788, NULL },
- { "a146", 788, NULL },
- { "a147", 788, NULL },
- { "a148", 788, NULL },
- { "a149", 788, NULL },
- { "a90", 390, NULL },
- { "a91", 276, NULL },
- { "a92", 276, NULL },
- { "space", 278, NULL },
- { "a93", 317, NULL },
- { "a94", 317, NULL },
- { "a95", 334, NULL },
- { "a96", 334, NULL },
- { "a97", 392, NULL },
- { "a98", 392, NULL },
- { "a99", 668, NULL },
- { "a150", 788, NULL },
- { "a151", 788, NULL },
- { "a152", 788, NULL },
- { "a153", 788, NULL },
- { "a154", 788, NULL },
- { "a155", 788, NULL },
- { "a156", 788, NULL },
- { "a157", 788, NULL },
- { "a158", 788, NULL },
- { "a159", 788, NULL },
- { "a160", 894, NULL },
- { "a161", 838, NULL },
- { "a162", 924, NULL },
- { "a163", 1016, NULL },
- { "a164", 458, NULL },
- { "a165", 924, NULL },
- { "a166", 918, NULL },
- { "a167", 927, NULL },
- { "a168", 928, NULL },
- { "a169", 928, NULL },
- { "a170", 834, NULL },
- { "a171", 873, NULL },
- { "a172", 828, NULL },
- { "a173", 924, NULL },
- { "a174", 917, NULL },
- { "a175", 930, NULL },
- { "a176", 931, NULL },
- { "a177", 463, NULL },
- { "a178", 883, NULL },
- { "a179", 836, NULL },
- { "a180", 867, NULL },
- { "a181", 696, NULL },
- { "a182", 874, NULL },
- { "a183", 760, NULL },
- { "a184", 946, NULL },
- { "a185", 865, NULL },
- { "a186", 967, NULL },
- { "a187", 831, NULL },
- { "a188", 873, NULL },
- { "a189", 927, NULL },
- { "a1", 974, NULL },
- { "a2", 961, NULL },
- { "a3", 980, NULL },
- { "a4", 719, NULL },
- { "a5", 789, NULL },
- { "a6", 494, NULL },
- { "a7", 552, NULL },
- { "a8", 537, NULL },
- { "a9", 577, NULL },
- { "a190", 970, NULL },
- { "a191", 918, NULL },
- { "a192", 748, NULL },
- { "a193", 836, NULL },
- { "a194", 771, NULL },
- { "a195", 888, NULL },
- { "a196", 748, NULL },
- { "a197", 771, NULL },
- { "a198", 888, NULL },
- { "a199", 867, NULL },
- { "a10", 692, NULL },
- { "a11", 960, NULL },
- { "a12", 939, NULL },
- { "a13", 549, NULL },
- { "a14", 855, NULL },
- { "a15", 911, NULL },
- { "a16", 933, NULL },
- { "a17", 945, NULL },
- { "a18", 974, NULL },
- { "a19", 755, NULL },
- { "a20", 846, NULL },
- { "a21", 762, NULL },
- { "a22", 761, NULL },
- { "a23", 571, NULL },
- { "a24", 677, NULL },
- { "a25", 763, NULL },
- { "a26", 760, NULL },
- { "a27", 759, NULL },
- { "a28", 754, NULL },
- { "a29", 786, NULL },
- { "a30", 788, NULL },
- { "a31", 788, NULL },
- { "a32", 790, NULL },
- { "a33", 793, NULL },
- { "a34", 794, NULL },
- { "a35", 816, NULL },
- { "a36", 823, NULL },
- { "a37", 789, NULL },
- { "a38", 841, NULL },
- { "a39", 823, NULL },
- { "a40", 833, NULL },
- { "a41", 816, NULL },
- { "a42", 831, NULL },
- { "a43", 923, NULL },
- { "a44", 744, NULL },
- { "a45", 723, NULL },
- { "a46", 749, NULL },
- { "a47", 790, NULL },
- { "a48", 792, NULL },
- { "a49", 695, NULL },
- { "a100", 668, NULL },
- { "a101", 732, NULL },
- { "a102", 544, NULL },
- { "a103", 544, NULL },
- { "a104", 910, NULL },
- { "a105", 911, NULL },
- { "a106", 667, NULL },
- { "a107", 760, NULL },
- { "a108", 760, NULL },
- { "a109", 626, NULL },
- { "a50", 776, NULL },
- { "a51", 768, NULL },
- { "a52", 792, NULL },
- { "a53", 759, NULL },
- { "a54", 707, NULL },
- { "a55", 708, NULL },
- { "a56", 682, NULL },
- { "a57", 701, NULL },
- { "a58", 826, NULL },
- { "a59", 815, NULL },
- { "a110", 694, NULL },
- { "a111", 595, NULL },
- { "a112", 776, NULL },
- { "a117", 690, NULL },
- { "a118", 791, NULL },
- { "a119", 790, NULL },
- { "a60", 789, NULL },
- { "a61", 789, NULL },
- { "a62", 707, NULL },
- { "a63", 687, NULL },
- { "a64", 696, NULL },
- { "a65", 689, NULL },
- { "a66", 786, NULL },
- { "a67", 787, NULL },
- { "a68", 713, NULL },
- { "a69", 791, NULL },
- { "a200", 696, NULL },
- { "a201", 874, NULL },
- { "a120", 788, NULL },
- { "a121", 788, NULL },
- { "a202", 974, NULL },
- { "a122", 788, NULL },
- { "a203", 762, NULL },
- { "a123", 788, NULL },
- { "a204", 759, NULL },
- { "a205", 509, NULL },
- { "a124", 788, NULL },
- { "a206", 410, NULL },
- { "a125", 788, NULL },
- { "a126", 788, NULL },
- { "a127", 788, NULL },
- { "a128", 788, NULL },
- { "a129", 788, NULL },
- { "a70", 785, NULL },
- { "a71", 791, NULL },
- { "a72", 873, NULL },
- { "a73", 761, NULL },
- { "a74", 762, NULL },
- { "a75", 759, NULL },
- { "a76", 892, NULL },
- { "a77", 892, NULL },
- { "a78", 788, NULL },
- { "a79", 784, NULL },
- { "a130", 788, NULL },
- { "a131", 788, NULL },
- { "a132", 788, NULL },
- { "a133", 788, NULL },
- { "a134", 788, NULL },
- { "a135", 788, NULL },
- { "a136", 788, NULL },
- { "a137", 788, NULL },
- { "a138", 788, NULL },
- { "a139", 788, NULL }
-};
-
-BuiltinFont builtinFonts[] = {
- { "Courier", standardEncoding, 624, -207, { -40, -290, 640, 795}, NULL },
- { "Courier-Bold", standardEncoding, 674, -257, {-100, -350, 700, 855}, NULL },
- { "Courier-BoldOblique", standardEncoding, 674, -257, {-145, -350, 817, 855}, NULL },
- { "Courier-Oblique", standardEncoding, 624, -207, { -85, -290, 759, 795}, NULL },
- { "Helvetica", standardEncoding, 729, -219, {-174, -220, 1001, 944}, NULL },
- { "Helvetica-Bold", standardEncoding, 729, -219, {-173, -221, 1003, 936}, NULL },
- { "Helvetica-BoldOblique", standardEncoding, 729, -219, {-177, -221, 1107, 936}, NULL },
- { "Helvetica-Oblique", standardEncoding, 729, -219, {-178, -220, 1108, 944}, NULL },
- { "Symbol", symbolEncoding, 1010, -293, {-180, -293, 1090, 1010}, NULL },
- { "Times-Bold", standardEncoding, 670, -210, {-172, -256, 1008, 965}, NULL },
- { "Times-BoldItalic", standardEncoding, 682, -203, {-168, -232, 1014, 894}, NULL },
- { "Times-Italic", standardEncoding, 684, -206, {-176, -252, 990, 930}, NULL },
- { "Times-Roman", standardEncoding, 682, -217, {-170, -223, 1024, 896}, NULL },
- { "ZapfDingbats", zapfDingbatsEncoding, 820, -143, { -1, -143, 981, 820}, NULL }
-};
-
-BuiltinFont *builtinFontSubst[] = {
- &builtinFonts[0],
- &builtinFonts[3],
- &builtinFonts[1],
- &builtinFonts[2],
- &builtinFonts[4],
- &builtinFonts[7],
- &builtinFonts[5],
- &builtinFonts[6],
- &builtinFonts[12],
- &builtinFonts[11],
- &builtinFonts[9],
- &builtinFonts[10]
-};
-
-void initBuiltinFontTables() {
- builtinFonts[0].widths = new BuiltinFontWidths(courierWidthsTab, 260);
- builtinFonts[1].widths = new BuiltinFontWidths(courierBoldWidthsTab, 260);
- builtinFonts[2].widths = new BuiltinFontWidths(courierBoldObliqueWidthsTab, 260);
- builtinFonts[3].widths = new BuiltinFontWidths(courierObliqueWidthsTab, 260);
- builtinFonts[4].widths = new BuiltinFontWidths(helveticaWidthsTab, 228);
- builtinFonts[5].widths = new BuiltinFontWidths(helveticaBoldWidthsTab, 229);
- builtinFonts[6].widths = new BuiltinFontWidths(helveticaBoldObliqueWidthsTab, 228);
- builtinFonts[7].widths = new BuiltinFontWidths(helveticaObliqueWidthsTab, 228);
- builtinFonts[8].widths = new BuiltinFontWidths(symbolWidthsTab, 189);
- builtinFonts[9].widths = new BuiltinFontWidths(timesBoldWidthsTab, 228);
- builtinFonts[10].widths = new BuiltinFontWidths(timesBoldItalicWidthsTab, 228);
- builtinFonts[11].widths = new BuiltinFontWidths(timesItalicWidthsTab, 228);
- builtinFonts[12].widths = new BuiltinFontWidths(timesRomanWidthsTab, 228);
- builtinFonts[13].widths = new BuiltinFontWidths(zapfDingbatsWidthsTab, 202);
-}
-
-void freeBuiltinFontTables() {
- int i;
-
- for (i = 0; i < 14; ++i) {
- delete builtinFonts[i].widths;
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cpp b/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cpp
new file mode 100644
index 000000000..3120d0852
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/BuiltinFontTables.cpp
@@ -0,0 +1,3367 @@
+//========================================================================
+//
+// BuiltinFontTables.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdlib.h>
+#include "FontEncodingTables.h"
+#include "BuiltinFontTables.h"
+
+static BuiltinFontWidth courierWidthsTab[] = {
+ { "Ntilde", 600, NULL },
+ { "comma", 600, NULL },
+ { "cedilla", 600, NULL },
+ { "plusminus", 600, NULL },
+ { "arrowup", 600, NULL },
+ { "circumflex", 600, NULL },
+ { "dotaccent", 600, NULL },
+ { "LL", 600, NULL },
+ { "asciitilde", 600, NULL },
+ { "colon", 600, NULL },
+ { "onehalf", 600, NULL },
+ { "dollar", 600, NULL },
+ { "ntilde", 600, NULL },
+ { "left", 600, NULL },
+ { "minus", 600, NULL },
+ { "yen", 600, NULL },
+ { "space", 600, NULL },
+ { "questiondown", 600, NULL },
+ { "emdash", 600, NULL },
+ { "Agrave", 600, NULL },
+ { "three", 600, NULL },
+ { "numbersign", 600, NULL },
+ { "A", 600, NULL },
+ { "B", 600, NULL },
+ { "C", 600, NULL },
+ { "D", 600, NULL },
+ { "E", 600, NULL },
+ { "onequarter", 600, NULL },
+ { "F", 600, NULL },
+ { "G", 600, NULL },
+ { "H", 600, NULL },
+ { "I", 600, NULL },
+ { "J", 600, NULL },
+ { "K", 600, NULL },
+ { "L", 600, NULL },
+ { "backslash", 600, NULL },
+ { "periodcentered", 600, NULL },
+ { "M", 600, NULL },
+ { "N", 600, NULL },
+ { "O", 600, NULL },
+ { "P", 600, NULL },
+ { "Q", 600, NULL },
+ { "R", 600, NULL },
+ { "Aacute", 600, NULL },
+ { "caron", 600, NULL },
+ { "S", 600, NULL },
+ { "T", 600, NULL },
+ { "U", 600, NULL },
+ { "agrave", 600, NULL },
+ { "V", 600, NULL },
+ { "tab", 600, NULL },
+ { "W", 600, NULL },
+ { "ll", 600, NULL },
+ { "equal", 600, NULL },
+ { "question", 600, NULL },
+ { "X", 600, NULL },
+ { "Y", 600, NULL },
+ { "Z", 600, NULL },
+ { "four", 600, NULL },
+ { "a", 600, NULL },
+ { "b", 600, NULL },
+ { "c", 600, NULL },
+ { "d", 600, NULL },
+ { "e", 600, NULL },
+ { "f", 600, NULL },
+ { "g", 600, NULL },
+ { "bullet", 600, NULL },
+ { "h", 600, NULL },
+ { "i", 600, NULL },
+ { "Oslash", 600, NULL },
+ { "dagger", 600, NULL },
+ { "j", 600, NULL },
+ { "k", 600, NULL },
+ { "l", 600, NULL },
+ { "m", 600, NULL },
+ { "n", 600, NULL },
+ { "o", 600, NULL },
+ { "ordfeminine", 600, NULL },
+ { "ring", 600, NULL },
+ { "p", 600, NULL },
+ { "q", 600, NULL },
+ { "r", 600, NULL },
+ { "twosuperior", 600, NULL },
+ { "largebullet", 600, NULL },
+ { "aacute", 600, NULL },
+ { "s", 600, NULL },
+ { "OE", 600, NULL },
+ { "t", 600, NULL },
+ { "divide", 600, NULL },
+ { "u", 600, NULL },
+ { "v", 600, NULL },
+ { "w", 600, NULL },
+ { "x", 600, NULL },
+ { "y", 600, NULL },
+ { "z", 600, NULL },
+ { "hungarumlaut", 600, NULL },
+ { "quotedbl", 600, NULL },
+ { "mu", 600, NULL },
+ { "Scaron", 600, NULL },
+ { "Lslash", 600, NULL },
+ { "semicolon", 600, NULL },
+ { "oslash", 600, NULL },
+ { "parenright", 600, NULL },
+ { "Ecircumflex", 600, NULL },
+ { "trademark", 600, NULL },
+ { "daggerdbl", 600, NULL },
+ { "macron", 600, NULL },
+ { "Otilde", 600, NULL },
+ { "ellipsis", 600, NULL },
+ { "scaron", 600, NULL },
+ { "AE", 600, NULL },
+ { "Ucircumflex", 600, NULL },
+ { "lslash", 600, NULL },
+ { "lira", 600, NULL },
+ { "quotedblleft", 600, NULL },
+ { "hyphen", 600, NULL },
+ { "guilsinglright", 600, NULL },
+ { "quotesingle", 600, NULL },
+ { "eight", 600, NULL },
+ { "exclamdown", 600, NULL },
+ { "endash", 600, NULL },
+ { "oe", 600, NULL },
+ { "ecircumflex", 600, NULL },
+ { "copyright", 600, NULL },
+ { "Adieresis", 600, NULL },
+ { "Egrave", 600, NULL },
+ { "slash", 600, NULL },
+ { "Edieresis", 600, NULL },
+ { "otilde", 600, NULL },
+ { "Idieresis", 600, NULL },
+ { "parenleft", 600, NULL },
+ { "one", 600, NULL },
+ { "ucircumflex", 600, NULL },
+ { "Odieresis", 600, NULL },
+ { "bracketleft", 600, NULL },
+ { "Ugrave", 600, NULL },
+ { "quoteright", 600, NULL },
+ { "Udieresis", 600, NULL },
+ { "perthousand", 600, NULL },
+ { "Ydieresis", 600, NULL },
+ { "Eacute", 600, NULL },
+ { "adieresis", 600, NULL },
+ { "egrave", 600, NULL },
+ { "edieresis", 600, NULL },
+ { "idieresis", 600, NULL },
+ { "Eth", 600, NULL },
+ { "ae", 600, NULL },
+ { "asterisk", 600, NULL },
+ { "odieresis", 600, NULL },
+ { "Uacute", 600, NULL },
+ { "ugrave", 600, NULL },
+ { "five", 600, NULL },
+ { "nine", 600, NULL },
+ { "udieresis", 600, NULL },
+ { "Zcaron", 600, NULL },
+ { "threequarters", 600, NULL },
+ { "guillemotright", 600, NULL },
+ { "ydieresis", 600, NULL },
+ { "Ccedilla", 600, NULL },
+ { "tilde", 600, NULL },
+ { "at", 600, NULL },
+ { "eacute", 600, NULL },
+ { "Gcaron", 600, NULL },
+ { "underscore", 600, NULL },
+ { "zero", 600, NULL },
+ { "multiply", 600, NULL },
+ { "Scedilla", 600, NULL },
+ { "eth", 600, NULL },
+ { "Ograve", 600, NULL },
+ { "uacute", 600, NULL },
+ { "braceleft", 600, NULL },
+ { "Thorn", 600, NULL },
+ { "zcaron", 600, NULL },
+ { "ccedilla", 600, NULL },
+ { "gcaron", 600, NULL },
+ { "Oacute", 600, NULL },
+ { "Ocircumflex", 600, NULL },
+ { "scedilla", 600, NULL },
+ { "ogonek", 600, NULL },
+ { "arrowdown", 600, NULL },
+ { "ograve", 600, NULL },
+ { "thorn", 600, NULL },
+ { "degree", 600, NULL },
+ { "registered", 600, NULL },
+ { "percent", 600, NULL },
+ { "Aring", 600, NULL },
+ { "six", 600, NULL },
+ { "paragraph", 600, NULL },
+ { "two", 600, NULL },
+ { "Igrave", 600, NULL },
+ { "oacute", 600, NULL },
+ { "ocircumflex", 600, NULL },
+ { "asciicircum", 600, NULL },
+ { "aring", 600, NULL },
+ { "square", 600, NULL },
+ { "grave", 600, NULL },
+ { "bracketright", 600, NULL },
+ { "ampersand", 600, NULL },
+ { "Iacute", 600, NULL },
+ { "igrave", 600, NULL },
+ { "return", 600, NULL },
+ { "plus", 600, NULL },
+ { "quotesinglbase", 600, NULL },
+ { "Yacute", 600, NULL },
+ { "threesuperior", 600, NULL },
+ { "acute", 600, NULL },
+ { "notegraphic", 600, NULL },
+ { "section", 600, NULL },
+ { "arrowleft", 600, NULL },
+ { "dieresis", 600, NULL },
+ { "quotedblbase", 600, NULL },
+ { "iacute", 600, NULL },
+ { "up", 600, NULL },
+ { "florin", 600, NULL },
+ { "yacute", 600, NULL },
+ { "fi", 600, NULL },
+ { "fl", 600, NULL },
+ { "Acircumflex", 600, NULL },
+ { "Icircumflex", 600, NULL },
+ { "guillemotleft", 600, NULL },
+ { "germandbls", 600, NULL },
+ { "seven", 600, NULL },
+ { "indent", 600, NULL },
+ { "prescription", 600, NULL },
+ { "dectab", 600, NULL },
+ { "ordmasculine", 600, NULL },
+ { "dotlessi", 600, NULL },
+ { "sterling", 600, NULL },
+ { "IJ", 600, NULL },
+ { "acircumflex", 600, NULL },
+ { "overscore", 600, NULL },
+ { "braceright", 600, NULL },
+ { "icircumflex", 600, NULL },
+ { "graybox", 600, NULL },
+ { "quotedblright", 600, NULL },
+ { "center", 600, NULL },
+ { "stop", 600, NULL },
+ { "cent", 600, NULL },
+ { "currency", 600, NULL },
+ { "logicalnot", 600, NULL },
+ { "Idot", 600, NULL },
+ { "merge", 600, NULL },
+ { "Atilde", 600, NULL },
+ { "breve", 600, NULL },
+ { "bar", 600, NULL },
+ { "fraction", 600, NULL },
+ { "less", 600, NULL },
+ { "down", 600, NULL },
+ { "guilsinglleft", 600, NULL },
+ { "exclam", 600, NULL },
+ { "period", 600, NULL },
+ { "arrowright", 600, NULL },
+ { "format", 600, NULL },
+ { "greater", 600, NULL },
+ { "atilde", 600, NULL },
+ { "ij", 600, NULL },
+ { "brokenbar", 600, NULL },
+ { "arrowboth", 600, NULL },
+ { "quoteleft", 600, NULL },
+ { "onesuperior", 600, NULL }
+};
+
+static BuiltinFontWidth courierBoldWidthsTab[] = {
+ { "Ntilde", 600, NULL },
+ { "comma", 600, NULL },
+ { "cedilla", 600, NULL },
+ { "plusminus", 600, NULL },
+ { "arrowup", 600, NULL },
+ { "circumflex", 600, NULL },
+ { "dotaccent", 600, NULL },
+ { "LL", 600, NULL },
+ { "asciitilde", 600, NULL },
+ { "colon", 600, NULL },
+ { "onehalf", 600, NULL },
+ { "dollar", 600, NULL },
+ { "ntilde", 600, NULL },
+ { "left", 600, NULL },
+ { "minus", 600, NULL },
+ { "yen", 600, NULL },
+ { "space", 600, NULL },
+ { "questiondown", 600, NULL },
+ { "emdash", 600, NULL },
+ { "Agrave", 600, NULL },
+ { "three", 600, NULL },
+ { "numbersign", 600, NULL },
+ { "A", 600, NULL },
+ { "B", 600, NULL },
+ { "C", 600, NULL },
+ { "D", 600, NULL },
+ { "E", 600, NULL },
+ { "onequarter", 600, NULL },
+ { "F", 600, NULL },
+ { "G", 600, NULL },
+ { "H", 600, NULL },
+ { "I", 600, NULL },
+ { "J", 600, NULL },
+ { "K", 600, NULL },
+ { "backslash", 600, NULL },
+ { "L", 600, NULL },
+ { "periodcentered", 600, NULL },
+ { "M", 600, NULL },
+ { "N", 600, NULL },
+ { "O", 600, NULL },
+ { "P", 600, NULL },
+ { "Q", 600, NULL },
+ { "R", 600, NULL },
+ { "Aacute", 600, NULL },
+ { "caron", 600, NULL },
+ { "S", 600, NULL },
+ { "T", 600, NULL },
+ { "U", 600, NULL },
+ { "agrave", 600, NULL },
+ { "V", 600, NULL },
+ { "tab", 600, NULL },
+ { "W", 600, NULL },
+ { "ll", 600, NULL },
+ { "X", 600, NULL },
+ { "question", 600, NULL },
+ { "equal", 600, NULL },
+ { "Y", 600, NULL },
+ { "Z", 600, NULL },
+ { "four", 600, NULL },
+ { "a", 600, NULL },
+ { "b", 600, NULL },
+ { "c", 600, NULL },
+ { "d", 600, NULL },
+ { "e", 600, NULL },
+ { "f", 600, NULL },
+ { "g", 600, NULL },
+ { "bullet", 600, NULL },
+ { "h", 600, NULL },
+ { "i", 600, NULL },
+ { "Oslash", 600, NULL },
+ { "dagger", 600, NULL },
+ { "j", 600, NULL },
+ { "k", 600, NULL },
+ { "l", 600, NULL },
+ { "m", 600, NULL },
+ { "n", 600, NULL },
+ { "o", 600, NULL },
+ { "ordfeminine", 600, NULL },
+ { "ring", 600, NULL },
+ { "p", 600, NULL },
+ { "q", 600, NULL },
+ { "r", 600, NULL },
+ { "twosuperior", 600, NULL },
+ { "largebullet", 600, NULL },
+ { "aacute", 600, NULL },
+ { "s", 600, NULL },
+ { "OE", 600, NULL },
+ { "t", 600, NULL },
+ { "divide", 600, NULL },
+ { "u", 600, NULL },
+ { "v", 600, NULL },
+ { "w", 600, NULL },
+ { "x", 600, NULL },
+ { "y", 600, NULL },
+ { "z", 600, NULL },
+ { "hungarumlaut", 600, NULL },
+ { "quotedbl", 600, NULL },
+ { "mu", 600, NULL },
+ { "Scaron", 600, NULL },
+ { "Lslash", 600, NULL },
+ { "semicolon", 600, NULL },
+ { "oslash", 600, NULL },
+ { "parenright", 600, NULL },
+ { "Ecircumflex", 600, NULL },
+ { "trademark", 600, NULL },
+ { "daggerdbl", 600, NULL },
+ { "macron", 600, NULL },
+ { "Otilde", 600, NULL },
+ { "ellipsis", 600, NULL },
+ { "scaron", 600, NULL },
+ { "AE", 600, NULL },
+ { "Ucircumflex", 600, NULL },
+ { "lslash", 600, NULL },
+ { "lira", 600, NULL },
+ { "quotedblleft", 600, NULL },
+ { "guilsinglright", 600, NULL },
+ { "hyphen", 600, NULL },
+ { "quotesingle", 600, NULL },
+ { "eight", 600, NULL },
+ { "exclamdown", 600, NULL },
+ { "endash", 600, NULL },
+ { "oe", 600, NULL },
+ { "ecircumflex", 600, NULL },
+ { "copyright", 600, NULL },
+ { "Adieresis", 600, NULL },
+ { "Egrave", 600, NULL },
+ { "slash", 600, NULL },
+ { "Edieresis", 600, NULL },
+ { "otilde", 600, NULL },
+ { "Idieresis", 600, NULL },
+ { "parenleft", 600, NULL },
+ { "one", 600, NULL },
+ { "ucircumflex", 600, NULL },
+ { "Odieresis", 600, NULL },
+ { "bracketleft", 600, NULL },
+ { "Ugrave", 600, NULL },
+ { "quoteright", 600, NULL },
+ { "Udieresis", 600, NULL },
+ { "perthousand", 600, NULL },
+ { "Ydieresis", 600, NULL },
+ { "Eacute", 600, NULL },
+ { "adieresis", 600, NULL },
+ { "egrave", 600, NULL },
+ { "edieresis", 600, NULL },
+ { "idieresis", 600, NULL },
+ { "Eth", 600, NULL },
+ { "ae", 600, NULL },
+ { "asterisk", 600, NULL },
+ { "odieresis", 600, NULL },
+ { "Uacute", 600, NULL },
+ { "ugrave", 600, NULL },
+ { "nine", 600, NULL },
+ { "five", 600, NULL },
+ { "udieresis", 600, NULL },
+ { "Zcaron", 600, NULL },
+ { "threequarters", 600, NULL },
+ { "guillemotright", 600, NULL },
+ { "ydieresis", 600, NULL },
+ { "Ccedilla", 600, NULL },
+ { "tilde", 600, NULL },
+ { "at", 600, NULL },
+ { "eacute", 600, NULL },
+ { "Gcaron", 600, NULL },
+ { "underscore", 600, NULL },
+ { "multiply", 600, NULL },
+ { "zero", 600, NULL },
+ { "eth", 600, NULL },
+ { "Scedilla", 600, NULL },
+ { "Ograve", 600, NULL },
+ { "uacute", 600, NULL },
+ { "braceleft", 600, NULL },
+ { "Thorn", 600, NULL },
+ { "zcaron", 600, NULL },
+ { "ccedilla", 600, NULL },
+ { "gcaron", 600, NULL },
+ { "scedilla", 600, NULL },
+ { "Ocircumflex", 600, NULL },
+ { "Oacute", 600, NULL },
+ { "arrowdown", 600, NULL },
+ { "ogonek", 600, NULL },
+ { "ograve", 600, NULL },
+ { "thorn", 600, NULL },
+ { "degree", 600, NULL },
+ { "registered", 600, NULL },
+ { "Aring", 600, NULL },
+ { "percent", 600, NULL },
+ { "six", 600, NULL },
+ { "paragraph", 600, NULL },
+ { "two", 600, NULL },
+ { "Igrave", 600, NULL },
+ { "ocircumflex", 600, NULL },
+ { "oacute", 600, NULL },
+ { "asciicircum", 600, NULL },
+ { "square", 600, NULL },
+ { "aring", 600, NULL },
+ { "grave", 600, NULL },
+ { "bracketright", 600, NULL },
+ { "Iacute", 600, NULL },
+ { "ampersand", 600, NULL },
+ { "igrave", 600, NULL },
+ { "return", 600, NULL },
+ { "plus", 600, NULL },
+ { "quotesinglbase", 600, NULL },
+ { "Yacute", 600, NULL },
+ { "threesuperior", 600, NULL },
+ { "acute", 600, NULL },
+ { "notegraphic", 600, NULL },
+ { "section", 600, NULL },
+ { "arrowleft", 600, NULL },
+ { "dieresis", 600, NULL },
+ { "iacute", 600, NULL },
+ { "quotedblbase", 600, NULL },
+ { "up", 600, NULL },
+ { "florin", 600, NULL },
+ { "yacute", 600, NULL },
+ { "fi", 600, NULL },
+ { "fl", 600, NULL },
+ { "Acircumflex", 600, NULL },
+ { "Icircumflex", 600, NULL },
+ { "guillemotleft", 600, NULL },
+ { "germandbls", 600, NULL },
+ { "seven", 600, NULL },
+ { "prescription", 600, NULL },
+ { "indent", 600, NULL },
+ { "dectab", 600, NULL },
+ { "ordmasculine", 600, NULL },
+ { "dotlessi", 600, NULL },
+ { "sterling", 600, NULL },
+ { "acircumflex", 600, NULL },
+ { "IJ", 600, NULL },
+ { "overscore", 600, NULL },
+ { "icircumflex", 600, NULL },
+ { "braceright", 600, NULL },
+ { "graybox", 600, NULL },
+ { "quotedblright", 600, NULL },
+ { "center", 600, NULL },
+ { "stop", 600, NULL },
+ { "cent", 600, NULL },
+ { "currency", 600, NULL },
+ { "logicalnot", 600, NULL },
+ { "merge", 600, NULL },
+ { "Idot", 600, NULL },
+ { "Atilde", 600, NULL },
+ { "breve", 600, NULL },
+ { "bar", 600, NULL },
+ { "fraction", 600, NULL },
+ { "less", 600, NULL },
+ { "down", 600, NULL },
+ { "guilsinglleft", 600, NULL },
+ { "exclam", 600, NULL },
+ { "period", 600, NULL },
+ { "format", 600, NULL },
+ { "arrowright", 600, NULL },
+ { "greater", 600, NULL },
+ { "ij", 600, NULL },
+ { "atilde", 600, NULL },
+ { "brokenbar", 600, NULL },
+ { "arrowboth", 600, NULL },
+ { "quoteleft", 600, NULL },
+ { "onesuperior", 600, NULL }
+};
+
+static BuiltinFontWidth courierBoldObliqueWidthsTab[] = {
+ { "Ntilde", 600, NULL },
+ { "comma", 600, NULL },
+ { "cedilla", 600, NULL },
+ { "plusminus", 600, NULL },
+ { "arrowup", 600, NULL },
+ { "circumflex", 600, NULL },
+ { "dotaccent", 600, NULL },
+ { "LL", 600, NULL },
+ { "asciitilde", 600, NULL },
+ { "colon", 600, NULL },
+ { "onehalf", 600, NULL },
+ { "dollar", 600, NULL },
+ { "ntilde", 600, NULL },
+ { "left", 600, NULL },
+ { "minus", 600, NULL },
+ { "yen", 600, NULL },
+ { "space", 600, NULL },
+ { "questiondown", 600, NULL },
+ { "emdash", 600, NULL },
+ { "Agrave", 600, NULL },
+ { "three", 600, NULL },
+ { "numbersign", 600, NULL },
+ { "A", 600, NULL },
+ { "B", 600, NULL },
+ { "C", 600, NULL },
+ { "D", 600, NULL },
+ { "E", 600, NULL },
+ { "onequarter", 600, NULL },
+ { "F", 600, NULL },
+ { "G", 600, NULL },
+ { "H", 600, NULL },
+ { "I", 600, NULL },
+ { "J", 600, NULL },
+ { "K", 600, NULL },
+ { "backslash", 600, NULL },
+ { "L", 600, NULL },
+ { "periodcentered", 600, NULL },
+ { "M", 600, NULL },
+ { "N", 600, NULL },
+ { "O", 600, NULL },
+ { "P", 600, NULL },
+ { "Q", 600, NULL },
+ { "R", 600, NULL },
+ { "Aacute", 600, NULL },
+ { "caron", 600, NULL },
+ { "S", 600, NULL },
+ { "T", 600, NULL },
+ { "U", 600, NULL },
+ { "agrave", 600, NULL },
+ { "V", 600, NULL },
+ { "tab", 600, NULL },
+ { "W", 600, NULL },
+ { "ll", 600, NULL },
+ { "X", 600, NULL },
+ { "question", 600, NULL },
+ { "equal", 600, NULL },
+ { "Y", 600, NULL },
+ { "Z", 600, NULL },
+ { "four", 600, NULL },
+ { "a", 600, NULL },
+ { "b", 600, NULL },
+ { "c", 600, NULL },
+ { "d", 600, NULL },
+ { "e", 600, NULL },
+ { "f", 600, NULL },
+ { "g", 600, NULL },
+ { "bullet", 600, NULL },
+ { "h", 600, NULL },
+ { "i", 600, NULL },
+ { "Oslash", 600, NULL },
+ { "dagger", 600, NULL },
+ { "j", 600, NULL },
+ { "k", 600, NULL },
+ { "l", 600, NULL },
+ { "m", 600, NULL },
+ { "n", 600, NULL },
+ { "o", 600, NULL },
+ { "ordfeminine", 600, NULL },
+ { "ring", 600, NULL },
+ { "p", 600, NULL },
+ { "q", 600, NULL },
+ { "r", 600, NULL },
+ { "twosuperior", 600, NULL },
+ { "largebullet", 600, NULL },
+ { "aacute", 600, NULL },
+ { "s", 600, NULL },
+ { "OE", 600, NULL },
+ { "t", 600, NULL },
+ { "divide", 600, NULL },
+ { "u", 600, NULL },
+ { "v", 600, NULL },
+ { "w", 600, NULL },
+ { "x", 600, NULL },
+ { "y", 600, NULL },
+ { "z", 600, NULL },
+ { "hungarumlaut", 600, NULL },
+ { "quotedbl", 600, NULL },
+ { "mu", 600, NULL },
+ { "Scaron", 600, NULL },
+ { "Lslash", 600, NULL },
+ { "semicolon", 600, NULL },
+ { "oslash", 600, NULL },
+ { "parenright", 600, NULL },
+ { "Ecircumflex", 600, NULL },
+ { "trademark", 600, NULL },
+ { "daggerdbl", 600, NULL },
+ { "macron", 600, NULL },
+ { "Otilde", 600, NULL },
+ { "ellipsis", 600, NULL },
+ { "scaron", 600, NULL },
+ { "AE", 600, NULL },
+ { "Ucircumflex", 600, NULL },
+ { "lslash", 600, NULL },
+ { "lira", 600, NULL },
+ { "quotedblleft", 600, NULL },
+ { "guilsinglright", 600, NULL },
+ { "hyphen", 600, NULL },
+ { "quotesingle", 600, NULL },
+ { "eight", 600, NULL },
+ { "exclamdown", 600, NULL },
+ { "endash", 600, NULL },
+ { "oe", 600, NULL },
+ { "ecircumflex", 600, NULL },
+ { "copyright", 600, NULL },
+ { "Adieresis", 600, NULL },
+ { "Egrave", 600, NULL },
+ { "slash", 600, NULL },
+ { "Edieresis", 600, NULL },
+ { "otilde", 600, NULL },
+ { "Idieresis", 600, NULL },
+ { "parenleft", 600, NULL },
+ { "one", 600, NULL },
+ { "ucircumflex", 600, NULL },
+ { "Odieresis", 600, NULL },
+ { "bracketleft", 600, NULL },
+ { "Ugrave", 600, NULL },
+ { "quoteright", 600, NULL },
+ { "Udieresis", 600, NULL },
+ { "perthousand", 600, NULL },
+ { "Ydieresis", 600, NULL },
+ { "Eacute", 600, NULL },
+ { "adieresis", 600, NULL },
+ { "egrave", 600, NULL },
+ { "edieresis", 600, NULL },
+ { "idieresis", 600, NULL },
+ { "Eth", 600, NULL },
+ { "ae", 600, NULL },
+ { "asterisk", 600, NULL },
+ { "odieresis", 600, NULL },
+ { "Uacute", 600, NULL },
+ { "ugrave", 600, NULL },
+ { "nine", 600, NULL },
+ { "five", 600, NULL },
+ { "udieresis", 600, NULL },
+ { "Zcaron", 600, NULL },
+ { "threequarters", 600, NULL },
+ { "guillemotright", 600, NULL },
+ { "ydieresis", 600, NULL },
+ { "Ccedilla", 600, NULL },
+ { "tilde", 600, NULL },
+ { "at", 600, NULL },
+ { "eacute", 600, NULL },
+ { "Gcaron", 600, NULL },
+ { "underscore", 600, NULL },
+ { "multiply", 600, NULL },
+ { "zero", 600, NULL },
+ { "eth", 600, NULL },
+ { "Scedilla", 600, NULL },
+ { "Ograve", 600, NULL },
+ { "uacute", 600, NULL },
+ { "braceleft", 600, NULL },
+ { "Thorn", 600, NULL },
+ { "zcaron", 600, NULL },
+ { "ccedilla", 600, NULL },
+ { "gcaron", 600, NULL },
+ { "scedilla", 600, NULL },
+ { "Ocircumflex", 600, NULL },
+ { "Oacute", 600, NULL },
+ { "arrowdown", 600, NULL },
+ { "ogonek", 600, NULL },
+ { "ograve", 600, NULL },
+ { "thorn", 600, NULL },
+ { "degree", 600, NULL },
+ { "registered", 600, NULL },
+ { "Aring", 600, NULL },
+ { "percent", 600, NULL },
+ { "six", 600, NULL },
+ { "paragraph", 600, NULL },
+ { "two", 600, NULL },
+ { "Igrave", 600, NULL },
+ { "ocircumflex", 600, NULL },
+ { "oacute", 600, NULL },
+ { "asciicircum", 600, NULL },
+ { "square", 600, NULL },
+ { "aring", 600, NULL },
+ { "grave", 600, NULL },
+ { "bracketright", 600, NULL },
+ { "Iacute", 600, NULL },
+ { "ampersand", 600, NULL },
+ { "igrave", 600, NULL },
+ { "return", 600, NULL },
+ { "plus", 600, NULL },
+ { "quotesinglbase", 600, NULL },
+ { "Yacute", 600, NULL },
+ { "threesuperior", 600, NULL },
+ { "acute", 600, NULL },
+ { "notegraphic", 600, NULL },
+ { "section", 600, NULL },
+ { "arrowleft", 600, NULL },
+ { "dieresis", 600, NULL },
+ { "iacute", 600, NULL },
+ { "quotedblbase", 600, NULL },
+ { "up", 600, NULL },
+ { "florin", 600, NULL },
+ { "yacute", 600, NULL },
+ { "fi", 600, NULL },
+ { "fl", 600, NULL },
+ { "Acircumflex", 600, NULL },
+ { "Icircumflex", 600, NULL },
+ { "guillemotleft", 600, NULL },
+ { "germandbls", 600, NULL },
+ { "seven", 600, NULL },
+ { "prescription", 600, NULL },
+ { "indent", 600, NULL },
+ { "dectab", 600, NULL },
+ { "ordmasculine", 600, NULL },
+ { "dotlessi", 600, NULL },
+ { "sterling", 600, NULL },
+ { "acircumflex", 600, NULL },
+ { "IJ", 600, NULL },
+ { "overscore", 600, NULL },
+ { "icircumflex", 600, NULL },
+ { "braceright", 600, NULL },
+ { "graybox", 600, NULL },
+ { "quotedblright", 600, NULL },
+ { "center", 600, NULL },
+ { "stop", 600, NULL },
+ { "cent", 600, NULL },
+ { "currency", 600, NULL },
+ { "logicalnot", 600, NULL },
+ { "merge", 600, NULL },
+ { "Idot", 600, NULL },
+ { "Atilde", 600, NULL },
+ { "breve", 600, NULL },
+ { "bar", 600, NULL },
+ { "fraction", 600, NULL },
+ { "less", 600, NULL },
+ { "down", 600, NULL },
+ { "guilsinglleft", 600, NULL },
+ { "exclam", 600, NULL },
+ { "period", 600, NULL },
+ { "format", 600, NULL },
+ { "arrowright", 600, NULL },
+ { "greater", 600, NULL },
+ { "ij", 600, NULL },
+ { "atilde", 600, NULL },
+ { "brokenbar", 600, NULL },
+ { "arrowboth", 600, NULL },
+ { "quoteleft", 600, NULL },
+ { "onesuperior", 600, NULL }
+};
+
+static BuiltinFontWidth courierObliqueWidthsTab[] = {
+ { "Ntilde", 600, NULL },
+ { "comma", 600, NULL },
+ { "cedilla", 600, NULL },
+ { "plusminus", 600, NULL },
+ { "arrowup", 600, NULL },
+ { "circumflex", 600, NULL },
+ { "dotaccent", 600, NULL },
+ { "LL", 600, NULL },
+ { "asciitilde", 600, NULL },
+ { "colon", 600, NULL },
+ { "onehalf", 600, NULL },
+ { "dollar", 600, NULL },
+ { "ntilde", 600, NULL },
+ { "left", 600, NULL },
+ { "minus", 600, NULL },
+ { "yen", 600, NULL },
+ { "space", 600, NULL },
+ { "questiondown", 600, NULL },
+ { "emdash", 600, NULL },
+ { "Agrave", 600, NULL },
+ { "three", 600, NULL },
+ { "numbersign", 600, NULL },
+ { "A", 600, NULL },
+ { "B", 600, NULL },
+ { "C", 600, NULL },
+ { "D", 600, NULL },
+ { "E", 600, NULL },
+ { "onequarter", 600, NULL },
+ { "F", 600, NULL },
+ { "G", 600, NULL },
+ { "H", 600, NULL },
+ { "I", 600, NULL },
+ { "J", 600, NULL },
+ { "K", 600, NULL },
+ { "backslash", 600, NULL },
+ { "L", 600, NULL },
+ { "periodcentered", 600, NULL },
+ { "M", 600, NULL },
+ { "N", 600, NULL },
+ { "O", 600, NULL },
+ { "P", 600, NULL },
+ { "Q", 600, NULL },
+ { "R", 600, NULL },
+ { "Aacute", 600, NULL },
+ { "caron", 600, NULL },
+ { "S", 600, NULL },
+ { "T", 600, NULL },
+ { "U", 600, NULL },
+ { "agrave", 600, NULL },
+ { "V", 600, NULL },
+ { "tab", 600, NULL },
+ { "W", 600, NULL },
+ { "ll", 600, NULL },
+ { "X", 600, NULL },
+ { "question", 600, NULL },
+ { "equal", 600, NULL },
+ { "Y", 600, NULL },
+ { "Z", 600, NULL },
+ { "four", 600, NULL },
+ { "a", 600, NULL },
+ { "b", 600, NULL },
+ { "c", 600, NULL },
+ { "d", 600, NULL },
+ { "e", 600, NULL },
+ { "f", 600, NULL },
+ { "g", 600, NULL },
+ { "bullet", 600, NULL },
+ { "h", 600, NULL },
+ { "i", 600, NULL },
+ { "Oslash", 600, NULL },
+ { "dagger", 600, NULL },
+ { "j", 600, NULL },
+ { "k", 600, NULL },
+ { "l", 600, NULL },
+ { "m", 600, NULL },
+ { "n", 600, NULL },
+ { "o", 600, NULL },
+ { "ordfeminine", 600, NULL },
+ { "ring", 600, NULL },
+ { "p", 600, NULL },
+ { "q", 600, NULL },
+ { "r", 600, NULL },
+ { "twosuperior", 600, NULL },
+ { "largebullet", 600, NULL },
+ { "aacute", 600, NULL },
+ { "s", 600, NULL },
+ { "OE", 600, NULL },
+ { "t", 600, NULL },
+ { "divide", 600, NULL },
+ { "u", 600, NULL },
+ { "v", 600, NULL },
+ { "w", 600, NULL },
+ { "x", 600, NULL },
+ { "y", 600, NULL },
+ { "z", 600, NULL },
+ { "hungarumlaut", 600, NULL },
+ { "quotedbl", 600, NULL },
+ { "mu", 600, NULL },
+ { "Scaron", 600, NULL },
+ { "Lslash", 600, NULL },
+ { "semicolon", 600, NULL },
+ { "oslash", 600, NULL },
+ { "parenright", 600, NULL },
+ { "Ecircumflex", 600, NULL },
+ { "trademark", 600, NULL },
+ { "daggerdbl", 600, NULL },
+ { "macron", 600, NULL },
+ { "Otilde", 600, NULL },
+ { "ellipsis", 600, NULL },
+ { "scaron", 600, NULL },
+ { "AE", 600, NULL },
+ { "Ucircumflex", 600, NULL },
+ { "lslash", 600, NULL },
+ { "lira", 600, NULL },
+ { "quotedblleft", 600, NULL },
+ { "guilsinglright", 600, NULL },
+ { "hyphen", 600, NULL },
+ { "quotesingle", 600, NULL },
+ { "eight", 600, NULL },
+ { "exclamdown", 600, NULL },
+ { "endash", 600, NULL },
+ { "oe", 600, NULL },
+ { "ecircumflex", 600, NULL },
+ { "copyright", 600, NULL },
+ { "Adieresis", 600, NULL },
+ { "Egrave", 600, NULL },
+ { "slash", 600, NULL },
+ { "Edieresis", 600, NULL },
+ { "otilde", 600, NULL },
+ { "Idieresis", 600, NULL },
+ { "parenleft", 600, NULL },
+ { "one", 600, NULL },
+ { "ucircumflex", 600, NULL },
+ { "Odieresis", 600, NULL },
+ { "bracketleft", 600, NULL },
+ { "Ugrave", 600, NULL },
+ { "quoteright", 600, NULL },
+ { "Udieresis", 600, NULL },
+ { "perthousand", 600, NULL },
+ { "Ydieresis", 600, NULL },
+ { "Eacute", 600, NULL },
+ { "adieresis", 600, NULL },
+ { "egrave", 600, NULL },
+ { "edieresis", 600, NULL },
+ { "idieresis", 600, NULL },
+ { "Eth", 600, NULL },
+ { "ae", 600, NULL },
+ { "asterisk", 600, NULL },
+ { "odieresis", 600, NULL },
+ { "Uacute", 600, NULL },
+ { "ugrave", 600, NULL },
+ { "nine", 600, NULL },
+ { "five", 600, NULL },
+ { "udieresis", 600, NULL },
+ { "Zcaron", 600, NULL },
+ { "threequarters", 600, NULL },
+ { "guillemotright", 600, NULL },
+ { "ydieresis", 600, NULL },
+ { "Ccedilla", 600, NULL },
+ { "tilde", 600, NULL },
+ { "at", 600, NULL },
+ { "eacute", 600, NULL },
+ { "Gcaron", 600, NULL },
+ { "underscore", 600, NULL },
+ { "multiply", 600, NULL },
+ { "zero", 600, NULL },
+ { "eth", 600, NULL },
+ { "Scedilla", 600, NULL },
+ { "Ograve", 600, NULL },
+ { "uacute", 600, NULL },
+ { "braceleft", 600, NULL },
+ { "Thorn", 600, NULL },
+ { "zcaron", 600, NULL },
+ { "ccedilla", 600, NULL },
+ { "gcaron", 600, NULL },
+ { "scedilla", 600, NULL },
+ { "Ocircumflex", 600, NULL },
+ { "Oacute", 600, NULL },
+ { "arrowdown", 600, NULL },
+ { "ogonek", 600, NULL },
+ { "ograve", 600, NULL },
+ { "thorn", 600, NULL },
+ { "degree", 600, NULL },
+ { "registered", 600, NULL },
+ { "Aring", 600, NULL },
+ { "percent", 600, NULL },
+ { "six", 600, NULL },
+ { "paragraph", 600, NULL },
+ { "two", 600, NULL },
+ { "Igrave", 600, NULL },
+ { "ocircumflex", 600, NULL },
+ { "oacute", 600, NULL },
+ { "asciicircum", 600, NULL },
+ { "square", 600, NULL },
+ { "aring", 600, NULL },
+ { "grave", 600, NULL },
+ { "bracketright", 600, NULL },
+ { "Iacute", 600, NULL },
+ { "ampersand", 600, NULL },
+ { "igrave", 600, NULL },
+ { "return", 600, NULL },
+ { "plus", 600, NULL },
+ { "quotesinglbase", 600, NULL },
+ { "Yacute", 600, NULL },
+ { "threesuperior", 600, NULL },
+ { "acute", 600, NULL },
+ { "notegraphic", 600, NULL },
+ { "section", 600, NULL },
+ { "arrowleft", 600, NULL },
+ { "dieresis", 600, NULL },
+ { "iacute", 600, NULL },
+ { "quotedblbase", 600, NULL },
+ { "up", 600, NULL },
+ { "florin", 600, NULL },
+ { "yacute", 600, NULL },
+ { "fi", 600, NULL },
+ { "fl", 600, NULL },
+ { "Acircumflex", 600, NULL },
+ { "Icircumflex", 600, NULL },
+ { "guillemotleft", 600, NULL },
+ { "germandbls", 600, NULL },
+ { "seven", 600, NULL },
+ { "prescription", 600, NULL },
+ { "indent", 600, NULL },
+ { "dectab", 600, NULL },
+ { "ordmasculine", 600, NULL },
+ { "dotlessi", 600, NULL },
+ { "sterling", 600, NULL },
+ { "acircumflex", 600, NULL },
+ { "IJ", 600, NULL },
+ { "overscore", 600, NULL },
+ { "icircumflex", 600, NULL },
+ { "braceright", 600, NULL },
+ { "graybox", 600, NULL },
+ { "quotedblright", 600, NULL },
+ { "center", 600, NULL },
+ { "stop", 600, NULL },
+ { "cent", 600, NULL },
+ { "currency", 600, NULL },
+ { "logicalnot", 600, NULL },
+ { "merge", 600, NULL },
+ { "Idot", 600, NULL },
+ { "Atilde", 600, NULL },
+ { "breve", 600, NULL },
+ { "bar", 600, NULL },
+ { "fraction", 600, NULL },
+ { "less", 600, NULL },
+ { "down", 600, NULL },
+ { "guilsinglleft", 600, NULL },
+ { "exclam", 600, NULL },
+ { "period", 600, NULL },
+ { "format", 600, NULL },
+ { "arrowright", 600, NULL },
+ { "greater", 600, NULL },
+ { "ij", 600, NULL },
+ { "atilde", 600, NULL },
+ { "brokenbar", 600, NULL },
+ { "arrowboth", 600, NULL },
+ { "quoteleft", 600, NULL },
+ { "onesuperior", 600, NULL }
+};
+
+static BuiltinFontWidth helveticaWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 278, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 584, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 584, NULL },
+ { "colon", 278, NULL },
+ { "onehalf", 834, NULL },
+ { "dollar", 556, NULL },
+ { "ntilde", 556, NULL },
+ { "minus", 584, NULL },
+ { "yen", 556, NULL },
+ { "space", 278, NULL },
+ { "questiondown", 611, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 667, NULL },
+ { "three", 556, NULL },
+ { "numbersign", 556, NULL },
+ { "A", 667, NULL },
+ { "B", 667, NULL },
+ { "C", 722, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 834, NULL },
+ { "F", 611, NULL },
+ { "G", 778, NULL },
+ { "H", 722, NULL },
+ { "I", 278, NULL },
+ { "J", 500, NULL },
+ { "K", 667, NULL },
+ { "backslash", 278, NULL },
+ { "L", 556, NULL },
+ { "periodcentered", 278, NULL },
+ { "M", 833, NULL },
+ { "N", 722, NULL },
+ { "O", 778, NULL },
+ { "P", 667, NULL },
+ { "Q", 778, NULL },
+ { "R", 722, NULL },
+ { "Aacute", 667, NULL },
+ { "caron", 333, NULL },
+ { "S", 667, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 556, NULL },
+ { "V", 667, NULL },
+ { "W", 944, NULL },
+ { "X", 667, NULL },
+ { "question", 556, NULL },
+ { "equal", 584, NULL },
+ { "Y", 667, NULL },
+ { "Z", 611, NULL },
+ { "four", 556, NULL },
+ { "a", 556, NULL },
+ { "b", 556, NULL },
+ { "c", 500, NULL },
+ { "d", 556, NULL },
+ { "e", 556, NULL },
+ { "f", 278, NULL },
+ { "g", 556, NULL },
+ { "bullet", 350, NULL },
+ { "h", 556, NULL },
+ { "i", 222, NULL },
+ { "Oslash", 778, NULL },
+ { "dagger", 556, NULL },
+ { "j", 222, NULL },
+ { "k", 500, NULL },
+ { "l", 222, NULL },
+ { "m", 833, NULL },
+ { "n", 556, NULL },
+ { "o", 556, NULL },
+ { "ordfeminine", 370, NULL },
+ { "ring", 333, NULL },
+ { "p", 556, NULL },
+ { "q", 556, NULL },
+ { "r", 333, NULL },
+ { "twosuperior", 333, NULL },
+ { "aacute", 556, NULL },
+ { "s", 500, NULL },
+ { "OE", 1000, NULL },
+ { "t", 278, NULL },
+ { "divide", 584, NULL },
+ { "u", 556, NULL },
+ { "v", 500, NULL },
+ { "w", 722, NULL },
+ { "x", 500, NULL },
+ { "y", 500, NULL },
+ { "z", 500, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 355, NULL },
+ { "mu", 556, NULL },
+ { "Scaron", 667, NULL },
+ { "Lslash", 556, NULL },
+ { "semicolon", 278, NULL },
+ { "oslash", 611, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 556, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 778, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 500, NULL },
+ { "AE", 1000, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 222, NULL },
+ { "quotedblleft", 333, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 191, NULL },
+ { "eight", 556, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 556, NULL },
+ { "oe", 944, NULL },
+ { "ecircumflex", 556, NULL },
+ { "copyright", 737, NULL },
+ { "Adieresis", 667, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 556, NULL },
+ { "Idieresis", 278, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 556, NULL },
+ { "ucircumflex", 556, NULL },
+ { "Odieresis", 778, NULL },
+ { "bracketleft", 278, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 222, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 667, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 556, NULL },
+ { "egrave", 556, NULL },
+ { "edieresis", 556, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 889, NULL },
+ { "asterisk", 389, NULL },
+ { "odieresis", 556, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 556, NULL },
+ { "nine", 556, NULL },
+ { "five", 556, NULL },
+ { "udieresis", 556, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 834, NULL },
+ { "guillemotright", 556, NULL },
+ { "ydieresis", 500, NULL },
+ { "Ccedilla", 722, NULL },
+ { "tilde", 333, NULL },
+ { "at", 1015, NULL },
+ { "eacute", 556, NULL },
+ { "underscore", 556, NULL },
+ { "multiply", 584, NULL },
+ { "zero", 556, NULL },
+ { "eth", 556, NULL },
+ { "Ograve", 778, NULL },
+ { "uacute", 556, NULL },
+ { "braceleft", 334, NULL },
+ { "Thorn", 667, NULL },
+ { "zcaron", 500, NULL },
+ { "ccedilla", 500, NULL },
+ { "Ocircumflex", 778, NULL },
+ { "Oacute", 778, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 556, NULL },
+ { "thorn", 556, NULL },
+ { "degree", 400, NULL },
+ { "registered", 737, NULL },
+ { "Aring", 667, NULL },
+ { "percent", 889, NULL },
+ { "six", 556, NULL },
+ { "paragraph", 537, NULL },
+ { "two", 556, NULL },
+ { "Igrave", 278, NULL },
+ { "ocircumflex", 556, NULL },
+ { "oacute", 556, NULL },
+ { "asciicircum", 469, NULL },
+ { "aring", 556, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 278, NULL },
+ { "Iacute", 278, NULL },
+ { "ampersand", 667, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 584, NULL },
+ { "quotesinglbase", 222, NULL },
+ { "Yacute", 667, NULL },
+ { "threesuperior", 333, NULL },
+ { "acute", 333, NULL },
+ { "section", 556, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 333, NULL },
+ { "florin", 556, NULL },
+ { "yacute", 500, NULL },
+ { "fi", 500, NULL },
+ { "fl", 500, NULL },
+ { "Acircumflex", 667, NULL },
+ { "Icircumflex", 278, NULL },
+ { "guillemotleft", 556, NULL },
+ { "germandbls", 611, NULL },
+ { "seven", 556, NULL },
+ { "ordmasculine", 365, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 556, NULL },
+ { "acircumflex", 556, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 334, NULL },
+ { "quotedblright", 333, NULL },
+ { "cent", 556, NULL },
+ { "currency", 556, NULL },
+ { "logicalnot", 584, NULL },
+ { "Atilde", 667, NULL },
+ { "breve", 333, NULL },
+ { "bar", 260, NULL },
+ { "fraction", 167, NULL },
+ { "less", 584, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 278, NULL },
+ { "period", 278, NULL },
+ { "greater", 584, NULL },
+ { "atilde", 556, NULL },
+ { "brokenbar", 260, NULL },
+ { "quoteleft", 222, NULL },
+ { "onesuperior", 333, NULL }
+};
+
+static BuiltinFontWidth helveticaBoldWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 278, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 584, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 584, NULL },
+ { "colon", 333, NULL },
+ { "onehalf", 834, NULL },
+ { "dollar", 556, NULL },
+ { "ntilde", 611, NULL },
+ { "minus", 584, NULL },
+ { "yen", 556, NULL },
+ { "space", 278, NULL },
+ { "questiondown", 611, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 722, NULL },
+ { "three", 556, NULL },
+ { "numbersign", 556, NULL },
+ { "A", 722, NULL },
+ { "B", 722, NULL },
+ { "C", 722, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 834, NULL },
+ { "F", 611, NULL },
+ { "G", 778, NULL },
+ { "H", 722, NULL },
+ { "I", 278, NULL },
+ { "J", 556, NULL },
+ { "K", 722, NULL },
+ { "backslash", 278, NULL },
+ { "L", 611, NULL },
+ { "periodcentered", 278, NULL },
+ { "M", 833, NULL },
+ { "N", 722, NULL },
+ { "O", 778, NULL },
+ { "P", 667, NULL },
+ { "Q", 778, NULL },
+ { "R", 722, NULL },
+ { "Aacute", 722, NULL },
+ { "caron", 333, NULL },
+ { "S", 667, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 556, NULL },
+ { "V", 667, NULL },
+ { "W", 944, NULL },
+ { "X", 667, NULL },
+ { "question", 611, NULL },
+ { "equal", 584, NULL },
+ { "Y", 667, NULL },
+ { "Z", 611, NULL },
+ { "four", 556, NULL },
+ { "a", 556, NULL },
+ { "b", 611, NULL },
+ { "c", 556, NULL },
+ { "d", 611, NULL },
+ { "e", 556, NULL },
+ { "f", 333, NULL },
+ { "g", 611, NULL },
+ { "bullet", 350, NULL },
+ { "h", 611, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 778, NULL },
+ { "dagger", 556, NULL },
+ { "j", 278, NULL },
+ { "k", 556, NULL },
+ { "l", 278, NULL },
+ { "m", 889, NULL },
+ { "n", 611, NULL },
+ { "o", 611, NULL },
+ { "ordfeminine", 370, NULL },
+ { "ring", 333, NULL },
+ { "p", 611, NULL },
+ { "q", 611, NULL },
+ { "r", 389, NULL },
+ { "twosuperior", 333, NULL },
+ { "aacute", 556, NULL },
+ { "s", 556, NULL },
+ { "OE", 1000, NULL },
+ { "t", 333, NULL },
+ { "divide", 584, NULL },
+ { "u", 611, NULL },
+ { "v", 556, NULL },
+ { "w", 778, NULL },
+ { "x", 556, NULL },
+ { "y", 556, NULL },
+ { "z", 500, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 474, NULL },
+ { "mu", 611, NULL },
+ { "Scaron", 667, NULL },
+ { "Lslash", 611, NULL },
+ { "semicolon", 333, NULL },
+ { "oslash", 611, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 556, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 778, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 556, NULL },
+ { "AE", 1000, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 500, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 238, NULL },
+ { "eight", 556, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 556, NULL },
+ { "oe", 944, NULL },
+ { "ecircumflex", 556, NULL },
+ { "copyright", 737, NULL },
+ { "Adieresis", 722, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 611, NULL },
+ { "Idieresis", 278, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 556, NULL },
+ { "ucircumflex", 611, NULL },
+ { "Odieresis", 778, NULL },
+ { "bracketleft", 333, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 278, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 667, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 556, NULL },
+ { "egrave", 556, NULL },
+ { "edieresis", 556, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 889, NULL },
+ { "asterisk", 389, NULL },
+ { "odieresis", 611, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 611, NULL },
+ { "nine", 556, NULL },
+ { "five", 556, NULL },
+ { "udieresis", 611, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 834, NULL },
+ { "guillemotright", 556, NULL },
+ { "ydieresis", 556, NULL },
+ { "Ccedilla", 722, NULL },
+ { "tilde", 333, NULL },
+ { "dbldaggerumlaut", 556, NULL },
+ { "at", 975, NULL },
+ { "eacute", 556, NULL },
+ { "underscore", 556, NULL },
+ { "multiply", 584, NULL },
+ { "zero", 556, NULL },
+ { "eth", 611, NULL },
+ { "Ograve", 778, NULL },
+ { "uacute", 611, NULL },
+ { "braceleft", 389, NULL },
+ { "Thorn", 667, NULL },
+ { "zcaron", 500, NULL },
+ { "ccedilla", 556, NULL },
+ { "Ocircumflex", 778, NULL },
+ { "Oacute", 778, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 611, NULL },
+ { "thorn", 611, NULL },
+ { "degree", 400, NULL },
+ { "registered", 737, NULL },
+ { "Aring", 722, NULL },
+ { "percent", 889, NULL },
+ { "six", 556, NULL },
+ { "paragraph", 556, NULL },
+ { "two", 556, NULL },
+ { "Igrave", 278, NULL },
+ { "ocircumflex", 611, NULL },
+ { "oacute", 611, NULL },
+ { "asciicircum", 584, NULL },
+ { "aring", 556, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 333, NULL },
+ { "Iacute", 278, NULL },
+ { "ampersand", 722, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 584, NULL },
+ { "quotesinglbase", 278, NULL },
+ { "Yacute", 667, NULL },
+ { "threesuperior", 333, NULL },
+ { "acute", 333, NULL },
+ { "section", 556, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 500, NULL },
+ { "florin", 556, NULL },
+ { "yacute", 556, NULL },
+ { "fi", 611, NULL },
+ { "fl", 611, NULL },
+ { "Acircumflex", 722, NULL },
+ { "Icircumflex", 278, NULL },
+ { "guillemotleft", 556, NULL },
+ { "germandbls", 611, NULL },
+ { "seven", 556, NULL },
+ { "ordmasculine", 365, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 556, NULL },
+ { "acircumflex", 556, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 389, NULL },
+ { "quotedblright", 500, NULL },
+ { "cent", 556, NULL },
+ { "currency", 556, NULL },
+ { "logicalnot", 584, NULL },
+ { "Atilde", 722, NULL },
+ { "breve", 333, NULL },
+ { "bar", 280, NULL },
+ { "fraction", 167, NULL },
+ { "less", 584, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 333, NULL },
+ { "period", 278, NULL },
+ { "greater", 584, NULL },
+ { "atilde", 556, NULL },
+ { "brokenbar", 280, NULL },
+ { "quoteleft", 278, NULL },
+ { "onesuperior", 333, NULL }
+};
+
+static BuiltinFontWidth helveticaBoldObliqueWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 278, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 584, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 584, NULL },
+ { "colon", 333, NULL },
+ { "onehalf", 834, NULL },
+ { "dollar", 556, NULL },
+ { "ntilde", 611, NULL },
+ { "minus", 584, NULL },
+ { "yen", 556, NULL },
+ { "space", 278, NULL },
+ { "questiondown", 611, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 722, NULL },
+ { "three", 556, NULL },
+ { "numbersign", 556, NULL },
+ { "A", 722, NULL },
+ { "B", 722, NULL },
+ { "C", 722, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 834, NULL },
+ { "F", 611, NULL },
+ { "G", 778, NULL },
+ { "H", 722, NULL },
+ { "I", 278, NULL },
+ { "J", 556, NULL },
+ { "K", 722, NULL },
+ { "backslash", 278, NULL },
+ { "L", 611, NULL },
+ { "periodcentered", 278, NULL },
+ { "M", 833, NULL },
+ { "N", 722, NULL },
+ { "O", 778, NULL },
+ { "P", 667, NULL },
+ { "Q", 778, NULL },
+ { "R", 722, NULL },
+ { "Aacute", 722, NULL },
+ { "caron", 333, NULL },
+ { "S", 667, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 556, NULL },
+ { "V", 667, NULL },
+ { "W", 944, NULL },
+ { "X", 667, NULL },
+ { "question", 611, NULL },
+ { "equal", 584, NULL },
+ { "Y", 667, NULL },
+ { "Z", 611, NULL },
+ { "four", 556, NULL },
+ { "a", 556, NULL },
+ { "b", 611, NULL },
+ { "c", 556, NULL },
+ { "d", 611, NULL },
+ { "e", 556, NULL },
+ { "f", 333, NULL },
+ { "g", 611, NULL },
+ { "bullet", 350, NULL },
+ { "h", 611, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 778, NULL },
+ { "dagger", 556, NULL },
+ { "j", 278, NULL },
+ { "k", 556, NULL },
+ { "l", 278, NULL },
+ { "m", 889, NULL },
+ { "n", 611, NULL },
+ { "o", 611, NULL },
+ { "ordfeminine", 370, NULL },
+ { "ring", 333, NULL },
+ { "p", 611, NULL },
+ { "q", 611, NULL },
+ { "r", 389, NULL },
+ { "twosuperior", 333, NULL },
+ { "aacute", 556, NULL },
+ { "s", 556, NULL },
+ { "OE", 1000, NULL },
+ { "t", 333, NULL },
+ { "divide", 584, NULL },
+ { "u", 611, NULL },
+ { "v", 556, NULL },
+ { "w", 778, NULL },
+ { "x", 556, NULL },
+ { "y", 556, NULL },
+ { "z", 500, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 474, NULL },
+ { "mu", 611, NULL },
+ { "Scaron", 667, NULL },
+ { "Lslash", 611, NULL },
+ { "semicolon", 333, NULL },
+ { "oslash", 611, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 556, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 778, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 556, NULL },
+ { "AE", 1000, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 500, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 238, NULL },
+ { "eight", 556, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 556, NULL },
+ { "oe", 944, NULL },
+ { "ecircumflex", 556, NULL },
+ { "copyright", 737, NULL },
+ { "Adieresis", 722, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 611, NULL },
+ { "Idieresis", 278, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 556, NULL },
+ { "ucircumflex", 611, NULL },
+ { "Odieresis", 778, NULL },
+ { "bracketleft", 333, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 278, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 667, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 556, NULL },
+ { "egrave", 556, NULL },
+ { "edieresis", 556, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 889, NULL },
+ { "asterisk", 389, NULL },
+ { "odieresis", 611, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 611, NULL },
+ { "nine", 556, NULL },
+ { "five", 556, NULL },
+ { "udieresis", 611, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 834, NULL },
+ { "guillemotright", 556, NULL },
+ { "ydieresis", 556, NULL },
+ { "Ccedilla", 722, NULL },
+ { "tilde", 333, NULL },
+ { "at", 975, NULL },
+ { "eacute", 556, NULL },
+ { "underscore", 556, NULL },
+ { "multiply", 584, NULL },
+ { "zero", 556, NULL },
+ { "eth", 611, NULL },
+ { "Ograve", 778, NULL },
+ { "uacute", 611, NULL },
+ { "braceleft", 389, NULL },
+ { "Thorn", 667, NULL },
+ { "zcaron", 500, NULL },
+ { "ccedilla", 556, NULL },
+ { "Ocircumflex", 778, NULL },
+ { "Oacute", 778, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 611, NULL },
+ { "thorn", 611, NULL },
+ { "degree", 400, NULL },
+ { "registered", 737, NULL },
+ { "Aring", 722, NULL },
+ { "percent", 889, NULL },
+ { "six", 556, NULL },
+ { "paragraph", 556, NULL },
+ { "two", 556, NULL },
+ { "Igrave", 278, NULL },
+ { "ocircumflex", 611, NULL },
+ { "oacute", 611, NULL },
+ { "asciicircum", 584, NULL },
+ { "aring", 556, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 333, NULL },
+ { "Iacute", 278, NULL },
+ { "ampersand", 722, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 584, NULL },
+ { "quotesinglbase", 278, NULL },
+ { "Yacute", 667, NULL },
+ { "threesuperior", 333, NULL },
+ { "acute", 333, NULL },
+ { "section", 556, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 500, NULL },
+ { "florin", 556, NULL },
+ { "yacute", 556, NULL },
+ { "fi", 611, NULL },
+ { "fl", 611, NULL },
+ { "Acircumflex", 722, NULL },
+ { "Icircumflex", 278, NULL },
+ { "guillemotleft", 556, NULL },
+ { "germandbls", 611, NULL },
+ { "seven", 556, NULL },
+ { "ordmasculine", 365, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 556, NULL },
+ { "acircumflex", 556, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 389, NULL },
+ { "quotedblright", 500, NULL },
+ { "cent", 556, NULL },
+ { "currency", 556, NULL },
+ { "logicalnot", 584, NULL },
+ { "Atilde", 722, NULL },
+ { "breve", 333, NULL },
+ { "bar", 280, NULL },
+ { "fraction", 167, NULL },
+ { "less", 584, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 333, NULL },
+ { "period", 278, NULL },
+ { "greater", 584, NULL },
+ { "atilde", 556, NULL },
+ { "brokenbar", 280, NULL },
+ { "quoteleft", 278, NULL },
+ { "onesuperior", 333, NULL }
+};
+
+static BuiltinFontWidth helveticaObliqueWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 278, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 584, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 584, NULL },
+ { "colon", 278, NULL },
+ { "onehalf", 834, NULL },
+ { "dollar", 556, NULL },
+ { "ntilde", 556, NULL },
+ { "minus", 584, NULL },
+ { "yen", 556, NULL },
+ { "space", 278, NULL },
+ { "questiondown", 611, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 667, NULL },
+ { "three", 556, NULL },
+ { "numbersign", 556, NULL },
+ { "A", 667, NULL },
+ { "B", 667, NULL },
+ { "C", 722, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 834, NULL },
+ { "F", 611, NULL },
+ { "G", 778, NULL },
+ { "H", 722, NULL },
+ { "I", 278, NULL },
+ { "J", 500, NULL },
+ { "K", 667, NULL },
+ { "backslash", 278, NULL },
+ { "L", 556, NULL },
+ { "periodcentered", 278, NULL },
+ { "M", 833, NULL },
+ { "N", 722, NULL },
+ { "O", 778, NULL },
+ { "P", 667, NULL },
+ { "Q", 778, NULL },
+ { "R", 722, NULL },
+ { "Aacute", 667, NULL },
+ { "caron", 333, NULL },
+ { "S", 667, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 556, NULL },
+ { "V", 667, NULL },
+ { "W", 944, NULL },
+ { "X", 667, NULL },
+ { "question", 556, NULL },
+ { "equal", 584, NULL },
+ { "Y", 667, NULL },
+ { "Z", 611, NULL },
+ { "four", 556, NULL },
+ { "a", 556, NULL },
+ { "b", 556, NULL },
+ { "c", 500, NULL },
+ { "d", 556, NULL },
+ { "e", 556, NULL },
+ { "f", 278, NULL },
+ { "g", 556, NULL },
+ { "bullet", 350, NULL },
+ { "h", 556, NULL },
+ { "i", 222, NULL },
+ { "Oslash", 778, NULL },
+ { "dagger", 556, NULL },
+ { "j", 222, NULL },
+ { "k", 500, NULL },
+ { "l", 222, NULL },
+ { "m", 833, NULL },
+ { "n", 556, NULL },
+ { "o", 556, NULL },
+ { "ordfeminine", 370, NULL },
+ { "ring", 333, NULL },
+ { "p", 556, NULL },
+ { "q", 556, NULL },
+ { "r", 333, NULL },
+ { "twosuperior", 333, NULL },
+ { "aacute", 556, NULL },
+ { "s", 500, NULL },
+ { "OE", 1000, NULL },
+ { "t", 278, NULL },
+ { "divide", 584, NULL },
+ { "u", 556, NULL },
+ { "v", 500, NULL },
+ { "w", 722, NULL },
+ { "x", 500, NULL },
+ { "y", 500, NULL },
+ { "z", 500, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 355, NULL },
+ { "mu", 556, NULL },
+ { "Scaron", 667, NULL },
+ { "Lslash", 556, NULL },
+ { "semicolon", 278, NULL },
+ { "oslash", 611, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 556, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 778, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 500, NULL },
+ { "AE", 1000, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 222, NULL },
+ { "quotedblleft", 333, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 191, NULL },
+ { "eight", 556, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 556, NULL },
+ { "oe", 944, NULL },
+ { "ecircumflex", 556, NULL },
+ { "copyright", 737, NULL },
+ { "Adieresis", 667, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 556, NULL },
+ { "Idieresis", 278, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 556, NULL },
+ { "ucircumflex", 556, NULL },
+ { "Odieresis", 778, NULL },
+ { "bracketleft", 278, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 222, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 667, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 556, NULL },
+ { "egrave", 556, NULL },
+ { "edieresis", 556, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 889, NULL },
+ { "asterisk", 389, NULL },
+ { "odieresis", 556, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 556, NULL },
+ { "nine", 556, NULL },
+ { "five", 556, NULL },
+ { "udieresis", 556, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 834, NULL },
+ { "guillemotright", 556, NULL },
+ { "ydieresis", 500, NULL },
+ { "Ccedilla", 722, NULL },
+ { "tilde", 333, NULL },
+ { "at", 1015, NULL },
+ { "eacute", 556, NULL },
+ { "underscore", 556, NULL },
+ { "multiply", 584, NULL },
+ { "zero", 556, NULL },
+ { "eth", 556, NULL },
+ { "Ograve", 778, NULL },
+ { "uacute", 556, NULL },
+ { "braceleft", 334, NULL },
+ { "Thorn", 667, NULL },
+ { "zcaron", 500, NULL },
+ { "ccedilla", 500, NULL },
+ { "Ocircumflex", 778, NULL },
+ { "Oacute", 778, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 556, NULL },
+ { "thorn", 556, NULL },
+ { "degree", 400, NULL },
+ { "registered", 737, NULL },
+ { "Aring", 667, NULL },
+ { "percent", 889, NULL },
+ { "six", 556, NULL },
+ { "paragraph", 537, NULL },
+ { "two", 556, NULL },
+ { "Igrave", 278, NULL },
+ { "ocircumflex", 556, NULL },
+ { "oacute", 556, NULL },
+ { "asciicircum", 469, NULL },
+ { "aring", 556, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 278, NULL },
+ { "Iacute", 278, NULL },
+ { "ampersand", 667, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 584, NULL },
+ { "quotesinglbase", 222, NULL },
+ { "Yacute", 667, NULL },
+ { "threesuperior", 333, NULL },
+ { "acute", 333, NULL },
+ { "section", 556, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 333, NULL },
+ { "florin", 556, NULL },
+ { "yacute", 500, NULL },
+ { "fi", 500, NULL },
+ { "fl", 500, NULL },
+ { "Acircumflex", 667, NULL },
+ { "Icircumflex", 278, NULL },
+ { "guillemotleft", 556, NULL },
+ { "germandbls", 611, NULL },
+ { "seven", 556, NULL },
+ { "ordmasculine", 365, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 556, NULL },
+ { "acircumflex", 556, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 334, NULL },
+ { "quotedblright", 333, NULL },
+ { "cent", 556, NULL },
+ { "currency", 556, NULL },
+ { "logicalnot", 584, NULL },
+ { "Atilde", 667, NULL },
+ { "breve", 333, NULL },
+ { "bar", 260, NULL },
+ { "fraction", 167, NULL },
+ { "less", 584, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 278, NULL },
+ { "period", 278, NULL },
+ { "greater", 584, NULL },
+ { "atilde", 556, NULL },
+ { "brokenbar", 260, NULL },
+ { "quoteleft", 222, NULL },
+ { "onesuperior", 333, NULL }
+};
+
+static BuiltinFontWidth symbolWidthsTab[] = {
+ { "bracketleftex", 384, NULL },
+ { "alpha", 631, NULL },
+ { "union", 768, NULL },
+ { "infinity", 713, NULL },
+ { "comma", 250, NULL },
+ { "copyrightsans", 790, NULL },
+ { "plusminus", 549, NULL },
+ { "arrowup", 603, NULL },
+ { "apple", 790, NULL },
+ { "parenleftbt", 384, NULL },
+ { "notelement", 713, NULL },
+ { "colon", 278, NULL },
+ { "beta", 549, NULL },
+ { "braceleftbt", 494, NULL },
+ { "Lambda", 686, NULL },
+ { "Phi", 763, NULL },
+ { "minus", 549, NULL },
+ { "space", 250, NULL },
+ { "Sigma", 592, NULL },
+ { "approxequal", 549, NULL },
+ { "minute", 247, NULL },
+ { "circleplus", 768, NULL },
+ { "Omicron", 722, NULL },
+ { "three", 500, NULL },
+ { "numbersign", 500, NULL },
+ { "lambda", 549, NULL },
+ { "phi", 521, NULL },
+ { "aleph", 823, NULL },
+ { "Tau", 611, NULL },
+ { "spade", 753, NULL },
+ { "logicaland", 603, NULL },
+ { "sigma", 603, NULL },
+ { "propersuperset", 713, NULL },
+ { "omicron", 549, NULL },
+ { "question", 444, NULL },
+ { "equal", 549, NULL },
+ { "Epsilon", 611, NULL },
+ { "emptyset", 823, NULL },
+ { "diamond", 753, NULL },
+ { "four", 500, NULL },
+ { "Mu", 889, NULL },
+ { "parenlefttp", 384, NULL },
+ { "club", 753, NULL },
+ { "bullet", 460, NULL },
+ { "Omega", 768, NULL },
+ { "tau", 439, NULL },
+ { "Upsilon", 690, NULL },
+ { "bracelefttp", 494, NULL },
+ { "heart", 753, NULL },
+ { "divide", 549, NULL },
+ { "epsilon", 439, NULL },
+ { "logicalor", 603, NULL },
+ { "parenleftex", 384, NULL },
+ { "greaterequal", 549, NULL },
+ { "mu", 576, NULL },
+ { "Nu", 722, NULL },
+ { "therefore", 863, NULL },
+ { "notsubset", 713, NULL },
+ { "omega", 686, NULL },
+ { "semicolon", 278, NULL },
+ { "element", 713, NULL },
+ { "upsilon", 576, NULL },
+ { "existential", 549, NULL },
+ { "integralbt", 686, NULL },
+ { "lessequal", 549, NULL },
+ { "phi1", 603, NULL },
+ { "lozenge", 494, NULL },
+ { "trademarkserif", 890, NULL },
+ { "parenright", 333, NULL },
+ { "reflexsuperset", 713, NULL },
+ { "sigma1", 439, NULL },
+ { "nu", 521, NULL },
+ { "Gamma", 603, NULL },
+ { "angleright", 329, NULL },
+ { "ellipsis", 1000, NULL },
+ { "Rho", 556, NULL },
+ { "parenrightbt", 384, NULL },
+ { "radicalex", 500, NULL },
+ { "eight", 500, NULL },
+ { "angleleft", 329, NULL },
+ { "arrowdbldown", 603, NULL },
+ { "congruent", 549, NULL },
+ { "Theta", 741, NULL },
+ { "intersection", 768, NULL },
+ { "Pi", 768, NULL },
+ { "slash", 278, NULL },
+ { "registerserif", 790, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 500, NULL },
+ { "gamma", 411, NULL },
+ { "bracketleft", 333, NULL },
+ { "rho", 549, NULL },
+ { "circlemultiply", 768, NULL },
+ { "Chi", 722, NULL },
+ { "theta", 521, NULL },
+ { "pi", 549, NULL },
+ { "integraltp", 686, NULL },
+ { "Eta", 722, NULL },
+ { "product", 823, NULL },
+ { "nine", 500, NULL },
+ { "five", 500, NULL },
+ { "propersubset", 713, NULL },
+ { "bracketrightbt", 384, NULL },
+ { "trademarksans", 786, NULL },
+ { "dotmath", 250, NULL },
+ { "integralex", 686, NULL },
+ { "chi", 549, NULL },
+ { "parenrighttp", 384, NULL },
+ { "eta", 603, NULL },
+ { "underscore", 500, NULL },
+ { "multiply", 549, NULL },
+ { "zero", 500, NULL },
+ { "partialdiff", 494, NULL },
+ { "angle", 768, NULL },
+ { "arrowdblleft", 987, NULL },
+ { "braceleft", 480, NULL },
+ { "parenrightex", 384, NULL },
+ { "Rfraktur", 795, NULL },
+ { "Zeta", 611, NULL },
+ { "braceex", 494, NULL },
+ { "arrowdblup", 603, NULL },
+ { "arrowdown", 603, NULL },
+ { "Ifraktur", 686, NULL },
+ { "degree", 400, NULL },
+ { "Iota", 333, NULL },
+ { "perpendicular", 658, NULL },
+ { "radical", 549, NULL },
+ { "asteriskmath", 500, NULL },
+ { "percent", 833, NULL },
+ { "zeta", 494, NULL },
+ { "six", 500, NULL },
+ { "two", 500, NULL },
+ { "weierstrass", 987, NULL },
+ { "summation", 713, NULL },
+ { "bracketrighttp", 384, NULL },
+ { "carriagereturn", 658, NULL },
+ { "suchthat", 439, NULL },
+ { "arrowvertex", 603, NULL },
+ { "Delta", 612, NULL },
+ { "iota", 329, NULL },
+ { "arrowhorizex", 1000, NULL },
+ { "bracketrightex", 384, NULL },
+ { "bracketright", 333, NULL },
+ { "ampersand", 778, NULL },
+ { "plus", 549, NULL },
+ { "proportional", 713, NULL },
+ { "delta", 494, NULL },
+ { "copyrightserif", 790, NULL },
+ { "bracerightmid", 494, NULL },
+ { "arrowleft", 987, NULL },
+ { "second", 411, NULL },
+ { "arrowdblboth", 1042, NULL },
+ { "florin", 500, NULL },
+ { "Psi", 795, NULL },
+ { "bracerightbt", 494, NULL },
+ { "bracketleftbt", 384, NULL },
+ { "seven", 500, NULL },
+ { "braceleftmid", 494, NULL },
+ { "notequal", 549, NULL },
+ { "psi", 686, NULL },
+ { "equivalence", 549, NULL },
+ { "universal", 713, NULL },
+ { "arrowdblright", 987, NULL },
+ { "braceright", 480, NULL },
+ { "reflexsubset", 713, NULL },
+ { "Xi", 645, NULL },
+ { "theta1", 631, NULL },
+ { "logicalnot", 713, NULL },
+ { "Kappa", 722, NULL },
+ { "similar", 549, NULL },
+ { "bar", 200, NULL },
+ { "fraction", 167, NULL },
+ { "less", 549, NULL },
+ { "registersans", 790, NULL },
+ { "omega1", 713, NULL },
+ { "exclam", 333, NULL },
+ { "Upsilon1", 620, NULL },
+ { "bracerighttp", 494, NULL },
+ { "xi", 493, NULL },
+ { "period", 250, NULL },
+ { "Alpha", 722, NULL },
+ { "arrowright", 987, NULL },
+ { "greater", 549, NULL },
+ { "bracketlefttp", 384, NULL },
+ { "kappa", 549, NULL },
+ { "gradient", 713, NULL },
+ { "integral", 274, NULL },
+ { "arrowboth", 1042, NULL },
+ { "Beta", 667, NULL }
+};
+
+static BuiltinFontWidth timesBoldWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 250, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 570, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 520, NULL },
+ { "colon", 333, NULL },
+ { "onehalf", 750, NULL },
+ { "dollar", 500, NULL },
+ { "ntilde", 556, NULL },
+ { "minus", 570, NULL },
+ { "yen", 500, NULL },
+ { "space", 250, NULL },
+ { "questiondown", 500, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 722, NULL },
+ { "three", 500, NULL },
+ { "numbersign", 500, NULL },
+ { "A", 722, NULL },
+ { "B", 667, NULL },
+ { "C", 722, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 750, NULL },
+ { "F", 611, NULL },
+ { "G", 778, NULL },
+ { "H", 778, NULL },
+ { "I", 389, NULL },
+ { "J", 500, NULL },
+ { "K", 778, NULL },
+ { "backslash", 278, NULL },
+ { "L", 667, NULL },
+ { "periodcentered", 250, NULL },
+ { "M", 944, NULL },
+ { "N", 722, NULL },
+ { "O", 778, NULL },
+ { "P", 611, NULL },
+ { "Q", 778, NULL },
+ { "R", 722, NULL },
+ { "Aacute", 722, NULL },
+ { "caron", 333, NULL },
+ { "S", 556, NULL },
+ { "T", 667, NULL },
+ { "U", 722, NULL },
+ { "agrave", 500, NULL },
+ { "V", 722, NULL },
+ { "W", 1000, NULL },
+ { "X", 722, NULL },
+ { "question", 500, NULL },
+ { "equal", 570, NULL },
+ { "Y", 722, NULL },
+ { "Z", 667, NULL },
+ { "four", 500, NULL },
+ { "a", 500, NULL },
+ { "b", 556, NULL },
+ { "c", 444, NULL },
+ { "d", 556, NULL },
+ { "e", 444, NULL },
+ { "f", 333, NULL },
+ { "g", 500, NULL },
+ { "bullet", 350, NULL },
+ { "h", 556, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 778, NULL },
+ { "dagger", 500, NULL },
+ { "j", 333, NULL },
+ { "k", 556, NULL },
+ { "l", 278, NULL },
+ { "m", 833, NULL },
+ { "n", 556, NULL },
+ { "o", 500, NULL },
+ { "ordfeminine", 300, NULL },
+ { "ring", 333, NULL },
+ { "p", 556, NULL },
+ { "q", 556, NULL },
+ { "r", 444, NULL },
+ { "twosuperior", 300, NULL },
+ { "aacute", 500, NULL },
+ { "s", 389, NULL },
+ { "OE", 1000, NULL },
+ { "t", 333, NULL },
+ { "divide", 570, NULL },
+ { "u", 556, NULL },
+ { "v", 500, NULL },
+ { "w", 722, NULL },
+ { "x", 500, NULL },
+ { "y", 500, NULL },
+ { "z", 444, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 555, NULL },
+ { "mu", 556, NULL },
+ { "Scaron", 556, NULL },
+ { "Lslash", 667, NULL },
+ { "semicolon", 333, NULL },
+ { "oslash", 500, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 500, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 778, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 389, NULL },
+ { "AE", 1000, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 500, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 278, NULL },
+ { "eight", 500, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 500, NULL },
+ { "oe", 722, NULL },
+ { "ecircumflex", 444, NULL },
+ { "copyright", 747, NULL },
+ { "Adieresis", 722, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 500, NULL },
+ { "Idieresis", 389, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 500, NULL },
+ { "ucircumflex", 556, NULL },
+ { "Odieresis", 778, NULL },
+ { "bracketleft", 333, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 333, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 722, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 500, NULL },
+ { "egrave", 444, NULL },
+ { "edieresis", 444, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 722, NULL },
+ { "asterisk", 500, NULL },
+ { "odieresis", 500, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 556, NULL },
+ { "nine", 500, NULL },
+ { "five", 500, NULL },
+ { "udieresis", 556, NULL },
+ { "Zcaron", 667, NULL },
+ { "threequarters", 750, NULL },
+ { "guillemotright", 500, NULL },
+ { "ydieresis", 500, NULL },
+ { "Ccedilla", 722, NULL },
+ { "tilde", 333, NULL },
+ { "at", 930, NULL },
+ { "eacute", 444, NULL },
+ { "underscore", 500, NULL },
+ { "multiply", 570, NULL },
+ { "zero", 500, NULL },
+ { "eth", 500, NULL },
+ { "Ograve", 778, NULL },
+ { "uacute", 556, NULL },
+ { "braceleft", 394, NULL },
+ { "Thorn", 611, NULL },
+ { "zcaron", 444, NULL },
+ { "ccedilla", 444, NULL },
+ { "Ocircumflex", 778, NULL },
+ { "Oacute", 778, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 500, NULL },
+ { "thorn", 556, NULL },
+ { "degree", 400, NULL },
+ { "registered", 747, NULL },
+ { "Aring", 722, NULL },
+ { "percent", 1000, NULL },
+ { "six", 500, NULL },
+ { "paragraph", 540, NULL },
+ { "two", 500, NULL },
+ { "Igrave", 389, NULL },
+ { "ocircumflex", 500, NULL },
+ { "oacute", 500, NULL },
+ { "asciicircum", 581, NULL },
+ { "aring", 500, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 333, NULL },
+ { "Iacute", 389, NULL },
+ { "ampersand", 833, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 570, NULL },
+ { "quotesinglbase", 333, NULL },
+ { "Yacute", 722, NULL },
+ { "threesuperior", 300, NULL },
+ { "acute", 333, NULL },
+ { "section", 500, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 500, NULL },
+ { "florin", 500, NULL },
+ { "yacute", 500, NULL },
+ { "fi", 556, NULL },
+ { "fl", 556, NULL },
+ { "Acircumflex", 722, NULL },
+ { "Icircumflex", 389, NULL },
+ { "guillemotleft", 500, NULL },
+ { "germandbls", 556, NULL },
+ { "seven", 500, NULL },
+ { "ordmasculine", 330, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 500, NULL },
+ { "acircumflex", 500, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 394, NULL },
+ { "quotedblright", 500, NULL },
+ { "cent", 500, NULL },
+ { "currency", 500, NULL },
+ { "logicalnot", 570, NULL },
+ { "Atilde", 722, NULL },
+ { "breve", 333, NULL },
+ { "bar", 220, NULL },
+ { "fraction", 167, NULL },
+ { "less", 570, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 333, NULL },
+ { "period", 250, NULL },
+ { "greater", 570, NULL },
+ { "atilde", 500, NULL },
+ { "brokenbar", 220, NULL },
+ { "quoteleft", 333, NULL },
+ { "onesuperior", 300, NULL }
+};
+
+static BuiltinFontWidth timesBoldItalicWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 250, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 570, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 570, NULL },
+ { "colon", 333, NULL },
+ { "onehalf", 750, NULL },
+ { "dollar", 500, NULL },
+ { "ntilde", 556, NULL },
+ { "minus", 606, NULL },
+ { "yen", 500, NULL },
+ { "space", 250, NULL },
+ { "questiondown", 500, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 667, NULL },
+ { "three", 500, NULL },
+ { "numbersign", 500, NULL },
+ { "A", 667, NULL },
+ { "B", 667, NULL },
+ { "C", 667, NULL },
+ { "D", 722, NULL },
+ { "E", 667, NULL },
+ { "onequarter", 750, NULL },
+ { "F", 667, NULL },
+ { "G", 722, NULL },
+ { "H", 778, NULL },
+ { "I", 389, NULL },
+ { "J", 500, NULL },
+ { "K", 667, NULL },
+ { "backslash", 278, NULL },
+ { "L", 611, NULL },
+ { "periodcentered", 250, NULL },
+ { "M", 889, NULL },
+ { "N", 722, NULL },
+ { "O", 722, NULL },
+ { "P", 611, NULL },
+ { "Q", 722, NULL },
+ { "R", 667, NULL },
+ { "Aacute", 667, NULL },
+ { "caron", 333, NULL },
+ { "S", 556, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 500, NULL },
+ { "V", 667, NULL },
+ { "W", 889, NULL },
+ { "X", 667, NULL },
+ { "question", 500, NULL },
+ { "equal", 570, NULL },
+ { "Y", 611, NULL },
+ { "Z", 611, NULL },
+ { "four", 500, NULL },
+ { "a", 500, NULL },
+ { "b", 500, NULL },
+ { "c", 444, NULL },
+ { "d", 500, NULL },
+ { "e", 444, NULL },
+ { "f", 333, NULL },
+ { "g", 500, NULL },
+ { "bullet", 350, NULL },
+ { "h", 556, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 722, NULL },
+ { "dagger", 500, NULL },
+ { "j", 278, NULL },
+ { "k", 500, NULL },
+ { "l", 278, NULL },
+ { "m", 778, NULL },
+ { "n", 556, NULL },
+ { "o", 500, NULL },
+ { "ordfeminine", 266, NULL },
+ { "ring", 333, NULL },
+ { "p", 500, NULL },
+ { "q", 500, NULL },
+ { "r", 389, NULL },
+ { "twosuperior", 300, NULL },
+ { "aacute", 500, NULL },
+ { "s", 389, NULL },
+ { "OE", 944, NULL },
+ { "t", 278, NULL },
+ { "divide", 570, NULL },
+ { "u", 556, NULL },
+ { "v", 444, NULL },
+ { "w", 667, NULL },
+ { "x", 500, NULL },
+ { "y", 444, NULL },
+ { "z", 389, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 555, NULL },
+ { "mu", 576, NULL },
+ { "Scaron", 556, NULL },
+ { "Lslash", 611, NULL },
+ { "semicolon", 333, NULL },
+ { "oslash", 500, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 667, NULL },
+ { "trademark", 1000, NULL },
+ { "daggerdbl", 500, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 722, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 389, NULL },
+ { "AE", 944, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 500, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 278, NULL },
+ { "eight", 500, NULL },
+ { "exclamdown", 389, NULL },
+ { "endash", 500, NULL },
+ { "oe", 722, NULL },
+ { "ecircumflex", 444, NULL },
+ { "copyright", 747, NULL },
+ { "Adieresis", 667, NULL },
+ { "Egrave", 667, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 667, NULL },
+ { "otilde", 500, NULL },
+ { "Idieresis", 389, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 500, NULL },
+ { "ucircumflex", 556, NULL },
+ { "Odieresis", 722, NULL },
+ { "bracketleft", 333, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 333, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 611, NULL },
+ { "Eacute", 667, NULL },
+ { "adieresis", 500, NULL },
+ { "egrave", 444, NULL },
+ { "edieresis", 444, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 722, NULL },
+ { "asterisk", 500, NULL },
+ { "odieresis", 500, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 556, NULL },
+ { "nine", 500, NULL },
+ { "five", 500, NULL },
+ { "udieresis", 556, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 750, NULL },
+ { "guillemotright", 500, NULL },
+ { "ydieresis", 444, NULL },
+ { "Ccedilla", 667, NULL },
+ { "tilde", 333, NULL },
+ { "at", 832, NULL },
+ { "eacute", 444, NULL },
+ { "underscore", 500, NULL },
+ { "multiply", 570, NULL },
+ { "zero", 500, NULL },
+ { "eth", 500, NULL },
+ { "Ograve", 722, NULL },
+ { "uacute", 556, NULL },
+ { "braceleft", 348, NULL },
+ { "Thorn", 611, NULL },
+ { "zcaron", 389, NULL },
+ { "ccedilla", 444, NULL },
+ { "Ocircumflex", 722, NULL },
+ { "Oacute", 722, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 500, NULL },
+ { "thorn", 500, NULL },
+ { "degree", 400, NULL },
+ { "registered", 747, NULL },
+ { "Aring", 667, NULL },
+ { "percent", 833, NULL },
+ { "six", 500, NULL },
+ { "paragraph", 500, NULL },
+ { "two", 500, NULL },
+ { "Igrave", 389, NULL },
+ { "ocircumflex", 500, NULL },
+ { "oacute", 500, NULL },
+ { "asciicircum", 570, NULL },
+ { "aring", 500, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 333, NULL },
+ { "Iacute", 389, NULL },
+ { "ampersand", 778, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 570, NULL },
+ { "quotesinglbase", 333, NULL },
+ { "Yacute", 611, NULL },
+ { "threesuperior", 300, NULL },
+ { "acute", 333, NULL },
+ { "section", 500, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 500, NULL },
+ { "florin", 500, NULL },
+ { "yacute", 444, NULL },
+ { "fi", 556, NULL },
+ { "fl", 556, NULL },
+ { "Acircumflex", 667, NULL },
+ { "Icircumflex", 389, NULL },
+ { "guillemotleft", 500, NULL },
+ { "germandbls", 500, NULL },
+ { "seven", 500, NULL },
+ { "ordmasculine", 300, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 500, NULL },
+ { "acircumflex", 500, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 348, NULL },
+ { "quotedblright", 500, NULL },
+ { "cent", 500, NULL },
+ { "currency", 500, NULL },
+ { "logicalnot", 606, NULL },
+ { "Atilde", 667, NULL },
+ { "breve", 333, NULL },
+ { "bar", 220, NULL },
+ { "fraction", 167, NULL },
+ { "less", 570, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 389, NULL },
+ { "period", 250, NULL },
+ { "greater", 570, NULL },
+ { "atilde", 500, NULL },
+ { "brokenbar", 220, NULL },
+ { "quoteleft", 333, NULL },
+ { "onesuperior", 300, NULL }
+};
+
+static BuiltinFontWidth timesItalicWidthsTab[] = {
+ { "Ntilde", 667, NULL },
+ { "comma", 250, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 675, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 541, NULL },
+ { "colon", 333, NULL },
+ { "onehalf", 750, NULL },
+ { "dollar", 500, NULL },
+ { "ntilde", 500, NULL },
+ { "minus", 675, NULL },
+ { "yen", 500, NULL },
+ { "space", 250, NULL },
+ { "questiondown", 500, NULL },
+ { "emdash", 889, NULL },
+ { "Agrave", 611, NULL },
+ { "three", 500, NULL },
+ { "numbersign", 500, NULL },
+ { "A", 611, NULL },
+ { "B", 611, NULL },
+ { "C", 667, NULL },
+ { "D", 722, NULL },
+ { "E", 611, NULL },
+ { "onequarter", 750, NULL },
+ { "F", 611, NULL },
+ { "G", 722, NULL },
+ { "H", 722, NULL },
+ { "I", 333, NULL },
+ { "J", 444, NULL },
+ { "K", 667, NULL },
+ { "backslash", 278, NULL },
+ { "L", 556, NULL },
+ { "periodcentered", 250, NULL },
+ { "M", 833, NULL },
+ { "N", 667, NULL },
+ { "O", 722, NULL },
+ { "P", 611, NULL },
+ { "Q", 722, NULL },
+ { "R", 611, NULL },
+ { "Aacute", 611, NULL },
+ { "caron", 333, NULL },
+ { "S", 500, NULL },
+ { "T", 556, NULL },
+ { "U", 722, NULL },
+ { "agrave", 500, NULL },
+ { "V", 611, NULL },
+ { "W", 833, NULL },
+ { "X", 611, NULL },
+ { "question", 500, NULL },
+ { "equal", 675, NULL },
+ { "Y", 556, NULL },
+ { "Z", 556, NULL },
+ { "four", 500, NULL },
+ { "a", 500, NULL },
+ { "b", 500, NULL },
+ { "c", 444, NULL },
+ { "d", 500, NULL },
+ { "e", 444, NULL },
+ { "f", 278, NULL },
+ { "g", 500, NULL },
+ { "bullet", 350, NULL },
+ { "h", 500, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 722, NULL },
+ { "dagger", 500, NULL },
+ { "j", 278, NULL },
+ { "k", 444, NULL },
+ { "l", 278, NULL },
+ { "m", 722, NULL },
+ { "n", 500, NULL },
+ { "o", 500, NULL },
+ { "ordfeminine", 276, NULL },
+ { "ring", 333, NULL },
+ { "p", 500, NULL },
+ { "q", 500, NULL },
+ { "r", 389, NULL },
+ { "twosuperior", 300, NULL },
+ { "aacute", 500, NULL },
+ { "s", 389, NULL },
+ { "OE", 944, NULL },
+ { "t", 278, NULL },
+ { "divide", 675, NULL },
+ { "u", 500, NULL },
+ { "v", 444, NULL },
+ { "w", 667, NULL },
+ { "x", 444, NULL },
+ { "y", 444, NULL },
+ { "z", 389, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 420, NULL },
+ { "mu", 500, NULL },
+ { "Scaron", 500, NULL },
+ { "Lslash", 556, NULL },
+ { "semicolon", 333, NULL },
+ { "oslash", 500, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 611, NULL },
+ { "trademark", 980, NULL },
+ { "daggerdbl", 500, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 722, NULL },
+ { "ellipsis", 889, NULL },
+ { "scaron", 389, NULL },
+ { "AE", 889, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 556, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 214, NULL },
+ { "eight", 500, NULL },
+ { "exclamdown", 389, NULL },
+ { "endash", 500, NULL },
+ { "oe", 667, NULL },
+ { "ecircumflex", 444, NULL },
+ { "copyright", 760, NULL },
+ { "Adieresis", 611, NULL },
+ { "Egrave", 611, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 611, NULL },
+ { "otilde", 500, NULL },
+ { "Idieresis", 333, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 500, NULL },
+ { "ucircumflex", 500, NULL },
+ { "Odieresis", 722, NULL },
+ { "bracketleft", 389, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 333, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 556, NULL },
+ { "Eacute", 611, NULL },
+ { "adieresis", 500, NULL },
+ { "egrave", 444, NULL },
+ { "edieresis", 444, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 667, NULL },
+ { "asterisk", 500, NULL },
+ { "odieresis", 500, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 500, NULL },
+ { "nine", 500, NULL },
+ { "five", 500, NULL },
+ { "udieresis", 500, NULL },
+ { "Zcaron", 556, NULL },
+ { "threequarters", 750, NULL },
+ { "guillemotright", 500, NULL },
+ { "ydieresis", 444, NULL },
+ { "Ccedilla", 667, NULL },
+ { "tilde", 333, NULL },
+ { "at", 920, NULL },
+ { "eacute", 444, NULL },
+ { "underscore", 500, NULL },
+ { "multiply", 675, NULL },
+ { "zero", 500, NULL },
+ { "eth", 500, NULL },
+ { "Ograve", 722, NULL },
+ { "uacute", 500, NULL },
+ { "braceleft", 400, NULL },
+ { "Thorn", 611, NULL },
+ { "zcaron", 389, NULL },
+ { "ccedilla", 444, NULL },
+ { "Ocircumflex", 722, NULL },
+ { "Oacute", 722, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 500, NULL },
+ { "thorn", 500, NULL },
+ { "degree", 400, NULL },
+ { "registered", 760, NULL },
+ { "Aring", 611, NULL },
+ { "percent", 833, NULL },
+ { "six", 500, NULL },
+ { "paragraph", 523, NULL },
+ { "two", 500, NULL },
+ { "Igrave", 333, NULL },
+ { "ocircumflex", 500, NULL },
+ { "oacute", 500, NULL },
+ { "asciicircum", 422, NULL },
+ { "aring", 500, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 389, NULL },
+ { "Iacute", 333, NULL },
+ { "ampersand", 778, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 675, NULL },
+ { "quotesinglbase", 333, NULL },
+ { "Yacute", 556, NULL },
+ { "threesuperior", 300, NULL },
+ { "acute", 333, NULL },
+ { "section", 500, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 556, NULL },
+ { "florin", 500, NULL },
+ { "yacute", 444, NULL },
+ { "fi", 500, NULL },
+ { "fl", 500, NULL },
+ { "Acircumflex", 611, NULL },
+ { "Icircumflex", 333, NULL },
+ { "guillemotleft", 500, NULL },
+ { "germandbls", 500, NULL },
+ { "seven", 500, NULL },
+ { "ordmasculine", 310, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 500, NULL },
+ { "acircumflex", 500, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 400, NULL },
+ { "quotedblright", 556, NULL },
+ { "cent", 500, NULL },
+ { "currency", 500, NULL },
+ { "logicalnot", 675, NULL },
+ { "Atilde", 611, NULL },
+ { "breve", 333, NULL },
+ { "bar", 275, NULL },
+ { "fraction", 167, NULL },
+ { "less", 675, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 333, NULL },
+ { "period", 250, NULL },
+ { "greater", 675, NULL },
+ { "atilde", 500, NULL },
+ { "brokenbar", 275, NULL },
+ { "quoteleft", 333, NULL },
+ { "onesuperior", 300, NULL }
+};
+
+static BuiltinFontWidth timesRomanWidthsTab[] = {
+ { "Ntilde", 722, NULL },
+ { "comma", 250, NULL },
+ { "cedilla", 333, NULL },
+ { "plusminus", 564, NULL },
+ { "circumflex", 333, NULL },
+ { "dotaccent", 333, NULL },
+ { "asciitilde", 541, NULL },
+ { "colon", 278, NULL },
+ { "onehalf", 750, NULL },
+ { "dollar", 500, NULL },
+ { "ntilde", 500, NULL },
+ { "minus", 564, NULL },
+ { "yen", 500, NULL },
+ { "space", 250, NULL },
+ { "questiondown", 444, NULL },
+ { "emdash", 1000, NULL },
+ { "Agrave", 722, NULL },
+ { "three", 500, NULL },
+ { "numbersign", 500, NULL },
+ { "A", 722, NULL },
+ { "B", 667, NULL },
+ { "C", 667, NULL },
+ { "D", 722, NULL },
+ { "E", 611, NULL },
+ { "onequarter", 750, NULL },
+ { "F", 556, NULL },
+ { "G", 722, NULL },
+ { "H", 722, NULL },
+ { "I", 333, NULL },
+ { "J", 389, NULL },
+ { "K", 722, NULL },
+ { "backslash", 278, NULL },
+ { "L", 611, NULL },
+ { "periodcentered", 250, NULL },
+ { "M", 889, NULL },
+ { "N", 722, NULL },
+ { "O", 722, NULL },
+ { "P", 556, NULL },
+ { "Q", 722, NULL },
+ { "R", 667, NULL },
+ { "Aacute", 722, NULL },
+ { "caron", 333, NULL },
+ { "S", 556, NULL },
+ { "T", 611, NULL },
+ { "U", 722, NULL },
+ { "agrave", 444, NULL },
+ { "V", 722, NULL },
+ { "W", 944, NULL },
+ { "X", 722, NULL },
+ { "question", 444, NULL },
+ { "equal", 564, NULL },
+ { "Y", 722, NULL },
+ { "Z", 611, NULL },
+ { "four", 500, NULL },
+ { "a", 444, NULL },
+ { "b", 500, NULL },
+ { "c", 444, NULL },
+ { "d", 500, NULL },
+ { "e", 444, NULL },
+ { "f", 333, NULL },
+ { "g", 500, NULL },
+ { "bullet", 350, NULL },
+ { "h", 500, NULL },
+ { "i", 278, NULL },
+ { "Oslash", 722, NULL },
+ { "dagger", 500, NULL },
+ { "j", 278, NULL },
+ { "k", 500, NULL },
+ { "l", 278, NULL },
+ { "m", 778, NULL },
+ { "n", 500, NULL },
+ { "o", 500, NULL },
+ { "ordfeminine", 276, NULL },
+ { "ring", 333, NULL },
+ { "p", 500, NULL },
+ { "q", 500, NULL },
+ { "r", 333, NULL },
+ { "twosuperior", 300, NULL },
+ { "aacute", 444, NULL },
+ { "s", 389, NULL },
+ { "OE", 889, NULL },
+ { "t", 278, NULL },
+ { "divide", 564, NULL },
+ { "u", 500, NULL },
+ { "v", 500, NULL },
+ { "w", 722, NULL },
+ { "x", 500, NULL },
+ { "y", 500, NULL },
+ { "z", 444, NULL },
+ { "hungarumlaut", 333, NULL },
+ { "quotedbl", 408, NULL },
+ { "mu", 500, NULL },
+ { "Scaron", 556, NULL },
+ { "Lslash", 611, NULL },
+ { "semicolon", 278, NULL },
+ { "oslash", 500, NULL },
+ { "parenright", 333, NULL },
+ { "Ecircumflex", 611, NULL },
+ { "trademark", 980, NULL },
+ { "daggerdbl", 500, NULL },
+ { "macron", 333, NULL },
+ { "Otilde", 722, NULL },
+ { "ellipsis", 1000, NULL },
+ { "scaron", 389, NULL },
+ { "AE", 889, NULL },
+ { "Ucircumflex", 722, NULL },
+ { "lslash", 278, NULL },
+ { "quotedblleft", 444, NULL },
+ { "guilsinglright", 333, NULL },
+ { "hyphen", 333, NULL },
+ { "quotesingle", 180, NULL },
+ { "eight", 500, NULL },
+ { "exclamdown", 333, NULL },
+ { "endash", 500, NULL },
+ { "oe", 722, NULL },
+ { "ecircumflex", 444, NULL },
+ { "copyright", 760, NULL },
+ { "Adieresis", 722, NULL },
+ { "Egrave", 611, NULL },
+ { "slash", 278, NULL },
+ { "Edieresis", 611, NULL },
+ { "otilde", 500, NULL },
+ { "Idieresis", 333, NULL },
+ { "parenleft", 333, NULL },
+ { "one", 500, NULL },
+ { "ucircumflex", 500, NULL },
+ { "Odieresis", 722, NULL },
+ { "bracketleft", 333, NULL },
+ { "Ugrave", 722, NULL },
+ { "quoteright", 333, NULL },
+ { "Udieresis", 722, NULL },
+ { "perthousand", 1000, NULL },
+ { "Ydieresis", 722, NULL },
+ { "Eacute", 611, NULL },
+ { "adieresis", 444, NULL },
+ { "egrave", 444, NULL },
+ { "edieresis", 444, NULL },
+ { "idieresis", 278, NULL },
+ { "Eth", 722, NULL },
+ { "ae", 667, NULL },
+ { "asterisk", 500, NULL },
+ { "odieresis", 500, NULL },
+ { "Uacute", 722, NULL },
+ { "ugrave", 500, NULL },
+ { "nine", 500, NULL },
+ { "five", 500, NULL },
+ { "udieresis", 500, NULL },
+ { "Zcaron", 611, NULL },
+ { "threequarters", 750, NULL },
+ { "guillemotright", 500, NULL },
+ { "ydieresis", 500, NULL },
+ { "Ccedilla", 667, NULL },
+ { "tilde", 333, NULL },
+ { "at", 921, NULL },
+ { "eacute", 444, NULL },
+ { "underscore", 500, NULL },
+ { "multiply", 564, NULL },
+ { "zero", 500, NULL },
+ { "eth", 500, NULL },
+ { "Ograve", 722, NULL },
+ { "uacute", 500, NULL },
+ { "braceleft", 480, NULL },
+ { "Thorn", 556, NULL },
+ { "zcaron", 444, NULL },
+ { "ccedilla", 444, NULL },
+ { "Ocircumflex", 722, NULL },
+ { "Oacute", 722, NULL },
+ { "ogonek", 333, NULL },
+ { "ograve", 500, NULL },
+ { "thorn", 500, NULL },
+ { "degree", 400, NULL },
+ { "registered", 760, NULL },
+ { "Aring", 722, NULL },
+ { "percent", 833, NULL },
+ { "six", 500, NULL },
+ { "paragraph", 453, NULL },
+ { "two", 500, NULL },
+ { "Igrave", 333, NULL },
+ { "ocircumflex", 500, NULL },
+ { "oacute", 500, NULL },
+ { "asciicircum", 469, NULL },
+ { "aring", 444, NULL },
+ { "grave", 333, NULL },
+ { "bracketright", 333, NULL },
+ { "Iacute", 333, NULL },
+ { "ampersand", 778, NULL },
+ { "igrave", 278, NULL },
+ { "plus", 564, NULL },
+ { "quotesinglbase", 333, NULL },
+ { "Yacute", 722, NULL },
+ { "threesuperior", 300, NULL },
+ { "acute", 333, NULL },
+ { "section", 500, NULL },
+ { "dieresis", 333, NULL },
+ { "iacute", 278, NULL },
+ { "quotedblbase", 444, NULL },
+ { "florin", 500, NULL },
+ { "yacute", 500, NULL },
+ { "fi", 556, NULL },
+ { "fl", 556, NULL },
+ { "Acircumflex", 722, NULL },
+ { "Icircumflex", 333, NULL },
+ { "guillemotleft", 500, NULL },
+ { "germandbls", 500, NULL },
+ { "seven", 500, NULL },
+ { "ordmasculine", 310, NULL },
+ { "dotlessi", 278, NULL },
+ { "sterling", 500, NULL },
+ { "acircumflex", 444, NULL },
+ { "icircumflex", 278, NULL },
+ { "braceright", 480, NULL },
+ { "quotedblright", 444, NULL },
+ { "cent", 500, NULL },
+ { "currency", 500, NULL },
+ { "logicalnot", 564, NULL },
+ { "Atilde", 722, NULL },
+ { "breve", 333, NULL },
+ { "bar", 200, NULL },
+ { "fraction", 167, NULL },
+ { "less", 564, NULL },
+ { "guilsinglleft", 333, NULL },
+ { "exclam", 333, NULL },
+ { "period", 250, NULL },
+ { "greater", 564, NULL },
+ { "atilde", 444, NULL },
+ { "brokenbar", 200, NULL },
+ { "quoteleft", 333, NULL },
+ { "onesuperior", 300, NULL }
+};
+
+static BuiltinFontWidth zapfDingbatsWidthsTab[] = {
+ { "a81", 438, NULL },
+ { "a82", 138, NULL },
+ { "a83", 277, NULL },
+ { "a84", 415, NULL },
+ { "a85", 509, NULL },
+ { "a86", 410, NULL },
+ { "a87", 234, NULL },
+ { "a88", 234, NULL },
+ { "a89", 390, NULL },
+ { "a140", 788, NULL },
+ { "a141", 788, NULL },
+ { "a142", 788, NULL },
+ { "a143", 788, NULL },
+ { "a144", 788, NULL },
+ { "a145", 788, NULL },
+ { "a146", 788, NULL },
+ { "a147", 788, NULL },
+ { "a148", 788, NULL },
+ { "a149", 788, NULL },
+ { "a90", 390, NULL },
+ { "a91", 276, NULL },
+ { "a92", 276, NULL },
+ { "space", 278, NULL },
+ { "a93", 317, NULL },
+ { "a94", 317, NULL },
+ { "a95", 334, NULL },
+ { "a96", 334, NULL },
+ { "a97", 392, NULL },
+ { "a98", 392, NULL },
+ { "a99", 668, NULL },
+ { "a150", 788, NULL },
+ { "a151", 788, NULL },
+ { "a152", 788, NULL },
+ { "a153", 788, NULL },
+ { "a154", 788, NULL },
+ { "a155", 788, NULL },
+ { "a156", 788, NULL },
+ { "a157", 788, NULL },
+ { "a158", 788, NULL },
+ { "a159", 788, NULL },
+ { "a160", 894, NULL },
+ { "a161", 838, NULL },
+ { "a162", 924, NULL },
+ { "a163", 1016, NULL },
+ { "a164", 458, NULL },
+ { "a165", 924, NULL },
+ { "a166", 918, NULL },
+ { "a167", 927, NULL },
+ { "a168", 928, NULL },
+ { "a169", 928, NULL },
+ { "a170", 834, NULL },
+ { "a171", 873, NULL },
+ { "a172", 828, NULL },
+ { "a173", 924, NULL },
+ { "a174", 917, NULL },
+ { "a175", 930, NULL },
+ { "a176", 931, NULL },
+ { "a177", 463, NULL },
+ { "a178", 883, NULL },
+ { "a179", 836, NULL },
+ { "a180", 867, NULL },
+ { "a181", 696, NULL },
+ { "a182", 874, NULL },
+ { "a183", 760, NULL },
+ { "a184", 946, NULL },
+ { "a185", 865, NULL },
+ { "a186", 967, NULL },
+ { "a187", 831, NULL },
+ { "a188", 873, NULL },
+ { "a189", 927, NULL },
+ { "a1", 974, NULL },
+ { "a2", 961, NULL },
+ { "a3", 980, NULL },
+ { "a4", 719, NULL },
+ { "a5", 789, NULL },
+ { "a6", 494, NULL },
+ { "a7", 552, NULL },
+ { "a8", 537, NULL },
+ { "a9", 577, NULL },
+ { "a190", 970, NULL },
+ { "a191", 918, NULL },
+ { "a192", 748, NULL },
+ { "a193", 836, NULL },
+ { "a194", 771, NULL },
+ { "a195", 888, NULL },
+ { "a196", 748, NULL },
+ { "a197", 771, NULL },
+ { "a198", 888, NULL },
+ { "a199", 867, NULL },
+ { "a10", 692, NULL },
+ { "a11", 960, NULL },
+ { "a12", 939, NULL },
+ { "a13", 549, NULL },
+ { "a14", 855, NULL },
+ { "a15", 911, NULL },
+ { "a16", 933, NULL },
+ { "a17", 945, NULL },
+ { "a18", 974, NULL },
+ { "a19", 755, NULL },
+ { "a20", 846, NULL },
+ { "a21", 762, NULL },
+ { "a22", 761, NULL },
+ { "a23", 571, NULL },
+ { "a24", 677, NULL },
+ { "a25", 763, NULL },
+ { "a26", 760, NULL },
+ { "a27", 759, NULL },
+ { "a28", 754, NULL },
+ { "a29", 786, NULL },
+ { "a30", 788, NULL },
+ { "a31", 788, NULL },
+ { "a32", 790, NULL },
+ { "a33", 793, NULL },
+ { "a34", 794, NULL },
+ { "a35", 816, NULL },
+ { "a36", 823, NULL },
+ { "a37", 789, NULL },
+ { "a38", 841, NULL },
+ { "a39", 823, NULL },
+ { "a40", 833, NULL },
+ { "a41", 816, NULL },
+ { "a42", 831, NULL },
+ { "a43", 923, NULL },
+ { "a44", 744, NULL },
+ { "a45", 723, NULL },
+ { "a46", 749, NULL },
+ { "a47", 790, NULL },
+ { "a48", 792, NULL },
+ { "a49", 695, NULL },
+ { "a100", 668, NULL },
+ { "a101", 732, NULL },
+ { "a102", 544, NULL },
+ { "a103", 544, NULL },
+ { "a104", 910, NULL },
+ { "a105", 911, NULL },
+ { "a106", 667, NULL },
+ { "a107", 760, NULL },
+ { "a108", 760, NULL },
+ { "a109", 626, NULL },
+ { "a50", 776, NULL },
+ { "a51", 768, NULL },
+ { "a52", 792, NULL },
+ { "a53", 759, NULL },
+ { "a54", 707, NULL },
+ { "a55", 708, NULL },
+ { "a56", 682, NULL },
+ { "a57", 701, NULL },
+ { "a58", 826, NULL },
+ { "a59", 815, NULL },
+ { "a110", 694, NULL },
+ { "a111", 595, NULL },
+ { "a112", 776, NULL },
+ { "a117", 690, NULL },
+ { "a118", 791, NULL },
+ { "a119", 790, NULL },
+ { "a60", 789, NULL },
+ { "a61", 789, NULL },
+ { "a62", 707, NULL },
+ { "a63", 687, NULL },
+ { "a64", 696, NULL },
+ { "a65", 689, NULL },
+ { "a66", 786, NULL },
+ { "a67", 787, NULL },
+ { "a68", 713, NULL },
+ { "a69", 791, NULL },
+ { "a200", 696, NULL },
+ { "a201", 874, NULL },
+ { "a120", 788, NULL },
+ { "a121", 788, NULL },
+ { "a202", 974, NULL },
+ { "a122", 788, NULL },
+ { "a203", 762, NULL },
+ { "a123", 788, NULL },
+ { "a204", 759, NULL },
+ { "a205", 509, NULL },
+ { "a124", 788, NULL },
+ { "a206", 410, NULL },
+ { "a125", 788, NULL },
+ { "a126", 788, NULL },
+ { "a127", 788, NULL },
+ { "a128", 788, NULL },
+ { "a129", 788, NULL },
+ { "a70", 785, NULL },
+ { "a71", 791, NULL },
+ { "a72", 873, NULL },
+ { "a73", 761, NULL },
+ { "a74", 762, NULL },
+ { "a75", 759, NULL },
+ { "a76", 892, NULL },
+ { "a77", 892, NULL },
+ { "a78", 788, NULL },
+ { "a79", 784, NULL },
+ { "a130", 788, NULL },
+ { "a131", 788, NULL },
+ { "a132", 788, NULL },
+ { "a133", 788, NULL },
+ { "a134", 788, NULL },
+ { "a135", 788, NULL },
+ { "a136", 788, NULL },
+ { "a137", 788, NULL },
+ { "a138", 788, NULL },
+ { "a139", 788, NULL }
+};
+
+BuiltinFont builtinFonts[] = {
+ { "Courier", standardEncoding, 624, -207, { -40, -290, 640, 795}, NULL },
+ { "Courier-Bold", standardEncoding, 674, -257, {-100, -350, 700, 855}, NULL },
+ { "Courier-BoldOblique", standardEncoding, 674, -257, {-145, -350, 817, 855}, NULL },
+ { "Courier-Oblique", standardEncoding, 624, -207, { -85, -290, 759, 795}, NULL },
+ { "Helvetica", standardEncoding, 729, -219, {-174, -220, 1001, 944}, NULL },
+ { "Helvetica-Bold", standardEncoding, 729, -219, {-173, -221, 1003, 936}, NULL },
+ { "Helvetica-BoldOblique", standardEncoding, 729, -219, {-177, -221, 1107, 936}, NULL },
+ { "Helvetica-Oblique", standardEncoding, 729, -219, {-178, -220, 1108, 944}, NULL },
+ { "Symbol", symbolEncoding, 1010, -293, {-180, -293, 1090, 1010}, NULL },
+ { "Times-Bold", standardEncoding, 670, -210, {-172, -256, 1008, 965}, NULL },
+ { "Times-BoldItalic", standardEncoding, 682, -203, {-168, -232, 1014, 894}, NULL },
+ { "Times-Italic", standardEncoding, 684, -206, {-176, -252, 990, 930}, NULL },
+ { "Times-Roman", standardEncoding, 682, -217, {-170, -223, 1024, 896}, NULL },
+ { "ZapfDingbats", zapfDingbatsEncoding, 820, -143, { -1, -143, 981, 820}, NULL }
+};
+
+BuiltinFont *builtinFontSubst[] = {
+ &builtinFonts[0],
+ &builtinFonts[3],
+ &builtinFonts[1],
+ &builtinFonts[2],
+ &builtinFonts[4],
+ &builtinFonts[7],
+ &builtinFonts[5],
+ &builtinFonts[6],
+ &builtinFonts[12],
+ &builtinFonts[11],
+ &builtinFonts[9],
+ &builtinFonts[10]
+};
+
+void initBuiltinFontTables() {
+ builtinFonts[0].widths = new BuiltinFontWidths(courierWidthsTab, 260);
+ builtinFonts[1].widths = new BuiltinFontWidths(courierBoldWidthsTab, 260);
+ builtinFonts[2].widths = new BuiltinFontWidths(courierBoldObliqueWidthsTab, 260);
+ builtinFonts[3].widths = new BuiltinFontWidths(courierObliqueWidthsTab, 260);
+ builtinFonts[4].widths = new BuiltinFontWidths(helveticaWidthsTab, 228);
+ builtinFonts[5].widths = new BuiltinFontWidths(helveticaBoldWidthsTab, 229);
+ builtinFonts[6].widths = new BuiltinFontWidths(helveticaBoldObliqueWidthsTab, 228);
+ builtinFonts[7].widths = new BuiltinFontWidths(helveticaObliqueWidthsTab, 228);
+ builtinFonts[8].widths = new BuiltinFontWidths(symbolWidthsTab, 189);
+ builtinFonts[9].widths = new BuiltinFontWidths(timesBoldWidthsTab, 228);
+ builtinFonts[10].widths = new BuiltinFontWidths(timesBoldItalicWidthsTab, 228);
+ builtinFonts[11].widths = new BuiltinFontWidths(timesItalicWidthsTab, 228);
+ builtinFonts[12].widths = new BuiltinFontWidths(timesRomanWidthsTab, 228);
+ builtinFonts[13].widths = new BuiltinFontWidths(zapfDingbatsWidthsTab, 202);
+}
+
+void freeBuiltinFontTables() {
+ int i;
+
+ for (i = 0; i < 14; ++i) {
+ delete builtinFonts[i].widths;
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/CMap.cc b/filters/kword/pdf/xpdf/xpdf/CMap.cc
deleted file mode 100644
index b00021835..000000000
--- a/filters/kword/pdf/xpdf/xpdf/CMap.cc
+++ /dev/null
@@ -1,360 +0,0 @@
-//========================================================================
-//
-// CMap.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "gfile.h"
-#include "GString.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "PSTokenizer.h"
-#include "CMap.h"
-
-//------------------------------------------------------------------------
-
-struct CMapVectorEntry {
- GBool isVector;
- union {
- CMapVectorEntry *vector;
- CID cid;
- };
-};
-
-//------------------------------------------------------------------------
-
-static int getCharFromFile(void *data) {
- return fgetc((FILE *)data);
-}
-
-//------------------------------------------------------------------------
-
-CMap *CMap::parse(CMapCache *cache, GString *collectionA,
- GString *cMapNameA) {
- FILE *f;
- CMap *cmap;
- PSTokenizer *pst;
- char tok1[256], tok2[256], tok3[256];
- int n1, n2, n3;
- Guint start, end;
-
- if (!(f = globalParams->findCMapFile(collectionA, cMapNameA))) {
-
- // Check for an identity CMap.
- if (!cMapNameA->cmp("Identity") || !cMapNameA->cmp("Identity-H")) {
- return new CMap(collectionA->copy(), cMapNameA->copy(), 0);
- }
- if (!cMapNameA->cmp("Identity-V")) {
- return new CMap(collectionA->copy(), cMapNameA->copy(), 1);
- }
-
- error(-1, "Couldn't find '%s' CMap file for '%s' collection",
- cMapNameA->getCString(), collectionA->getCString());
- return NULL;
- }
-
- cmap = new CMap(collectionA->copy(), cMapNameA->copy());
-
- pst = new PSTokenizer(&getCharFromFile, f);
- pst->getToken(tok1, sizeof(tok1), &n1);
- while (pst->getToken(tok2, sizeof(tok2), &n2)) {
- if (!strcmp(tok2, "usecmap")) {
- if (tok1[0] == '/') {
- cmap->useCMap(cache, tok1 + 1);
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else if (!strcmp(tok1, "/WMode")) {
- cmap->wMode = atoi(tok2);
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else if (!strcmp(tok2, "begincodespacerange")) {
- while (pst->getToken(tok1, sizeof(tok1), &n1)) {
- if (!strcmp(tok1, "endcodespacerange")) {
- break;
- }
- if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
- !strcmp(tok2, "endcodespacerange")) {
- error(-1, "Illegal entry in codespacerange block in CMap");
- break;
- }
- if (tok1[0] == '<' && tok2[0] == '<' &&
- n1 == n2 && n1 >= 4 && (n1 & 1) == 0) {
- tok1[n1 - 1] = tok2[n1 - 1] = '\0';
- sscanf(tok1 + 1, "%x", &start);
- sscanf(tok2 + 1, "%x", &end);
- n1 = (n1 - 2) / 2;
- cmap->addCodeSpace(cmap->vector, start, end, n1);
- }
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else if (!strcmp(tok2, "begincidrange")) {
- while (pst->getToken(tok1, sizeof(tok1), &n1)) {
- if (!strcmp(tok1, "endcidrange")) {
- break;
- }
- if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
- !strcmp(tok2, "endcidrange") ||
- !pst->getToken(tok3, sizeof(tok3), &n3) ||
- !strcmp(tok3, "endcidrange")) {
- error(-1, "Illegal entry in cidrange block in CMap");
- break;
- }
- if (tok1[0] == '<' && tok2[0] == '<' &&
- n1 == n2 && n1 >= 4 && (n1 & 1) == 0) {
- tok1[n1 - 1] = tok2[n1 - 1] = '\0';
- sscanf(tok1 + 1, "%x", &start);
- sscanf(tok2 + 1, "%x", &end);
- n1 = (n1 - 2) / 2;
- cmap->addCIDs(start, end, n1, (CID)atoi(tok3));
- }
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else {
- strcpy(tok1, tok2);
- }
- }
- delete pst;
-
- fclose(f);
-
- return cmap;
-}
-
-CMap::CMap(GString *collectionA, GString *cMapNameA) {
- int i;
-
- collection = collectionA;
- cMapName = cMapNameA;
- wMode = 0;
- vector = (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
- for (i = 0; i < 256; ++i) {
- vector[i].isVector = gFalse;
- vector[i].cid = 0;
- }
- refCnt = 1;
-}
-
-CMap::CMap(GString *collectionA, GString *cMapNameA, int wModeA) {
- collection = collectionA;
- cMapName = cMapNameA;
- wMode = wModeA;
- vector = NULL;
- refCnt = 1;
-}
-
-void CMap::useCMap(CMapCache *cache, char *useName) {
- GString *useNameStr;
- CMap *subCMap;
-
- useNameStr = new GString(useName);
- subCMap = cache->getCMap(collection, useNameStr);
- delete useNameStr;
- if (!subCMap) {
- return;
- }
- copyVector(vector, subCMap->vector);
- subCMap->decRefCnt();
-}
-
-void CMap::copyVector(CMapVectorEntry *dest, CMapVectorEntry *src) {
- int i, j;
-
- for (i = 0; i < 256; ++i) {
- if (src[i].isVector) {
- if (!dest[i].isVector) {
- dest[i].isVector = gTrue;
- dest[i].vector =
- (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
- for (j = 0; j < 256; ++j) {
- dest[i].vector[j].isVector = gFalse;
- dest[i].vector[j].cid = 0;
- }
- }
- copyVector(dest[i].vector, src[i].vector);
- } else {
- if (dest[i].isVector) {
- error(-1, "Collision in usecmap");
- } else {
- dest[i].cid = src[i].cid;
- }
- }
- }
-}
-
-void CMap::addCodeSpace(CMapVectorEntry *vec, Guint start, Guint end,
- Guint nBytes) {
- Guint start2, end2;
- int startByte, endByte, i, j;
-
- if (nBytes > 1) {
- startByte = (start >> (8 * (nBytes - 1))) & 0xff;
- endByte = (end >> (8 * (nBytes - 1))) & 0xff;
- start2 = start & ((1 << (8 * (nBytes - 1))) - 1);
- end2 = end & ((1 << (8 * (nBytes - 1))) - 1);
- for (i = startByte; i <= endByte; ++i) {
- if (!vec[i].isVector) {
- vec[i].isVector = gTrue;
- vec[i].vector =
- (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
- for (j = 0; j < 256; ++j) {
- vec[i].vector[j].isVector = gFalse;
- vec[i].vector[j].cid = 0;
- }
- }
- addCodeSpace(vec[i].vector, start2, end2, nBytes - 1);
- }
- }
-}
-
-void CMap::addCIDs(Guint start, Guint end, Guint nBytes, CID firstCID) {
- CMapVectorEntry *vec;
- CID cid;
- int byte;
- Guint i;
-
- vec = vector;
- for (i = nBytes - 1; i >= 1; --i) {
- byte = (start >> (8 * i)) & 0xff;
- if (!vec[byte].isVector) {
- error(-1, "Invalid CID (%*x - %*x) in CMap",
- 2*nBytes, start, 2*nBytes, end);
- return;
- }
- vec = vec[byte].vector;
- }
- cid = firstCID;
- for (byte = (int)(start & 0xff); byte <= (int)(end & 0xff); ++byte) {
- if (vec[byte].isVector) {
- error(-1, "Invalid CID (%*x - %*x) in CMap",
- 2*nBytes, start, 2*nBytes, end);
- } else {
- vec[byte].cid = cid;
- }
- ++cid;
- }
-}
-
-CMap::~CMap() {
- delete collection;
- delete cMapName;
- if (vector) {
- freeCMapVector(vector);
- }
-}
-
-void CMap::freeCMapVector(CMapVectorEntry *vec) {
- int i;
-
- for (i = 0; i < 256; ++i) {
- if (vec[i].isVector) {
- freeCMapVector(vec[i].vector);
- }
- }
- gfree(vec);
-}
-
-void CMap::incRefCnt() {
- ++refCnt;
-}
-
-void CMap::decRefCnt() {
- if (--refCnt == 0) {
- delete this;
- }
-}
-
-GBool CMap::match(GString *collectionA, GString *cMapNameA) {
- return !collection->cmp(collectionA) && !cMapName->cmp(cMapNameA);
-}
-
-CID CMap::getCID(char *s, int len, int *nUsed) {
- CMapVectorEntry *vec;
- int n, i;
-
- if (!(vec = vector)) {
- // identity CMap
- *nUsed = 2;
- if (len < 2) {
- return 0;
- }
- return ((s[0] & 0xff) << 8) + (s[1] & 0xff);
- }
- n = 0;
- while (1) {
- if (n >= len) {
- *nUsed = n;
- return 0;
- }
- i = s[n++] & 0xff;
- if (!vec[i].isVector) {
- *nUsed = n;
- return vec[i].cid;
- }
- vec = vec[i].vector;
- }
-}
-
-//------------------------------------------------------------------------
-
-CMapCache::CMapCache() {
- int i;
-
- for (i = 0; i < cMapCacheSize; ++i) {
- cache[i] = NULL;
- }
-}
-
-CMapCache::~CMapCache() {
- int i;
-
- for (i = 0; i < cMapCacheSize; ++i) {
- if (cache[i]) {
- cache[i]->decRefCnt();
- }
- }
-}
-
-CMap *CMapCache::getCMap(GString *collection, GString *cMapName) {
- CMap *cmap;
- int i, j;
-
- if (cache[0] && cache[0]->match(collection, cMapName)) {
- cache[0]->incRefCnt();
- return cache[0];
- }
- for (i = 1; i < cMapCacheSize; ++i) {
- if (cache[i] && cache[i]->match(collection, cMapName)) {
- cmap = cache[i];
- for (j = i; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = cmap;
- cmap->incRefCnt();
- return cmap;
- }
- }
- if ((cmap = CMap::parse(this, collection, cMapName))) {
- if (cache[cMapCacheSize - 1]) {
- cache[cMapCacheSize - 1]->decRefCnt();
- }
- for (j = cMapCacheSize - 1; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = cmap;
- cmap->incRefCnt();
- return cmap;
- }
- return NULL;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/CMap.cpp b/filters/kword/pdf/xpdf/xpdf/CMap.cpp
new file mode 100644
index 000000000..09a7bfe43
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/CMap.cpp
@@ -0,0 +1,360 @@
+//========================================================================
+//
+// CMap.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "gfile.h"
+#include "GString.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "PSTokenizer.h"
+#include "CMap.h"
+
+//------------------------------------------------------------------------
+
+struct CMapVectorEntry {
+ GBool isVector;
+ union {
+ CMapVectorEntry *vector;
+ CID cid;
+ };
+};
+
+//------------------------------------------------------------------------
+
+static int getCharFromFile(void *data) {
+ return fgetc((FILE *)data);
+}
+
+//------------------------------------------------------------------------
+
+CMap *CMap::parse(CMapCache *cache, GString *collectionA,
+ GString *cMapNameA) {
+ FILE *f;
+ CMap *cmap;
+ PSTokenizer *pst;
+ char tok1[256], tok2[256], tok3[256];
+ int n1, n2, n3;
+ Guint start, end;
+
+ if (!(f = globalParams->findCMapFile(collectionA, cMapNameA))) {
+
+ // Check for an identity CMap.
+ if (!cMapNameA->cmp("Identity") || !cMapNameA->cmp("Identity-H")) {
+ return new CMap(collectionA->copy(), cMapNameA->copy(), 0);
+ }
+ if (!cMapNameA->cmp("Identity-V")) {
+ return new CMap(collectionA->copy(), cMapNameA->copy(), 1);
+ }
+
+ error(-1, "Couldn't find '%s' CMap file for '%s' collection",
+ cMapNameA->getCString(), collectionA->getCString());
+ return NULL;
+ }
+
+ cmap = new CMap(collectionA->copy(), cMapNameA->copy());
+
+ pst = new PSTokenizer(&getCharFromFile, f);
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ while (pst->getToken(tok2, sizeof(tok2), &n2)) {
+ if (!strcmp(tok2, "usecmap")) {
+ if (tok1[0] == '/') {
+ cmap->useCMap(cache, tok1 + 1);
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else if (!strcmp(tok1, "/WMode")) {
+ cmap->wMode = atoi(tok2);
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else if (!strcmp(tok2, "begincodespacerange")) {
+ while (pst->getToken(tok1, sizeof(tok1), &n1)) {
+ if (!strcmp(tok1, "endcodespacerange")) {
+ break;
+ }
+ if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
+ !strcmp(tok2, "endcodespacerange")) {
+ error(-1, "Illegal entry in codespacerange block in CMap");
+ break;
+ }
+ if (tok1[0] == '<' && tok2[0] == '<' &&
+ n1 == n2 && n1 >= 4 && (n1 & 1) == 0) {
+ tok1[n1 - 1] = tok2[n1 - 1] = '\0';
+ sscanf(tok1 + 1, "%x", &start);
+ sscanf(tok2 + 1, "%x", &end);
+ n1 = (n1 - 2) / 2;
+ cmap->addCodeSpace(cmap->vector, start, end, n1);
+ }
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else if (!strcmp(tok2, "begincidrange")) {
+ while (pst->getToken(tok1, sizeof(tok1), &n1)) {
+ if (!strcmp(tok1, "endcidrange")) {
+ break;
+ }
+ if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
+ !strcmp(tok2, "endcidrange") ||
+ !pst->getToken(tok3, sizeof(tok3), &n3) ||
+ !strcmp(tok3, "endcidrange")) {
+ error(-1, "Illegal entry in cidrange block in CMap");
+ break;
+ }
+ if (tok1[0] == '<' && tok2[0] == '<' &&
+ n1 == n2 && n1 >= 4 && (n1 & 1) == 0) {
+ tok1[n1 - 1] = tok2[n1 - 1] = '\0';
+ sscanf(tok1 + 1, "%x", &start);
+ sscanf(tok2 + 1, "%x", &end);
+ n1 = (n1 - 2) / 2;
+ cmap->addCIDs(start, end, n1, (CID)atoi(tok3));
+ }
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else {
+ strcpy(tok1, tok2);
+ }
+ }
+ delete pst;
+
+ fclose(f);
+
+ return cmap;
+}
+
+CMap::CMap(GString *collectionA, GString *cMapNameA) {
+ int i;
+
+ collection = collectionA;
+ cMapName = cMapNameA;
+ wMode = 0;
+ vector = (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
+ for (i = 0; i < 256; ++i) {
+ vector[i].isVector = gFalse;
+ vector[i].cid = 0;
+ }
+ refCnt = 1;
+}
+
+CMap::CMap(GString *collectionA, GString *cMapNameA, int wModeA) {
+ collection = collectionA;
+ cMapName = cMapNameA;
+ wMode = wModeA;
+ vector = NULL;
+ refCnt = 1;
+}
+
+void CMap::useCMap(CMapCache *cache, char *useName) {
+ GString *useNameStr;
+ CMap *subCMap;
+
+ useNameStr = new GString(useName);
+ subCMap = cache->getCMap(collection, useNameStr);
+ delete useNameStr;
+ if (!subCMap) {
+ return;
+ }
+ copyVector(vector, subCMap->vector);
+ subCMap->decRefCnt();
+}
+
+void CMap::copyVector(CMapVectorEntry *dest, CMapVectorEntry *src) {
+ int i, j;
+
+ for (i = 0; i < 256; ++i) {
+ if (src[i].isVector) {
+ if (!dest[i].isVector) {
+ dest[i].isVector = gTrue;
+ dest[i].vector =
+ (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
+ for (j = 0; j < 256; ++j) {
+ dest[i].vector[j].isVector = gFalse;
+ dest[i].vector[j].cid = 0;
+ }
+ }
+ copyVector(dest[i].vector, src[i].vector);
+ } else {
+ if (dest[i].isVector) {
+ error(-1, "Collision in usecmap");
+ } else {
+ dest[i].cid = src[i].cid;
+ }
+ }
+ }
+}
+
+void CMap::addCodeSpace(CMapVectorEntry *vec, Guint start, Guint end,
+ Guint nBytes) {
+ Guint start2, end2;
+ int startByte, endByte, i, j;
+
+ if (nBytes > 1) {
+ startByte = (start >> (8 * (nBytes - 1))) & 0xff;
+ endByte = (end >> (8 * (nBytes - 1))) & 0xff;
+ start2 = start & ((1 << (8 * (nBytes - 1))) - 1);
+ end2 = end & ((1 << (8 * (nBytes - 1))) - 1);
+ for (i = startByte; i <= endByte; ++i) {
+ if (!vec[i].isVector) {
+ vec[i].isVector = gTrue;
+ vec[i].vector =
+ (CMapVectorEntry *)gmalloc(256 * sizeof(CMapVectorEntry));
+ for (j = 0; j < 256; ++j) {
+ vec[i].vector[j].isVector = gFalse;
+ vec[i].vector[j].cid = 0;
+ }
+ }
+ addCodeSpace(vec[i].vector, start2, end2, nBytes - 1);
+ }
+ }
+}
+
+void CMap::addCIDs(Guint start, Guint end, Guint nBytes, CID firstCID) {
+ CMapVectorEntry *vec;
+ CID cid;
+ int byte;
+ Guint i;
+
+ vec = vector;
+ for (i = nBytes - 1; i >= 1; --i) {
+ byte = (start >> (8 * i)) & 0xff;
+ if (!vec[byte].isVector) {
+ error(-1, "Invalid CID (%*x - %*x) in CMap",
+ 2*nBytes, start, 2*nBytes, end);
+ return;
+ }
+ vec = vec[byte].vector;
+ }
+ cid = firstCID;
+ for (byte = (int)(start & 0xff); byte <= (int)(end & 0xff); ++byte) {
+ if (vec[byte].isVector) {
+ error(-1, "Invalid CID (%*x - %*x) in CMap",
+ 2*nBytes, start, 2*nBytes, end);
+ } else {
+ vec[byte].cid = cid;
+ }
+ ++cid;
+ }
+}
+
+CMap::~CMap() {
+ delete collection;
+ delete cMapName;
+ if (vector) {
+ freeCMapVector(vector);
+ }
+}
+
+void CMap::freeCMapVector(CMapVectorEntry *vec) {
+ int i;
+
+ for (i = 0; i < 256; ++i) {
+ if (vec[i].isVector) {
+ freeCMapVector(vec[i].vector);
+ }
+ }
+ gfree(vec);
+}
+
+void CMap::incRefCnt() {
+ ++refCnt;
+}
+
+void CMap::decRefCnt() {
+ if (--refCnt == 0) {
+ delete this;
+ }
+}
+
+GBool CMap::match(GString *collectionA, GString *cMapNameA) {
+ return !collection->cmp(collectionA) && !cMapName->cmp(cMapNameA);
+}
+
+CID CMap::getCID(char *s, int len, int *nUsed) {
+ CMapVectorEntry *vec;
+ int n, i;
+
+ if (!(vec = vector)) {
+ // identity CMap
+ *nUsed = 2;
+ if (len < 2) {
+ return 0;
+ }
+ return ((s[0] & 0xff) << 8) + (s[1] & 0xff);
+ }
+ n = 0;
+ while (1) {
+ if (n >= len) {
+ *nUsed = n;
+ return 0;
+ }
+ i = s[n++] & 0xff;
+ if (!vec[i].isVector) {
+ *nUsed = n;
+ return vec[i].cid;
+ }
+ vec = vec[i].vector;
+ }
+}
+
+//------------------------------------------------------------------------
+
+CMapCache::CMapCache() {
+ int i;
+
+ for (i = 0; i < cMapCacheSize; ++i) {
+ cache[i] = NULL;
+ }
+}
+
+CMapCache::~CMapCache() {
+ int i;
+
+ for (i = 0; i < cMapCacheSize; ++i) {
+ if (cache[i]) {
+ cache[i]->decRefCnt();
+ }
+ }
+}
+
+CMap *CMapCache::getCMap(GString *collection, GString *cMapName) {
+ CMap *cmap;
+ int i, j;
+
+ if (cache[0] && cache[0]->match(collection, cMapName)) {
+ cache[0]->incRefCnt();
+ return cache[0];
+ }
+ for (i = 1; i < cMapCacheSize; ++i) {
+ if (cache[i] && cache[i]->match(collection, cMapName)) {
+ cmap = cache[i];
+ for (j = i; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = cmap;
+ cmap->incRefCnt();
+ return cmap;
+ }
+ }
+ if ((cmap = CMap::parse(this, collection, cMapName))) {
+ if (cache[cMapCacheSize - 1]) {
+ cache[cMapCacheSize - 1]->decRefCnt();
+ }
+ for (j = cMapCacheSize - 1; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = cmap;
+ cmap->incRefCnt();
+ return cmap;
+ }
+ return NULL;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Catalog.cc b/filters/kword/pdf/xpdf/xpdf/Catalog.cc
deleted file mode 100644
index 8f7e6b04e..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Catalog.cc
+++ /dev/null
@@ -1,371 +0,0 @@
-//========================================================================
-//
-// Catalog.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <limits.h>
-#include <stddef.h>
-#include "gmem.h"
-#include "Object.h"
-#include "XRef.h"
-#include "Array.h"
-#include "Dict.h"
-#include "Page.h"
-#include "Error.h"
-#include "Link.h"
-#include "Catalog.h"
-
-// This define is used to limit the depth of recursive readPageTree calls
-// This is needed because the page tree nodes can reference their parents
-// leaving us in an infinite loop
-// Most sane pdf documents don't have a call depth higher than 10
-#define MAX_CALL_DEPTH 1000
-
-//------------------------------------------------------------------------
-// Catalog
-//------------------------------------------------------------------------
-
-Catalog::Catalog(XRef *xrefA) {
- Object catDict, pagesDict;
- Object obj, obj2;
- int numPages0;
- int i;
-
- ok = gTrue;
- xref = xrefA;
- pages = NULL;
- pageRefs = NULL;
- numPages = pagesSize = 0;
- baseURI = NULL;
-
- xref->getCatalog(&catDict);
- if (!catDict.isDict()) {
- error(-1, "Catalog object is wrong type (%s)", catDict.getTypeName());
- goto err1;
- }
-
- // read page tree
- catDict.dictLookup("Pages", &pagesDict);
- // This should really be isDict("Pages"), but I've seen at least one
- // PDF file where the /Type entry is missing.
- if (!pagesDict.isDict()) {
- error(-1, "Top-level pages object is wrong type (%s)",
- pagesDict.getTypeName());
- goto err2;
- }
- pagesDict.dictLookup("Count", &obj);
- if (!obj.isInt()) {
- error(-1, "Page count in top-level pages object is wrong type (%s)",
- obj.getTypeName());
- goto err3;
- }
- pagesSize = numPages0 = obj.getInt();
- obj.free();
- if ((unsigned) pagesSize >= INT_MAX / sizeof(Page *) ||
- (unsigned) pagesSize >= INT_MAX / sizeof(Ref)) {
- error(-1, "Invalid 'pagesSize'");
- ok = gFalse;
- return;
- }
- pages = (Page **)gmalloc(pagesSize * sizeof(Page *));
- pageRefs = (Ref *)gmalloc(pagesSize * sizeof(Ref));
- for (i = 0; i < pagesSize; ++i) {
- pages[i] = NULL;
- pageRefs[i].num = -1;
- pageRefs[i].gen = -1;
- }
- numPages = readPageTree(pagesDict.getDict(), NULL, 0, 0);
- if (numPages != numPages0) {
- error(-1, "Page count in top-level pages object is incorrect");
- }
- pagesDict.free();
-
- // read named destination dictionary
- catDict.dictLookup("Dests", &dests);
-
- // read root of named destination tree
- if (catDict.dictLookup("Names", &obj)->isDict())
- obj.dictLookup("Dests", &nameTree);
- else
- nameTree.initNull();
- obj.free();
-
- // read base URI
- if (catDict.dictLookup("URI", &obj)->isDict()) {
- if (obj.dictLookup("Base", &obj2)->isString()) {
- baseURI = obj2.getString()->copy();
- }
- obj2.free();
- }
- obj.free();
-
- // get the metadata stream
- catDict.dictLookup("Metadata", &metadata);
-
- // get the structure tree root
- catDict.dictLookup("StructTreeRoot", &structTreeRoot);
-
- // get the outline dictionary
- catDict.dictLookup("Outlines", &outline);
-
- catDict.free();
- return;
-
- err3:
- obj.free();
- err2:
- pagesDict.free();
- err1:
- catDict.free();
- dests.initNull();
- nameTree.initNull();
- ok = gFalse;
-}
-
-Catalog::~Catalog() {
- int i;
-
- if (pages) {
- for (i = 0; i < pagesSize; ++i) {
- if (pages[i]) {
- delete pages[i];
- }
- }
- gfree(pages);
- gfree(pageRefs);
- }
- dests.free();
- nameTree.free();
- if (baseURI) {
- delete baseURI;
- }
- metadata.free();
- structTreeRoot.free();
- outline.free();
-}
-
-GString *Catalog::readMetadata() {
- GString *s;
- Dict *dict;
- Object obj;
- int c;
-
- if (!metadata.isStream()) {
- return NULL;
- }
- dict = metadata.streamGetDict();
- if (!dict->lookup("Subtype", &obj)->isName("XML")) {
- error(-1, "Unknown Metadata type: '%s'",
- obj.isName() ? obj.getName() : "???");
- }
- obj.free();
- s = new GString();
- metadata.streamReset();
- while ((c = metadata.streamGetChar()) != EOF) {
- s->append(c);
- }
- metadata.streamClose();
- return s;
-}
-
-int Catalog::readPageTree(Dict *pagesDict, PageAttrs *attrs, int start, int callDepth) {
- Object kids;
- Object kid;
- Object kidRef;
- PageAttrs *attrs1, *attrs2;
- Page *page;
- int i, j;
-
- attrs1 = new PageAttrs(attrs, pagesDict);
- pagesDict->lookup("Kids", &kids);
- if (!kids.isArray()) {
- error(-1, "Kids object (page %d) is wrong type (%s)",
- start+1, kids.getTypeName());
- goto err1;
- }
- for (i = 0; i < kids.arrayGetLength(); ++i) {
- kids.arrayGet(i, &kid);
- if (kid.isDict("Page")) {
- attrs2 = new PageAttrs(attrs1, kid.getDict());
- page = new Page(xref, start+1, kid.getDict(), attrs2);
- if (!page->isOk()) {
- ++start;
- goto err3;
- }
- if (start >= pagesSize) {
- pagesSize += 32;
- if ((unsigned) pagesSize >= INT_MAX / sizeof(Page *) ||
- (unsigned) pagesSize >= INT_MAX / sizeof(Ref)) {
- error(-1, "Invalid 'pagesSize' parameter.");
- goto err3;
- }
- pages = (Page **)grealloc(pages, pagesSize * sizeof(Page *));
- pageRefs = (Ref *)grealloc(pageRefs, pagesSize * sizeof(Ref));
- for (j = pagesSize - 32; j < pagesSize; ++j) {
- pages[j] = NULL;
- pageRefs[j].num = -1;
- pageRefs[j].gen = -1;
- }
- }
- pages[start] = page;
- kids.arrayGetNF(i, &kidRef);
- if (kidRef.isRef()) {
- pageRefs[start].num = kidRef.getRefNum();
- pageRefs[start].gen = kidRef.getRefGen();
- }
- kidRef.free();
- ++start;
- // This should really be isDict("Pages"), but I've seen at least one
- // PDF file where the /Type entry is missing.
- } else if (kid.isDict()) {
- if (callDepth > MAX_CALL_DEPTH) {
- error(-1, "Limit of %d recursive calls reached while reading the page tree. If your document is correct and not a test to try to force a crash, please report a bug.", MAX_CALL_DEPTH);
- } else {
- if ((start = readPageTree(kid.getDict(), attrs1, start, callDepth + 1))
- < 0)
- goto err2;
- }
- } else {
- error(-1, "Kid object (page %d) is wrong type (%s)",
- start+1, kid.getTypeName());
- goto err2;
- }
- kid.free();
- }
- delete attrs1;
- kids.free();
- return start;
-
- err3:
- delete page;
- err2:
- kid.free();
- err1:
- kids.free();
- delete attrs1;
- ok = gFalse;
- return -1;
-}
-
-int Catalog::findPage(int num, int gen) {
- int i;
-
- for (i = 0; i < numPages; ++i) {
- if (pageRefs[i].num == num && pageRefs[i].gen == gen)
- return i + 1;
- }
- return 0;
-}
-
-LinkDest *Catalog::findDest(GString *name) {
- LinkDest *dest;
- Object obj1, obj2;
- GBool found;
-
- // try named destination dictionary then name tree
- found = gFalse;
- if (dests.isDict()) {
- if (!dests.dictLookup(name->getCString(), &obj1)->isNull())
- found = gTrue;
- else
- obj1.free();
- }
- if (!found && nameTree.isDict()) {
- if (!findDestInTree(&nameTree, name, &obj1)->isNull())
- found = gTrue;
- else
- obj1.free();
- }
- if (!found)
- return NULL;
-
- // construct LinkDest
- dest = NULL;
- if (obj1.isArray()) {
- dest = new LinkDest(obj1.getArray());
- } else if (obj1.isDict()) {
- if (obj1.dictLookup("D", &obj2)->isArray())
- dest = new LinkDest(obj2.getArray());
- else
- error(-1, "Bad named destination value");
- obj2.free();
- } else {
- error(-1, "Bad named destination value");
- }
- obj1.free();
- if (dest && !dest->isOk()) {
- delete dest;
- dest = NULL;
- }
-
- return dest;
-}
-
-Object *Catalog::findDestInTree(Object *tree, GString *name, Object *obj) {
- Object names, name1;
- Object kids, kid, limits, low, high;
- GBool done, found;
- int cmp, i;
-
- // leaf node
- if (tree->dictLookup("Names", &names)->isArray()) {
- done = found = gFalse;
- for (i = 0; !done && i < names.arrayGetLength(); i += 2) {
- if (names.arrayGet(i, &name1)->isString()) {
- cmp = name->cmp(name1.getString());
- if (cmp == 0) {
- names.arrayGet(i+1, obj);
- found = gTrue;
- done = gTrue;
- } else if (cmp < 0) {
- done = gTrue;
- }
- name1.free();
- }
- }
- names.free();
- if (!found)
- obj->initNull();
- return obj;
- }
- names.free();
-
- // root or intermediate node
- done = gFalse;
- if (tree->dictLookup("Kids", &kids)->isArray()) {
- for (i = 0; !done && i < kids.arrayGetLength(); ++i) {
- if (kids.arrayGet(i, &kid)->isDict()) {
- if (kid.dictLookup("Limits", &limits)->isArray()) {
- if (limits.arrayGet(0, &low)->isString() &&
- name->cmp(low.getString()) >= 0) {
- if (limits.arrayGet(1, &high)->isString() &&
- name->cmp(high.getString()) <= 0) {
- findDestInTree(&kid, name, obj);
- done = gTrue;
- }
- high.free();
- }
- low.free();
- }
- limits.free();
- }
- kid.free();
- }
- }
- kids.free();
-
- // name was outside of ranges of all kids
- if (!done)
- obj->initNull();
-
- return obj;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Catalog.cpp b/filters/kword/pdf/xpdf/xpdf/Catalog.cpp
new file mode 100644
index 000000000..583666b22
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Catalog.cpp
@@ -0,0 +1,371 @@
+//========================================================================
+//
+// Catalog.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <limits.h>
+#include <stddef.h>
+#include "gmem.h"
+#include "Object.h"
+#include "XRef.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Page.h"
+#include "Error.h"
+#include "Link.h"
+#include "Catalog.h"
+
+// This define is used to limit the depth of recursive readPageTree calls
+// This is needed because the page tree nodes can reference their parents
+// leaving us in an infinite loop
+// Most sane pdf documents don't have a call depth higher than 10
+#define MAX_CALL_DEPTH 1000
+
+//------------------------------------------------------------------------
+// Catalog
+//------------------------------------------------------------------------
+
+Catalog::Catalog(XRef *xrefA) {
+ Object catDict, pagesDict;
+ Object obj, obj2;
+ int numPages0;
+ int i;
+
+ ok = gTrue;
+ xref = xrefA;
+ pages = NULL;
+ pageRefs = NULL;
+ numPages = pagesSize = 0;
+ baseURI = NULL;
+
+ xref->getCatalog(&catDict);
+ if (!catDict.isDict()) {
+ error(-1, "Catalog object is wrong type (%s)", catDict.getTypeName());
+ goto err1;
+ }
+
+ // read page tree
+ catDict.dictLookup("Pages", &pagesDict);
+ // This should really be isDict("Pages"), but I've seen at least one
+ // PDF file where the /Type entry is missing.
+ if (!pagesDict.isDict()) {
+ error(-1, "Top-level pages object is wrong type (%s)",
+ pagesDict.getTypeName());
+ goto err2;
+ }
+ pagesDict.dictLookup("Count", &obj);
+ if (!obj.isInt()) {
+ error(-1, "Page count in top-level pages object is wrong type (%s)",
+ obj.getTypeName());
+ goto err3;
+ }
+ pagesSize = numPages0 = obj.getInt();
+ obj.free();
+ if ((unsigned) pagesSize >= INT_MAX / sizeof(Page *) ||
+ (unsigned) pagesSize >= INT_MAX / sizeof(Ref)) {
+ error(-1, "Invalid 'pagesSize'");
+ ok = gFalse;
+ return;
+ }
+ pages = (Page **)gmalloc(pagesSize * sizeof(Page *));
+ pageRefs = (Ref *)gmalloc(pagesSize * sizeof(Ref));
+ for (i = 0; i < pagesSize; ++i) {
+ pages[i] = NULL;
+ pageRefs[i].num = -1;
+ pageRefs[i].gen = -1;
+ }
+ numPages = readPageTree(pagesDict.getDict(), NULL, 0, 0);
+ if (numPages != numPages0) {
+ error(-1, "Page count in top-level pages object is incorrect");
+ }
+ pagesDict.free();
+
+ // read named destination dictionary
+ catDict.dictLookup("Dests", &dests);
+
+ // read root of named destination tree
+ if (catDict.dictLookup("Names", &obj)->isDict())
+ obj.dictLookup("Dests", &nameTree);
+ else
+ nameTree.initNull();
+ obj.free();
+
+ // read base URI
+ if (catDict.dictLookup("URI", &obj)->isDict()) {
+ if (obj.dictLookup("Base", &obj2)->isString()) {
+ baseURI = obj2.getString()->copy();
+ }
+ obj2.free();
+ }
+ obj.free();
+
+ // get the metadata stream
+ catDict.dictLookup("Metadata", &metadata);
+
+ // get the structure tree root
+ catDict.dictLookup("StructTreeRoot", &structTreeRoot);
+
+ // get the outline dictionary
+ catDict.dictLookup("Outlines", &outline);
+
+ catDict.free();
+ return;
+
+ err3:
+ obj.free();
+ err2:
+ pagesDict.free();
+ err1:
+ catDict.free();
+ dests.initNull();
+ nameTree.initNull();
+ ok = gFalse;
+}
+
+Catalog::~Catalog() {
+ int i;
+
+ if (pages) {
+ for (i = 0; i < pagesSize; ++i) {
+ if (pages[i]) {
+ delete pages[i];
+ }
+ }
+ gfree(pages);
+ gfree(pageRefs);
+ }
+ dests.free();
+ nameTree.free();
+ if (baseURI) {
+ delete baseURI;
+ }
+ metadata.free();
+ structTreeRoot.free();
+ outline.free();
+}
+
+GString *Catalog::readMetadata() {
+ GString *s;
+ Dict *dict;
+ Object obj;
+ int c;
+
+ if (!metadata.isStream()) {
+ return NULL;
+ }
+ dict = metadata.streamGetDict();
+ if (!dict->lookup("Subtype", &obj)->isName("XML")) {
+ error(-1, "Unknown Metadata type: '%s'",
+ obj.isName() ? obj.getName() : "???");
+ }
+ obj.free();
+ s = new GString();
+ metadata.streamReset();
+ while ((c = metadata.streamGetChar()) != EOF) {
+ s->append(c);
+ }
+ metadata.streamClose();
+ return s;
+}
+
+int Catalog::readPageTree(Dict *pagesDict, PageAttrs *attrs, int start, int callDepth) {
+ Object kids;
+ Object kid;
+ Object kidRef;
+ PageAttrs *attrs1, *attrs2;
+ Page *page;
+ int i, j;
+
+ attrs1 = new PageAttrs(attrs, pagesDict);
+ pagesDict->lookup("Kids", &kids);
+ if (!kids.isArray()) {
+ error(-1, "Kids object (page %d) is wrong type (%s)",
+ start+1, kids.getTypeName());
+ goto err1;
+ }
+ for (i = 0; i < kids.arrayGetLength(); ++i) {
+ kids.arrayGet(i, &kid);
+ if (kid.isDict("Page")) {
+ attrs2 = new PageAttrs(attrs1, kid.getDict());
+ page = new Page(xref, start+1, kid.getDict(), attrs2);
+ if (!page->isOk()) {
+ ++start;
+ goto err3;
+ }
+ if (start >= pagesSize) {
+ pagesSize += 32;
+ if ((unsigned) pagesSize >= INT_MAX / sizeof(Page *) ||
+ (unsigned) pagesSize >= INT_MAX / sizeof(Ref)) {
+ error(-1, "Invalid 'pagesSize' parameter.");
+ goto err3;
+ }
+ pages = (Page **)grealloc(pages, pagesSize * sizeof(Page *));
+ pageRefs = (Ref *)grealloc(pageRefs, pagesSize * sizeof(Ref));
+ for (j = pagesSize - 32; j < pagesSize; ++j) {
+ pages[j] = NULL;
+ pageRefs[j].num = -1;
+ pageRefs[j].gen = -1;
+ }
+ }
+ pages[start] = page;
+ kids.arrayGetNF(i, &kidRef);
+ if (kidRef.isRef()) {
+ pageRefs[start].num = kidRef.getRefNum();
+ pageRefs[start].gen = kidRef.getRefGen();
+ }
+ kidRef.free();
+ ++start;
+ // This should really be isDict("Pages"), but I've seen at least one
+ // PDF file where the /Type entry is missing.
+ } else if (kid.isDict()) {
+ if (callDepth > MAX_CALL_DEPTH) {
+ error(-1, "Limit of %d recursive calls reached while reading the page tree. If your document is correct and not a test to try to force a crash, please report a bug.", MAX_CALL_DEPTH);
+ } else {
+ if ((start = readPageTree(kid.getDict(), attrs1, start, callDepth + 1))
+ < 0)
+ goto err2;
+ }
+ } else {
+ error(-1, "Kid object (page %d) is wrong type (%s)",
+ start+1, kid.getTypeName());
+ goto err2;
+ }
+ kid.free();
+ }
+ delete attrs1;
+ kids.free();
+ return start;
+
+ err3:
+ delete page;
+ err2:
+ kid.free();
+ err1:
+ kids.free();
+ delete attrs1;
+ ok = gFalse;
+ return -1;
+}
+
+int Catalog::findPage(int num, int gen) {
+ int i;
+
+ for (i = 0; i < numPages; ++i) {
+ if (pageRefs[i].num == num && pageRefs[i].gen == gen)
+ return i + 1;
+ }
+ return 0;
+}
+
+LinkDest *Catalog::findDest(GString *name) {
+ LinkDest *dest;
+ Object obj1, obj2;
+ GBool found;
+
+ // try named destination dictionary then name tree
+ found = gFalse;
+ if (dests.isDict()) {
+ if (!dests.dictLookup(name->getCString(), &obj1)->isNull())
+ found = gTrue;
+ else
+ obj1.free();
+ }
+ if (!found && nameTree.isDict()) {
+ if (!findDestInTree(&nameTree, name, &obj1)->isNull())
+ found = gTrue;
+ else
+ obj1.free();
+ }
+ if (!found)
+ return NULL;
+
+ // construct LinkDest
+ dest = NULL;
+ if (obj1.isArray()) {
+ dest = new LinkDest(obj1.getArray());
+ } else if (obj1.isDict()) {
+ if (obj1.dictLookup("D", &obj2)->isArray())
+ dest = new LinkDest(obj2.getArray());
+ else
+ error(-1, "Bad named destination value");
+ obj2.free();
+ } else {
+ error(-1, "Bad named destination value");
+ }
+ obj1.free();
+ if (dest && !dest->isOk()) {
+ delete dest;
+ dest = NULL;
+ }
+
+ return dest;
+}
+
+Object *Catalog::findDestInTree(Object *tree, GString *name, Object *obj) {
+ Object names, name1;
+ Object kids, kid, limits, low, high;
+ GBool done, found;
+ int cmp, i;
+
+ // leaf node
+ if (tree->dictLookup("Names", &names)->isArray()) {
+ done = found = gFalse;
+ for (i = 0; !done && i < names.arrayGetLength(); i += 2) {
+ if (names.arrayGet(i, &name1)->isString()) {
+ cmp = name->cmp(name1.getString());
+ if (cmp == 0) {
+ names.arrayGet(i+1, obj);
+ found = gTrue;
+ done = gTrue;
+ } else if (cmp < 0) {
+ done = gTrue;
+ }
+ name1.free();
+ }
+ }
+ names.free();
+ if (!found)
+ obj->initNull();
+ return obj;
+ }
+ names.free();
+
+ // root or intermediate node
+ done = gFalse;
+ if (tree->dictLookup("Kids", &kids)->isArray()) {
+ for (i = 0; !done && i < kids.arrayGetLength(); ++i) {
+ if (kids.arrayGet(i, &kid)->isDict()) {
+ if (kid.dictLookup("Limits", &limits)->isArray()) {
+ if (limits.arrayGet(0, &low)->isString() &&
+ name->cmp(low.getString()) >= 0) {
+ if (limits.arrayGet(1, &high)->isString() &&
+ name->cmp(high.getString()) <= 0) {
+ findDestInTree(&kid, name, obj);
+ done = gTrue;
+ }
+ high.free();
+ }
+ low.free();
+ }
+ limits.free();
+ }
+ kid.free();
+ }
+ }
+ kids.free();
+
+ // name was outside of ranges of all kids
+ if (!done)
+ obj->initNull();
+
+ return obj;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cc b/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cc
deleted file mode 100644
index f61d4007d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cc
+++ /dev/null
@@ -1,392 +0,0 @@
-//========================================================================
-//
-// CharCodeToUnicode.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include "gmem.h"
-#include "gfile.h"
-#include "GString.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "PSTokenizer.h"
-#include "CharCodeToUnicode.h"
-
-//------------------------------------------------------------------------
-
-#define maxUnicodeString 8
-
-struct CharCodeToUnicodeString {
- CharCode c;
- Unicode u[maxUnicodeString];
- int len;
-};
-
-//------------------------------------------------------------------------
-
-static int getCharFromString(void *data) {
- char *p;
- int c;
-
- p = *(char **)data;
- if (*p) {
- c = *p++;
- *(char **)data = p;
- } else {
- c = EOF;
- }
- return c;
-}
-
-static int getCharFromFile(void *data) {
- return fgetc((FILE *)data);
-}
-
-//------------------------------------------------------------------------
-
-CharCodeToUnicode *CharCodeToUnicode::parseCIDToUnicode(GString *collectionA) {
- FILE *f;
- Unicode *mapA;
- CharCode size, mapLenA;
- char buf[64];
- Unicode u;
- CharCodeToUnicode *ctu;
-
- if (!(f = globalParams->getCIDToUnicodeFile(collectionA))) {
- error(-1, "Couldn't find cidToUnicode file for the '%s' collection",
- collectionA->getCString());
- return NULL;
- }
-
- size = 32768;
- mapA = (Unicode *)gmalloc(size * sizeof(Unicode));
- mapLenA = 0;
-
- while (getLine(buf, sizeof(buf), f)) {
- if (mapLenA == size) {
- size *= 2;
- mapA = (Unicode *)grealloc(mapA, size * sizeof(Unicode));
- }
- if (sscanf(buf, "%x", &u) == 1) {
- mapA[mapLenA] = u;
- } else {
- error(-1, "Bad line (%d) in cidToUnicode file for the '%s' collection",
- (int)(mapLenA + 1), collectionA->getCString());
- mapA[mapLenA] = 0;
- }
- ++mapLenA;
- }
- fclose(f);
-
- ctu = new CharCodeToUnicode(collectionA->copy(), mapA, mapLenA, gTrue,
- NULL, 0);
- gfree(mapA);
- return ctu;
-}
-
-CharCodeToUnicode *CharCodeToUnicode::make8BitToUnicode(Unicode *toUnicode) {
- return new CharCodeToUnicode(NULL, toUnicode, 256, gTrue, NULL, 0);
-}
-
-CharCodeToUnicode *CharCodeToUnicode::parseCMap(GString *buf, int nBits) {
- CharCodeToUnicode *ctu;
- char *p;
-
- ctu = new CharCodeToUnicode(NULL);
- p = buf->getCString();
- ctu->parseCMap1(&getCharFromString, &p, nBits);
- return ctu;
-}
-
-void CharCodeToUnicode::parseCMap1(int (*getCharFunc)(void *), void *data,
- int nBits) {
- PSTokenizer *pst;
- char tok1[256], tok2[256], tok3[256];
- int nDigits, n1, n2, n3;
- CharCode oldLen, i;
- CharCode code1, code2;
- Unicode u;
- char uHex[5];
- int j;
- GString *name;
- FILE *f;
-
- nDigits = nBits / 4;
- pst = new PSTokenizer(getCharFunc, data);
- pst->getToken(tok1, sizeof(tok1), &n1);
- while (pst->getToken(tok2, sizeof(tok2), &n2)) {
- if (!strcmp(tok2, "usecmap")) {
- if (tok1[0] == '/') {
- name = new GString(tok1 + 1);
- if ((f = globalParams->findToUnicodeFile(name))) {
- parseCMap1(&getCharFromFile, f, nBits);
- fclose(f);
- } else {
- error(-1, "Couldn't find ToUnicode CMap file for '%s'",
- name->getCString());
- }
- delete name;
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else if (!strcmp(tok2, "beginbfchar")) {
- while (pst->getToken(tok1, sizeof(tok1), &n1)) {
- if (!strcmp(tok1, "endbfchar")) {
- break;
- }
- if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
- !strcmp(tok2, "endbfchar")) {
- error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
- break;
- }
- if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
- tok2[0] == '<' && tok2[n2 - 1] == '>')) {
- error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
- continue;
- }
- tok1[n1 - 1] = tok2[n2 - 1] = '\0';
- if (sscanf(tok1 + 1, "%x", &code1) != 1) {
- error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
- continue;
- }
- if (code1 >= mapLen) {
- oldLen = mapLen;
- mapLen = (code1 + 256) & ~255;
- map = (Unicode *)grealloc(map, mapLen * sizeof(Unicode));
- for (i = oldLen; i < mapLen; ++i) {
- map[i] = 0;
- }
- }
- if (n2 == 6) {
- if (sscanf(tok2 + 1, "%x", &u) != 1) {
- error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
- continue;
- }
- map[code1] = u;
- } else {
- map[code1] = 0;
- if (sMapLen == sMapSize) {
- sMapSize += 8;
- sMap = (CharCodeToUnicodeString *)
- grealloc(sMap, sMapSize * sizeof(CharCodeToUnicodeString));
- }
- sMap[sMapLen].c = code1;
- sMap[sMapLen].len = (n2 - 2) / 4;
- for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) {
- strncpy(uHex, tok2 + 1 + j*4, 4);
- uHex[4] = '\0';
- if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) {
- error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
- }
- }
- ++sMapLen;
- }
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else if (!strcmp(tok2, "beginbfrange")) {
- while (pst->getToken(tok1, sizeof(tok1), &n1)) {
- if (!strcmp(tok1, "endbfrange")) {
- break;
- }
- if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
- !strcmp(tok2, "endbfrange") ||
- !pst->getToken(tok3, sizeof(tok3), &n3) ||
- !strcmp(tok3, "endbfrange")) {
- error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
- break;
- }
- if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
- n2 == 2 + nDigits && tok2[0] == '<' && tok2[n2 - 1] == '>' &&
- tok3[0] == '<' && tok3[n3 - 1] == '>')) {
- error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
- continue;
- }
- tok1[n1 - 1] = tok2[n2 - 1] = tok3[n3 - 1] = '\0';
- if (sscanf(tok1 + 1, "%x", &code1) != 1 ||
- sscanf(tok2 + 1, "%x", &code2) != 1) {
- error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
- continue;
- }
- if (code2 >= mapLen) {
- oldLen = mapLen;
- mapLen = (code2 + 256) & ~255;
- map = (Unicode *)grealloc(map, mapLen * sizeof(Unicode));
- for (i = oldLen; i < mapLen; ++i) {
- map[i] = 0;
- }
- }
- if (n3 == 6) {
- if (sscanf(tok3 + 1, "%x", &u) != 1) {
- error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
- continue;
- }
- for (; code1 <= code2; ++code1) {
- map[code1] = u++;
- }
- } else {
- if (sMapLen + (int)(code2 - code1 + 1) > sMapSize) {
- sMapSize = (sMapSize + (code2 - code1 + 1) + 7) & ~7;
- sMap = (CharCodeToUnicodeString *)
- grealloc(sMap, sMapSize * sizeof(CharCodeToUnicodeString));
- }
- for (i = 0; code1 <= code2; ++code1, ++i) {
- map[code1] = 0;
- sMap[sMapLen].c = code1;
- sMap[sMapLen].len = (n3 - 2) / 4;
- for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) {
- strncpy(uHex, tok3 + 1 + j*4, 4);
- uHex[4] = '\0';
- if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) {
- error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
- }
- }
- sMap[sMapLen].u[sMap[sMapLen].len - 1] += i;
- ++sMapLen;
- }
- }
- }
- pst->getToken(tok1, sizeof(tok1), &n1);
- } else {
- strcpy(tok1, tok2);
- }
- }
- delete pst;
-}
-
-CharCodeToUnicode::CharCodeToUnicode(GString *collectionA) {
- CharCode i;
-
- collection = collectionA;
- mapLen = 256;
- map = (Unicode *)gmalloc(mapLen * sizeof(Unicode));
- for (i = 0; i < mapLen; ++i) {
- map[i] = 0;
- }
- sMap = NULL;
- sMapLen = sMapSize = 0;
- refCnt = 1;
-}
-
-CharCodeToUnicode::CharCodeToUnicode(GString *collectionA, Unicode *mapA,
- CharCode mapLenA, GBool copyMap,
- CharCodeToUnicodeString *sMapA,
- int sMapLenA) {
- collection = collectionA;
- mapLen = mapLenA;
- if (copyMap) {
- map = (Unicode *)gmalloc(mapLen * sizeof(Unicode));
- memcpy(map, mapA, mapLen * sizeof(Unicode));
- } else {
- map = mapA;
- }
- sMap = sMapA;
- sMapLen = sMapSize = sMapLenA;
- refCnt = 1;
-}
-
-CharCodeToUnicode::~CharCodeToUnicode() {
- if (collection) {
- delete collection;
- }
- gfree(map);
- if (sMap) {
- gfree(sMap);
- }
-}
-
-void CharCodeToUnicode::incRefCnt() {
- ++refCnt;
-}
-
-void CharCodeToUnicode::decRefCnt() {
- if (--refCnt == 0) {
- delete this;
- }
-}
-
-GBool CharCodeToUnicode::match(GString *collectionA) {
- return collection && !collection->cmp(collectionA);
-}
-
-int CharCodeToUnicode::mapToUnicode(CharCode c, Unicode *u, int size) {
- int i, j;
-
- if (c >= mapLen) {
- return 0;
- }
- if (map[c]) {
- u[0] = map[c];
- return 1;
- }
- for (i = 0; i < sMapLen; ++i) {
- if (sMap[i].c == c) {
- for (j = 0; j < sMap[i].len && j < size; ++j) {
- u[j] = sMap[i].u[j];
- }
- return j;
- }
- }
- return 0;
-}
-
-//------------------------------------------------------------------------
-
-CIDToUnicodeCache::CIDToUnicodeCache() {
- int i;
-
- for (i = 0; i < cidToUnicodeCacheSize; ++i) {
- cache[i] = NULL;
- }
-}
-
-CIDToUnicodeCache::~CIDToUnicodeCache() {
- int i;
-
- for (i = 0; i < cidToUnicodeCacheSize; ++i) {
- if (cache[i]) {
- cache[i]->decRefCnt();
- }
- }
-}
-
-CharCodeToUnicode *CIDToUnicodeCache::getCIDToUnicode(GString *collection) {
- CharCodeToUnicode *ctu;
- int i, j;
-
- if (cache[0] && cache[0]->match(collection)) {
- cache[0]->incRefCnt();
- return cache[0];
- }
- for (i = 1; i < cidToUnicodeCacheSize; ++i) {
- if (cache[i] && cache[i]->match(collection)) {
- ctu = cache[i];
- for (j = i; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = ctu;
- ctu->incRefCnt();
- return ctu;
- }
- }
- if ((ctu = CharCodeToUnicode::parseCIDToUnicode(collection))) {
- if (cache[cidToUnicodeCacheSize - 1]) {
- cache[cidToUnicodeCacheSize - 1]->decRefCnt();
- }
- for (j = cidToUnicodeCacheSize - 1; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = ctu;
- ctu->incRefCnt();
- return ctu;
- }
- return NULL;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cpp b/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cpp
new file mode 100644
index 000000000..1a01b37d6
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/CharCodeToUnicode.cpp
@@ -0,0 +1,392 @@
+//========================================================================
+//
+// CharCodeToUnicode.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "gmem.h"
+#include "gfile.h"
+#include "GString.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "PSTokenizer.h"
+#include "CharCodeToUnicode.h"
+
+//------------------------------------------------------------------------
+
+#define maxUnicodeString 8
+
+struct CharCodeToUnicodeString {
+ CharCode c;
+ Unicode u[maxUnicodeString];
+ int len;
+};
+
+//------------------------------------------------------------------------
+
+static int getCharFromString(void *data) {
+ char *p;
+ int c;
+
+ p = *(char **)data;
+ if (*p) {
+ c = *p++;
+ *(char **)data = p;
+ } else {
+ c = EOF;
+ }
+ return c;
+}
+
+static int getCharFromFile(void *data) {
+ return fgetc((FILE *)data);
+}
+
+//------------------------------------------------------------------------
+
+CharCodeToUnicode *CharCodeToUnicode::parseCIDToUnicode(GString *collectionA) {
+ FILE *f;
+ Unicode *mapA;
+ CharCode size, mapLenA;
+ char buf[64];
+ Unicode u;
+ CharCodeToUnicode *ctu;
+
+ if (!(f = globalParams->getCIDToUnicodeFile(collectionA))) {
+ error(-1, "Couldn't find cidToUnicode file for the '%s' collection",
+ collectionA->getCString());
+ return NULL;
+ }
+
+ size = 32768;
+ mapA = (Unicode *)gmalloc(size * sizeof(Unicode));
+ mapLenA = 0;
+
+ while (getLine(buf, sizeof(buf), f)) {
+ if (mapLenA == size) {
+ size *= 2;
+ mapA = (Unicode *)grealloc(mapA, size * sizeof(Unicode));
+ }
+ if (sscanf(buf, "%x", &u) == 1) {
+ mapA[mapLenA] = u;
+ } else {
+ error(-1, "Bad line (%d) in cidToUnicode file for the '%s' collection",
+ (int)(mapLenA + 1), collectionA->getCString());
+ mapA[mapLenA] = 0;
+ }
+ ++mapLenA;
+ }
+ fclose(f);
+
+ ctu = new CharCodeToUnicode(collectionA->copy(), mapA, mapLenA, gTrue,
+ NULL, 0);
+ gfree(mapA);
+ return ctu;
+}
+
+CharCodeToUnicode *CharCodeToUnicode::make8BitToUnicode(Unicode *toUnicode) {
+ return new CharCodeToUnicode(NULL, toUnicode, 256, gTrue, NULL, 0);
+}
+
+CharCodeToUnicode *CharCodeToUnicode::parseCMap(GString *buf, int nBits) {
+ CharCodeToUnicode *ctu;
+ char *p;
+
+ ctu = new CharCodeToUnicode(NULL);
+ p = buf->getCString();
+ ctu->parseCMap1(&getCharFromString, &p, nBits);
+ return ctu;
+}
+
+void CharCodeToUnicode::parseCMap1(int (*getCharFunc)(void *), void *data,
+ int nBits) {
+ PSTokenizer *pst;
+ char tok1[256], tok2[256], tok3[256];
+ int nDigits, n1, n2, n3;
+ CharCode oldLen, i;
+ CharCode code1, code2;
+ Unicode u;
+ char uHex[5];
+ int j;
+ GString *name;
+ FILE *f;
+
+ nDigits = nBits / 4;
+ pst = new PSTokenizer(getCharFunc, data);
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ while (pst->getToken(tok2, sizeof(tok2), &n2)) {
+ if (!strcmp(tok2, "usecmap")) {
+ if (tok1[0] == '/') {
+ name = new GString(tok1 + 1);
+ if ((f = globalParams->findToUnicodeFile(name))) {
+ parseCMap1(&getCharFromFile, f, nBits);
+ fclose(f);
+ } else {
+ error(-1, "Couldn't find ToUnicode CMap file for '%s'",
+ name->getCString());
+ }
+ delete name;
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else if (!strcmp(tok2, "beginbfchar")) {
+ while (pst->getToken(tok1, sizeof(tok1), &n1)) {
+ if (!strcmp(tok1, "endbfchar")) {
+ break;
+ }
+ if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
+ !strcmp(tok2, "endbfchar")) {
+ error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
+ break;
+ }
+ if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
+ tok2[0] == '<' && tok2[n2 - 1] == '>')) {
+ error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
+ continue;
+ }
+ tok1[n1 - 1] = tok2[n2 - 1] = '\0';
+ if (sscanf(tok1 + 1, "%x", &code1) != 1) {
+ error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
+ continue;
+ }
+ if (code1 >= mapLen) {
+ oldLen = mapLen;
+ mapLen = (code1 + 256) & ~255;
+ map = (Unicode *)grealloc(map, mapLen * sizeof(Unicode));
+ for (i = oldLen; i < mapLen; ++i) {
+ map[i] = 0;
+ }
+ }
+ if (n2 == 6) {
+ if (sscanf(tok2 + 1, "%x", &u) != 1) {
+ error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
+ continue;
+ }
+ map[code1] = u;
+ } else {
+ map[code1] = 0;
+ if (sMapLen == sMapSize) {
+ sMapSize += 8;
+ sMap = (CharCodeToUnicodeString *)
+ grealloc(sMap, sMapSize * sizeof(CharCodeToUnicodeString));
+ }
+ sMap[sMapLen].c = code1;
+ sMap[sMapLen].len = (n2 - 2) / 4;
+ for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) {
+ strncpy(uHex, tok2 + 1 + j*4, 4);
+ uHex[4] = '\0';
+ if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) {
+ error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
+ }
+ }
+ ++sMapLen;
+ }
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else if (!strcmp(tok2, "beginbfrange")) {
+ while (pst->getToken(tok1, sizeof(tok1), &n1)) {
+ if (!strcmp(tok1, "endbfrange")) {
+ break;
+ }
+ if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
+ !strcmp(tok2, "endbfrange") ||
+ !pst->getToken(tok3, sizeof(tok3), &n3) ||
+ !strcmp(tok3, "endbfrange")) {
+ error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
+ break;
+ }
+ if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
+ n2 == 2 + nDigits && tok2[0] == '<' && tok2[n2 - 1] == '>' &&
+ tok3[0] == '<' && tok3[n3 - 1] == '>')) {
+ error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
+ continue;
+ }
+ tok1[n1 - 1] = tok2[n2 - 1] = tok3[n3 - 1] = '\0';
+ if (sscanf(tok1 + 1, "%x", &code1) != 1 ||
+ sscanf(tok2 + 1, "%x", &code2) != 1) {
+ error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
+ continue;
+ }
+ if (code2 >= mapLen) {
+ oldLen = mapLen;
+ mapLen = (code2 + 256) & ~255;
+ map = (Unicode *)grealloc(map, mapLen * sizeof(Unicode));
+ for (i = oldLen; i < mapLen; ++i) {
+ map[i] = 0;
+ }
+ }
+ if (n3 == 6) {
+ if (sscanf(tok3 + 1, "%x", &u) != 1) {
+ error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
+ continue;
+ }
+ for (; code1 <= code2; ++code1) {
+ map[code1] = u++;
+ }
+ } else {
+ if (sMapLen + (int)(code2 - code1 + 1) > sMapSize) {
+ sMapSize = (sMapSize + (code2 - code1 + 1) + 7) & ~7;
+ sMap = (CharCodeToUnicodeString *)
+ grealloc(sMap, sMapSize * sizeof(CharCodeToUnicodeString));
+ }
+ for (i = 0; code1 <= code2; ++code1, ++i) {
+ map[code1] = 0;
+ sMap[sMapLen].c = code1;
+ sMap[sMapLen].len = (n3 - 2) / 4;
+ for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) {
+ strncpy(uHex, tok3 + 1 + j*4, 4);
+ uHex[4] = '\0';
+ if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) {
+ error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
+ }
+ }
+ sMap[sMapLen].u[sMap[sMapLen].len - 1] += i;
+ ++sMapLen;
+ }
+ }
+ }
+ pst->getToken(tok1, sizeof(tok1), &n1);
+ } else {
+ strcpy(tok1, tok2);
+ }
+ }
+ delete pst;
+}
+
+CharCodeToUnicode::CharCodeToUnicode(GString *collectionA) {
+ CharCode i;
+
+ collection = collectionA;
+ mapLen = 256;
+ map = (Unicode *)gmalloc(mapLen * sizeof(Unicode));
+ for (i = 0; i < mapLen; ++i) {
+ map[i] = 0;
+ }
+ sMap = NULL;
+ sMapLen = sMapSize = 0;
+ refCnt = 1;
+}
+
+CharCodeToUnicode::CharCodeToUnicode(GString *collectionA, Unicode *mapA,
+ CharCode mapLenA, GBool copyMap,
+ CharCodeToUnicodeString *sMapA,
+ int sMapLenA) {
+ collection = collectionA;
+ mapLen = mapLenA;
+ if (copyMap) {
+ map = (Unicode *)gmalloc(mapLen * sizeof(Unicode));
+ memcpy(map, mapA, mapLen * sizeof(Unicode));
+ } else {
+ map = mapA;
+ }
+ sMap = sMapA;
+ sMapLen = sMapSize = sMapLenA;
+ refCnt = 1;
+}
+
+CharCodeToUnicode::~CharCodeToUnicode() {
+ if (collection) {
+ delete collection;
+ }
+ gfree(map);
+ if (sMap) {
+ gfree(sMap);
+ }
+}
+
+void CharCodeToUnicode::incRefCnt() {
+ ++refCnt;
+}
+
+void CharCodeToUnicode::decRefCnt() {
+ if (--refCnt == 0) {
+ delete this;
+ }
+}
+
+GBool CharCodeToUnicode::match(GString *collectionA) {
+ return collection && !collection->cmp(collectionA);
+}
+
+int CharCodeToUnicode::mapToUnicode(CharCode c, Unicode *u, int size) {
+ int i, j;
+
+ if (c >= mapLen) {
+ return 0;
+ }
+ if (map[c]) {
+ u[0] = map[c];
+ return 1;
+ }
+ for (i = 0; i < sMapLen; ++i) {
+ if (sMap[i].c == c) {
+ for (j = 0; j < sMap[i].len && j < size; ++j) {
+ u[j] = sMap[i].u[j];
+ }
+ return j;
+ }
+ }
+ return 0;
+}
+
+//------------------------------------------------------------------------
+
+CIDToUnicodeCache::CIDToUnicodeCache() {
+ int i;
+
+ for (i = 0; i < cidToUnicodeCacheSize; ++i) {
+ cache[i] = NULL;
+ }
+}
+
+CIDToUnicodeCache::~CIDToUnicodeCache() {
+ int i;
+
+ for (i = 0; i < cidToUnicodeCacheSize; ++i) {
+ if (cache[i]) {
+ cache[i]->decRefCnt();
+ }
+ }
+}
+
+CharCodeToUnicode *CIDToUnicodeCache::getCIDToUnicode(GString *collection) {
+ CharCodeToUnicode *ctu;
+ int i, j;
+
+ if (cache[0] && cache[0]->match(collection)) {
+ cache[0]->incRefCnt();
+ return cache[0];
+ }
+ for (i = 1; i < cidToUnicodeCacheSize; ++i) {
+ if (cache[i] && cache[i]->match(collection)) {
+ ctu = cache[i];
+ for (j = i; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = ctu;
+ ctu->incRefCnt();
+ return ctu;
+ }
+ }
+ if ((ctu = CharCodeToUnicode::parseCIDToUnicode(collection))) {
+ if (cache[cidToUnicodeCacheSize - 1]) {
+ cache[cidToUnicodeCacheSize - 1]->decRefCnt();
+ }
+ for (j = cidToUnicodeCacheSize - 1; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = ctu;
+ ctu->incRefCnt();
+ return ctu;
+ }
+ return NULL;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Decrypt.cc b/filters/kword/pdf/xpdf/xpdf/Decrypt.cc
deleted file mode 100644
index 920cd63f4..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Decrypt.cc
+++ /dev/null
@@ -1,401 +0,0 @@
-//========================================================================
-//
-// Decrypt.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "gmem.h"
-#include "Decrypt.h"
-
-static void rc4InitKey(Guchar *key, int keyLen, Guchar *state);
-static Guchar rc4DecryptByte(Guchar *state, Guchar *x, Guchar *y, Guchar c);
-static void md5(Guchar *msg, int msgLen, Guchar *digest);
-
-static Guchar passwordPad[32] = {
- 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
- 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
- 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
- 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
-};
-
-//------------------------------------------------------------------------
-// Decrypt
-//------------------------------------------------------------------------
-
-Decrypt::Decrypt(Guchar *fileKey, int keyLength, int objNum, int objGen) {
- int i;
-
- // construct object key
- for (i = 0; i < keyLength; ++i) {
- objKey[i] = fileKey[i];
- }
- objKey[keyLength] = objNum & 0xff;
- objKey[keyLength + 1] = (objNum >> 8) & 0xff;
- objKey[keyLength + 2] = (objNum >> 16) & 0xff;
- objKey[keyLength + 3] = objGen & 0xff;
- objKey[keyLength + 4] = (objGen >> 8) & 0xff;
- md5(objKey, keyLength + 5, objKey);
-
- // set up for decryption
- x = y = 0;
- if ((objKeyLength = keyLength + 5) > 16) {
- objKeyLength = 16;
- }
- rc4InitKey(objKey, objKeyLength, state);
-}
-
-void Decrypt::reset() {
- x = y = 0;
- rc4InitKey(objKey, objKeyLength, state);
-}
-
-Guchar Decrypt::decryptByte(Guchar c) {
- return rc4DecryptByte(state, &x, &y, c);
-}
-
-GBool Decrypt::makeFileKey(int encVersion, int encRevision, int keyLength,
- GString *ownerKey, GString *userKey,
- int permissions, GString *fileID,
- GString *ownerPassword, GString *userPassword,
- Guchar *fileKey, GBool *ownerPasswordOk) {
- Guchar test[32], test2[32];
- GString *userPassword2;
- Guchar fState[256];
- Guchar tmpKey[16];
- Guchar fx, fy;
- int len, i, j;
-
- // try using the supplied owner password to generate the user password
- if (ownerPassword) {
- len = ownerPassword->getLength();
- if (len < 32) {
- memcpy(test, ownerPassword->getCString(), len);
- memcpy(test + len, passwordPad, 32 - len);
- } else {
- memcpy(test, ownerPassword->getCString(), 32);
- }
- } else {
- memcpy(test, passwordPad, 32);
- }
- md5(test, 32, test);
- if (encRevision == 3) {
- for (i = 0; i < 50; ++i) {
- md5(test, 16, test);
- }
- }
- if (encRevision == 2) {
- rc4InitKey(test, keyLength, fState);
- fx = fy = 0;
- for (i = 0; i < 32; ++i) {
- test2[i] = rc4DecryptByte(fState, &fx, &fy, ownerKey->getChar(i));
- }
- } else {
- memcpy(test2, ownerKey->getCString(), 32);
- for (i = 19; i >= 0; --i) {
- for (j = 0; j < keyLength; ++j) {
- tmpKey[j] = test[j] ^ i;
- }
- rc4InitKey(tmpKey, keyLength, fState);
- fx = fy = 0;
- for (j = 0; j < 32; ++j) {
- test2[j] = rc4DecryptByte(fState, &fx, &fy, test2[j]);
- }
- }
- }
- userPassword2 = new GString((char *)test2, 32);
- if (makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey,
- permissions, fileID, userPassword2, fileKey)) {
- *ownerPasswordOk = gTrue;
- delete userPassword2;
- return gTrue;
- }
- *ownerPasswordOk = gFalse;
- delete userPassword2;
-
- // try using the supplied user password
- return makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey,
- permissions, fileID, userPassword, fileKey);
-}
-
-GBool Decrypt::makeFileKey2(int /*encVersion*/, int encRevision, int keyLength,
- GString *ownerKey, GString *userKey,
- int permissions, GString *fileID,
- GString *userPassword, Guchar *fileKey) {
- Guchar *buf;
- Guchar test[32];
- Guchar fState[256];
- Guchar tmpKey[16];
- Guchar fx, fy;
- int len, i, j;
- GBool ok;
-
- // generate file key
- buf = (Guchar *)gmalloc(68 + fileID->getLength());
- if (userPassword) {
- len = userPassword->getLength();
- if (len < 32) {
- memcpy(buf, userPassword->getCString(), len);
- memcpy(buf + len, passwordPad, 32 - len);
- } else {
- memcpy(buf, userPassword->getCString(), 32);
- }
- } else {
- memcpy(buf, passwordPad, 32);
- }
- memcpy(buf + 32, ownerKey->getCString(), 32);
- buf[64] = permissions & 0xff;
- buf[65] = (permissions >> 8) & 0xff;
- buf[66] = (permissions >> 16) & 0xff;
- buf[67] = (permissions >> 24) & 0xff;
- memcpy(buf + 68, fileID->getCString(), fileID->getLength());
- md5(buf, 68 + fileID->getLength(), fileKey);
- if (encRevision == 3) {
- for (i = 0; i < 50; ++i) {
- md5(fileKey, keyLength, fileKey);
- }
- }
-
- // test user password
- if (encRevision == 2) {
- rc4InitKey(fileKey, keyLength, fState);
- fx = fy = 0;
- for (i = 0; i < 32; ++i) {
- test[i] = rc4DecryptByte(fState, &fx, &fy, userKey->getChar(i));
- }
- ok = memcmp(test, passwordPad, 32) == 0;
- } else if (encRevision == 3) {
- memcpy(test, userKey->getCString(), 32);
- for (i = 19; i >= 0; --i) {
- for (j = 0; j < keyLength; ++j) {
- tmpKey[j] = fileKey[j] ^ i;
- }
- rc4InitKey(tmpKey, keyLength, fState);
- fx = fy = 0;
- for (j = 0; j < 32; ++j) {
- test[j] = rc4DecryptByte(fState, &fx, &fy, test[j]);
- }
- }
- memcpy(buf, passwordPad, 32);
- memcpy(buf + 32, fileID->getCString(), fileID->getLength());
- md5(buf, 32 + fileID->getLength(), buf);
- ok = memcmp(test, buf, 16) == 0;
- } else {
- ok = gFalse;
- }
-
- gfree(buf);
- return ok;
-}
-
-//------------------------------------------------------------------------
-// RC4-compatible decryption
-//------------------------------------------------------------------------
-
-static void rc4InitKey(Guchar *key, int keyLen, Guchar *state) {
- Guchar index1, index2;
- Guchar t;
- int i;
-
- for (i = 0; i < 256; ++i)
- state[i] = i;
- index1 = index2 = 0;
- for (i = 0; i < 256; ++i) {
- index2 = (key[index1] + state[i] + index2) % 256;
- t = state[i];
- state[i] = state[index2];
- state[index2] = t;
- index1 = (index1 + 1) % keyLen;
- }
-}
-
-static Guchar rc4DecryptByte(Guchar *state, Guchar *x, Guchar *y, Guchar c) {
- Guchar x1, y1, tx, ty;
-
- x1 = *x = (*x + 1) % 256;
- y1 = *y = (state[*x] + *y) % 256;
- tx = state[x1];
- ty = state[y1];
- state[x1] = ty;
- state[y1] = tx;
- return c ^ state[(tx + ty) % 256];
-}
-
-//------------------------------------------------------------------------
-// MD5 message digest
-//------------------------------------------------------------------------
-
-// this works around a bug in older Sun compilers
-static inline Gulong rotateLeft(Gulong x, int r) {
- x &= 0xffffffff;
- return ((x << r) | (x >> (32 - r))) & 0xffffffff;
-}
-
-static inline Gulong md5Round1(Gulong a, Gulong b, Gulong c, Gulong d,
- Gulong Xk, Gulong s, Gulong Ti) {
- return b + rotateLeft((a + ((b & c) | (~b & d)) + Xk + Ti), s);
-}
-
-static inline Gulong md5Round2(Gulong a, Gulong b, Gulong c, Gulong d,
- Gulong Xk, Gulong s, Gulong Ti) {
- return b + rotateLeft((a + ((b & d) | (c & ~d)) + Xk + Ti), s);
-}
-
-static inline Gulong md5Round3(Gulong a, Gulong b, Gulong c, Gulong d,
- Gulong Xk, Gulong s, Gulong Ti) {
- return b + rotateLeft((a + (b ^ c ^ d) + Xk + Ti), s);
-}
-
-static inline Gulong md5Round4(Gulong a, Gulong b, Gulong c, Gulong d,
- Gulong Xk, Gulong s, Gulong Ti) {
- return b + rotateLeft((a + (c ^ (b | ~d)) + Xk + Ti), s);
-}
-
-static void md5(Guchar *msg, int msgLen, Guchar *digest) {
- Gulong x[16];
- Gulong a, b, c, d, aa, bb, cc, dd;
- int n64;
- int i, j, k;
-
- // compute number of 64-byte blocks
- // (length + pad byte (0x80) + 8 bytes for length)
- n64 = (msgLen + 1 + 8 + 63) / 64;
-
- // initialize a, b, c, d
- a = 0x67452301;
- b = 0xefcdab89;
- c = 0x98badcfe;
- d = 0x10325476;
-
- // loop through blocks
- k = 0;
- for (i = 0; i < n64; ++i) {
-
- // grab a 64-byte block
- for (j = 0; j < 16 && k < msgLen - 3; ++j, k += 4)
- x[j] = (((((msg[k+3] << 8) + msg[k+2]) << 8) + msg[k+1]) << 8) + msg[k];
- if (i == n64 - 1) {
- if (k == msgLen - 3)
- x[j] = 0x80000000 + (((msg[k+2] << 8) + msg[k+1]) << 8) + msg[k];
- else if (k == msgLen - 2)
- x[j] = 0x800000 + (msg[k+1] << 8) + msg[k];
- else if (k == msgLen - 1)
- x[j] = 0x8000 + msg[k];
- else
- x[j] = 0x80;
- ++j;
- while (j < 16)
- x[j++] = 0;
- x[14] = msgLen << 3;
- }
-
- // save a, b, c, d
- aa = a;
- bb = b;
- cc = c;
- dd = d;
-
- // round 1
- a = md5Round1(a, b, c, d, x[0], 7, 0xd76aa478);
- d = md5Round1(d, a, b, c, x[1], 12, 0xe8c7b756);
- c = md5Round1(c, d, a, b, x[2], 17, 0x242070db);
- b = md5Round1(b, c, d, a, x[3], 22, 0xc1bdceee);
- a = md5Round1(a, b, c, d, x[4], 7, 0xf57c0faf);
- d = md5Round1(d, a, b, c, x[5], 12, 0x4787c62a);
- c = md5Round1(c, d, a, b, x[6], 17, 0xa8304613);
- b = md5Round1(b, c, d, a, x[7], 22, 0xfd469501);
- a = md5Round1(a, b, c, d, x[8], 7, 0x698098d8);
- d = md5Round1(d, a, b, c, x[9], 12, 0x8b44f7af);
- c = md5Round1(c, d, a, b, x[10], 17, 0xffff5bb1);
- b = md5Round1(b, c, d, a, x[11], 22, 0x895cd7be);
- a = md5Round1(a, b, c, d, x[12], 7, 0x6b901122);
- d = md5Round1(d, a, b, c, x[13], 12, 0xfd987193);
- c = md5Round1(c, d, a, b, x[14], 17, 0xa679438e);
- b = md5Round1(b, c, d, a, x[15], 22, 0x49b40821);
-
- // round 2
- a = md5Round2(a, b, c, d, x[1], 5, 0xf61e2562);
- d = md5Round2(d, a, b, c, x[6], 9, 0xc040b340);
- c = md5Round2(c, d, a, b, x[11], 14, 0x265e5a51);
- b = md5Round2(b, c, d, a, x[0], 20, 0xe9b6c7aa);
- a = md5Round2(a, b, c, d, x[5], 5, 0xd62f105d);
- d = md5Round2(d, a, b, c, x[10], 9, 0x02441453);
- c = md5Round2(c, d, a, b, x[15], 14, 0xd8a1e681);
- b = md5Round2(b, c, d, a, x[4], 20, 0xe7d3fbc8);
- a = md5Round2(a, b, c, d, x[9], 5, 0x21e1cde6);
- d = md5Round2(d, a, b, c, x[14], 9, 0xc33707d6);
- c = md5Round2(c, d, a, b, x[3], 14, 0xf4d50d87);
- b = md5Round2(b, c, d, a, x[8], 20, 0x455a14ed);
- a = md5Round2(a, b, c, d, x[13], 5, 0xa9e3e905);
- d = md5Round2(d, a, b, c, x[2], 9, 0xfcefa3f8);
- c = md5Round2(c, d, a, b, x[7], 14, 0x676f02d9);
- b = md5Round2(b, c, d, a, x[12], 20, 0x8d2a4c8a);
-
- // round 3
- a = md5Round3(a, b, c, d, x[5], 4, 0xfffa3942);
- d = md5Round3(d, a, b, c, x[8], 11, 0x8771f681);
- c = md5Round3(c, d, a, b, x[11], 16, 0x6d9d6122);
- b = md5Round3(b, c, d, a, x[14], 23, 0xfde5380c);
- a = md5Round3(a, b, c, d, x[1], 4, 0xa4beea44);
- d = md5Round3(d, a, b, c, x[4], 11, 0x4bdecfa9);
- c = md5Round3(c, d, a, b, x[7], 16, 0xf6bb4b60);
- b = md5Round3(b, c, d, a, x[10], 23, 0xbebfbc70);
- a = md5Round3(a, b, c, d, x[13], 4, 0x289b7ec6);
- d = md5Round3(d, a, b, c, x[0], 11, 0xeaa127fa);
- c = md5Round3(c, d, a, b, x[3], 16, 0xd4ef3085);
- b = md5Round3(b, c, d, a, x[6], 23, 0x04881d05);
- a = md5Round3(a, b, c, d, x[9], 4, 0xd9d4d039);
- d = md5Round3(d, a, b, c, x[12], 11, 0xe6db99e5);
- c = md5Round3(c, d, a, b, x[15], 16, 0x1fa27cf8);
- b = md5Round3(b, c, d, a, x[2], 23, 0xc4ac5665);
-
- // round 4
- a = md5Round4(a, b, c, d, x[0], 6, 0xf4292244);
- d = md5Round4(d, a, b, c, x[7], 10, 0x432aff97);
- c = md5Round4(c, d, a, b, x[14], 15, 0xab9423a7);
- b = md5Round4(b, c, d, a, x[5], 21, 0xfc93a039);
- a = md5Round4(a, b, c, d, x[12], 6, 0x655b59c3);
- d = md5Round4(d, a, b, c, x[3], 10, 0x8f0ccc92);
- c = md5Round4(c, d, a, b, x[10], 15, 0xffeff47d);
- b = md5Round4(b, c, d, a, x[1], 21, 0x85845dd1);
- a = md5Round4(a, b, c, d, x[8], 6, 0x6fa87e4f);
- d = md5Round4(d, a, b, c, x[15], 10, 0xfe2ce6e0);
- c = md5Round4(c, d, a, b, x[6], 15, 0xa3014314);
- b = md5Round4(b, c, d, a, x[13], 21, 0x4e0811a1);
- a = md5Round4(a, b, c, d, x[4], 6, 0xf7537e82);
- d = md5Round4(d, a, b, c, x[11], 10, 0xbd3af235);
- c = md5Round4(c, d, a, b, x[2], 15, 0x2ad7d2bb);
- b = md5Round4(b, c, d, a, x[9], 21, 0xeb86d391);
-
- // increment a, b, c, d
- a += aa;
- b += bb;
- c += cc;
- d += dd;
- }
-
- // break digest into bytes
- digest[0] = a & 0xff;
- digest[1] = (a >>= 8) & 0xff;
- digest[2] = (a >>= 8) & 0xff;
- digest[3] = (a >>= 8) & 0xff;
- digest[4] = b & 0xff;
- digest[5] = (b >>= 8) & 0xff;
- digest[6] = (b >>= 8) & 0xff;
- digest[7] = (b >>= 8) & 0xff;
- digest[8] = c & 0xff;
- digest[9] = (c >>= 8) & 0xff;
- digest[10] = (c >>= 8) & 0xff;
- digest[11] = (c >>= 8) & 0xff;
- digest[12] = d & 0xff;
- digest[13] = (d >>= 8) & 0xff;
- digest[14] = (d >>= 8) & 0xff;
- digest[15] = (d >>= 8) & 0xff;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Decrypt.cpp b/filters/kword/pdf/xpdf/xpdf/Decrypt.cpp
new file mode 100644
index 000000000..11767f752
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Decrypt.cpp
@@ -0,0 +1,401 @@
+//========================================================================
+//
+// Decrypt.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "gmem.h"
+#include "Decrypt.h"
+
+static void rc4InitKey(Guchar *key, int keyLen, Guchar *state);
+static Guchar rc4DecryptByte(Guchar *state, Guchar *x, Guchar *y, Guchar c);
+static void md5(Guchar *msg, int msgLen, Guchar *digest);
+
+static Guchar passwordPad[32] = {
+ 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
+ 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
+ 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
+ 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
+};
+
+//------------------------------------------------------------------------
+// Decrypt
+//------------------------------------------------------------------------
+
+Decrypt::Decrypt(Guchar *fileKey, int keyLength, int objNum, int objGen) {
+ int i;
+
+ // construct object key
+ for (i = 0; i < keyLength; ++i) {
+ objKey[i] = fileKey[i];
+ }
+ objKey[keyLength] = objNum & 0xff;
+ objKey[keyLength + 1] = (objNum >> 8) & 0xff;
+ objKey[keyLength + 2] = (objNum >> 16) & 0xff;
+ objKey[keyLength + 3] = objGen & 0xff;
+ objKey[keyLength + 4] = (objGen >> 8) & 0xff;
+ md5(objKey, keyLength + 5, objKey);
+
+ // set up for decryption
+ x = y = 0;
+ if ((objKeyLength = keyLength + 5) > 16) {
+ objKeyLength = 16;
+ }
+ rc4InitKey(objKey, objKeyLength, state);
+}
+
+void Decrypt::reset() {
+ x = y = 0;
+ rc4InitKey(objKey, objKeyLength, state);
+}
+
+Guchar Decrypt::decryptByte(Guchar c) {
+ return rc4DecryptByte(state, &x, &y, c);
+}
+
+GBool Decrypt::makeFileKey(int encVersion, int encRevision, int keyLength,
+ GString *ownerKey, GString *userKey,
+ int permissions, GString *fileID,
+ GString *ownerPassword, GString *userPassword,
+ Guchar *fileKey, GBool *ownerPasswordOk) {
+ Guchar test[32], test2[32];
+ GString *userPassword2;
+ Guchar fState[256];
+ Guchar tmpKey[16];
+ Guchar fx, fy;
+ int len, i, j;
+
+ // try using the supplied owner password to generate the user password
+ if (ownerPassword) {
+ len = ownerPassword->getLength();
+ if (len < 32) {
+ memcpy(test, ownerPassword->getCString(), len);
+ memcpy(test + len, passwordPad, 32 - len);
+ } else {
+ memcpy(test, ownerPassword->getCString(), 32);
+ }
+ } else {
+ memcpy(test, passwordPad, 32);
+ }
+ md5(test, 32, test);
+ if (encRevision == 3) {
+ for (i = 0; i < 50; ++i) {
+ md5(test, 16, test);
+ }
+ }
+ if (encRevision == 2) {
+ rc4InitKey(test, keyLength, fState);
+ fx = fy = 0;
+ for (i = 0; i < 32; ++i) {
+ test2[i] = rc4DecryptByte(fState, &fx, &fy, ownerKey->getChar(i));
+ }
+ } else {
+ memcpy(test2, ownerKey->getCString(), 32);
+ for (i = 19; i >= 0; --i) {
+ for (j = 0; j < keyLength; ++j) {
+ tmpKey[j] = test[j] ^ i;
+ }
+ rc4InitKey(tmpKey, keyLength, fState);
+ fx = fy = 0;
+ for (j = 0; j < 32; ++j) {
+ test2[j] = rc4DecryptByte(fState, &fx, &fy, test2[j]);
+ }
+ }
+ }
+ userPassword2 = new GString((char *)test2, 32);
+ if (makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey,
+ permissions, fileID, userPassword2, fileKey)) {
+ *ownerPasswordOk = gTrue;
+ delete userPassword2;
+ return gTrue;
+ }
+ *ownerPasswordOk = gFalse;
+ delete userPassword2;
+
+ // try using the supplied user password
+ return makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey,
+ permissions, fileID, userPassword, fileKey);
+}
+
+GBool Decrypt::makeFileKey2(int /*encVersion*/, int encRevision, int keyLength,
+ GString *ownerKey, GString *userKey,
+ int permissions, GString *fileID,
+ GString *userPassword, Guchar *fileKey) {
+ Guchar *buf;
+ Guchar test[32];
+ Guchar fState[256];
+ Guchar tmpKey[16];
+ Guchar fx, fy;
+ int len, i, j;
+ GBool ok;
+
+ // generate file key
+ buf = (Guchar *)gmalloc(68 + fileID->getLength());
+ if (userPassword) {
+ len = userPassword->getLength();
+ if (len < 32) {
+ memcpy(buf, userPassword->getCString(), len);
+ memcpy(buf + len, passwordPad, 32 - len);
+ } else {
+ memcpy(buf, userPassword->getCString(), 32);
+ }
+ } else {
+ memcpy(buf, passwordPad, 32);
+ }
+ memcpy(buf + 32, ownerKey->getCString(), 32);
+ buf[64] = permissions & 0xff;
+ buf[65] = (permissions >> 8) & 0xff;
+ buf[66] = (permissions >> 16) & 0xff;
+ buf[67] = (permissions >> 24) & 0xff;
+ memcpy(buf + 68, fileID->getCString(), fileID->getLength());
+ md5(buf, 68 + fileID->getLength(), fileKey);
+ if (encRevision == 3) {
+ for (i = 0; i < 50; ++i) {
+ md5(fileKey, keyLength, fileKey);
+ }
+ }
+
+ // test user password
+ if (encRevision == 2) {
+ rc4InitKey(fileKey, keyLength, fState);
+ fx = fy = 0;
+ for (i = 0; i < 32; ++i) {
+ test[i] = rc4DecryptByte(fState, &fx, &fy, userKey->getChar(i));
+ }
+ ok = memcmp(test, passwordPad, 32) == 0;
+ } else if (encRevision == 3) {
+ memcpy(test, userKey->getCString(), 32);
+ for (i = 19; i >= 0; --i) {
+ for (j = 0; j < keyLength; ++j) {
+ tmpKey[j] = fileKey[j] ^ i;
+ }
+ rc4InitKey(tmpKey, keyLength, fState);
+ fx = fy = 0;
+ for (j = 0; j < 32; ++j) {
+ test[j] = rc4DecryptByte(fState, &fx, &fy, test[j]);
+ }
+ }
+ memcpy(buf, passwordPad, 32);
+ memcpy(buf + 32, fileID->getCString(), fileID->getLength());
+ md5(buf, 32 + fileID->getLength(), buf);
+ ok = memcmp(test, buf, 16) == 0;
+ } else {
+ ok = gFalse;
+ }
+
+ gfree(buf);
+ return ok;
+}
+
+//------------------------------------------------------------------------
+// RC4-compatible decryption
+//------------------------------------------------------------------------
+
+static void rc4InitKey(Guchar *key, int keyLen, Guchar *state) {
+ Guchar index1, index2;
+ Guchar t;
+ int i;
+
+ for (i = 0; i < 256; ++i)
+ state[i] = i;
+ index1 = index2 = 0;
+ for (i = 0; i < 256; ++i) {
+ index2 = (key[index1] + state[i] + index2) % 256;
+ t = state[i];
+ state[i] = state[index2];
+ state[index2] = t;
+ index1 = (index1 + 1) % keyLen;
+ }
+}
+
+static Guchar rc4DecryptByte(Guchar *state, Guchar *x, Guchar *y, Guchar c) {
+ Guchar x1, y1, tx, ty;
+
+ x1 = *x = (*x + 1) % 256;
+ y1 = *y = (state[*x] + *y) % 256;
+ tx = state[x1];
+ ty = state[y1];
+ state[x1] = ty;
+ state[y1] = tx;
+ return c ^ state[(tx + ty) % 256];
+}
+
+//------------------------------------------------------------------------
+// MD5 message digest
+//------------------------------------------------------------------------
+
+// this works around a bug in older Sun compilers
+static inline Gulong rotateLeft(Gulong x, int r) {
+ x &= 0xffffffff;
+ return ((x << r) | (x >> (32 - r))) & 0xffffffff;
+}
+
+static inline Gulong md5Round1(Gulong a, Gulong b, Gulong c, Gulong d,
+ Gulong Xk, Gulong s, Gulong Ti) {
+ return b + rotateLeft((a + ((b & c) | (~b & d)) + Xk + Ti), s);
+}
+
+static inline Gulong md5Round2(Gulong a, Gulong b, Gulong c, Gulong d,
+ Gulong Xk, Gulong s, Gulong Ti) {
+ return b + rotateLeft((a + ((b & d) | (c & ~d)) + Xk + Ti), s);
+}
+
+static inline Gulong md5Round3(Gulong a, Gulong b, Gulong c, Gulong d,
+ Gulong Xk, Gulong s, Gulong Ti) {
+ return b + rotateLeft((a + (b ^ c ^ d) + Xk + Ti), s);
+}
+
+static inline Gulong md5Round4(Gulong a, Gulong b, Gulong c, Gulong d,
+ Gulong Xk, Gulong s, Gulong Ti) {
+ return b + rotateLeft((a + (c ^ (b | ~d)) + Xk + Ti), s);
+}
+
+static void md5(Guchar *msg, int msgLen, Guchar *digest) {
+ Gulong x[16];
+ Gulong a, b, c, d, aa, bb, cc, dd;
+ int n64;
+ int i, j, k;
+
+ // compute number of 64-byte blocks
+ // (length + pad byte (0x80) + 8 bytes for length)
+ n64 = (msgLen + 1 + 8 + 63) / 64;
+
+ // initialize a, b, c, d
+ a = 0x67452301;
+ b = 0xefcdab89;
+ c = 0x98badcfe;
+ d = 0x10325476;
+
+ // loop through blocks
+ k = 0;
+ for (i = 0; i < n64; ++i) {
+
+ // grab a 64-byte block
+ for (j = 0; j < 16 && k < msgLen - 3; ++j, k += 4)
+ x[j] = (((((msg[k+3] << 8) + msg[k+2]) << 8) + msg[k+1]) << 8) + msg[k];
+ if (i == n64 - 1) {
+ if (k == msgLen - 3)
+ x[j] = 0x80000000 + (((msg[k+2] << 8) + msg[k+1]) << 8) + msg[k];
+ else if (k == msgLen - 2)
+ x[j] = 0x800000 + (msg[k+1] << 8) + msg[k];
+ else if (k == msgLen - 1)
+ x[j] = 0x8000 + msg[k];
+ else
+ x[j] = 0x80;
+ ++j;
+ while (j < 16)
+ x[j++] = 0;
+ x[14] = msgLen << 3;
+ }
+
+ // save a, b, c, d
+ aa = a;
+ bb = b;
+ cc = c;
+ dd = d;
+
+ // round 1
+ a = md5Round1(a, b, c, d, x[0], 7, 0xd76aa478);
+ d = md5Round1(d, a, b, c, x[1], 12, 0xe8c7b756);
+ c = md5Round1(c, d, a, b, x[2], 17, 0x242070db);
+ b = md5Round1(b, c, d, a, x[3], 22, 0xc1bdceee);
+ a = md5Round1(a, b, c, d, x[4], 7, 0xf57c0faf);
+ d = md5Round1(d, a, b, c, x[5], 12, 0x4787c62a);
+ c = md5Round1(c, d, a, b, x[6], 17, 0xa8304613);
+ b = md5Round1(b, c, d, a, x[7], 22, 0xfd469501);
+ a = md5Round1(a, b, c, d, x[8], 7, 0x698098d8);
+ d = md5Round1(d, a, b, c, x[9], 12, 0x8b44f7af);
+ c = md5Round1(c, d, a, b, x[10], 17, 0xffff5bb1);
+ b = md5Round1(b, c, d, a, x[11], 22, 0x895cd7be);
+ a = md5Round1(a, b, c, d, x[12], 7, 0x6b901122);
+ d = md5Round1(d, a, b, c, x[13], 12, 0xfd987193);
+ c = md5Round1(c, d, a, b, x[14], 17, 0xa679438e);
+ b = md5Round1(b, c, d, a, x[15], 22, 0x49b40821);
+
+ // round 2
+ a = md5Round2(a, b, c, d, x[1], 5, 0xf61e2562);
+ d = md5Round2(d, a, b, c, x[6], 9, 0xc040b340);
+ c = md5Round2(c, d, a, b, x[11], 14, 0x265e5a51);
+ b = md5Round2(b, c, d, a, x[0], 20, 0xe9b6c7aa);
+ a = md5Round2(a, b, c, d, x[5], 5, 0xd62f105d);
+ d = md5Round2(d, a, b, c, x[10], 9, 0x02441453);
+ c = md5Round2(c, d, a, b, x[15], 14, 0xd8a1e681);
+ b = md5Round2(b, c, d, a, x[4], 20, 0xe7d3fbc8);
+ a = md5Round2(a, b, c, d, x[9], 5, 0x21e1cde6);
+ d = md5Round2(d, a, b, c, x[14], 9, 0xc33707d6);
+ c = md5Round2(c, d, a, b, x[3], 14, 0xf4d50d87);
+ b = md5Round2(b, c, d, a, x[8], 20, 0x455a14ed);
+ a = md5Round2(a, b, c, d, x[13], 5, 0xa9e3e905);
+ d = md5Round2(d, a, b, c, x[2], 9, 0xfcefa3f8);
+ c = md5Round2(c, d, a, b, x[7], 14, 0x676f02d9);
+ b = md5Round2(b, c, d, a, x[12], 20, 0x8d2a4c8a);
+
+ // round 3
+ a = md5Round3(a, b, c, d, x[5], 4, 0xfffa3942);
+ d = md5Round3(d, a, b, c, x[8], 11, 0x8771f681);
+ c = md5Round3(c, d, a, b, x[11], 16, 0x6d9d6122);
+ b = md5Round3(b, c, d, a, x[14], 23, 0xfde5380c);
+ a = md5Round3(a, b, c, d, x[1], 4, 0xa4beea44);
+ d = md5Round3(d, a, b, c, x[4], 11, 0x4bdecfa9);
+ c = md5Round3(c, d, a, b, x[7], 16, 0xf6bb4b60);
+ b = md5Round3(b, c, d, a, x[10], 23, 0xbebfbc70);
+ a = md5Round3(a, b, c, d, x[13], 4, 0x289b7ec6);
+ d = md5Round3(d, a, b, c, x[0], 11, 0xeaa127fa);
+ c = md5Round3(c, d, a, b, x[3], 16, 0xd4ef3085);
+ b = md5Round3(b, c, d, a, x[6], 23, 0x04881d05);
+ a = md5Round3(a, b, c, d, x[9], 4, 0xd9d4d039);
+ d = md5Round3(d, a, b, c, x[12], 11, 0xe6db99e5);
+ c = md5Round3(c, d, a, b, x[15], 16, 0x1fa27cf8);
+ b = md5Round3(b, c, d, a, x[2], 23, 0xc4ac5665);
+
+ // round 4
+ a = md5Round4(a, b, c, d, x[0], 6, 0xf4292244);
+ d = md5Round4(d, a, b, c, x[7], 10, 0x432aff97);
+ c = md5Round4(c, d, a, b, x[14], 15, 0xab9423a7);
+ b = md5Round4(b, c, d, a, x[5], 21, 0xfc93a039);
+ a = md5Round4(a, b, c, d, x[12], 6, 0x655b59c3);
+ d = md5Round4(d, a, b, c, x[3], 10, 0x8f0ccc92);
+ c = md5Round4(c, d, a, b, x[10], 15, 0xffeff47d);
+ b = md5Round4(b, c, d, a, x[1], 21, 0x85845dd1);
+ a = md5Round4(a, b, c, d, x[8], 6, 0x6fa87e4f);
+ d = md5Round4(d, a, b, c, x[15], 10, 0xfe2ce6e0);
+ c = md5Round4(c, d, a, b, x[6], 15, 0xa3014314);
+ b = md5Round4(b, c, d, a, x[13], 21, 0x4e0811a1);
+ a = md5Round4(a, b, c, d, x[4], 6, 0xf7537e82);
+ d = md5Round4(d, a, b, c, x[11], 10, 0xbd3af235);
+ c = md5Round4(c, d, a, b, x[2], 15, 0x2ad7d2bb);
+ b = md5Round4(b, c, d, a, x[9], 21, 0xeb86d391);
+
+ // increment a, b, c, d
+ a += aa;
+ b += bb;
+ c += cc;
+ d += dd;
+ }
+
+ // break digest into bytes
+ digest[0] = a & 0xff;
+ digest[1] = (a >>= 8) & 0xff;
+ digest[2] = (a >>= 8) & 0xff;
+ digest[3] = (a >>= 8) & 0xff;
+ digest[4] = b & 0xff;
+ digest[5] = (b >>= 8) & 0xff;
+ digest[6] = (b >>= 8) & 0xff;
+ digest[7] = (b >>= 8) & 0xff;
+ digest[8] = c & 0xff;
+ digest[9] = (c >>= 8) & 0xff;
+ digest[10] = (c >>= 8) & 0xff;
+ digest[11] = (c >>= 8) & 0xff;
+ digest[12] = d & 0xff;
+ digest[13] = (d >>= 8) & 0xff;
+ digest[14] = (d >>= 8) & 0xff;
+ digest[15] = (d >>= 8) & 0xff;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Dict.cc b/filters/kword/pdf/xpdf/xpdf/Dict.cc
deleted file mode 100644
index 351c23a02..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Dict.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-//========================================================================
-//
-// Dict.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include <string.h>
-#include "gmem.h"
-#include "Object.h"
-#include "XRef.h"
-#include "Dict.h"
-
-//------------------------------------------------------------------------
-// Dict
-//------------------------------------------------------------------------
-
-Dict::Dict(XRef *xrefA) {
- xref = xrefA;
- entries = NULL;
- size = length = 0;
- ref = 1;
-}
-
-Dict::~Dict() {
- int i;
-
- for (i = 0; i < length; ++i) {
- gfree(entries[i].key);
- entries[i].val.free();
- }
- gfree(entries);
-}
-
-void Dict::add(char *key, Object *val) {
- if (length + 1 > size) {
- size += 8;
- entries = (DictEntry *)grealloc(entries, size * sizeof(DictEntry));
- }
- entries[length].key = key;
- entries[length].val = *val;
- ++length;
-}
-
-inline DictEntry *Dict::find(const char *key) {
- int i;
-
- for (i = 0; i < length; ++i) {
- if (!strcmp(key, entries[i].key))
- return &entries[i];
- }
- return NULL;
-}
-
-GBool Dict::is(const char *type) {
- DictEntry *e;
-
- return (e = find("Type")) && e->val.isName(type);
-}
-
-Object *Dict::lookup(const char *key, Object *obj) {
- DictEntry *e;
-
- return (e = find(key)) ? e->val.fetch(xref, obj) : obj->initNull();
-}
-
-Object *Dict::lookupNF(const char *key, Object *obj) {
- DictEntry *e;
-
- return (e = find(key)) ? e->val.copy(obj) : obj->initNull();
-}
-
-char *Dict::getKey(int i) {
- return entries[i].key;
-}
-
-Object *Dict::getVal(int i, Object *obj) {
- return entries[i].val.fetch(xref, obj);
-}
-
-Object *Dict::getValNF(int i, Object *obj) {
- return entries[i].val.copy(obj);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Dict.cpp b/filters/kword/pdf/xpdf/xpdf/Dict.cpp
new file mode 100644
index 000000000..70592a61b
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Dict.cpp
@@ -0,0 +1,91 @@
+//========================================================================
+//
+// Dict.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include <string.h>
+#include "gmem.h"
+#include "Object.h"
+#include "XRef.h"
+#include "Dict.h"
+
+//------------------------------------------------------------------------
+// Dict
+//------------------------------------------------------------------------
+
+Dict::Dict(XRef *xrefA) {
+ xref = xrefA;
+ entries = NULL;
+ size = length = 0;
+ ref = 1;
+}
+
+Dict::~Dict() {
+ int i;
+
+ for (i = 0; i < length; ++i) {
+ gfree(entries[i].key);
+ entries[i].val.free();
+ }
+ gfree(entries);
+}
+
+void Dict::add(char *key, Object *val) {
+ if (length + 1 > size) {
+ size += 8;
+ entries = (DictEntry *)grealloc(entries, size * sizeof(DictEntry));
+ }
+ entries[length].key = key;
+ entries[length].val = *val;
+ ++length;
+}
+
+inline DictEntry *Dict::find(const char *key) {
+ int i;
+
+ for (i = 0; i < length; ++i) {
+ if (!strcmp(key, entries[i].key))
+ return &entries[i];
+ }
+ return NULL;
+}
+
+GBool Dict::is(const char *type) {
+ DictEntry *e;
+
+ return (e = find("Type")) && e->val.isName(type);
+}
+
+Object *Dict::lookup(const char *key, Object *obj) {
+ DictEntry *e;
+
+ return (e = find(key)) ? e->val.fetch(xref, obj) : obj->initNull();
+}
+
+Object *Dict::lookupNF(const char *key, Object *obj) {
+ DictEntry *e;
+
+ return (e = find(key)) ? e->val.copy(obj) : obj->initNull();
+}
+
+char *Dict::getKey(int i) {
+ return entries[i].key;
+}
+
+Object *Dict::getVal(int i, Object *obj) {
+ return entries[i].val.fetch(xref, obj);
+}
+
+Object *Dict::getValNF(int i, Object *obj) {
+ return entries[i].val.copy(obj);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Error.cc b/filters/kword/pdf/xpdf/xpdf/Error.cc
deleted file mode 100644
index c1985ca85..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Error.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-//========================================================================
-//
-// Error.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stddef.h>
-#include <stdarg.h>
-#include "GlobalParams.h"
-#include "Error.h"
-
-void CDECL error(int pos, const char *msg, ...) {
- va_list args;
-
- // NB: this can be called before the globalParams object is created
- if (globalParams && globalParams->getErrQuiet()) {
- return;
- }
- if (pos >= 0) {
- fprintf(stderr, "Error (%d): ", pos);
- } else {
- fprintf(stderr, "Error: ");
- }
- va_start(args, msg);
- vfprintf(stderr, msg, args);
- va_end(args);
- fprintf(stderr, "\n");
- fflush(stderr);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Error.cpp b/filters/kword/pdf/xpdf/xpdf/Error.cpp
new file mode 100644
index 000000000..e7312a006
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Error.cpp
@@ -0,0 +1,38 @@
+//========================================================================
+//
+// Error.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include "GlobalParams.h"
+#include "Error.h"
+
+void CDECL error(int pos, const char *msg, ...) {
+ va_list args;
+
+ // NB: this can be called before the globalParams object is created
+ if (globalParams && globalParams->getErrQuiet()) {
+ return;
+ }
+ if (pos >= 0) {
+ fprintf(stderr, "Error (%d): ", pos);
+ } else {
+ fprintf(stderr, "Error: ");
+ }
+ va_start(args, msg);
+ vfprintf(stderr, msg, args);
+ va_end(args);
+ fprintf(stderr, "\n");
+ fflush(stderr);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/FTFont.cc b/filters/kword/pdf/xpdf/xpdf/FTFont.cc
deleted file mode 100644
index 8de09e0e6..000000000
--- a/filters/kword/pdf/xpdf/xpdf/FTFont.cc
+++ /dev/null
@@ -1,685 +0,0 @@
-//========================================================================
-//
-// FTFont.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <math.h>
-#include <string.h>
-#include "gmem.h"
-#include "freetype/ftoutln.h"
-#include "freetype/internal/ftobjs.h"
-#if 1 //~ cff cid->gid map
-#include "freetype/internal/cfftypes.h"
-#include "freetype/internal/tttypes.h"
-#endif
-#include "GlobalParams.h"
-#include "GfxState.h"
-#include "FTFont.h"
-
-//------------------------------------------------------------------------
-
-FTFontEngine::FTFontEngine(Display *displayA, Visual *visualA, int depthA,
- Colormap colormapA, GBool aaA):
- SFontEngine(displayA, visualA, depthA, colormapA) {
-
- ok = gFalse;
- if (FT_Init_FreeType(&lib)) {
- return;
- }
- aa = aaA;
- ok = gTrue;
-}
-
-FTFontEngine::~FTFontEngine() {
- FT_Done_FreeType(lib);
-}
-
-//------------------------------------------------------------------------
-
-FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName,
- char **fontEnc, GBool pdfFontHasEncoding) {
- char *name;
- int unicodeCmap, macRomanCmap, msSymbolCmap;
- int i, j;
-
- ok = gFalse;
- engine = engineA;
- codeMap = NULL;
- if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
- return;
- }
-
- if (!strcmp(face->driver->root.clazz->module_name, "type1") ||
- !strcmp(face->driver->root.clazz->module_name, "cff")) {
-
- mode = ftFontModeCodeMapDirect;
- codeMap = (Guint *)gmalloc(256 * sizeof(Guint));
- for (i = 0; i < 256; ++i) {
- codeMap[i] = 0;
- if ((name = fontEnc[i])) {
- codeMap[i] = FT_Get_Name_Index(face, name);
- }
- }
-
- } else {
-
- // To match up with the Adobe-defined behaviour, we choose a cmap
- // like this:
- // 1. If the PDF font has an encoding:
- // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
- // and use the Unicode indexes, not the char codes.
- // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
- // and reverse map the char names through MacRomanEncoding to
- // get char codes.
- // 2. If the PDF font does not have an encoding:
- // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
- // and use char codes directly.
- // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
- // and use (0xf000 + char code).
- // 3. If none of these rules apply, use the first cmap and hope for
- // the best (this shouldn't happen).
- unicodeCmap = macRomanCmap = msSymbolCmap = 0xffff;
- for (i = 0; i < face->num_charmaps; ++i) {
- if (face->charmaps[i]->platform_id == 3 &&
- face->charmaps[i]->encoding_id == 1) {
- unicodeCmap = i;
- } else if (face->charmaps[i]->platform_id == 1 &&
- face->charmaps[i]->encoding_id == 0) {
- macRomanCmap = i;
- } else if (face->charmaps[i]->platform_id == 3 &&
- face->charmaps[i]->encoding_id == 0) {
- msSymbolCmap = i;
- }
- }
- i = 0;
- mode = ftFontModeCharCode;
- charMapOffset = 0;
- if (pdfFontHasEncoding) {
- if (unicodeCmap != 0xffff) {
- i = unicodeCmap;
- mode = ftFontModeUnicode;
- } else if (macRomanCmap != 0xffff) {
- i = macRomanCmap;
- mode = ftFontModeCodeMap;
- codeMap = (Guint *)gmalloc(256 * sizeof(Guint));
- for (j = 0; j < 256; ++j) {
- if (fontEnc[j]) {
- codeMap[j] = globalParams->getMacRomanCharCode(fontEnc[j]);
- } else {
- codeMap[j] = 0;
- }
- }
- }
- } else {
- if (macRomanCmap != 0xffff) {
- i = macRomanCmap;
- mode = ftFontModeCharCode;
- } else if (msSymbolCmap != 0xffff) {
- i = msSymbolCmap;
- mode = ftFontModeCharCodeOffset;
- charMapOffset = 0xf000;
- }
- }
- if (FT_Set_Charmap(face, face->charmaps[i])) {
- return;
- }
- }
-
- ok = gTrue;
-}
-
-FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName,
- Gushort *cidToGIDA, int cidToGIDLenA) {
- ok = gFalse;
- engine = engineA;
- codeMap = NULL;
- if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
- return;
- }
- cidToGID = cidToGIDA;
- cidToGIDLen = cidToGIDLenA;
- mode = ftFontModeCIDToGIDMap;
- ok = gTrue;
-}
-
-FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName) {
- ok = gFalse;
- engine = engineA;
- codeMap = NULL;
- if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
- return;
- }
- cidToGID = NULL;
- cidToGIDLen = 0;
- mode = ftFontModeCFFCharset;
- ok = gTrue;
-}
-
-FTFontFile::~FTFontFile() {
- if (face) {
- FT_Done_Face(face);
- }
- if (codeMap) {
- gfree(codeMap);
- }
-}
-
-//------------------------------------------------------------------------
-
-FTFont::FTFont(FTFontFile *fontFileA, double *m) {
- FTFontEngine *engine;
- FT_Face face;
- double size, div;
- int x, xMin, xMax;
- int y, yMin, yMax;
- int i;
-
- ok = gFalse;
- fontFile = fontFileA;
- engine = fontFile->engine;
- face = fontFile->face;
- if (FT_New_Size(face, &sizeObj)) {
- return;
- }
- face->size = sizeObj;
- size = sqrt(m[2]*m[2] + m[3]*m[3]);
- if (FT_Set_Pixel_Sizes(face, 0, (int)size)) {
- return;
- }
-
- div = face->bbox.xMax > 20000 ? 65536 : 1;
-
- // transform the four corners of the font bounding box -- the min
- // and max values form the bounding box of the transformed font
- x = (int)((m[0] * face->bbox.xMin + m[2] * face->bbox.yMin) /
- (div * face->units_per_EM));
- xMin = xMax = x;
- y = (int)((m[1] * face->bbox.xMin + m[3] * face->bbox.yMin) /
- (div * face->units_per_EM));
- yMin = yMax = y;
- x = (int)((m[0] * face->bbox.xMin + m[2] * face->bbox.yMax) /
- (div * face->units_per_EM));
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * face->bbox.xMin + m[3] * face->bbox.yMax) /
- (div * face->units_per_EM));
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)((m[0] * face->bbox.xMax + m[2] * face->bbox.yMin) /
- (div * face->units_per_EM));
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * face->bbox.xMax + m[3] * face->bbox.yMin) /
- (div * face->units_per_EM));
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)((m[0] * face->bbox.xMax + m[2] * face->bbox.yMax) /
- (div * face->units_per_EM));
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * face->bbox.xMax + m[3] * face->bbox.yMax) /
- (div * face->units_per_EM));
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- // This is a kludge: some buggy PDF generators embed fonts with
- // zero bounding boxes.
- if (xMax == xMin) {
- xMin = 0;
- xMax = (int)size;
- }
- if (yMax == yMin) {
- yMin = 0;
- yMax = (int)(1.2 * size);
- }
- // this should be (max - min + 1), but we add some padding to
- // deal with rounding errors, bogus bboxes, etc.
- glyphW = xMax - xMin + 3;
- glyphW += glyphW >> 1;
- glyphH = yMax - yMin + 3;
- glyphH += glyphH >> 1;
- if (engine->aa) {
- glyphSize = glyphW * glyphH;
- } else {
- glyphSize = ((glyphW + 7) >> 3) * glyphH;
- }
-
- // set up the glyph pixmap cache
- cacheAssoc = 8;
- if (glyphSize <= 256) {
- cacheSets = 8;
- } else if (glyphSize <= 512) {
- cacheSets = 4;
- } else if (glyphSize <= 1024) {
- cacheSets = 2;
- } else {
- cacheSets = 1;
- }
- cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
- cacheTags = (FTFontCacheTag *)gmalloc(cacheSets * cacheAssoc *
- sizeof(FTFontCacheTag));
- for (i = 0; i < cacheSets * cacheAssoc; ++i) {
- cacheTags[i].mru = i & (cacheAssoc - 1);
- }
-
- // create the XImage
- if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
- ZPixmap, 0, NULL, glyphW, glyphH, 8, 0))) {
- return;
- }
- image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
-
- // compute the transform matrix
- matrix.xx = (FT_Fixed)((m[0] / size) * 65536);
- matrix.yx = (FT_Fixed)((m[1] / size) * 65536);
- matrix.xy = (FT_Fixed)((m[2] / size) * 65536);
- matrix.yy = (FT_Fixed)((m[3] / size) * 65536);
-
- ok = gTrue;
-}
-
-FTFont::~FTFont() {
- gfree(cacheTags);
- gfree(cache);
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
-}
-
-GBool FTFont::drawChar(Drawable d, int w, int h, GC gc,
- int x, int y, int r, int g, int b,
- CharCode c, Unicode u) {
- FTFontEngine *engine;
- XColor xcolor;
- int bgR, bgG, bgB;
- Gulong colors[5];
- Guchar *p;
- int pix;
- int xOffset, yOffset, x0, y0, x1, y1, gw, gh, w0, h0;
- int xx, yy, xx1;
-
- engine = fontFile->engine;
-
- // no Unicode index for this char - don't draw anything
- if (fontFile->mode == ftFontModeUnicode && u == 0) {
- return gFalse;
- }
-
- // generate the glyph pixmap
- if (!(p = getGlyphPixmap(c, u, &xOffset, &yOffset, &gw, &gh))) {
- return gFalse;
- }
-
- // compute: (x0,y0) = position in destination drawable
- // (x1,y1) = position in glyph image
- // (w0,h0) = size of image transfer
- x0 = x - xOffset;
- y0 = y - yOffset;
- x1 = 0;
- y1 = 0;
- w0 = gw;
- h0 = gh;
- if (x0 < 0) {
- x1 = -x0;
- w0 += x0;
- x0 = 0;
- }
- if (x0 + w0 > w) {
- w0 = w - x0;
- }
- if (w0 < 0) {
- return gTrue;
- }
- if (y0 < 0) {
- y1 = -y0;
- h0 += y0;
- y0 = 0;
- }
- if (y0 + h0 > h) {
- h0 = h - y0;
- }
- if (h0 < 0) {
- return gTrue;
- }
-
- // read the X image
- XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
- ZPixmap, image, x1, y1);
-
- if (engine->aa) {
-
- // compute the colors
- xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
- XQueryColor(engine->display, engine->colormap, &xcolor);
- bgR = xcolor.red;
- bgG = xcolor.green;
- bgB = xcolor.blue;
- colors[1] = engine->findColor((r + 3*bgR) / 4,
- (g + 3*bgG) / 4,
- (b + 3*bgB) / 4);
- colors[2] = engine->findColor((r + bgR) / 2,
- (g + bgG) / 2,
- (b + bgB) / 2);
- colors[3] = engine->findColor((3*r + bgR) / 4,
- (3*g + bgG) / 4,
- (3*b + bgB) / 4);
- colors[4] = engine->findColor(r, g, b);
-
- // stuff the glyph pixmap into the X image
- for (yy = 0; yy < gh; ++yy) {
- for (xx = 0; xx < gw; ++xx) {
- pix = *p++ & 0xff;
- // this is a heuristic which seems to produce decent
- // results -- the linear mapping would be:
- // pix = (pix * 5) / 256;
- pix = ((pix + 10) * 5) / 256;
- if (pix > 4) {
- pix = 4;
- }
- if (pix > 0) {
- XPutPixel(image, xx, yy, colors[pix]);
- }
- }
- }
-
- } else {
-
- // one color
- colors[1] = engine->findColor(r, g, b);
-
- // stuff the glyph bitmap into the X image
- for (yy = 0; yy < gh; ++yy) {
- for (xx = 0; xx < gw; xx += 8) {
- pix = *p++;
- for (xx1 = xx; xx1 < xx + 8 && xx1 < gw; ++xx1) {
- if (pix & 0x80) {
- XPutPixel(image, xx1, yy, colors[1]);
- }
- pix <<= 1;
- }
- }
- }
-
- }
-
- // draw the X image
- XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
-
- return gTrue;
-}
-
-Guchar *FTFont::getGlyphPixmap(CharCode c, Unicode u,
- int *x, int *y, int *w, int *h) {
- FT_GlyphSlot slot;
- FT_UInt idx;
- int rowSize;
- int i, j, k;
- Guchar *ret, *p, *q;
-
- // check the cache
- i = (c & (cacheSets - 1)) * cacheAssoc;
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
- *x = cacheTags[i+j].x;
- *y = cacheTags[i+j].y;
- *w = cacheTags[i+j].w;
- *h = cacheTags[i+j].h;
- for (k = 0; k < cacheAssoc; ++k) {
- if (k != j &&
- (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
- ++cacheTags[i+k].mru;
- }
- }
- cacheTags[i+j].mru = 0x8000;
- return cache + (i+j) * glyphSize;
- }
- }
-
- // generate the glyph pixmap or bitmap
- fontFile->face->size = sizeObj;
- FT_Set_Transform(fontFile->face, &matrix, NULL);
- slot = fontFile->face->glyph;
- idx = getGlyphIndex(c, u);
- // if we have the FT2 bytecode interpreter, autohinting won't be used
-#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
- if (FT_Load_Glyph(fontFile->face, idx, FT_LOAD_DEFAULT)) {
- return gFalse;
- }
-#else
- // FT2's autohinting doesn't always work very well (especially with
- // font subsets), so turn it off if anti-aliasing is enabled; if
- // anti-aliasing is disabled, this seems to be a tossup - some fonts
- // look better with hinting, some without, so leave hinting on
- if (FT_Load_Glyph(fontFile->face, idx,
- fontFile->engine->aa ? FT_LOAD_NO_HINTING
- : FT_LOAD_DEFAULT)) {
- return gFalse;
- }
-#endif
- if (FT_Render_Glyph(slot,
- fontFile->engine->aa ? ft_render_mode_normal :
- ft_render_mode_mono)) {
- return gFalse;
- }
- *x = -slot->bitmap_left;
- *y = slot->bitmap_top;
- *w = slot->bitmap.width;
- *h = slot->bitmap.rows;
- if (*w > glyphW || *h > glyphH) {
-#if 1 //~ debug
- fprintf(stderr, "Weird FreeType glyph size: %d > %d or %d > %d\n",
- *w, glyphW, *h, glyphH);
-#endif
- return NULL;
- }
-
- // store glyph pixmap in cache
- ret = NULL;
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
- cacheTags[i+j].mru = 0x8000;
- cacheTags[i+j].code = c;
- cacheTags[i+j].x = *x;
- cacheTags[i+j].y = *y;
- cacheTags[i+j].w = *w;
- cacheTags[i+j].h = *h;
- if (fontFile->engine->aa) {
- rowSize = *w;
- } else {
- rowSize = (*w + 7) >> 3;
- }
- ret = cache + (i+j) * glyphSize;
- for (k = 0, p = ret, q = slot->bitmap.buffer;
- k < slot->bitmap.rows;
- ++k, p += rowSize, q += slot->bitmap.pitch) {
- memcpy(p, q, rowSize);
- }
- } else {
- ++cacheTags[i+j].mru;
- }
- }
- return ret;
-}
-
-GBool FTFont::getCharPath(CharCode c, Unicode u, GfxState *state) {
- static FT_Outline_Funcs outlineFuncs = {
- &charPathMoveTo,
- &charPathLineTo,
- &charPathConicTo,
- &charPathCubicTo,
- 0, 0
- };
- FT_GlyphSlot slot;
- FT_UInt idx;
- FT_Glyph glyph;
-
- fontFile->face->size = sizeObj;
- FT_Set_Transform(fontFile->face, &matrix, NULL);
- slot = fontFile->face->glyph;
- idx = getGlyphIndex(c, u);
-#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
- if (FT_Load_Glyph(fontFile->face, idx, FT_LOAD_DEFAULT)) {
- return gFalse;
- }
-#else
- // FT2's autohinting doesn't always work very well (especially with
- // font subsets), so turn it off if anti-aliasing is enabled; if
- // anti-aliasing is disabled, this seems to be a tossup - some fonts
- // look better with hinting, some without, so leave hinting on
- if (FT_Load_Glyph(fontFile->face, idx,
- fontFile->engine->aa ? FT_LOAD_NO_HINTING
- : FT_LOAD_DEFAULT)) {
- return gFalse;
- }
-#endif
- if (FT_Get_Glyph(slot, &glyph)) {
- return gFalse;
- }
- FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline,
- &outlineFuncs, state);
- return gTrue;
-}
-
-int FTFont::charPathMoveTo(FT_Vector *pt, void *state) {
- ((GfxState *)state)->moveTo(pt->x / 64.0, -pt->y / 64.0);
- return 0;
-}
-
-int FTFont::charPathLineTo(FT_Vector *pt, void *state) {
- ((GfxState *)state)->lineTo(pt->x / 64.0, -pt->y / 64.0);
- return 0;
-}
-
-int FTFont::charPathConicTo(FT_Vector *ctrl, FT_Vector *pt, void *state) {
- double x0, y0, x1, y1, x2, y2, x3, y3, xc, yc;
-
- x0 = ((GfxState *)state)->getCurX();
- y0 = ((GfxState *)state)->getCurY();
- xc = ctrl->x / 64.0;
- yc = -ctrl->y / 64.0;
- x3 = pt->x / 64.0;
- y3 = -pt->y / 64.0;
-
- // A second-order Bezier curve is defined by two endpoints, p0 and
- // p3, and one control point, pc:
- //
- // p(t) = (1-t)^2*p0 + t*(1-t)*pc + t^2*p3
- //
- // A third-order Bezier curve is defined by the same two endpoints,
- // p0 and p3, and two control points, p1 and p2:
- //
- // p(t) = (1-t)^3*p0 + 3t*(1-t)^2*p1 + 3t^2*(1-t)*p2 + t^3*p3
- //
- // Applying some algebra, we can convert a second-order curve to a
- // third-order curve:
- //
- // p1 = (1/3) * (p0 + 2pc)
- // p2 = (1/3) * (2pc + p3)
-
- x1 = (1.0 / 3.0) * (x0 + 2 * xc);
- y1 = (1.0 / 3.0) * (y0 + 2 * yc);
- x2 = (1.0 / 3.0) * (2 * xc + x3);
- y2 = (1.0 / 3.0) * (2 * yc + y3);
-
- ((GfxState *)state)->curveTo(x1, y1, x2, y2, x3, y3);
- return 0;
-}
-
-int FTFont::charPathCubicTo(FT_Vector *ctrl1, FT_Vector *ctrl2,
- FT_Vector *pt, void *state) {
- ((GfxState *)state)->curveTo(ctrl1->x / 64.0, -ctrl1->y / 64.0,
- ctrl2->x / 64.0, -ctrl2->y / 64.0,
- pt->x / 64.0, -pt->y / 64.0);
- return 0;
-}
-
-FT_UInt FTFont::getGlyphIndex(CharCode c, Unicode u) {
- FT_UInt idx;
- int j;
-
- idx = 0; // make gcc happy
- switch (fontFile->mode) {
- case ftFontModeUnicode:
- idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)u);
- break;
- case ftFontModeCharCode:
- idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)c);
- break;
- case ftFontModeCharCodeOffset:
- idx = FT_Get_Char_Index(fontFile->face,
- (FT_ULong)(c + fontFile->charMapOffset));
- break;
- case ftFontModeCodeMap:
- if (c <= 0xff) {
- idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)fontFile->codeMap[c]);
- } else {
- idx = 0;
- }
- break;
- case ftFontModeCodeMapDirect:
- if (c <= 0xff) {
- idx = (FT_UInt)fontFile->codeMap[c];
- } else {
- idx = 0;
- }
- break;
- case ftFontModeCIDToGIDMap:
- if (fontFile->cidToGIDLen) {
- if ((int)c < fontFile->cidToGIDLen) {
- idx = (FT_UInt)fontFile->cidToGID[c];
- } else {
- idx = (FT_UInt)0;
- }
- } else {
- idx = (FT_UInt)c;
- }
- break;
- case ftFontModeCFFCharset:
-#if 1 //~ cff cid->gid map
-#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 0
- CFF_Font *cff = (CFF_Font *)((TT_Face)fontFile->face)->extra.data;
-#else
- CFF_Font cff = (CFF_Font)((TT_Face)fontFile->face)->extra.data;
-#endif
- idx = 0;
- for (j = 0; j < (int)cff->num_glyphs; ++j) {
- if (cff->charset.sids[j] == c) {
- idx = j;
- break;
- }
- }
-#endif
- break;
- }
- return idx;
-}
-
-#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
diff --git a/filters/kword/pdf/xpdf/xpdf/FTFont.cpp b/filters/kword/pdf/xpdf/xpdf/FTFont.cpp
new file mode 100644
index 000000000..f993ca05e
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/FTFont.cpp
@@ -0,0 +1,685 @@
+//========================================================================
+//
+// FTFont.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <math.h>
+#include <string.h>
+#include "gmem.h"
+#include "freetype/ftoutln.h"
+#include "freetype/internal/ftobjs.h"
+#if 1 //~ cff cid->gid map
+#include "freetype/internal/cfftypes.h"
+#include "freetype/internal/tttypes.h"
+#endif
+#include "GlobalParams.h"
+#include "GfxState.h"
+#include "FTFont.h"
+
+//------------------------------------------------------------------------
+
+FTFontEngine::FTFontEngine(Display *displayA, Visual *visualA, int depthA,
+ Colormap colormapA, GBool aaA):
+ SFontEngine(displayA, visualA, depthA, colormapA) {
+
+ ok = gFalse;
+ if (FT_Init_FreeType(&lib)) {
+ return;
+ }
+ aa = aaA;
+ ok = gTrue;
+}
+
+FTFontEngine::~FTFontEngine() {
+ FT_Done_FreeType(lib);
+}
+
+//------------------------------------------------------------------------
+
+FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName,
+ char **fontEnc, GBool pdfFontHasEncoding) {
+ char *name;
+ int unicodeCmap, macRomanCmap, msSymbolCmap;
+ int i, j;
+
+ ok = gFalse;
+ engine = engineA;
+ codeMap = NULL;
+ if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
+ return;
+ }
+
+ if (!strcmp(face->driver->root.clazz->module_name, "type1") ||
+ !strcmp(face->driver->root.clazz->module_name, "cff")) {
+
+ mode = ftFontModeCodeMapDirect;
+ codeMap = (Guint *)gmalloc(256 * sizeof(Guint));
+ for (i = 0; i < 256; ++i) {
+ codeMap[i] = 0;
+ if ((name = fontEnc[i])) {
+ codeMap[i] = FT_Get_Name_Index(face, name);
+ }
+ }
+
+ } else {
+
+ // To match up with the Adobe-defined behaviour, we choose a cmap
+ // like this:
+ // 1. If the PDF font has an encoding:
+ // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
+ // and use the Unicode indexes, not the char codes.
+ // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and reverse map the char names through MacRomanEncoding to
+ // get char codes.
+ // 2. If the PDF font does not have an encoding:
+ // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and use char codes directly.
+ // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
+ // and use (0xf000 + char code).
+ // 3. If none of these rules apply, use the first cmap and hope for
+ // the best (this shouldn't happen).
+ unicodeCmap = macRomanCmap = msSymbolCmap = 0xffff;
+ for (i = 0; i < face->num_charmaps; ++i) {
+ if (face->charmaps[i]->platform_id == 3 &&
+ face->charmaps[i]->encoding_id == 1) {
+ unicodeCmap = i;
+ } else if (face->charmaps[i]->platform_id == 1 &&
+ face->charmaps[i]->encoding_id == 0) {
+ macRomanCmap = i;
+ } else if (face->charmaps[i]->platform_id == 3 &&
+ face->charmaps[i]->encoding_id == 0) {
+ msSymbolCmap = i;
+ }
+ }
+ i = 0;
+ mode = ftFontModeCharCode;
+ charMapOffset = 0;
+ if (pdfFontHasEncoding) {
+ if (unicodeCmap != 0xffff) {
+ i = unicodeCmap;
+ mode = ftFontModeUnicode;
+ } else if (macRomanCmap != 0xffff) {
+ i = macRomanCmap;
+ mode = ftFontModeCodeMap;
+ codeMap = (Guint *)gmalloc(256 * sizeof(Guint));
+ for (j = 0; j < 256; ++j) {
+ if (fontEnc[j]) {
+ codeMap[j] = globalParams->getMacRomanCharCode(fontEnc[j]);
+ } else {
+ codeMap[j] = 0;
+ }
+ }
+ }
+ } else {
+ if (macRomanCmap != 0xffff) {
+ i = macRomanCmap;
+ mode = ftFontModeCharCode;
+ } else if (msSymbolCmap != 0xffff) {
+ i = msSymbolCmap;
+ mode = ftFontModeCharCodeOffset;
+ charMapOffset = 0xf000;
+ }
+ }
+ if (FT_Set_Charmap(face, face->charmaps[i])) {
+ return;
+ }
+ }
+
+ ok = gTrue;
+}
+
+FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName,
+ Gushort *cidToGIDA, int cidToGIDLenA) {
+ ok = gFalse;
+ engine = engineA;
+ codeMap = NULL;
+ if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
+ return;
+ }
+ cidToGID = cidToGIDA;
+ cidToGIDLen = cidToGIDLenA;
+ mode = ftFontModeCIDToGIDMap;
+ ok = gTrue;
+}
+
+FTFontFile::FTFontFile(FTFontEngine *engineA, char *fontFileName) {
+ ok = gFalse;
+ engine = engineA;
+ codeMap = NULL;
+ if (FT_New_Face(engine->lib, fontFileName, 0, &face)) {
+ return;
+ }
+ cidToGID = NULL;
+ cidToGIDLen = 0;
+ mode = ftFontModeCFFCharset;
+ ok = gTrue;
+}
+
+FTFontFile::~FTFontFile() {
+ if (face) {
+ FT_Done_Face(face);
+ }
+ if (codeMap) {
+ gfree(codeMap);
+ }
+}
+
+//------------------------------------------------------------------------
+
+FTFont::FTFont(FTFontFile *fontFileA, double *m) {
+ FTFontEngine *engine;
+ FT_Face face;
+ double size, div;
+ int x, xMin, xMax;
+ int y, yMin, yMax;
+ int i;
+
+ ok = gFalse;
+ fontFile = fontFileA;
+ engine = fontFile->engine;
+ face = fontFile->face;
+ if (FT_New_Size(face, &sizeObj)) {
+ return;
+ }
+ face->size = sizeObj;
+ size = sqrt(m[2]*m[2] + m[3]*m[3]);
+ if (FT_Set_Pixel_Sizes(face, 0, (int)size)) {
+ return;
+ }
+
+ div = face->bbox.xMax > 20000 ? 65536 : 1;
+
+ // transform the four corners of the font bounding box -- the min
+ // and max values form the bounding box of the transformed font
+ x = (int)((m[0] * face->bbox.xMin + m[2] * face->bbox.yMin) /
+ (div * face->units_per_EM));
+ xMin = xMax = x;
+ y = (int)((m[1] * face->bbox.xMin + m[3] * face->bbox.yMin) /
+ (div * face->units_per_EM));
+ yMin = yMax = y;
+ x = (int)((m[0] * face->bbox.xMin + m[2] * face->bbox.yMax) /
+ (div * face->units_per_EM));
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * face->bbox.xMin + m[3] * face->bbox.yMax) /
+ (div * face->units_per_EM));
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)((m[0] * face->bbox.xMax + m[2] * face->bbox.yMin) /
+ (div * face->units_per_EM));
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * face->bbox.xMax + m[3] * face->bbox.yMin) /
+ (div * face->units_per_EM));
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)((m[0] * face->bbox.xMax + m[2] * face->bbox.yMax) /
+ (div * face->units_per_EM));
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * face->bbox.xMax + m[3] * face->bbox.yMax) /
+ (div * face->units_per_EM));
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ // This is a kludge: some buggy PDF generators embed fonts with
+ // zero bounding boxes.
+ if (xMax == xMin) {
+ xMin = 0;
+ xMax = (int)size;
+ }
+ if (yMax == yMin) {
+ yMin = 0;
+ yMax = (int)(1.2 * size);
+ }
+ // this should be (max - min + 1), but we add some padding to
+ // deal with rounding errors, bogus bboxes, etc.
+ glyphW = xMax - xMin + 3;
+ glyphW += glyphW >> 1;
+ glyphH = yMax - yMin + 3;
+ glyphH += glyphH >> 1;
+ if (engine->aa) {
+ glyphSize = glyphW * glyphH;
+ } else {
+ glyphSize = ((glyphW + 7) >> 3) * glyphH;
+ }
+
+ // set up the glyph pixmap cache
+ cacheAssoc = 8;
+ if (glyphSize <= 256) {
+ cacheSets = 8;
+ } else if (glyphSize <= 512) {
+ cacheSets = 4;
+ } else if (glyphSize <= 1024) {
+ cacheSets = 2;
+ } else {
+ cacheSets = 1;
+ }
+ cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
+ cacheTags = (FTFontCacheTag *)gmalloc(cacheSets * cacheAssoc *
+ sizeof(FTFontCacheTag));
+ for (i = 0; i < cacheSets * cacheAssoc; ++i) {
+ cacheTags[i].mru = i & (cacheAssoc - 1);
+ }
+
+ // create the XImage
+ if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
+ ZPixmap, 0, NULL, glyphW, glyphH, 8, 0))) {
+ return;
+ }
+ image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
+
+ // compute the transform matrix
+ matrix.xx = (FT_Fixed)((m[0] / size) * 65536);
+ matrix.yx = (FT_Fixed)((m[1] / size) * 65536);
+ matrix.xy = (FT_Fixed)((m[2] / size) * 65536);
+ matrix.yy = (FT_Fixed)((m[3] / size) * 65536);
+
+ ok = gTrue;
+}
+
+FTFont::~FTFont() {
+ gfree(cacheTags);
+ gfree(cache);
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+}
+
+GBool FTFont::drawChar(Drawable d, int w, int h, GC gc,
+ int x, int y, int r, int g, int b,
+ CharCode c, Unicode u) {
+ FTFontEngine *engine;
+ XColor xcolor;
+ int bgR, bgG, bgB;
+ Gulong colors[5];
+ Guchar *p;
+ int pix;
+ int xOffset, yOffset, x0, y0, x1, y1, gw, gh, w0, h0;
+ int xx, yy, xx1;
+
+ engine = fontFile->engine;
+
+ // no Unicode index for this char - don't draw anything
+ if (fontFile->mode == ftFontModeUnicode && u == 0) {
+ return gFalse;
+ }
+
+ // generate the glyph pixmap
+ if (!(p = getGlyphPixmap(c, u, &xOffset, &yOffset, &gw, &gh))) {
+ return gFalse;
+ }
+
+ // compute: (x0,y0) = position in destination drawable
+ // (x1,y1) = position in glyph image
+ // (w0,h0) = size of image transfer
+ x0 = x - xOffset;
+ y0 = y - yOffset;
+ x1 = 0;
+ y1 = 0;
+ w0 = gw;
+ h0 = gh;
+ if (x0 < 0) {
+ x1 = -x0;
+ w0 += x0;
+ x0 = 0;
+ }
+ if (x0 + w0 > w) {
+ w0 = w - x0;
+ }
+ if (w0 < 0) {
+ return gTrue;
+ }
+ if (y0 < 0) {
+ y1 = -y0;
+ h0 += y0;
+ y0 = 0;
+ }
+ if (y0 + h0 > h) {
+ h0 = h - y0;
+ }
+ if (h0 < 0) {
+ return gTrue;
+ }
+
+ // read the X image
+ XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
+ ZPixmap, image, x1, y1);
+
+ if (engine->aa) {
+
+ // compute the colors
+ xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
+ XQueryColor(engine->display, engine->colormap, &xcolor);
+ bgR = xcolor.red;
+ bgG = xcolor.green;
+ bgB = xcolor.blue;
+ colors[1] = engine->findColor((r + 3*bgR) / 4,
+ (g + 3*bgG) / 4,
+ (b + 3*bgB) / 4);
+ colors[2] = engine->findColor((r + bgR) / 2,
+ (g + bgG) / 2,
+ (b + bgB) / 2);
+ colors[3] = engine->findColor((3*r + bgR) / 4,
+ (3*g + bgG) / 4,
+ (3*b + bgB) / 4);
+ colors[4] = engine->findColor(r, g, b);
+
+ // stuff the glyph pixmap into the X image
+ for (yy = 0; yy < gh; ++yy) {
+ for (xx = 0; xx < gw; ++xx) {
+ pix = *p++ & 0xff;
+ // this is a heuristic which seems to produce decent
+ // results -- the linear mapping would be:
+ // pix = (pix * 5) / 256;
+ pix = ((pix + 10) * 5) / 256;
+ if (pix > 4) {
+ pix = 4;
+ }
+ if (pix > 0) {
+ XPutPixel(image, xx, yy, colors[pix]);
+ }
+ }
+ }
+
+ } else {
+
+ // one color
+ colors[1] = engine->findColor(r, g, b);
+
+ // stuff the glyph bitmap into the X image
+ for (yy = 0; yy < gh; ++yy) {
+ for (xx = 0; xx < gw; xx += 8) {
+ pix = *p++;
+ for (xx1 = xx; xx1 < xx + 8 && xx1 < gw; ++xx1) {
+ if (pix & 0x80) {
+ XPutPixel(image, xx1, yy, colors[1]);
+ }
+ pix <<= 1;
+ }
+ }
+ }
+
+ }
+
+ // draw the X image
+ XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
+
+ return gTrue;
+}
+
+Guchar *FTFont::getGlyphPixmap(CharCode c, Unicode u,
+ int *x, int *y, int *w, int *h) {
+ FT_GlyphSlot slot;
+ FT_UInt idx;
+ int rowSize;
+ int i, j, k;
+ Guchar *ret, *p, *q;
+
+ // check the cache
+ i = (c & (cacheSets - 1)) * cacheAssoc;
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
+ *x = cacheTags[i+j].x;
+ *y = cacheTags[i+j].y;
+ *w = cacheTags[i+j].w;
+ *h = cacheTags[i+j].h;
+ for (k = 0; k < cacheAssoc; ++k) {
+ if (k != j &&
+ (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
+ ++cacheTags[i+k].mru;
+ }
+ }
+ cacheTags[i+j].mru = 0x8000;
+ return cache + (i+j) * glyphSize;
+ }
+ }
+
+ // generate the glyph pixmap or bitmap
+ fontFile->face->size = sizeObj;
+ FT_Set_Transform(fontFile->face, &matrix, NULL);
+ slot = fontFile->face->glyph;
+ idx = getGlyphIndex(c, u);
+ // if we have the FT2 bytecode interpreter, autohinting won't be used
+#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
+ if (FT_Load_Glyph(fontFile->face, idx, FT_LOAD_DEFAULT)) {
+ return gFalse;
+ }
+#else
+ // FT2's autohinting doesn't always work very well (especially with
+ // font subsets), so turn it off if anti-aliasing is enabled; if
+ // anti-aliasing is disabled, this seems to be a tossup - some fonts
+ // look better with hinting, some without, so leave hinting on
+ if (FT_Load_Glyph(fontFile->face, idx,
+ fontFile->engine->aa ? FT_LOAD_NO_HINTING
+ : FT_LOAD_DEFAULT)) {
+ return gFalse;
+ }
+#endif
+ if (FT_Render_Glyph(slot,
+ fontFile->engine->aa ? ft_render_mode_normal :
+ ft_render_mode_mono)) {
+ return gFalse;
+ }
+ *x = -slot->bitmap_left;
+ *y = slot->bitmap_top;
+ *w = slot->bitmap.width;
+ *h = slot->bitmap.rows;
+ if (*w > glyphW || *h > glyphH) {
+#if 1 //~ debug
+ fprintf(stderr, "Weird FreeType glyph size: %d > %d or %d > %d\n",
+ *w, glyphW, *h, glyphH);
+#endif
+ return NULL;
+ }
+
+ // store glyph pixmap in cache
+ ret = NULL;
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
+ cacheTags[i+j].mru = 0x8000;
+ cacheTags[i+j].code = c;
+ cacheTags[i+j].x = *x;
+ cacheTags[i+j].y = *y;
+ cacheTags[i+j].w = *w;
+ cacheTags[i+j].h = *h;
+ if (fontFile->engine->aa) {
+ rowSize = *w;
+ } else {
+ rowSize = (*w + 7) >> 3;
+ }
+ ret = cache + (i+j) * glyphSize;
+ for (k = 0, p = ret, q = slot->bitmap.buffer;
+ k < slot->bitmap.rows;
+ ++k, p += rowSize, q += slot->bitmap.pitch) {
+ memcpy(p, q, rowSize);
+ }
+ } else {
+ ++cacheTags[i+j].mru;
+ }
+ }
+ return ret;
+}
+
+GBool FTFont::getCharPath(CharCode c, Unicode u, GfxState *state) {
+ static FT_Outline_Funcs outlineFuncs = {
+ &charPathMoveTo,
+ &charPathLineTo,
+ &charPathConicTo,
+ &charPathCubicTo,
+ 0, 0
+ };
+ FT_GlyphSlot slot;
+ FT_UInt idx;
+ FT_Glyph glyph;
+
+ fontFile->face->size = sizeObj;
+ FT_Set_Transform(fontFile->face, &matrix, NULL);
+ slot = fontFile->face->glyph;
+ idx = getGlyphIndex(c, u);
+#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
+ if (FT_Load_Glyph(fontFile->face, idx, FT_LOAD_DEFAULT)) {
+ return gFalse;
+ }
+#else
+ // FT2's autohinting doesn't always work very well (especially with
+ // font subsets), so turn it off if anti-aliasing is enabled; if
+ // anti-aliasing is disabled, this seems to be a tossup - some fonts
+ // look better with hinting, some without, so leave hinting on
+ if (FT_Load_Glyph(fontFile->face, idx,
+ fontFile->engine->aa ? FT_LOAD_NO_HINTING
+ : FT_LOAD_DEFAULT)) {
+ return gFalse;
+ }
+#endif
+ if (FT_Get_Glyph(slot, &glyph)) {
+ return gFalse;
+ }
+ FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline,
+ &outlineFuncs, state);
+ return gTrue;
+}
+
+int FTFont::charPathMoveTo(FT_Vector *pt, void *state) {
+ ((GfxState *)state)->moveTo(pt->x / 64.0, -pt->y / 64.0);
+ return 0;
+}
+
+int FTFont::charPathLineTo(FT_Vector *pt, void *state) {
+ ((GfxState *)state)->lineTo(pt->x / 64.0, -pt->y / 64.0);
+ return 0;
+}
+
+int FTFont::charPathConicTo(FT_Vector *ctrl, FT_Vector *pt, void *state) {
+ double x0, y0, x1, y1, x2, y2, x3, y3, xc, yc;
+
+ x0 = ((GfxState *)state)->getCurX();
+ y0 = ((GfxState *)state)->getCurY();
+ xc = ctrl->x / 64.0;
+ yc = -ctrl->y / 64.0;
+ x3 = pt->x / 64.0;
+ y3 = -pt->y / 64.0;
+
+ // A second-order Bezier curve is defined by two endpoints, p0 and
+ // p3, and one control point, pc:
+ //
+ // p(t) = (1-t)^2*p0 + t*(1-t)*pc + t^2*p3
+ //
+ // A third-order Bezier curve is defined by the same two endpoints,
+ // p0 and p3, and two control points, p1 and p2:
+ //
+ // p(t) = (1-t)^3*p0 + 3t*(1-t)^2*p1 + 3t^2*(1-t)*p2 + t^3*p3
+ //
+ // Applying some algebra, we can convert a second-order curve to a
+ // third-order curve:
+ //
+ // p1 = (1/3) * (p0 + 2pc)
+ // p2 = (1/3) * (2pc + p3)
+
+ x1 = (1.0 / 3.0) * (x0 + 2 * xc);
+ y1 = (1.0 / 3.0) * (y0 + 2 * yc);
+ x2 = (1.0 / 3.0) * (2 * xc + x3);
+ y2 = (1.0 / 3.0) * (2 * yc + y3);
+
+ ((GfxState *)state)->curveTo(x1, y1, x2, y2, x3, y3);
+ return 0;
+}
+
+int FTFont::charPathCubicTo(FT_Vector *ctrl1, FT_Vector *ctrl2,
+ FT_Vector *pt, void *state) {
+ ((GfxState *)state)->curveTo(ctrl1->x / 64.0, -ctrl1->y / 64.0,
+ ctrl2->x / 64.0, -ctrl2->y / 64.0,
+ pt->x / 64.0, -pt->y / 64.0);
+ return 0;
+}
+
+FT_UInt FTFont::getGlyphIndex(CharCode c, Unicode u) {
+ FT_UInt idx;
+ int j;
+
+ idx = 0; // make gcc happy
+ switch (fontFile->mode) {
+ case ftFontModeUnicode:
+ idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)u);
+ break;
+ case ftFontModeCharCode:
+ idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)c);
+ break;
+ case ftFontModeCharCodeOffset:
+ idx = FT_Get_Char_Index(fontFile->face,
+ (FT_ULong)(c + fontFile->charMapOffset));
+ break;
+ case ftFontModeCodeMap:
+ if (c <= 0xff) {
+ idx = FT_Get_Char_Index(fontFile->face, (FT_ULong)fontFile->codeMap[c]);
+ } else {
+ idx = 0;
+ }
+ break;
+ case ftFontModeCodeMapDirect:
+ if (c <= 0xff) {
+ idx = (FT_UInt)fontFile->codeMap[c];
+ } else {
+ idx = 0;
+ }
+ break;
+ case ftFontModeCIDToGIDMap:
+ if (fontFile->cidToGIDLen) {
+ if ((int)c < fontFile->cidToGIDLen) {
+ idx = (FT_UInt)fontFile->cidToGID[c];
+ } else {
+ idx = (FT_UInt)0;
+ }
+ } else {
+ idx = (FT_UInt)c;
+ }
+ break;
+ case ftFontModeCFFCharset:
+#if 1 //~ cff cid->gid map
+#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 0
+ CFF_Font *cff = (CFF_Font *)((TT_Face)fontFile->face)->extra.data;
+#else
+ CFF_Font cff = (CFF_Font)((TT_Face)fontFile->face)->extra.data;
+#endif
+ idx = 0;
+ for (j = 0; j < (int)cff->num_glyphs; ++j) {
+ if (cff->charset.sids[j] == c) {
+ idx = j;
+ break;
+ }
+ }
+#endif
+ break;
+ }
+ return idx;
+}
+
+#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
diff --git a/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cc b/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cc
deleted file mode 100644
index db4f9dd8b..000000000
--- a/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cc
+++ /dev/null
@@ -1,1824 +0,0 @@
-//========================================================================
-//
-// FontEncodingTables.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdlib.h>
-#include "FontEncodingTables.h"
-
-const char *macRomanEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quotesingle",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
- "hyphen",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
- "bracketright",
- "asciicircum",
- "underscore",
- "grave",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
- "braceright",
- "asciitilde",
- NULL,
- "Adieresis",
- "Aring",
- "Ccedilla",
- "Eacute",
- "Ntilde",
- "Odieresis",
- "Udieresis",
- "aacute",
- "agrave",
- "acircumflex",
- "adieresis",
- "atilde",
- "aring",
- "ccedilla",
- "eacute",
- "egrave",
- "ecircumflex",
- "edieresis",
- "iacute",
- "igrave",
- "icircumflex",
- "idieresis",
- "ntilde",
- "oacute",
- "ograve",
- "ocircumflex",
- "odieresis",
- "otilde",
- "uacute",
- "ugrave",
- "ucircumflex",
- "udieresis",
- "dagger",
- "degree",
- "cent",
- "sterling",
- "section",
- "bullet",
- "paragraph",
- "germandbls",
- "registered",
- "copyright",
- "trademark",
- "acute",
- "dieresis",
- NULL,
- "AE",
- "Oslash",
- NULL,
- "plusminus",
- NULL,
- NULL,
- "yen",
- "mu",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "ordfeminine",
- "ordmasculine",
- NULL,
- "ae",
- "oslash",
- "questiondown",
- "exclamdown",
- "logicalnot",
- NULL,
- "florin",
- NULL,
- NULL,
- "guillemotleft",
- "guillemotright",
- "ellipsis",
- "space",
- "Agrave",
- "Atilde",
- "Otilde",
- "OE",
- "oe",
- "endash",
- "emdash",
- "quotedblleft",
- "quotedblright",
- "quoteleft",
- "quoteright",
- "divide",
- NULL,
- "ydieresis",
- "Ydieresis",
- "fraction",
- "currency",
- "guilsinglleft",
- "guilsinglright",
- "fi",
- "fl",
- "daggerdbl",
- "periodcentered",
- "quotesinglbase",
- "quotedblbase",
- "perthousand",
- "Acircumflex",
- "Ecircumflex",
- "Aacute",
- "Edieresis",
- "Egrave",
- "Iacute",
- "Icircumflex",
- "Idieresis",
- "Igrave",
- "Oacute",
- "Ocircumflex",
- NULL,
- "Ograve",
- "Uacute",
- "Ucircumflex",
- "Ugrave",
- "dotlessi",
- "circumflex",
- "tilde",
- "macron",
- "breve",
- "dotaccent",
- "ring",
- "cedilla",
- "hungarumlaut",
- "ogonek",
- "caron"
-};
-
-const char *macExpertEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclamsmall",
- "Hungarumlautsmall",
- "centoldstyle",
- "dollaroldstyle",
- "dollarsuperior",
- "ampersandsmall",
- "Acutesmall",
- "parenleftsuperior",
- "parenrightsuperior",
- "twodotenleader",
- "onedotenleader",
- "comma",
- "hyphen",
- "period",
- "fraction",
- "zerooldstyle",
- "oneoldstyle",
- "twooldstyle",
- "threeoldstyle",
- "fouroldstyle",
- "fiveoldstyle",
- "sixoldstyle",
- "sevenoldstyle",
- "eightoldstyle",
- "nineoldstyle",
- "colon",
- "semicolon",
- NULL,
- "threequartersemdash",
- NULL,
- "questionsmall",
- NULL,
- NULL,
- NULL,
- NULL,
- "Ethsmall",
- NULL,
- NULL,
- "onequarter",
- "onehalf",
- "threequarters",
- "oneeighth",
- "threeeighths",
- "fiveeighths",
- "seveneighths",
- "onethird",
- "twothirds",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "ff",
- "fi",
- "fl",
- "ffi",
- "ffl",
- "parenleftinferior",
- NULL,
- "parenrightinferior",
- "Circumflexsmall",
- "hypheninferior",
- "Gravesmall",
- "Asmall",
- "Bsmall",
- "Csmall",
- "Dsmall",
- "Esmall",
- "Fsmall",
- "Gsmall",
- "Hsmall",
- "Ismall",
- "Jsmall",
- "Ksmall",
- "Lsmall",
- "Msmall",
- "Nsmall",
- "Osmall",
- "Psmall",
- "Qsmall",
- "Rsmall",
- "Ssmall",
- "Tsmall",
- "Usmall",
- "Vsmall",
- "Wsmall",
- "Xsmall",
- "Ysmall",
- "Zsmall",
- "colonmonetary",
- "onefitted",
- "rupiah",
- "Tildesmall",
- NULL,
- NULL,
- "asuperior",
- "centsuperior",
- NULL,
- NULL,
- NULL,
- NULL,
- "Aacutesmall",
- "Agravesmall",
- "Acircumflexsmall",
- "Adieresissmall",
- "Atildesmall",
- "Aringsmall",
- "Ccedillasmall",
- "Eacutesmall",
- "Egravesmall",
- "Ecircumflexsmall",
- "Edieresissmall",
- "Iacutesmall",
- "Igravesmall",
- "Icircumflexsmall",
- "Idieresissmall",
- "Ntildesmall",
- "Oacutesmall",
- "Ogravesmall",
- "Ocircumflexsmall",
- "Odieresissmall",
- "Otildesmall",
- "Uacutesmall",
- "Ugravesmall",
- "Ucircumflexsmall",
- "Udieresissmall",
- NULL,
- "eightsuperior",
- "fourinferior",
- "threeinferior",
- "sixinferior",
- "eightinferior",
- "seveninferior",
- "Scaronsmall",
- NULL,
- "centinferior",
- "twoinferior",
- NULL,
- "Dieresissmall",
- NULL,
- "Caronsmall",
- "osuperior",
- "fiveinferior",
- NULL,
- "commainferior",
- "periodinferior",
- "Yacutesmall",
- NULL,
- "dollarinferior",
- NULL,
- NULL,
- "Thornsmall",
- NULL,
- "nineinferior",
- "zeroinferior",
- "Zcaronsmall",
- "AEsmall",
- "Oslashsmall",
- "questiondownsmall",
- "oneinferior",
- "Lslashsmall",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "Cedillasmall",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "OEsmall",
- "figuredash",
- "hyphensuperior",
- NULL,
- NULL,
- NULL,
- NULL,
- "exclamdownsmall",
- NULL,
- "Ydieresissmall",
- NULL,
- "onesuperior",
- "twosuperior",
- "threesuperior",
- "foursuperior",
- "fivesuperior",
- "sixsuperior",
- "sevensuperior",
- "ninesuperior",
- "zerosuperior",
- NULL,
- "esuperior",
- "rsuperior",
- "tsuperior",
- NULL,
- NULL,
- "isuperior",
- "ssuperior",
- "dsuperior",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "lsuperior",
- "Ogoneksmall",
- "Brevesmall",
- "Macronsmall",
- "bsuperior",
- "nsuperior",
- "msuperior",
- "commasuperior",
- "periodsuperior",
- "Dotaccentsmall",
- "Ringsmall",
- NULL,
- NULL,
- NULL,
- NULL
-};
-
-const char *winAnsiEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quotesingle",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
- "hyphen",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
- "bracketright",
- "asciicircum",
- "underscore",
- "grave",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
- "braceright",
- "asciitilde",
- "bullet",
- "Euro",
- "bullet",
- "quotesinglbase",
- "florin",
- "quotedblbase",
- "ellipsis",
- "dagger",
- "daggerdbl",
- "circumflex",
- "perthousand",
- "Scaron",
- "guilsinglleft",
- "OE",
- "bullet",
- "Zcaron",
- "bullet",
- "bullet",
- "quoteleft",
- "quoteright",
- "quotedblleft",
- "quotedblright",
- "bullet",
- "endash",
- "emdash",
- "tilde",
- "trademark",
- "scaron",
- "guilsinglright",
- "oe",
- "bullet",
- "zcaron",
- "Ydieresis",
- "space",
- "exclamdown",
- "cent",
- "sterling",
- "currency",
- "yen",
- "brokenbar",
- "section",
- "dieresis",
- "copyright",
- "ordfeminine",
- "guillemotleft",
- "logicalnot",
- "hyphen",
- "registered",
- "macron",
- "degree",
- "plusminus",
- "twosuperior",
- "threesuperior",
- "acute",
- "mu",
- "paragraph",
- "periodcentered",
- "cedilla",
- "onesuperior",
- "ordmasculine",
- "guillemotright",
- "onequarter",
- "onehalf",
- "threequarters",
- "questiondown",
- "Agrave",
- "Aacute",
- "Acircumflex",
- "Atilde",
- "Adieresis",
- "Aring",
- "AE",
- "Ccedilla",
- "Egrave",
- "Eacute",
- "Ecircumflex",
- "Edieresis",
- "Igrave",
- "Iacute",
- "Icircumflex",
- "Idieresis",
- "Eth",
- "Ntilde",
- "Ograve",
- "Oacute",
- "Ocircumflex",
- "Otilde",
- "Odieresis",
- "multiply",
- "Oslash",
- "Ugrave",
- "Uacute",
- "Ucircumflex",
- "Udieresis",
- "Yacute",
- "Thorn",
- "germandbls",
- "agrave",
- "aacute",
- "acircumflex",
- "atilde",
- "adieresis",
- "aring",
- "ae",
- "ccedilla",
- "egrave",
- "eacute",
- "ecircumflex",
- "edieresis",
- "igrave",
- "iacute",
- "icircumflex",
- "idieresis",
- "eth",
- "ntilde",
- "ograve",
- "oacute",
- "ocircumflex",
- "otilde",
- "odieresis",
- "divide",
- "oslash",
- "ugrave",
- "uacute",
- "ucircumflex",
- "udieresis",
- "yacute",
- "thorn",
- "ydieresis"
-};
-
-const char *standardEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quoteright",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
- "hyphen",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
- "bracketright",
- "asciicircum",
- "underscore",
- "quoteleft",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
- "braceright",
- "asciitilde",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "exclamdown",
- "cent",
- "sterling",
- "fraction",
- "yen",
- "florin",
- "section",
- "currency",
- "quotesingle",
- "quotedblleft",
- "guillemotleft",
- "guilsinglleft",
- "guilsinglright",
- "fi",
- "fl",
- NULL,
- "endash",
- "dagger",
- "daggerdbl",
- "periodcentered",
- NULL,
- "paragraph",
- "bullet",
- "quotesinglbase",
- "quotedblbase",
- "quotedblright",
- "guillemotright",
- "ellipsis",
- "perthousand",
- NULL,
- "questiondown",
- NULL,
- "grave",
- "acute",
- "circumflex",
- "tilde",
- "macron",
- "breve",
- "dotaccent",
- "dieresis",
- NULL,
- "ring",
- "cedilla",
- NULL,
- "hungarumlaut",
- "ogonek",
- "caron",
- "emdash",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "AE",
- NULL,
- "ordfeminine",
- NULL,
- NULL,
- NULL,
- NULL,
- "Lslash",
- "Oslash",
- "OE",
- "ordmasculine",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "ae",
- NULL,
- NULL,
- NULL,
- "dotlessi",
- NULL,
- NULL,
- "lslash",
- "oslash",
- "oe",
- "germandbls",
- NULL,
- NULL,
- NULL,
- NULL
-};
-
-const char *expertEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclamsmall",
- "Hungarumlautsmall",
- NULL,
- "dollaroldstyle",
- "dollarsuperior",
- "ampersandsmall",
- "Acutesmall",
- "parenleftsuperior",
- "parenrightsuperior",
- "twodotenleader",
- "onedotenleader",
- "comma",
- "hyphen",
- "period",
- "fraction",
- "zerooldstyle",
- "oneoldstyle",
- "twooldstyle",
- "threeoldstyle",
- "fouroldstyle",
- "fiveoldstyle",
- "sixoldstyle",
- "sevenoldstyle",
- "eightoldstyle",
- "nineoldstyle",
- "colon",
- "semicolon",
- "commasuperior",
- "threequartersemdash",
- "periodsuperior",
- "questionsmall",
- NULL,
- "asuperior",
- "bsuperior",
- "centsuperior",
- "dsuperior",
- "esuperior",
- NULL,
- NULL,
- NULL,
- "isuperior",
- NULL,
- NULL,
- "lsuperior",
- "msuperior",
- "nsuperior",
- "osuperior",
- NULL,
- NULL,
- "rsuperior",
- "ssuperior",
- "tsuperior",
- NULL,
- "ff",
- "fi",
- "fl",
- "ffi",
- "ffl",
- "parenleftinferior",
- NULL,
- "parenrightinferior",
- "Circumflexsmall",
- "hyphensuperior",
- "Gravesmall",
- "Asmall",
- "Bsmall",
- "Csmall",
- "Dsmall",
- "Esmall",
- "Fsmall",
- "Gsmall",
- "Hsmall",
- "Ismall",
- "Jsmall",
- "Ksmall",
- "Lsmall",
- "Msmall",
- "Nsmall",
- "Osmall",
- "Psmall",
- "Qsmall",
- "Rsmall",
- "Ssmall",
- "Tsmall",
- "Usmall",
- "Vsmall",
- "Wsmall",
- "Xsmall",
- "Ysmall",
- "Zsmall",
- "colonmonetary",
- "onefitted",
- "rupiah",
- "Tildesmall",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "exclamdownsmall",
- "centoldstyle",
- "Lslashsmall",
- NULL,
- NULL,
- "Scaronsmall",
- "Zcaronsmall",
- "Dieresissmall",
- "Brevesmall",
- "Caronsmall",
- NULL,
- "Dotaccentsmall",
- NULL,
- NULL,
- "Macronsmall",
- NULL,
- NULL,
- "figuredash",
- "hypheninferior",
- NULL,
- NULL,
- "Ogoneksmall",
- "Ringsmall",
- "Cedillasmall",
- NULL,
- NULL,
- NULL,
- "onequarter",
- "onehalf",
- "threequarters",
- "questiondownsmall",
- "oneeighth",
- "threeeighths",
- "fiveeighths",
- "seveneighths",
- "onethird",
- "twothirds",
- NULL,
- NULL,
- "zerosuperior",
- "onesuperior",
- "twosuperior",
- "threesuperior",
- "foursuperior",
- "fivesuperior",
- "sixsuperior",
- "sevensuperior",
- "eightsuperior",
- "ninesuperior",
- "zeroinferior",
- "oneinferior",
- "twoinferior",
- "threeinferior",
- "fourinferior",
- "fiveinferior",
- "sixinferior",
- "seveninferior",
- "eightinferior",
- "nineinferior",
- "centinferior",
- "dollarinferior",
- "periodinferior",
- "commainferior",
- "Agravesmall",
- "Aacutesmall",
- "Acircumflexsmall",
- "Atildesmall",
- "Adieresissmall",
- "Aringsmall",
- "AEsmall",
- "Ccedillasmall",
- "Egravesmall",
- "Eacutesmall",
- "Ecircumflexsmall",
- "Edieresissmall",
- "Igravesmall",
- "Iacutesmall",
- "Icircumflexsmall",
- "Idieresissmall",
- "Ethsmall",
- "Ntildesmall",
- "Ogravesmall",
- "Oacutesmall",
- "Ocircumflexsmall",
- "Otildesmall",
- "Odieresissmall",
- "OEsmall",
- "Oslashsmall",
- "Ugravesmall",
- "Uacutesmall",
- "Ucircumflexsmall",
- "Udieresissmall",
- "Yacutesmall",
- "Thornsmall",
- "Ydieresissmall"
-};
-
-const char *symbolEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "exclam",
- "universal",
- "numbersign",
- "existential",
- "percent",
- "ampersand",
- "suchthat",
- "parenleft",
- "parenright",
- "asteriskmath",
- "plus",
- "comma",
- "minus",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- "congruent",
- "Alpha",
- "Beta",
- "Chi",
- "Delta",
- "Epsilon",
- "Phi",
- "Gamma",
- "Eta",
- "Iota",
- "theta1",
- "Kappa",
- "Lambda",
- "Mu",
- "Nu",
- "Omicron",
- "Pi",
- "Theta",
- "Rho",
- "Sigma",
- "Tau",
- "Upsilon",
- "sigma1",
- "Omega",
- "Xi",
- "Psi",
- "Zeta",
- "bracketleft",
- "therefore",
- "bracketright",
- "perpendicular",
- "underscore",
- "radicalex",
- "alpha",
- "beta",
- "chi",
- "delta",
- "epsilon",
- "phi",
- "gamma",
- "eta",
- "iota",
- "phi1",
- "kappa",
- "lambda",
- "mu",
- "nu",
- "omicron",
- "pi",
- "theta",
- "rho",
- "sigma",
- "tau",
- "upsilon",
- "omega1",
- "omega",
- "xi",
- "psi",
- "zeta",
- "braceleft",
- "bar",
- "braceright",
- "similar",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "Upsilon1",
- "minute",
- "lessequal",
- "fraction",
- "infinity",
- "florin",
- "club",
- "diamond",
- "heart",
- "spade",
- "arrowboth",
- "arrowleft",
- "arrowup",
- "arrowright",
- "arrowdown",
- "degree",
- "plusminus",
- "second",
- "greaterequal",
- "multiply",
- "proportional",
- "partialdiff",
- "bullet",
- "divide",
- "notequal",
- "equivalence",
- "approxequal",
- "ellipsis",
- "arrowvertex",
- "arrowhorizex",
- "carriagereturn",
- "aleph",
- "Ifraktur",
- "Rfraktur",
- "weierstrass",
- "circlemultiply",
- "circleplus",
- "emptyset",
- "intersection",
- "union",
- "propersuperset",
- "reflexsuperset",
- "notsubset",
- "propersubset",
- "reflexsubset",
- "element",
- "notelement",
- "angle",
- "gradient",
- "registerserif",
- "copyrightserif",
- "trademarkserif",
- "product",
- "radical",
- "dotmath",
- "logicalnot",
- "logicaland",
- "logicalor",
- "arrowdblboth",
- "arrowdblleft",
- "arrowdblup",
- "arrowdblright",
- "arrowdbldown",
- "lozenge",
- "angleleft",
- "registersans",
- "copyrightsans",
- "trademarksans",
- "summation",
- "parenlefttp",
- "parenleftex",
- "parenleftbt",
- "bracketlefttp",
- "bracketleftex",
- "bracketleftbt",
- "bracelefttp",
- "braceleftmid",
- "braceleftbt",
- "braceex",
- NULL,
- "angleright",
- "integral",
- "integraltp",
- "integralex",
- "integralbt",
- "parenrighttp",
- "parenrightex",
- "parenrightbt",
- "bracketrighttp",
- "bracketrightex",
- "bracketrightbt",
- "bracerighttp",
- "bracerightmid",
- "bracerightbt",
- NULL
-};
-
-const char *zapfDingbatsEncoding[256] = {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "space",
- "a1",
- "a2",
- "a202",
- "a3",
- "a4",
- "a5",
- "a119",
- "a118",
- "a117",
- "a11",
- "a12",
- "a13",
- "a14",
- "a15",
- "a16",
- "a105",
- "a17",
- "a18",
- "a19",
- "a20",
- "a21",
- "a22",
- "a23",
- "a24",
- "a25",
- "a26",
- "a27",
- "a28",
- "a6",
- "a7",
- "a8",
- "a9",
- "a10",
- "a29",
- "a30",
- "a31",
- "a32",
- "a33",
- "a34",
- "a35",
- "a36",
- "a37",
- "a38",
- "a39",
- "a40",
- "a41",
- "a42",
- "a43",
- "a44",
- "a45",
- "a46",
- "a47",
- "a48",
- "a49",
- "a50",
- "a51",
- "a52",
- "a53",
- "a54",
- "a55",
- "a56",
- "a57",
- "a58",
- "a59",
- "a60",
- "a61",
- "a62",
- "a63",
- "a64",
- "a65",
- "a66",
- "a67",
- "a68",
- "a69",
- "a70",
- "a71",
- "a72",
- "a73",
- "a74",
- "a203",
- "a75",
- "a204",
- "a76",
- "a77",
- "a78",
- "a79",
- "a81",
- "a82",
- "a83",
- "a84",
- "a97",
- "a98",
- "a99",
- "a100",
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- "a101",
- "a102",
- "a103",
- "a104",
- "a106",
- "a107",
- "a108",
- "a112",
- "a111",
- "a110",
- "a109",
- "a120",
- "a121",
- "a122",
- "a123",
- "a124",
- "a125",
- "a126",
- "a127",
- "a128",
- "a129",
- "a130",
- "a131",
- "a132",
- "a133",
- "a134",
- "a135",
- "a136",
- "a137",
- "a138",
- "a139",
- "a140",
- "a141",
- "a142",
- "a143",
- "a144",
- "a145",
- "a146",
- "a147",
- "a148",
- "a149",
- "a150",
- "a151",
- "a152",
- "a153",
- "a154",
- "a155",
- "a156",
- "a157",
- "a158",
- "a159",
- "a160",
- "a161",
- "a163",
- "a164",
- "a196",
- "a165",
- "a192",
- "a166",
- "a167",
- "a168",
- "a169",
- "a170",
- "a171",
- "a172",
- "a173",
- "a162",
- "a174",
- "a175",
- "a176",
- "a177",
- "a178",
- "a179",
- "a193",
- "a180",
- "a199",
- "a181",
- "a200",
- "a182",
- NULL,
- "a201",
- "a183",
- "a184",
- "a197",
- "a185",
- "a194",
- "a198",
- "a186",
- "a195",
- "a187",
- "a188",
- "a189",
- "a190",
- "a191",
- NULL
-};
diff --git a/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cpp b/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cpp
new file mode 100644
index 000000000..83774bf87
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/FontEncodingTables.cpp
@@ -0,0 +1,1824 @@
+//========================================================================
+//
+// FontEncodingTables.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdlib.h>
+#include "FontEncodingTables.h"
+
+const char *macRomanEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclam",
+ "quotedbl",
+ "numbersign",
+ "dollar",
+ "percent",
+ "ampersand",
+ "quotesingle",
+ "parenleft",
+ "parenright",
+ "asterisk",
+ "plus",
+ "comma",
+ "hyphen",
+ "period",
+ "slash",
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "colon",
+ "semicolon",
+ "less",
+ "equal",
+ "greater",
+ "question",
+ "at",
+ "A",
+ "B",
+ "C",
+ "D",
+ "E",
+ "F",
+ "G",
+ "H",
+ "I",
+ "J",
+ "K",
+ "L",
+ "M",
+ "N",
+ "O",
+ "P",
+ "Q",
+ "R",
+ "S",
+ "T",
+ "U",
+ "V",
+ "W",
+ "X",
+ "Y",
+ "Z",
+ "bracketleft",
+ "backslash",
+ "bracketright",
+ "asciicircum",
+ "underscore",
+ "grave",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+ "g",
+ "h",
+ "i",
+ "j",
+ "k",
+ "l",
+ "m",
+ "n",
+ "o",
+ "p",
+ "q",
+ "r",
+ "s",
+ "t",
+ "u",
+ "v",
+ "w",
+ "x",
+ "y",
+ "z",
+ "braceleft",
+ "bar",
+ "braceright",
+ "asciitilde",
+ NULL,
+ "Adieresis",
+ "Aring",
+ "Ccedilla",
+ "Eacute",
+ "Ntilde",
+ "Odieresis",
+ "Udieresis",
+ "aacute",
+ "agrave",
+ "acircumflex",
+ "adieresis",
+ "atilde",
+ "aring",
+ "ccedilla",
+ "eacute",
+ "egrave",
+ "ecircumflex",
+ "edieresis",
+ "iacute",
+ "igrave",
+ "icircumflex",
+ "idieresis",
+ "ntilde",
+ "oacute",
+ "ograve",
+ "ocircumflex",
+ "odieresis",
+ "otilde",
+ "uacute",
+ "ugrave",
+ "ucircumflex",
+ "udieresis",
+ "dagger",
+ "degree",
+ "cent",
+ "sterling",
+ "section",
+ "bullet",
+ "paragraph",
+ "germandbls",
+ "registered",
+ "copyright",
+ "trademark",
+ "acute",
+ "dieresis",
+ NULL,
+ "AE",
+ "Oslash",
+ NULL,
+ "plusminus",
+ NULL,
+ NULL,
+ "yen",
+ "mu",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "ordfeminine",
+ "ordmasculine",
+ NULL,
+ "ae",
+ "oslash",
+ "questiondown",
+ "exclamdown",
+ "logicalnot",
+ NULL,
+ "florin",
+ NULL,
+ NULL,
+ "guillemotleft",
+ "guillemotright",
+ "ellipsis",
+ "space",
+ "Agrave",
+ "Atilde",
+ "Otilde",
+ "OE",
+ "oe",
+ "endash",
+ "emdash",
+ "quotedblleft",
+ "quotedblright",
+ "quoteleft",
+ "quoteright",
+ "divide",
+ NULL,
+ "ydieresis",
+ "Ydieresis",
+ "fraction",
+ "currency",
+ "guilsinglleft",
+ "guilsinglright",
+ "fi",
+ "fl",
+ "daggerdbl",
+ "periodcentered",
+ "quotesinglbase",
+ "quotedblbase",
+ "perthousand",
+ "Acircumflex",
+ "Ecircumflex",
+ "Aacute",
+ "Edieresis",
+ "Egrave",
+ "Iacute",
+ "Icircumflex",
+ "Idieresis",
+ "Igrave",
+ "Oacute",
+ "Ocircumflex",
+ NULL,
+ "Ograve",
+ "Uacute",
+ "Ucircumflex",
+ "Ugrave",
+ "dotlessi",
+ "circumflex",
+ "tilde",
+ "macron",
+ "breve",
+ "dotaccent",
+ "ring",
+ "cedilla",
+ "hungarumlaut",
+ "ogonek",
+ "caron"
+};
+
+const char *macExpertEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclamsmall",
+ "Hungarumlautsmall",
+ "centoldstyle",
+ "dollaroldstyle",
+ "dollarsuperior",
+ "ampersandsmall",
+ "Acutesmall",
+ "parenleftsuperior",
+ "parenrightsuperior",
+ "twodotenleader",
+ "onedotenleader",
+ "comma",
+ "hyphen",
+ "period",
+ "fraction",
+ "zerooldstyle",
+ "oneoldstyle",
+ "twooldstyle",
+ "threeoldstyle",
+ "fouroldstyle",
+ "fiveoldstyle",
+ "sixoldstyle",
+ "sevenoldstyle",
+ "eightoldstyle",
+ "nineoldstyle",
+ "colon",
+ "semicolon",
+ NULL,
+ "threequartersemdash",
+ NULL,
+ "questionsmall",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "Ethsmall",
+ NULL,
+ NULL,
+ "onequarter",
+ "onehalf",
+ "threequarters",
+ "oneeighth",
+ "threeeighths",
+ "fiveeighths",
+ "seveneighths",
+ "onethird",
+ "twothirds",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "ff",
+ "fi",
+ "fl",
+ "ffi",
+ "ffl",
+ "parenleftinferior",
+ NULL,
+ "parenrightinferior",
+ "Circumflexsmall",
+ "hypheninferior",
+ "Gravesmall",
+ "Asmall",
+ "Bsmall",
+ "Csmall",
+ "Dsmall",
+ "Esmall",
+ "Fsmall",
+ "Gsmall",
+ "Hsmall",
+ "Ismall",
+ "Jsmall",
+ "Ksmall",
+ "Lsmall",
+ "Msmall",
+ "Nsmall",
+ "Osmall",
+ "Psmall",
+ "Qsmall",
+ "Rsmall",
+ "Ssmall",
+ "Tsmall",
+ "Usmall",
+ "Vsmall",
+ "Wsmall",
+ "Xsmall",
+ "Ysmall",
+ "Zsmall",
+ "colonmonetary",
+ "onefitted",
+ "rupiah",
+ "Tildesmall",
+ NULL,
+ NULL,
+ "asuperior",
+ "centsuperior",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "Aacutesmall",
+ "Agravesmall",
+ "Acircumflexsmall",
+ "Adieresissmall",
+ "Atildesmall",
+ "Aringsmall",
+ "Ccedillasmall",
+ "Eacutesmall",
+ "Egravesmall",
+ "Ecircumflexsmall",
+ "Edieresissmall",
+ "Iacutesmall",
+ "Igravesmall",
+ "Icircumflexsmall",
+ "Idieresissmall",
+ "Ntildesmall",
+ "Oacutesmall",
+ "Ogravesmall",
+ "Ocircumflexsmall",
+ "Odieresissmall",
+ "Otildesmall",
+ "Uacutesmall",
+ "Ugravesmall",
+ "Ucircumflexsmall",
+ "Udieresissmall",
+ NULL,
+ "eightsuperior",
+ "fourinferior",
+ "threeinferior",
+ "sixinferior",
+ "eightinferior",
+ "seveninferior",
+ "Scaronsmall",
+ NULL,
+ "centinferior",
+ "twoinferior",
+ NULL,
+ "Dieresissmall",
+ NULL,
+ "Caronsmall",
+ "osuperior",
+ "fiveinferior",
+ NULL,
+ "commainferior",
+ "periodinferior",
+ "Yacutesmall",
+ NULL,
+ "dollarinferior",
+ NULL,
+ NULL,
+ "Thornsmall",
+ NULL,
+ "nineinferior",
+ "zeroinferior",
+ "Zcaronsmall",
+ "AEsmall",
+ "Oslashsmall",
+ "questiondownsmall",
+ "oneinferior",
+ "Lslashsmall",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "Cedillasmall",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "OEsmall",
+ "figuredash",
+ "hyphensuperior",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "exclamdownsmall",
+ NULL,
+ "Ydieresissmall",
+ NULL,
+ "onesuperior",
+ "twosuperior",
+ "threesuperior",
+ "foursuperior",
+ "fivesuperior",
+ "sixsuperior",
+ "sevensuperior",
+ "ninesuperior",
+ "zerosuperior",
+ NULL,
+ "esuperior",
+ "rsuperior",
+ "tsuperior",
+ NULL,
+ NULL,
+ "isuperior",
+ "ssuperior",
+ "dsuperior",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "lsuperior",
+ "Ogoneksmall",
+ "Brevesmall",
+ "Macronsmall",
+ "bsuperior",
+ "nsuperior",
+ "msuperior",
+ "commasuperior",
+ "periodsuperior",
+ "Dotaccentsmall",
+ "Ringsmall",
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+const char *winAnsiEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclam",
+ "quotedbl",
+ "numbersign",
+ "dollar",
+ "percent",
+ "ampersand",
+ "quotesingle",
+ "parenleft",
+ "parenright",
+ "asterisk",
+ "plus",
+ "comma",
+ "hyphen",
+ "period",
+ "slash",
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "colon",
+ "semicolon",
+ "less",
+ "equal",
+ "greater",
+ "question",
+ "at",
+ "A",
+ "B",
+ "C",
+ "D",
+ "E",
+ "F",
+ "G",
+ "H",
+ "I",
+ "J",
+ "K",
+ "L",
+ "M",
+ "N",
+ "O",
+ "P",
+ "Q",
+ "R",
+ "S",
+ "T",
+ "U",
+ "V",
+ "W",
+ "X",
+ "Y",
+ "Z",
+ "bracketleft",
+ "backslash",
+ "bracketright",
+ "asciicircum",
+ "underscore",
+ "grave",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+ "g",
+ "h",
+ "i",
+ "j",
+ "k",
+ "l",
+ "m",
+ "n",
+ "o",
+ "p",
+ "q",
+ "r",
+ "s",
+ "t",
+ "u",
+ "v",
+ "w",
+ "x",
+ "y",
+ "z",
+ "braceleft",
+ "bar",
+ "braceright",
+ "asciitilde",
+ "bullet",
+ "Euro",
+ "bullet",
+ "quotesinglbase",
+ "florin",
+ "quotedblbase",
+ "ellipsis",
+ "dagger",
+ "daggerdbl",
+ "circumflex",
+ "perthousand",
+ "Scaron",
+ "guilsinglleft",
+ "OE",
+ "bullet",
+ "Zcaron",
+ "bullet",
+ "bullet",
+ "quoteleft",
+ "quoteright",
+ "quotedblleft",
+ "quotedblright",
+ "bullet",
+ "endash",
+ "emdash",
+ "tilde",
+ "trademark",
+ "scaron",
+ "guilsinglright",
+ "oe",
+ "bullet",
+ "zcaron",
+ "Ydieresis",
+ "space",
+ "exclamdown",
+ "cent",
+ "sterling",
+ "currency",
+ "yen",
+ "brokenbar",
+ "section",
+ "dieresis",
+ "copyright",
+ "ordfeminine",
+ "guillemotleft",
+ "logicalnot",
+ "hyphen",
+ "registered",
+ "macron",
+ "degree",
+ "plusminus",
+ "twosuperior",
+ "threesuperior",
+ "acute",
+ "mu",
+ "paragraph",
+ "periodcentered",
+ "cedilla",
+ "onesuperior",
+ "ordmasculine",
+ "guillemotright",
+ "onequarter",
+ "onehalf",
+ "threequarters",
+ "questiondown",
+ "Agrave",
+ "Aacute",
+ "Acircumflex",
+ "Atilde",
+ "Adieresis",
+ "Aring",
+ "AE",
+ "Ccedilla",
+ "Egrave",
+ "Eacute",
+ "Ecircumflex",
+ "Edieresis",
+ "Igrave",
+ "Iacute",
+ "Icircumflex",
+ "Idieresis",
+ "Eth",
+ "Ntilde",
+ "Ograve",
+ "Oacute",
+ "Ocircumflex",
+ "Otilde",
+ "Odieresis",
+ "multiply",
+ "Oslash",
+ "Ugrave",
+ "Uacute",
+ "Ucircumflex",
+ "Udieresis",
+ "Yacute",
+ "Thorn",
+ "germandbls",
+ "agrave",
+ "aacute",
+ "acircumflex",
+ "atilde",
+ "adieresis",
+ "aring",
+ "ae",
+ "ccedilla",
+ "egrave",
+ "eacute",
+ "ecircumflex",
+ "edieresis",
+ "igrave",
+ "iacute",
+ "icircumflex",
+ "idieresis",
+ "eth",
+ "ntilde",
+ "ograve",
+ "oacute",
+ "ocircumflex",
+ "otilde",
+ "odieresis",
+ "divide",
+ "oslash",
+ "ugrave",
+ "uacute",
+ "ucircumflex",
+ "udieresis",
+ "yacute",
+ "thorn",
+ "ydieresis"
+};
+
+const char *standardEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclam",
+ "quotedbl",
+ "numbersign",
+ "dollar",
+ "percent",
+ "ampersand",
+ "quoteright",
+ "parenleft",
+ "parenright",
+ "asterisk",
+ "plus",
+ "comma",
+ "hyphen",
+ "period",
+ "slash",
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "colon",
+ "semicolon",
+ "less",
+ "equal",
+ "greater",
+ "question",
+ "at",
+ "A",
+ "B",
+ "C",
+ "D",
+ "E",
+ "F",
+ "G",
+ "H",
+ "I",
+ "J",
+ "K",
+ "L",
+ "M",
+ "N",
+ "O",
+ "P",
+ "Q",
+ "R",
+ "S",
+ "T",
+ "U",
+ "V",
+ "W",
+ "X",
+ "Y",
+ "Z",
+ "bracketleft",
+ "backslash",
+ "bracketright",
+ "asciicircum",
+ "underscore",
+ "quoteleft",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+ "g",
+ "h",
+ "i",
+ "j",
+ "k",
+ "l",
+ "m",
+ "n",
+ "o",
+ "p",
+ "q",
+ "r",
+ "s",
+ "t",
+ "u",
+ "v",
+ "w",
+ "x",
+ "y",
+ "z",
+ "braceleft",
+ "bar",
+ "braceright",
+ "asciitilde",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "exclamdown",
+ "cent",
+ "sterling",
+ "fraction",
+ "yen",
+ "florin",
+ "section",
+ "currency",
+ "quotesingle",
+ "quotedblleft",
+ "guillemotleft",
+ "guilsinglleft",
+ "guilsinglright",
+ "fi",
+ "fl",
+ NULL,
+ "endash",
+ "dagger",
+ "daggerdbl",
+ "periodcentered",
+ NULL,
+ "paragraph",
+ "bullet",
+ "quotesinglbase",
+ "quotedblbase",
+ "quotedblright",
+ "guillemotright",
+ "ellipsis",
+ "perthousand",
+ NULL,
+ "questiondown",
+ NULL,
+ "grave",
+ "acute",
+ "circumflex",
+ "tilde",
+ "macron",
+ "breve",
+ "dotaccent",
+ "dieresis",
+ NULL,
+ "ring",
+ "cedilla",
+ NULL,
+ "hungarumlaut",
+ "ogonek",
+ "caron",
+ "emdash",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "AE",
+ NULL,
+ "ordfeminine",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "Lslash",
+ "Oslash",
+ "OE",
+ "ordmasculine",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "ae",
+ NULL,
+ NULL,
+ NULL,
+ "dotlessi",
+ NULL,
+ NULL,
+ "lslash",
+ "oslash",
+ "oe",
+ "germandbls",
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+const char *expertEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclamsmall",
+ "Hungarumlautsmall",
+ NULL,
+ "dollaroldstyle",
+ "dollarsuperior",
+ "ampersandsmall",
+ "Acutesmall",
+ "parenleftsuperior",
+ "parenrightsuperior",
+ "twodotenleader",
+ "onedotenleader",
+ "comma",
+ "hyphen",
+ "period",
+ "fraction",
+ "zerooldstyle",
+ "oneoldstyle",
+ "twooldstyle",
+ "threeoldstyle",
+ "fouroldstyle",
+ "fiveoldstyle",
+ "sixoldstyle",
+ "sevenoldstyle",
+ "eightoldstyle",
+ "nineoldstyle",
+ "colon",
+ "semicolon",
+ "commasuperior",
+ "threequartersemdash",
+ "periodsuperior",
+ "questionsmall",
+ NULL,
+ "asuperior",
+ "bsuperior",
+ "centsuperior",
+ "dsuperior",
+ "esuperior",
+ NULL,
+ NULL,
+ NULL,
+ "isuperior",
+ NULL,
+ NULL,
+ "lsuperior",
+ "msuperior",
+ "nsuperior",
+ "osuperior",
+ NULL,
+ NULL,
+ "rsuperior",
+ "ssuperior",
+ "tsuperior",
+ NULL,
+ "ff",
+ "fi",
+ "fl",
+ "ffi",
+ "ffl",
+ "parenleftinferior",
+ NULL,
+ "parenrightinferior",
+ "Circumflexsmall",
+ "hyphensuperior",
+ "Gravesmall",
+ "Asmall",
+ "Bsmall",
+ "Csmall",
+ "Dsmall",
+ "Esmall",
+ "Fsmall",
+ "Gsmall",
+ "Hsmall",
+ "Ismall",
+ "Jsmall",
+ "Ksmall",
+ "Lsmall",
+ "Msmall",
+ "Nsmall",
+ "Osmall",
+ "Psmall",
+ "Qsmall",
+ "Rsmall",
+ "Ssmall",
+ "Tsmall",
+ "Usmall",
+ "Vsmall",
+ "Wsmall",
+ "Xsmall",
+ "Ysmall",
+ "Zsmall",
+ "colonmonetary",
+ "onefitted",
+ "rupiah",
+ "Tildesmall",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "exclamdownsmall",
+ "centoldstyle",
+ "Lslashsmall",
+ NULL,
+ NULL,
+ "Scaronsmall",
+ "Zcaronsmall",
+ "Dieresissmall",
+ "Brevesmall",
+ "Caronsmall",
+ NULL,
+ "Dotaccentsmall",
+ NULL,
+ NULL,
+ "Macronsmall",
+ NULL,
+ NULL,
+ "figuredash",
+ "hypheninferior",
+ NULL,
+ NULL,
+ "Ogoneksmall",
+ "Ringsmall",
+ "Cedillasmall",
+ NULL,
+ NULL,
+ NULL,
+ "onequarter",
+ "onehalf",
+ "threequarters",
+ "questiondownsmall",
+ "oneeighth",
+ "threeeighths",
+ "fiveeighths",
+ "seveneighths",
+ "onethird",
+ "twothirds",
+ NULL,
+ NULL,
+ "zerosuperior",
+ "onesuperior",
+ "twosuperior",
+ "threesuperior",
+ "foursuperior",
+ "fivesuperior",
+ "sixsuperior",
+ "sevensuperior",
+ "eightsuperior",
+ "ninesuperior",
+ "zeroinferior",
+ "oneinferior",
+ "twoinferior",
+ "threeinferior",
+ "fourinferior",
+ "fiveinferior",
+ "sixinferior",
+ "seveninferior",
+ "eightinferior",
+ "nineinferior",
+ "centinferior",
+ "dollarinferior",
+ "periodinferior",
+ "commainferior",
+ "Agravesmall",
+ "Aacutesmall",
+ "Acircumflexsmall",
+ "Atildesmall",
+ "Adieresissmall",
+ "Aringsmall",
+ "AEsmall",
+ "Ccedillasmall",
+ "Egravesmall",
+ "Eacutesmall",
+ "Ecircumflexsmall",
+ "Edieresissmall",
+ "Igravesmall",
+ "Iacutesmall",
+ "Icircumflexsmall",
+ "Idieresissmall",
+ "Ethsmall",
+ "Ntildesmall",
+ "Ogravesmall",
+ "Oacutesmall",
+ "Ocircumflexsmall",
+ "Otildesmall",
+ "Odieresissmall",
+ "OEsmall",
+ "Oslashsmall",
+ "Ugravesmall",
+ "Uacutesmall",
+ "Ucircumflexsmall",
+ "Udieresissmall",
+ "Yacutesmall",
+ "Thornsmall",
+ "Ydieresissmall"
+};
+
+const char *symbolEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "exclam",
+ "universal",
+ "numbersign",
+ "existential",
+ "percent",
+ "ampersand",
+ "suchthat",
+ "parenleft",
+ "parenright",
+ "asteriskmath",
+ "plus",
+ "comma",
+ "minus",
+ "period",
+ "slash",
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "colon",
+ "semicolon",
+ "less",
+ "equal",
+ "greater",
+ "question",
+ "congruent",
+ "Alpha",
+ "Beta",
+ "Chi",
+ "Delta",
+ "Epsilon",
+ "Phi",
+ "Gamma",
+ "Eta",
+ "Iota",
+ "theta1",
+ "Kappa",
+ "Lambda",
+ "Mu",
+ "Nu",
+ "Omicron",
+ "Pi",
+ "Theta",
+ "Rho",
+ "Sigma",
+ "Tau",
+ "Upsilon",
+ "sigma1",
+ "Omega",
+ "Xi",
+ "Psi",
+ "Zeta",
+ "bracketleft",
+ "therefore",
+ "bracketright",
+ "perpendicular",
+ "underscore",
+ "radicalex",
+ "alpha",
+ "beta",
+ "chi",
+ "delta",
+ "epsilon",
+ "phi",
+ "gamma",
+ "eta",
+ "iota",
+ "phi1",
+ "kappa",
+ "lambda",
+ "mu",
+ "nu",
+ "omicron",
+ "pi",
+ "theta",
+ "rho",
+ "sigma",
+ "tau",
+ "upsilon",
+ "omega1",
+ "omega",
+ "xi",
+ "psi",
+ "zeta",
+ "braceleft",
+ "bar",
+ "braceright",
+ "similar",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "Upsilon1",
+ "minute",
+ "lessequal",
+ "fraction",
+ "infinity",
+ "florin",
+ "club",
+ "diamond",
+ "heart",
+ "spade",
+ "arrowboth",
+ "arrowleft",
+ "arrowup",
+ "arrowright",
+ "arrowdown",
+ "degree",
+ "plusminus",
+ "second",
+ "greaterequal",
+ "multiply",
+ "proportional",
+ "partialdiff",
+ "bullet",
+ "divide",
+ "notequal",
+ "equivalence",
+ "approxequal",
+ "ellipsis",
+ "arrowvertex",
+ "arrowhorizex",
+ "carriagereturn",
+ "aleph",
+ "Ifraktur",
+ "Rfraktur",
+ "weierstrass",
+ "circlemultiply",
+ "circleplus",
+ "emptyset",
+ "intersection",
+ "union",
+ "propersuperset",
+ "reflexsuperset",
+ "notsubset",
+ "propersubset",
+ "reflexsubset",
+ "element",
+ "notelement",
+ "angle",
+ "gradient",
+ "registerserif",
+ "copyrightserif",
+ "trademarkserif",
+ "product",
+ "radical",
+ "dotmath",
+ "logicalnot",
+ "logicaland",
+ "logicalor",
+ "arrowdblboth",
+ "arrowdblleft",
+ "arrowdblup",
+ "arrowdblright",
+ "arrowdbldown",
+ "lozenge",
+ "angleleft",
+ "registersans",
+ "copyrightsans",
+ "trademarksans",
+ "summation",
+ "parenlefttp",
+ "parenleftex",
+ "parenleftbt",
+ "bracketlefttp",
+ "bracketleftex",
+ "bracketleftbt",
+ "bracelefttp",
+ "braceleftmid",
+ "braceleftbt",
+ "braceex",
+ NULL,
+ "angleright",
+ "integral",
+ "integraltp",
+ "integralex",
+ "integralbt",
+ "parenrighttp",
+ "parenrightex",
+ "parenrightbt",
+ "bracketrighttp",
+ "bracketrightex",
+ "bracketrightbt",
+ "bracerighttp",
+ "bracerightmid",
+ "bracerightbt",
+ NULL
+};
+
+const char *zapfDingbatsEncoding[256] = {
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "space",
+ "a1",
+ "a2",
+ "a202",
+ "a3",
+ "a4",
+ "a5",
+ "a119",
+ "a118",
+ "a117",
+ "a11",
+ "a12",
+ "a13",
+ "a14",
+ "a15",
+ "a16",
+ "a105",
+ "a17",
+ "a18",
+ "a19",
+ "a20",
+ "a21",
+ "a22",
+ "a23",
+ "a24",
+ "a25",
+ "a26",
+ "a27",
+ "a28",
+ "a6",
+ "a7",
+ "a8",
+ "a9",
+ "a10",
+ "a29",
+ "a30",
+ "a31",
+ "a32",
+ "a33",
+ "a34",
+ "a35",
+ "a36",
+ "a37",
+ "a38",
+ "a39",
+ "a40",
+ "a41",
+ "a42",
+ "a43",
+ "a44",
+ "a45",
+ "a46",
+ "a47",
+ "a48",
+ "a49",
+ "a50",
+ "a51",
+ "a52",
+ "a53",
+ "a54",
+ "a55",
+ "a56",
+ "a57",
+ "a58",
+ "a59",
+ "a60",
+ "a61",
+ "a62",
+ "a63",
+ "a64",
+ "a65",
+ "a66",
+ "a67",
+ "a68",
+ "a69",
+ "a70",
+ "a71",
+ "a72",
+ "a73",
+ "a74",
+ "a203",
+ "a75",
+ "a204",
+ "a76",
+ "a77",
+ "a78",
+ "a79",
+ "a81",
+ "a82",
+ "a83",
+ "a84",
+ "a97",
+ "a98",
+ "a99",
+ "a100",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ "a101",
+ "a102",
+ "a103",
+ "a104",
+ "a106",
+ "a107",
+ "a108",
+ "a112",
+ "a111",
+ "a110",
+ "a109",
+ "a120",
+ "a121",
+ "a122",
+ "a123",
+ "a124",
+ "a125",
+ "a126",
+ "a127",
+ "a128",
+ "a129",
+ "a130",
+ "a131",
+ "a132",
+ "a133",
+ "a134",
+ "a135",
+ "a136",
+ "a137",
+ "a138",
+ "a139",
+ "a140",
+ "a141",
+ "a142",
+ "a143",
+ "a144",
+ "a145",
+ "a146",
+ "a147",
+ "a148",
+ "a149",
+ "a150",
+ "a151",
+ "a152",
+ "a153",
+ "a154",
+ "a155",
+ "a156",
+ "a157",
+ "a158",
+ "a159",
+ "a160",
+ "a161",
+ "a163",
+ "a164",
+ "a196",
+ "a165",
+ "a192",
+ "a166",
+ "a167",
+ "a168",
+ "a169",
+ "a170",
+ "a171",
+ "a172",
+ "a173",
+ "a162",
+ "a174",
+ "a175",
+ "a176",
+ "a177",
+ "a178",
+ "a179",
+ "a193",
+ "a180",
+ "a199",
+ "a181",
+ "a200",
+ "a182",
+ NULL,
+ "a201",
+ "a183",
+ "a184",
+ "a197",
+ "a185",
+ "a194",
+ "a198",
+ "a186",
+ "a195",
+ "a187",
+ "a188",
+ "a189",
+ "a190",
+ "a191",
+ NULL
+};
diff --git a/filters/kword/pdf/xpdf/xpdf/FontFile.cc b/filters/kword/pdf/xpdf/xpdf/FontFile.cc
deleted file mode 100644
index ccb880bfb..000000000
--- a/filters/kword/pdf/xpdf/xpdf/FontFile.cc
+++ /dev/null
@@ -1,3883 +0,0 @@
-//========================================================================
-//
-// FontFile.cc
-//
-// Copyright 1999-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <math.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <stdarg.h>
-#include <string.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "CharCodeToUnicode.h"
-#include "FontEncodingTables.h"
-#include "FontFile.h"
-
-#include "CompactFontTables.h"
-
-//------------------------------------------------------------------------
-
-static inline const char *nextLine(const char *line, const char *end) {
- while (line < end && *line != '\n' && *line != '\r')
- ++line;
- while (line < end && *line == '\n' || *line == '\r')
- ++line;
- return line;
-}
-
-static const char hexChars[17] = "0123456789ABCDEF";
-
-//------------------------------------------------------------------------
-// FontFile
-//------------------------------------------------------------------------
-
-FontFile::FontFile() {
-}
-
-FontFile::~FontFile() {
-}
-
-//------------------------------------------------------------------------
-// Type1FontFile
-//------------------------------------------------------------------------
-
-Type1FontFile::Type1FontFile(const char *file, int len) {
- const char *line, *line1;
- char *p, *p2;
- GBool haveEncoding;
- char buf[256];
- char c;
- int n, code, i, j;
-
- name = NULL;
- encoding = (char **)gmalloc(256 * sizeof(char *));
- for (i = 0; i < 256; ++i) {
- encoding[i] = NULL;
- }
- haveEncoding = gFalse;
-
- for (i = 1, line = file;
- i <= 100 && line < file + len && !haveEncoding;
- ++i) {
-
- // get font name
- if (!strncmp(line, "/FontName", 9)) {
- strncpy(buf, line, 255);
- buf[255] = '\0';
- if ((p = strchr(buf+9, '/')) &&
- (p = strtok(p+1, " \t\n\r"))) {
- name = copyString(p);
- }
- line = nextLine(line, file + len);
-
- // get encoding
- } else if (!strncmp(line, "/Encoding StandardEncoding def", 30)) {
- for (j = 0; j < 256; ++j) {
- if (standardEncoding[j]) {
- encoding[j] = copyString(standardEncoding[j]);
- }
- }
- haveEncoding = gTrue;
- } else if (!strncmp(line, "/Encoding 256 array", 19)) {
- for (j = 0; j < 300; ++j) {
- line1 = nextLine(line, file + len);
- if ((n = line1 - line) > 255) {
- n = 255;
- }
- strncpy(buf, line, n);
- buf[n] = '\0';
- for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
- if (!strncmp(p, "dup", 3)) {
- for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
- for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
- if (*p2) {
- c = *p2;
- *p2 = '\0';
- if ((code = atoi(p)) < 256) {
- *p2 = c;
- for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
- if (*p == '/') {
- ++p;
- for (p2 = p; *p2 && *p2 != ' ' && *p2 != '\t'; ++p2) ;
- *p2 = '\0';
- encoding[code] = copyString(p);
- }
- }
- }
- } else {
- if (strtok(buf, " \t") &&
- (p = strtok(NULL, " \t\n\r")) && !strcmp(p, "def")) {
- break;
- }
- }
- line = line1;
- }
- //~ check for getinterval/putinterval junk
- haveEncoding = gTrue;
-
- } else {
- line = nextLine(line, file + len);
- }
- }
-}
-
-Type1FontFile::~Type1FontFile() {
- int i;
-
- if (name) {
- gfree(name);
- }
- for (i = 0; i < 256; ++i) {
- gfree(encoding[i]);
- }
- gfree(encoding);
-}
-
-//------------------------------------------------------------------------
-// Type1CFontFile
-//------------------------------------------------------------------------
-
-struct Type1CTopDict {
- int version;
- int notice;
- int copyright;
- int fullName;
- int familyName;
- int weight;
- int isFixedPitch;
- double italicAngle;
- double underlinePosition;
- double underlineThickness;
- int paintType;
- int charstringType;
- double fontMatrix[6];
- int uniqueID;
- double fontBBox[4];
- double strokeWidth;
- int charset;
- int encoding;
- int charStrings;
- int privateSize;
- int privateOffset;
-
- //----- CIDFont entries
- int registry;
- int ordering;
- int supplement;
- int fdArrayOffset;
- int fdSelectOffset;
-};
-
-struct Type1CPrivateDict {
- GString *dictData;
- int subrsOffset;
- double defaultWidthX;
- GBool defaultWidthXFP;
- double nominalWidthX;
- GBool nominalWidthXFP;
-};
-
-Type1CFontFile::Type1CFontFile(const char *fileA, int lenA) {
- Guchar *nameIdxPtr, *idxPtr0, *idxPtr1;
-
- file = fileA;
- len = lenA;
- name = NULL;
- encoding = NULL;
-
- // some tools embed Type 1C fonts with an extra whitespace char at
- // the beginning
- if (file[0] != '\x01') {
- ++file;
- }
-
- // read header
- topOffSize = file[3] & 0xff;
-
- // read name index (first font only)
- nameIdxPtr = (Guchar *)file + (file[2] & 0xff);
- idxPtr0 = getIndexValPtr(nameIdxPtr, 0);
- idxPtr1 = getIndexValPtr(nameIdxPtr, 1);
- name = new GString((char *)idxPtr0, idxPtr1 - idxPtr0);
-
- topDictIdxPtr = getIndexEnd(nameIdxPtr);
- stringIdxPtr = getIndexEnd(topDictIdxPtr);
- gsubrIdxPtr = getIndexEnd(stringIdxPtr);
-}
-
-Type1CFontFile::~Type1CFontFile() {
- int i;
-
- delete name;
- if (encoding) {
- for (i = 0; i < 256; ++i) {
- gfree(encoding[i]);
- }
- gfree(encoding);
- }
-}
-
-const char *Type1CFontFile::getName() {
- return name->getCString();
-}
-
-char **Type1CFontFile::getEncoding() {
- if (!encoding) {
- readNameAndEncoding();
- }
- return encoding;
-}
-
-void Type1CFontFile::readNameAndEncoding() {
- char buf[256];
- Guchar *idxPtr0, *idxPtr1, *ptr;
- int nGlyphs;
- int nCodes, nRanges, nLeft, nSups;
- Gushort *glyphNames;
- int charset, enc, charstrings;
- int encFormat;
- int c, sid;
- double x;
- GBool isFP;
- int key;
- int i, j;
-
- encoding = (char **)gmalloc(256 * sizeof(char *));
- for (i = 0; i < 256; ++i) {
- encoding[i] = NULL;
- }
-
- // read top dict (first font only)
- idxPtr0 = getIndexValPtr(topDictIdxPtr, 0);
- idxPtr1 = getIndexValPtr(topDictIdxPtr, 1);
- charset = enc = charstrings = 0;
- i = 0;
- ptr = idxPtr0;
- while (ptr < idxPtr1) {
- if (*ptr <= 27 || *ptr == 31) {
- key = *ptr++;
- if (key == 0x0c) {
- key = (key << 8) | *ptr++;
- }
- if (key == 0x0f) { // charset
- charset = (int)op[0];
- } else if (key == 0x10) { // encoding
- enc = (int)op[0];
- } else if (key == 0x11) { // charstrings
- charstrings = (int)op[0];
- }
- i = 0;
- } else {
- x = getNum(&ptr, &isFP);
- if (i < 48) {
- op[i++] = x;
- }
- }
- }
-
- // get number of glyphs from charstrings index
- nGlyphs = getIndexLen((Guchar *)file + charstrings);
-
- // read charset (GID -> name mapping)
- glyphNames = readCharset(charset, nGlyphs);
-
- // read encoding (GID -> code mapping)
- if (enc == 0) {
- for (i = 0; i < 256; ++i) {
- if (standardEncoding[i]) {
- encoding[i] = copyString(standardEncoding[i]);
- }
- }
- } else if (enc == 1) {
- for (i = 0; i < 256; ++i) {
- if (expertEncoding[i]) {
- encoding[i] = copyString(expertEncoding[i]);
- }
- }
- } else {
- ptr = (Guchar *)file + enc;
- encFormat = *ptr++;
- if ((encFormat & 0x7f) == 0) {
- nCodes = 1 + *ptr++;
- if (nCodes > nGlyphs) {
- nCodes = nGlyphs;
- }
- for (i = 1; i < nCodes; ++i) {
- c = *ptr++;
- encoding[c] = copyString(getString(glyphNames[i], buf));
- }
- } else if ((encFormat & 0x7f) == 1) {
- nRanges = *ptr++;
- nCodes = 1;
- for (i = 0; i < nRanges; ++i) {
- c = *ptr++;
- nLeft = *ptr++;
- for (j = 0; j <= nLeft && nCodes < nGlyphs; ++j) {
- encoding[c] = copyString(getString(glyphNames[nCodes], buf));
- ++nCodes;
- ++c;
- }
- }
- }
- if (encFormat & 0x80) {
- nSups = *ptr++;
- for (i = 0; i < nSups; ++i) {
- c = *ptr++;
- sid = getWord(ptr, 2);
- ptr += 2;
- encoding[c] = copyString(getString(sid, buf));
- }
- }
- }
-
- if (charset > 2) {
- gfree(glyphNames);
- }
-}
-
-void Type1CFontFile::convertToType1(FontFileOutputFunc outputFuncA,
- void *outputStreamA) {
- Type1CTopDict dict;
- Type1CPrivateDict privateDict;
- char buf[512], eBuf[256];
- Guchar *idxPtr0, *idxPtr1, *subrsIdxPtr, *charStringsIdxPtr, *ptr;
- int nGlyphs, nCodes, nRanges, nLeft, nSups;
- Gushort *glyphNames;
- int encFormat, nSubrs, nCharStrings;
- int c, sid;
- int i, j, n;
-
- outputFunc = outputFuncA;
- outputStream = outputStreamA;
-
- // read top dict (first font only)
- readTopDict(&dict);
-
- // get global subrs
- //~ ... global subrs are unimplemented
-
- // write header and font dictionary, up to encoding
- (*outputFunc)(outputStream, "%!FontType1-1.0: ", 17);
- (*outputFunc)(outputStream, name->getCString(), name->getLength());
- if (dict.version != 0) {
- getString(dict.version, buf);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "\n", 1);
- (*outputFunc)(outputStream, "11 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontInfo 10 dict dup begin\n", 28);
- if (dict.version != 0) {
- (*outputFunc)(outputStream, "/version (", 10);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.notice != 0) {
- getString(dict.notice, buf);
- (*outputFunc)(outputStream, "/Notice (", 9);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.copyright != 0) {
- getString(dict.copyright, buf);
- (*outputFunc)(outputStream, "/Copyright (", 12);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.fullName != 0) {
- getString(dict.fullName, buf);
- (*outputFunc)(outputStream, "/FullName (", 11);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.familyName != 0) {
- getString(dict.familyName, buf);
- (*outputFunc)(outputStream, "/FamilyName (", 13);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.weight != 0) {
- getString(dict.weight, buf);
- (*outputFunc)(outputStream, "/Weight (", 9);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") readonly def\n", 15);
- }
- if (dict.isFixedPitch) {
- (*outputFunc)(outputStream, "/isFixedPitch true def\n", 23);
- } else {
- (*outputFunc)(outputStream, "/isFixedPitch false def\n", 24);
- }
- sprintf(buf, "/ItalicAngle %g def\n", dict.italicAngle);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/UnderlinePosition %g def\n", dict.underlinePosition);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/UnderlineThickness %g def\n", dict.underlineThickness);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "end readonly def\n", 17);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, name->getCString(), name->getLength());
- (*outputFunc)(outputStream, " def\n", 5);
- sprintf(buf, "/PaintType %d def\n", dict.paintType);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
- sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] readonly def\n",
- dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
- dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/FontBBox [%g %g %g %g] readonly def\n",
- dict.fontBBox[0], dict.fontBBox[1],
- dict.fontBBox[2], dict.fontBBox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
- (*outputFunc)(outputStream, buf, strlen(buf));
- if (dict.uniqueID != 0) {
- sprintf(buf, "/UniqueID %d def\n", dict.uniqueID);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
-
- // get number of glyphs from charstrings index
- nGlyphs = getIndexLen((Guchar *)file + dict.charStrings);
-
- // read charset
- glyphNames = readCharset(dict.charset, nGlyphs);
-
- // read encoding (glyph -> code mapping), write Type 1 encoding
- (*outputFunc)(outputStream, "/Encoding ", 10);
- if (dict.encoding == 0) {
- (*outputFunc)(outputStream, "StandardEncoding def\n", 21);
- } else {
- (*outputFunc)(outputStream, "256 array\n", 10);
- (*outputFunc)(outputStream,
- "0 1 255 {1 index exch /.notdef put} for\n", 40);
- if (dict.encoding == 1) {
- for (i = 0; i < 256; ++i) {
- if (expertEncoding[i]) {
- sprintf(buf, "dup %d /%s put\n", i, expertEncoding[i]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- }
- } else {
- ptr = (Guchar *)file + dict.encoding;
- encFormat = *ptr++;
- if ((encFormat & 0x7f) == 0) {
- nCodes = 1 + *ptr++;
- if (nCodes > nGlyphs) {
- nCodes = nGlyphs;
- }
- for (i = 1; i < nCodes; ++i) {
- c = *ptr++;
- sprintf(buf, "dup %d /", c);
- (*outputFunc)(outputStream, buf, strlen(buf));
- getString(glyphNames[i], buf);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, " put\n", 5);
- }
- } else if ((encFormat & 0x7f) == 1) {
- nRanges = *ptr++;
- nCodes = 1;
- for (i = 0; i < nRanges; ++i) {
- c = *ptr++;
- nLeft = *ptr++;
- for (j = 0; j <= nLeft && nCodes < nGlyphs; ++j) {
- sprintf(buf, "dup %d /", c);
- (*outputFunc)(outputStream, buf, strlen(buf));
- getString(glyphNames[nCodes], buf);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, " put\n", 5);
- ++nCodes;
- ++c;
- }
- }
- }
- if (encFormat & 0x80) {
- nSups = *ptr++;
- for (i = 0; i < nSups; ++i) {
- c = *ptr++;
- sid = getWord(ptr, 2);
- ptr += 2;
- sprintf(buf, "dup %d /", c);
- (*outputFunc)(outputStream, buf, strlen(buf));
- getString(sid, buf);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, " put\n", 5);
- }
- }
- }
- (*outputFunc)(outputStream, "readonly def\n", 13);
- }
- (*outputFunc)(outputStream, "currentdict end\n", 16);
-
- // start the binary section
- (*outputFunc)(outputStream, "currentfile eexec\n", 18);
- r1 = 55665;
- line = 0;
-
- // get private dictionary
- eexecWrite("\x83\xca\x73\xd5");
- eexecWrite("dup /Private 32 dict dup begin\n");
- eexecWrite("/RD {string currentfile exch readstring pop} executeonly def\n");
- eexecWrite("/ND {noaccess def} executeonly def\n");
- eexecWrite("/NP {noaccess put} executeonly def\n");
- eexecWrite("/MinFeature {16 16} ND\n");
- readPrivateDict(&privateDict, dict.privateOffset, dict.privateSize);
- eexecWrite(privateDict.dictData->getCString());
- defaultWidthX = privateDict.defaultWidthX;
- defaultWidthXFP = privateDict.defaultWidthXFP;
- nominalWidthX = privateDict.nominalWidthX;
- nominalWidthXFP = privateDict.nominalWidthXFP;
-
- // get subrs
- if (privateDict.subrsOffset != 0) {
- subrsIdxPtr = (Guchar *)file + dict.privateOffset +
- privateDict.subrsOffset;
- nSubrs = getIndexLen(subrsIdxPtr);
- sprintf(eBuf, "/Subrs %d array\n", nSubrs);
- eexecWrite(eBuf);
- idxPtr1 = getIndexValPtr(subrsIdxPtr, 0);
- for (i = 0; i < nSubrs; ++i) {
- idxPtr0 = idxPtr1;
- idxPtr1 = getIndexValPtr(subrsIdxPtr, i+1);
- n = idxPtr1 - idxPtr0;
-#if 1 //~ Type 2 subrs are unimplemented
- error(-1, "Unimplemented Type 2 subrs");
-#else
- sprintf(eBuf, "dup %d %d RD ", i, n);
- eexecWrite(eBuf);
- eexecCvtGlyph(idxPtr0, n);
- eexecWrite(" NP\n");
-#endif
- }
- eexecWrite("ND\n");
- }
-
- // get CharStrings
- charStringsIdxPtr = (Guchar *)file + dict.charStrings;
- nCharStrings = getIndexLen(charStringsIdxPtr);
- sprintf(eBuf, "2 index /CharStrings %d dict dup begin\n", nCharStrings);
- eexecWrite(eBuf);
- idxPtr1 = getIndexValPtr(charStringsIdxPtr, 0);
- for (i = 0; i < nCharStrings; ++i) {
- idxPtr0 = idxPtr1;
- idxPtr1 = getIndexValPtr(charStringsIdxPtr, i+1);
- n = idxPtr1 - idxPtr0;
- eexecCvtGlyph(getString(glyphNames[i], buf), idxPtr0, n);
- }
- eexecWrite("end\n");
- eexecWrite("end\n");
- eexecWrite("readonly put\n");
- eexecWrite("noaccess put\n");
- eexecWrite("dup /FontName get exch definefont pop\n");
- eexecWrite("mark currentfile closefile\n");
-
- // trailer
- if (line > 0) {
- (*outputFunc)(outputStream, "\n", 1);
- }
- for (i = 0; i < 8; ++i) {
- (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65);
- }
- (*outputFunc)(outputStream, "cleartomark\n", 12);
-
- // clean up
- delete privateDict.dictData;
- if (dict.charset > 2) {
- gfree(glyphNames);
- }
-}
-
-void Type1CFontFile::convertToCIDType0(const char *psName,
- FontFileOutputFunc outputFuncA,
- void *outputStreamA) {
- Type1CTopDict dict;
- Type1CPrivateDict *privateDicts;
- GString *charStrings;
- int *charStringOffsets;
- Gushort *charset;
- int *cidMap;
- Guchar *fdSelect;
- Guchar *charStringsIdxPtr, *fdArrayIdx, *idxPtr0, *idxPtr1, *ptr;
- char buf[512], buf2[16];
- int nGlyphs, nCIDs, gdBytes, nFDs;
- int fdSelectFmt, nRanges, gid0, gid1, fd, offset;
- int key;
- double x;
- GBool isFP;
- int i, j, k, n;
-
- outputFunc = outputFuncA;
- outputStream = outputStreamA;
-
- (*outputFunc)(outputStream, "/CIDInit /ProcSet findresource begin\n", 37);
-
- // read top dict (first font only)
- readTopDict(&dict);
-
- // read the FDArray dictionaries and Private dictionaries
- if (dict.fdArrayOffset == 0) {
- nFDs = 1;
- privateDicts = (Type1CPrivateDict *)
- gmalloc(nFDs * sizeof(Type1CPrivateDict));
- privateDicts[0].dictData = new GString();
- privateDicts[0].subrsOffset = 0;
- privateDicts[0].defaultWidthX = 0;
- privateDicts[0].defaultWidthXFP = gFalse;
- privateDicts[0].nominalWidthX = 0;
- privateDicts[0].nominalWidthXFP = gFalse;
- } else {
- fdArrayIdx = (Guchar *)file + dict.fdArrayOffset;
- nFDs = getIndexLen(fdArrayIdx);
- privateDicts = (Type1CPrivateDict *)
- gmalloc(nFDs * sizeof(Type1CPrivateDict));
- idxPtr1 = getIndexValPtr(fdArrayIdx, 0);
- for (i = 0; i < nFDs; ++i) {
- privateDicts[i].dictData = NULL;
- idxPtr0 = idxPtr1;
- idxPtr1 = getIndexValPtr(fdArrayIdx, i + 1);
- ptr = idxPtr0;
- j = 0;
- while (ptr < idxPtr1) {
- if (*ptr <= 27 || *ptr == 31) {
- key = *ptr++;
- if (key == 0x0c) {
- key = (key << 8) | *ptr++;
- }
- if (key == 0x0012) {
- readPrivateDict(&privateDicts[i], (int)op[1], (int)op[0]);
- }
- j = 0;
- } else {
- x = getNum(&ptr, &isFP);
- if (j < 48) {
- op[j] = x;
- fp[j++] = isFP;
- }
- }
- }
- if (!privateDicts[i].dictData) {
- privateDicts[i].dictData = new GString();
- privateDicts[i].subrsOffset = 0;
- privateDicts[i].defaultWidthX = 0;
- privateDicts[i].defaultWidthXFP = gFalse;
- privateDicts[i].nominalWidthX = 0;
- privateDicts[i].nominalWidthXFP = gFalse;
- }
- }
- }
-
- // get the glyph count
- charStringsIdxPtr = (Guchar *)file + dict.charStrings;
- nGlyphs = getIndexLen(charStringsIdxPtr);
-
- // read the FDSelect table
- fdSelect = (Guchar *)gmalloc(nGlyphs);
- if (dict.fdSelectOffset == 0) {
- for (i = 0; i < nGlyphs; ++i) {
- fdSelect[i] = 0;
- }
- } else {
- ptr = (Guchar *)file + dict.fdSelectOffset;
- fdSelectFmt = *ptr++;
- if (fdSelectFmt == 0) {
- memcpy(fdSelect, ptr, nGlyphs);
- } else if (fdSelectFmt == 3) {
- nRanges = getWord(ptr, 2);
- ptr += 2;
- gid0 = getWord(ptr, 2);
- ptr += 2;
- for (i = 1; i <= nRanges; ++i) {
- fd = *ptr++;
- gid1 = getWord(ptr, 2);
- ptr += 2;
- for (j = gid0; j < gid1; ++j) {
- fdSelect[j] = fd;
- }
- gid0 = gid1;
- }
- } else {
- error(-1, "Unknown FDSelect table format in CID font");
- for (i = 0; i < nGlyphs; ++i) {
- fdSelect[i] = 0;
- }
- }
- }
-
- // read the charset, compute the CID-to-GID mapping
- charset = readCharset(dict.charset, nGlyphs);
- nCIDs = 0;
- for (i = 0; i < nGlyphs; ++i) {
- if (charset[i] >= nCIDs) {
- nCIDs = charset[i] + 1;
- }
- }
- cidMap = (int *)gmalloc(nCIDs * sizeof(int));
- for (i = 0; i < nCIDs; ++i) {
- cidMap[i] = -1;
- }
- for (i = 0; i < nGlyphs; ++i) {
- cidMap[charset[i]] = i;
- }
-
- // build the charstrings
- charStrings = new GString();
- charStringOffsets = (int *)gmalloc((nCIDs + 1) * sizeof(int));
- for (i = 0; i < nCIDs; ++i) {
- charStringOffsets[i] = charStrings->getLength();
- if (cidMap[i] >= 0) {
- idxPtr0 = getIndexValPtr(charStringsIdxPtr, cidMap[i]);
- idxPtr1 = getIndexValPtr(charStringsIdxPtr, cidMap[i]+1);
- n = idxPtr1 - idxPtr0;
- j = fdSelect[cidMap[i]];
- defaultWidthX = privateDicts[j].defaultWidthX;
- defaultWidthXFP = privateDicts[j].defaultWidthXFP;
- nominalWidthX = privateDicts[j].nominalWidthX;
- nominalWidthXFP = privateDicts[j].nominalWidthXFP;
- cvtGlyph(idxPtr0, n);
- charStrings->append(charBuf);
- delete charBuf;
- }
- }
- charStringOffsets[nCIDs] = charStrings->getLength();
-
- // compute gdBytes = number of bytes needed for charstring offsets
- // (offset size needs to account for the charstring offset table,
- // with a worst case of five bytes per entry, plus the charstrings
- // themselves)
- i = (nCIDs + 1) * 5 + charStrings->getLength();
- if (i < 0x100) {
- gdBytes = 1;
- } else if (i < 0x10000) {
- gdBytes = 2;
- } else if (i < 0x1000000) {
- gdBytes = 3;
- } else {
- gdBytes = 4;
- }
-
- // begin the font dictionary
- (*outputFunc)(outputStream, "20 dict begin\n", 14);
- (*outputFunc)(outputStream, "/CIDFontName /", 14);
- (*outputFunc)(outputStream, psName, strlen(psName));
- (*outputFunc)(outputStream, " def\n", 5);
- (*outputFunc)(outputStream, "/CIDFontType 0 def\n", 19);
- (*outputFunc)(outputStream, "/CIDSystemInfo 3 dict dup begin\n", 32);
- if (dict.registry > 0 && dict.ordering > 0) {
- getString(dict.registry, buf);
- (*outputFunc)(outputStream, " /Registry (", 13);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") def\n", 6);
- getString(dict.ordering, buf);
- (*outputFunc)(outputStream, " /Ordering (", 13);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, ") def\n", 6);
- } else {
- (*outputFunc)(outputStream, " /Registry (Adobe) def\n", 24);
- (*outputFunc)(outputStream, " /Ordering (Identity) def\n", 27);
- }
- sprintf(buf, " /Supplement %d def\n", dict.supplement);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "end def\n", 8);
- sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] def\n",
- dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
- dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/FontBBox [%g %g %g %g] def\n",
- dict.fontBBox[0], dict.fontBBox[1],
- dict.fontBBox[2], dict.fontBBox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FontInfo 1 dict dup begin\n", 27);
- (*outputFunc)(outputStream, " /FSType 8 def\n", 16);
- (*outputFunc)(outputStream, "end def\n", 8);
-
- // CIDFont-specific entries
- sprintf(buf, "/CIDCount %d def\n", nCIDs);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FDBytes 1 def\n", 15);
- sprintf(buf, "/GDBytes %d def\n", gdBytes);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/CIDMapOffset 0 def\n", 20);
- if (dict.paintType != 0) {
- sprintf(buf, "/PaintType %d def\n", dict.paintType);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
-
- // FDArray entry
- sprintf(buf, "/FDArray %d array\n", nFDs);
- (*outputFunc)(outputStream, buf, strlen(buf));
- for (i = 0; i < nFDs; ++i) {
- sprintf(buf, "dup %d 10 dict begin\n", i);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- sprintf(buf, "/PaintType %d def\n", dict.paintType);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/Private 32 dict begin\n", 23);
- (*outputFunc)(outputStream, privateDicts[i].dictData->getCString(),
- privateDicts[i].dictData->getLength());
- (*outputFunc)(outputStream, "currentdict end def\n", 20);
- (*outputFunc)(outputStream, "currentdict end put\n", 20);
- }
- (*outputFunc)(outputStream, "def\n", 4);
-
- //~ need to deal with subrs
-
- // start the binary section
- offset = (nCIDs + 1) * (1 + gdBytes);
- sprintf(buf, "(Hex) %d StartData\n",
- offset + charStrings->getLength());
- (*outputFunc)(outputStream, buf, strlen(buf));
-
- // write the charstring offset (CIDMap) table
- for (i = 0; i <= nCIDs; i += 6) {
- for (j = 0; j < 6 && i+j <= nCIDs; ++j) {
- if (i+j < nCIDs && cidMap[i+j] >= 0) {
- buf[0] = (char)fdSelect[cidMap[i+j]];
- } else {
- buf[0] = (char)0;
- }
- n = offset + charStringOffsets[i+j];
- for (k = gdBytes; k >= 1; --k) {
- buf[k] = (char)(n & 0xff);
- n >>= 8;
- }
- for (k = 0; k <= gdBytes; ++k) {
- sprintf(buf2, "%02x", buf[k] & 0xff);
- (*outputFunc)(outputStream, buf2, 2);
- }
- }
- (*outputFunc)(outputStream, "\n", 1);
- }
-
- // write the charstring data
- n = charStrings->getLength();
- for (i = 0; i < n; i += 32) {
- for (j = 0; j < 32 && i+j < n; ++j) {
- sprintf(buf, "%02x", charStrings->getChar(i+j) & 0xff);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- if (i + 32 >= n) {
- (*outputFunc)(outputStream, ">", 1);
- }
- (*outputFunc)(outputStream, "\n", 1);
- }
-
- for (i = 0; i < nFDs; ++i) {
- delete privateDicts[i].dictData;
- }
- gfree(privateDicts);
- gfree(cidMap);
- gfree(charset);
- gfree(charStringOffsets);
- delete charStrings;
- gfree(fdSelect);
-}
-
-void Type1CFontFile::convertToType0(const char *psName,
- FontFileOutputFunc outputFuncA,
- void *outputStreamA) {
- Type1CTopDict dict;
- Type1CPrivateDict *privateDicts;
- Gushort *charset;
- int *cidMap;
- Guchar *fdSelect;
- Guchar *charStringsIdxPtr, *fdArrayIdx, *idxPtr0, *idxPtr1, *ptr;
- char buf[512];
- char eBuf[256];
- int nGlyphs, nCIDs, nFDs;
- int fdSelectFmt, nRanges, gid0, gid1, fd;
- int key;
- double x;
- GBool isFP;
- int i, j, n;
-
- outputFunc = outputFuncA;
- outputStream = outputStreamA;
-
- // read top dict (first font only)
- readTopDict(&dict);
-
- // read the FDArray dictionaries and Private dictionaries
- if (dict.fdArrayOffset == 0) {
- nFDs = 1;
- privateDicts = (Type1CPrivateDict *)
- gmalloc(nFDs * sizeof(Type1CPrivateDict));
- privateDicts[0].dictData = new GString();
- privateDicts[0].subrsOffset = 0;
- privateDicts[0].defaultWidthX = 0;
- privateDicts[0].defaultWidthXFP = gFalse;
- privateDicts[0].nominalWidthX = 0;
- privateDicts[0].nominalWidthXFP = gFalse;
- } else {
- fdArrayIdx = (Guchar *)file + dict.fdArrayOffset;
- nFDs = getIndexLen(fdArrayIdx);
- privateDicts = (Type1CPrivateDict *)
- gmalloc(nFDs * sizeof(Type1CPrivateDict));
- idxPtr1 = getIndexValPtr(fdArrayIdx, 0);
- for (i = 0; i < nFDs; ++i) {
- privateDicts[i].dictData = NULL;
- idxPtr0 = idxPtr1;
- idxPtr1 = getIndexValPtr(fdArrayIdx, i + 1);
- ptr = idxPtr0;
- j = 0;
- while (ptr < idxPtr1) {
- if (*ptr <= 27 || *ptr == 31) {
- key = *ptr++;
- if (key == 0x0c) {
- key = (key << 8) | *ptr++;
- }
- if (key == 0x0012) {
- readPrivateDict(&privateDicts[i], (int)op[1], (int)op[0]);
- }
- j = 0;
- } else {
- x = getNum(&ptr, &isFP);
- if (j < 48) {
- op[j] = x;
- fp[j++] = isFP;
- }
- }
- }
- if (!privateDicts[i].dictData) {
- privateDicts[i].dictData = new GString();
- privateDicts[i].subrsOffset = 0;
- privateDicts[i].defaultWidthX = 0;
- privateDicts[i].defaultWidthXFP = gFalse;
- privateDicts[i].nominalWidthX = 0;
- privateDicts[i].nominalWidthXFP = gFalse;
- }
- }
- }
-
- // get the glyph count
- charStringsIdxPtr = (Guchar *)file + dict.charStrings;
- nGlyphs = getIndexLen(charStringsIdxPtr);
-
- // read the FDSelect table
- fdSelect = (Guchar *)gmalloc(nGlyphs);
- if (dict.fdSelectOffset == 0) {
- for (i = 0; i < nGlyphs; ++i) {
- fdSelect[i] = 0;
- }
- } else {
- ptr = (Guchar *)file + dict.fdSelectOffset;
- fdSelectFmt = *ptr++;
- if (fdSelectFmt == 0) {
- memcpy(fdSelect, ptr, nGlyphs);
- } else if (fdSelectFmt == 3) {
- nRanges = getWord(ptr, 2);
- ptr += 2;
- gid0 = getWord(ptr, 2);
- ptr += 2;
- for (i = 1; i <= nRanges; ++i) {
- fd = *ptr++;
- gid1 = getWord(ptr, 2);
- ptr += 2;
- for (j = gid0; j < gid1; ++j) {
- fdSelect[j] = fd;
- }
- gid0 = gid1;
- }
- } else {
- error(-1, "Unknown FDSelect table format in CID font");
- for (i = 0; i < nGlyphs; ++i) {
- fdSelect[i] = 0;
- }
- }
- }
-
- // read the charset, compute the CID-to-GID mapping
- charset = readCharset(dict.charset, nGlyphs);
- nCIDs = 0;
- for (i = 0; i < nGlyphs; ++i) {
- if (charset[i] >= nCIDs) {
- nCIDs = charset[i] + 1;
- }
- }
- cidMap = (int *)gmalloc(nCIDs * sizeof(int));
- for (i = 0; i < nCIDs; ++i) {
- cidMap[i] = -1;
- }
- for (i = 0; i < nGlyphs; ++i) {
- cidMap[charset[i]] = i;
- }
-
- // write the descendant Type 1 fonts
- for (i = 0; i < nCIDs; i += 256) {
-
- //~ this assumes that all CIDs in this block have the same FD --
- //~ to handle multiple FDs correctly, need to somehow divide the
- //~ font up by FD
- fd = 0;
- for (j = 0; j < 256 && i+j < nCIDs; ++j) {
- if (cidMap[i+j] >= 0) {
- fd = fdSelect[cidMap[i+j]];
- break;
- }
- }
-
- // font dictionary (unencrypted section)
- (*outputFunc)(outputStream, "16 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, psName, strlen(psName));
- sprintf(buf, "_%02x def\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
- sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] def\n",
- dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
- dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/FontBBox [%g %g %g %g] def\n",
- dict.fontBBox[0], dict.fontBBox[1],
- dict.fontBBox[2], dict.fontBBox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, "/PaintType %d def\n", dict.paintType);
- (*outputFunc)(outputStream, buf, strlen(buf));
- if (dict.paintType != 0) {
- sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
- for (j = 0; j < 256 && i+j < nCIDs; ++j) {
- sprintf(buf, "dup %d /c%02x put\n", j, j);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "readonly def\n", 13);
- (*outputFunc)(outputStream, "currentdict end\n", 16);
-
- // start the binary section
- (*outputFunc)(outputStream, "currentfile eexec\n", 18);
- r1 = 55665;
- line = 0;
-
- // start the private dictionary
- eexecWrite("\x83\xca\x73\xd5");
- eexecWrite("dup /Private 32 dict dup begin\n");
- eexecWrite("/RD {string currentfile exch readstring pop} executeonly def\n");
- eexecWrite("/ND {noaccess def} executeonly def\n");
- eexecWrite("/NP {noaccess put} executeonly def\n");
- eexecWrite("/MinFeature {16 16} ND\n");
- eexecWrite(privateDicts[fd].dictData->getCString());
- defaultWidthX = privateDicts[fd].defaultWidthX;
- defaultWidthXFP = privateDicts[fd].defaultWidthXFP;
- nominalWidthX = privateDicts[fd].nominalWidthX;
- nominalWidthXFP = privateDicts[fd].nominalWidthXFP;
-
- // start the CharStrings
- sprintf(eBuf, "2 index /CharStrings 256 dict dup begin\n");
- eexecWrite(eBuf);
-
- // write the .notdef CharString
- idxPtr0 = getIndexValPtr(charStringsIdxPtr, 0);
- idxPtr1 = getIndexValPtr(charStringsIdxPtr, 1);
- n = idxPtr1 - idxPtr0;
- eexecCvtGlyph(".notdef", idxPtr0, n);
-
- // write the CharStrings
- for (j = 0; j < 256 && i+j < nCIDs; ++j) {
- if (cidMap[i+j] >= 0) {
- idxPtr0 = getIndexValPtr(charStringsIdxPtr, cidMap[i+j]);
- idxPtr1 = getIndexValPtr(charStringsIdxPtr, cidMap[i+j]+1);
- n = idxPtr1 - idxPtr0;
- sprintf(buf, "c%02x", j);
- eexecCvtGlyph(buf, idxPtr0, n);
- }
- }
- eexecWrite("end\n");
- eexecWrite("end\n");
- eexecWrite("readonly put\n");
- eexecWrite("noaccess put\n");
- eexecWrite("dup /FontName get exch definefont pop\n");
- eexecWrite("mark currentfile closefile\n");
-
- // trailer
- if (line > 0) {
- (*outputFunc)(outputStream, "\n", 1);
- }
- for (j = 0; j < 8; ++j) {
- (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65);
- }
- (*outputFunc)(outputStream, "cleartomark\n", 12);
- }
-
- // write the Type 0 parent font
- (*outputFunc)(outputStream, "16 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, psName, strlen(psName));
- (*outputFunc)(outputStream, " def\n", 5);
- (*outputFunc)(outputStream, "/FontType 0 def\n", 16);
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- (*outputFunc)(outputStream, "/FMapType 2 def\n", 16);
- (*outputFunc)(outputStream, "/Encoding [\n", 12);
- for (i = 0; i < nCIDs; i += 256) {
- sprintf(buf, "%d\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "] def\n", 6);
- (*outputFunc)(outputStream, "/FDepVector [\n", 14);
- for (i = 0; i < nCIDs; i += 256) {
- (*outputFunc)(outputStream, "/", 1);
- (*outputFunc)(outputStream, psName, strlen(psName));
- sprintf(buf, "_%02x findfont\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "] def\n", 6);
- (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
-
- // clean up
- for (i = 0; i < nFDs; ++i) {
- delete privateDicts[i].dictData;
- }
- gfree(privateDicts);
- gfree(cidMap);
- gfree(charset);
- gfree(fdSelect);
-}
-
-void Type1CFontFile::readTopDict(Type1CTopDict *dict) {
- Guchar *idxPtr0, *idxPtr1, *ptr;
- double x;
- GBool isFP;
- int key;
- int i;
-
- idxPtr0 = getIndexValPtr(topDictIdxPtr, 0);
- idxPtr1 = getIndexValPtr(topDictIdxPtr, 1);
- dict->version = 0;
- dict->notice = 0;
- dict->copyright = 0;
- dict->fullName = 0;
- dict->familyName = 0;
- dict->weight = 0;
- dict->isFixedPitch = 0;
- dict->italicAngle = 0;
- dict->underlinePosition = -100;
- dict->underlineThickness = 50;
- dict->paintType = 0;
- dict->charstringType = 2;
- dict->fontMatrix[0] = 0.001;
- dict->fontMatrix[1] = 0;
- dict->fontMatrix[2] = 0;
- dict->fontMatrix[3] = 0.001;
- dict->fontMatrix[4] = 0;
- dict->fontMatrix[5] = 0;
- dict->uniqueID = 0;
- dict->fontBBox[0] = 0;
- dict->fontBBox[1] = 0;
- dict->fontBBox[2] = 0;
- dict->fontBBox[3] = 0;
- dict->strokeWidth = 0;
- dict->charset = 0;
- dict->encoding = 0;
- dict->charStrings = 0;
- dict->privateSize = 0;
- dict->privateOffset = 0;
- dict->registry = 0;
- dict->ordering = 0;
- dict->supplement = 0;
- dict->fdArrayOffset = 0;
- dict->fdSelectOffset = 0;
- i = 0;
- ptr = idxPtr0;
- while (ptr < idxPtr1) {
- if (*ptr <= 27 || *ptr == 31) {
- key = *ptr++;
- if (key == 0x0c) {
- key = (key << 8) | *ptr++;
- }
- switch (key) {
- case 0x0000: dict->version = (int)op[0]; break;
- case 0x0001: dict->notice = (int)op[0]; break;
- case 0x0c00: dict->copyright = (int)op[0]; break;
- case 0x0002: dict->fullName = (int)op[0]; break;
- case 0x0003: dict->familyName = (int)op[0]; break;
- case 0x0004: dict->weight = (int)op[0]; break;
- case 0x0c01: dict->isFixedPitch = (int)op[0]; break;
- case 0x0c02: dict->italicAngle = op[0]; break;
- case 0x0c03: dict->underlinePosition = op[0]; break;
- case 0x0c04: dict->underlineThickness = op[0]; break;
- case 0x0c05: dict->paintType = (int)op[0]; break;
- case 0x0c06: dict->charstringType = (int)op[0]; break;
- case 0x0c07: dict->fontMatrix[0] = op[0];
- dict->fontMatrix[1] = op[1];
- dict->fontMatrix[2] = op[2];
- dict->fontMatrix[3] = op[3];
- dict->fontMatrix[4] = op[4];
- dict->fontMatrix[5] = op[5]; break;
- case 0x000d: dict->uniqueID = (int)op[0]; break;
- case 0x0005: dict->fontBBox[0] = op[0];
- dict->fontBBox[1] = op[1];
- dict->fontBBox[2] = op[2];
- dict->fontBBox[3] = op[3]; break;
- case 0x0c08: dict->strokeWidth = op[0]; break;
- case 0x000f: dict->charset = (int)op[0]; break;
- case 0x0010: dict->encoding = (int)op[0]; break;
- case 0x0011: dict->charStrings = (int)op[0]; break;
- case 0x0012: dict->privateSize = (int)op[0];
- dict->privateOffset = (int)op[1]; break;
- case 0x0c1e: dict->registry = (int)op[0];
- dict->ordering = (int)op[1];
- dict->supplement = (int)op[2]; break;
- case 0x0c24: dict->fdArrayOffset = (int)op[0]; break;
- case 0x0c25: dict->fdSelectOffset = (int)op[0]; break;
- }
- i = 0;
- } else {
- x = getNum(&ptr, &isFP);
- if (i < 48) {
- op[i] = x;
- fp[i++] = isFP;
- }
- }
- }
-}
-
-void Type1CFontFile::readPrivateDict(Type1CPrivateDict *privateDict,
- int offset, int size) {
- Guchar *idxPtr0, *idxPtr1, *ptr;
- char eBuf[256];
- int key;
- double x;
- GBool isFP;
- int i;
-
- privateDict->dictData = new GString();
- privateDict->subrsOffset = 0;
- privateDict->defaultWidthX = 0;
- privateDict->defaultWidthXFP = gFalse;
- privateDict->nominalWidthX = 0;
- privateDict->nominalWidthXFP = gFalse;
- idxPtr0 = (Guchar *)file + offset;
- idxPtr1 = idxPtr0 + size;
- ptr = idxPtr0;
- i = 0;
- while (ptr < idxPtr1) {
- if (*ptr <= 27 || *ptr == 31) {
- key = *ptr++;
- if (key == 0x0c) {
- key = (key << 8) | *ptr++;
- }
- switch (key) {
- case 0x0006:
- getDeltaInt(eBuf, "BlueValues", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0007:
- getDeltaInt(eBuf, "OtherBlues", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0008:
- getDeltaInt(eBuf, "FamilyBlues", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0009:
- getDeltaInt(eBuf, "FamilyOtherBlues", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c09:
- sprintf(eBuf, "/BlueScale %g def\n", op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0a:
- sprintf(eBuf, "/BlueShift %d def\n", (int)op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0b:
- sprintf(eBuf, "/BlueFuzz %d def\n", (int)op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x000a:
- sprintf(eBuf, "/StdHW [%g] def\n", op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x000b:
- sprintf(eBuf, "/StdVW [%g] def\n", op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0c:
- getDeltaReal(eBuf, "StemSnapH", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0d:
- getDeltaReal(eBuf, "StemSnapV", op, i);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0e:
- sprintf(eBuf, "/ForceBold %s def\n", op[0] ? "true" : "false");
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c0f:
- sprintf(eBuf, "/ForceBoldThreshold %g def\n", op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c11:
- sprintf(eBuf, "/LanguageGroup %d def\n", (int)op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c12:
- sprintf(eBuf, "/ExpansionFactor %g def\n", op[0]);
- privateDict->dictData->append(eBuf);
- break;
- case 0x0c13:
- error(-1, "Got Type 1C InitialRandomSeed");
- break;
- case 0x0013:
- privateDict->subrsOffset = (int)op[0];
- break;
- case 0x0014:
- privateDict->defaultWidthX = op[0];
- privateDict->defaultWidthXFP = fp[0];
- break;
- case 0x0015:
- privateDict->nominalWidthX = op[0];
- privateDict->nominalWidthXFP = fp[0];
- break;
- default:
- error(-1, "Unknown Type 1C private dict entry %04x", key);
- break;
- }
- i = 0;
- } else {
- x = getNum(&ptr, &isFP);
- if (i < 48) {
- op[i] = x;
- fp[i++] = isFP;
- }
- }
- }
-}
-
-Gushort *Type1CFontFile::readCharset(int charset, int nGlyphs) {
- Gushort *glyphNames;
- Guchar *ptr;
- int charsetFormat, c;
- int nLeft, i, j;
-
- if (charset == 0) {
- glyphNames = type1CISOAdobeCharset;
- } else if (charset == 1) {
- glyphNames = type1CExpertCharset;
- } else if (charset == 2) {
- glyphNames = type1CExpertSubsetCharset;
- } else {
- glyphNames = (Gushort *)gmalloc(nGlyphs * sizeof(Gushort));
- glyphNames[0] = 0;
- ptr = (Guchar *)file + charset;
- charsetFormat = *ptr++;
- if (charsetFormat == 0) {
- for (i = 1; i < nGlyphs; ++i) {
- glyphNames[i] = getWord(ptr, 2);
- ptr += 2;
- }
- } else if (charsetFormat == 1) {
- i = 1;
- while (i < nGlyphs) {
- c = getWord(ptr, 2);
- ptr += 2;
- nLeft = *ptr++;
- for (j = 0; j <= nLeft && i < nGlyphs; ++j) {
- glyphNames[i++] = c++;
- }
- }
- } else if (charsetFormat == 2) {
- i = 1;
- while (i < nGlyphs) {
- c = getWord(ptr, 2);
- ptr += 2;
- nLeft = getWord(ptr, 2);
- ptr += 2;
- for (j = 0; j <= nLeft && i < nGlyphs; ++j) {
- glyphNames[i++] = c++;
- }
- }
- }
- }
- return glyphNames;
-}
-
-void Type1CFontFile::eexecWrite(const char *s) {
- const Guchar *p;
- Guchar x;
-
- for (p = (const Guchar *)s; *p; ++p) {
- x = *p ^ (r1 >> 8);
- r1 = (x + r1) * 52845 + 22719;
- (*outputFunc)(outputStream, &hexChars[x >> 4], 1);
- (*outputFunc)(outputStream, &hexChars[x & 0x0f], 1);
- line += 2;
- if (line == 64) {
- (*outputFunc)(outputStream, "\n", 1);
- line = 0;
- }
- }
-}
-
-void Type1CFontFile::eexecCvtGlyph(const char *glyphName, const Guchar *s, int n) {
- char eBuf[256];
-
- cvtGlyph(s, n);
- sprintf(eBuf, "/%s %d RD ", glyphName, charBuf->getLength());
- eexecWrite(eBuf);
- eexecWriteCharstring((Guchar *)charBuf->getCString(), charBuf->getLength());
- eexecWrite(" ND\n");
- delete charBuf;
-}
-
-void Type1CFontFile::cvtGlyph(const Guchar *s, int n) {
- int nHints;
- int x;
- GBool first = gTrue;
- double d, dx, dy;
- GBool dFP;
- Gushort r2;
- Guchar byte;
- int i, k;
-
- charBuf = new GString();
- charBuf->append((char)73);
- charBuf->append((char)58);
- charBuf->append((char)147);
- charBuf->append((char)134);
-
- i = 0;
- nOps = 0;
- nHints = 0;
- while (i < n) {
- if (s[i] == 12) {
- switch (s[i+1]) {
- case 0: // dotsection (should be Type 1 only?)
- // ignored
- break;
- case 34: // hflex
- if (nOps != 7) {
- error(-1, "Wrong number of args (%d) to Type 2 hflex", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(0, gFalse);
- eexecDumpOp1(8);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[5], fp[5]);
- eexecDumpNum(-op[2], fp[2]);
- eexecDumpNum(op[6], fp[6]);
- eexecDumpNum(0, gFalse);
- eexecDumpOp1(8);
- break;
- case 35: // flex
- if (nOps != 13) {
- error(-1, "Wrong number of args (%d) to Type 2 flex", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpNum(op[5], fp[5]);
- eexecDumpOp1(8);
- eexecDumpNum(op[6], fp[6]);
- eexecDumpNum(op[7], fp[7]);
- eexecDumpNum(op[8], fp[8]);
- eexecDumpNum(op[9], fp[9]);
- eexecDumpNum(op[10], fp[10]);
- eexecDumpNum(op[11], fp[11]);
- eexecDumpOp1(8);
- break;
- case 36: // hflex1
- if (nOps != 9) {
- error(-1, "Wrong number of args (%d) to Type 2 hflex1", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpNum(0, gFalse);
- eexecDumpOp1(8);
- eexecDumpNum(op[5], fp[5]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[6], fp[6]);
- eexecDumpNum(op[7], fp[7]);
- eexecDumpNum(op[8], fp[8]);
- eexecDumpNum(-(op[1] + op[3] + op[7]), fp[1] | fp[3] | fp[7]);
- eexecDumpOp1(8);
- break;
- case 37: // flex1
- if (nOps != 11) {
- error(-1, "Wrong number of args (%d) to Type 2 flex1", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpNum(op[5], fp[5]);
- eexecDumpOp1(8);
- eexecDumpNum(op[6], fp[6]);
- eexecDumpNum(op[7], fp[7]);
- eexecDumpNum(op[8], fp[8]);
- eexecDumpNum(op[9], fp[9]);
- dx = op[0] + op[2] + op[4] + op[6] + op[8];
- dy = op[1] + op[3] + op[5] + op[7] + op[9];
- if (fabs(dx) > fabs(dy)) {
- eexecDumpNum(op[10], fp[10]);
- eexecDumpNum(-dy, fp[1] | fp[3] | fp[5] | fp[7] | fp[9]);
- } else {
- eexecDumpNum(-dx, fp[0] | fp[2] | fp[4] | fp[6] | fp[8]);
- eexecDumpNum(op[10], fp[10]);
- }
- eexecDumpOp1(8);
- break;
- case 3: // and
- case 4: // or
- case 5: // not
- case 8: // store
- case 9: // abs
- case 10: // add
- case 11: // sub
- case 12: // div
- case 13: // load
- case 14: // neg
- case 15: // eq
- case 18: // drop
- case 20: // put
- case 21: // get
- case 22: // ifelse
- case 23: // random
- case 24: // mul
- case 26: // sqrt
- case 27: // dup
- case 28: // exch
- case 29: // index
- case 30: // roll
- error(-1, "Unimplemented Type 2 charstring op: 12.%d", s[i+1]);
- break;
- default:
- error(-1, "Illegal Type 2 charstring op: 12.%d", s[i+1]);
- break;
- }
- i += 2;
- nOps = 0;
- } else if (s[i] == 19) { // hintmask
- // ignored
- if (first) {
- cvtGlyphWidth(nOps == 1);
- first = gFalse;
- }
- if (nOps > 0) {
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 hintmask/vstemhm",
- nOps);
- }
- nHints += nOps / 2;
- }
- i += 1 + ((nHints + 7) >> 3);
- nOps = 0;
- } else if (s[i] == 20) { // cntrmask
- // ignored
- if (first) {
- cvtGlyphWidth(nOps == 1);
- first = gFalse;
- }
- if (nOps > 0) {
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 cntrmask/vstemhm",
- nOps);
- }
- nHints += nOps / 2;
- }
- i += 1 + ((nHints + 7) >> 3);
- nOps = 0;
- } else if (s[i] == 28) {
- x = (s[i+1] << 8) + s[i+2];
- if (x & 0x8000) {
- x |= -1 << 15;
- }
- if (nOps < 48) {
- fp[nOps] = gFalse;
- op[nOps++] = x;
- }
- i += 3;
- } else if (s[i] <= 31) {
- switch (s[i]) {
- case 4: // vmoveto
- if (first) {
- cvtGlyphWidth(nOps == 2);
- first = gFalse;
- }
- if (nOps != 1) {
- error(-1, "Wrong number of args (%d) to Type 2 vmoveto", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpOp1(4);
- break;
- case 5: // rlineto
- if (nOps < 2 || nOps % 2 != 0) {
- error(-1, "Wrong number of args (%d) to Type 2 rlineto", nOps);
- }
- for (k = 0; k < nOps; k += 2) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpOp1(5);
- }
- break;
- case 6: // hlineto
- if (nOps < 1) {
- error(-1, "Wrong number of args (%d) to Type 2 hlineto", nOps);
- }
- for (k = 0; k < nOps; ++k) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpOp1((k & 1) ? 7 : 6);
- }
- break;
- case 7: // vlineto
- if (nOps < 1) {
- error(-1, "Wrong number of args (%d) to Type 2 vlineto", nOps);
- }
- for (k = 0; k < nOps; ++k) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpOp1((k & 1) ? 6 : 7);
- }
- break;
- case 8: // rrcurveto
- if (nOps < 6 || nOps % 6 != 0) {
- error(-1, "Wrong number of args (%d) to Type 2 rrcurveto", nOps);
- }
- for (k = 0; k < nOps; k += 6) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(op[k+4], fp[k+4]);
- eexecDumpNum(op[k+5], fp[k+5]);
- eexecDumpOp1(8);
- }
- break;
- case 14: // endchar / seac
- if (first) {
- cvtGlyphWidth(nOps == 1 || nOps == 5);
- first = gFalse;
- }
- if (nOps == 4) {
- eexecDumpNum(0, 0);
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpOp2(6);
- } else if (nOps == 0) {
- eexecDumpOp1(14);
- } else {
- error(-1, "Wrong number of args (%d) to Type 2 endchar", nOps);
- }
- break;
- case 21: // rmoveto
- if (first) {
- cvtGlyphWidth(nOps == 3);
- first = gFalse;
- }
- if (nOps != 2) {
- error(-1, "Wrong number of args (%d) to Type 2 rmoveto", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpOp1(21);
- break;
- case 22: // hmoveto
- if (first) {
- cvtGlyphWidth(nOps == 2);
- first = gFalse;
- }
- if (nOps != 1) {
- error(-1, "Wrong number of args (%d) to Type 2 hmoveto", nOps);
- }
- eexecDumpNum(op[0], fp[0]);
- eexecDumpOp1(22);
- break;
- case 24: // rcurveline
- if (nOps < 8 || (nOps - 2) % 6 != 0) {
- error(-1, "Wrong number of args (%d) to Type 2 rcurveline", nOps);
- }
- for (k = 0; k < nOps - 2; k += 6) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(op[k+4], fp[k+4]);
- eexecDumpNum(op[k+5], fp[k+5]);
- eexecDumpOp1(8);
- }
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k]);
- eexecDumpOp1(5);
- break;
- case 25: // rlinecurve
- if (nOps < 8 || (nOps - 6) % 2 != 0) {
- error(-1, "Wrong number of args (%d) to Type 2 rlinecurve", nOps);
- }
- for (k = 0; k < nOps - 6; k += 2) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k]);
- eexecDumpOp1(5);
- }
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(op[k+4], fp[k+4]);
- eexecDumpNum(op[k+5], fp[k+5]);
- eexecDumpOp1(8);
- break;
- case 26: // vvcurveto
- if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
- error(-1, "Wrong number of args (%d) to Type 2 vvcurveto", nOps);
- }
- if (nOps % 2 == 1) {
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpOp1(8);
- k = 5;
- } else {
- k = 0;
- }
- for (; k < nOps; k += 4) {
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpOp1(8);
- }
- break;
- case 27: // hhcurveto
- if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
- error(-1, "Wrong number of args (%d) to Type 2 hhcurveto", nOps);
- }
- if (nOps % 2 == 1) {
- eexecDumpNum(op[1], fp[1]);
- eexecDumpNum(op[0], fp[0]);
- eexecDumpNum(op[2], fp[2]);
- eexecDumpNum(op[3], fp[3]);
- eexecDumpNum(op[4], fp[4]);
- eexecDumpNum(0, gFalse);
- eexecDumpOp1(8);
- k = 5;
- } else {
- k = 0;
- }
- for (; k < nOps; k += 4) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(0, gFalse);
- eexecDumpOp1(8);
- }
- break;
- case 30: // vhcurveto
- if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
- error(-1, "Wrong number of args (%d) to Type 2 vhcurveto", nOps);
- }
- for (k = 0; k < nOps && k != nOps-5; k += 4) {
- if (k % 8 == 0) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpOp1(30);
- } else {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpOp1(31);
- }
- }
- if (k == nOps-5) {
- if (k % 8 == 0) {
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(op[k+4], fp[k+4]);
- } else {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+4], fp[k+4]);
- eexecDumpNum(op[k+3], fp[k+3]);
- }
- eexecDumpOp1(8);
- }
- break;
- case 31: // hvcurveto
- if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
- error(-1, "Wrong number of args (%d) to Type 2 hvcurveto", nOps);
- }
- for (k = 0; k < nOps && k != nOps-5; k += 4) {
- if (k % 8 == 0) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpOp1(31);
- } else {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpOp1(30);
- }
- }
- if (k == nOps-5) {
- if (k % 8 == 0) {
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+4], fp[k+4]);
- eexecDumpNum(op[k+3], fp[k+3]);
- } else {
- eexecDumpNum(0, gFalse);
- eexecDumpNum(op[k], fp[k]);
- eexecDumpNum(op[k+1], fp[k+1]);
- eexecDumpNum(op[k+2], fp[k+2]);
- eexecDumpNum(op[k+3], fp[k+3]);
- eexecDumpNum(op[k+4], fp[k+4]);
- }
- eexecDumpOp1(8);
- }
- break;
- case 1: // hstem
- if (first) {
- cvtGlyphWidth(nOps & 1);
- first = gFalse;
- }
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 hstem", nOps);
- }
- d = 0;
- dFP = gFalse;
- for (k = 0; k < nOps; k += 2) {
- if (op[k+1] < 0) {
- d += op[k] + op[k+1];
- dFP |= fp[k] | fp[k+1];
- eexecDumpNum(d, dFP);
- eexecDumpNum(-op[k+1], fp[k+1]);
- } else {
- d += op[k];
- dFP |= fp[k];
- eexecDumpNum(d, dFP);
- eexecDumpNum(op[k+1], fp[k+1]);
- d += op[k+1];
- dFP |= fp[k+1];
- }
- eexecDumpOp1(1);
- }
- nHints += nOps / 2;
- break;
- case 3: // vstem
- if (first) {
- cvtGlyphWidth(nOps & 1);
- first = gFalse;
- }
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 vstem", nOps);
- }
- d = 0;
- dFP = gFalse;
- for (k = 0; k < nOps; k += 2) {
- if (op[k+1] < 0) {
- d += op[k] + op[k+1];
- dFP |= fp[k] | fp[k+1];
- eexecDumpNum(d, dFP);
- eexecDumpNum(-op[k+1], fp[k+1]);
- } else {
- d += op[k];
- dFP |= fp[k];
- eexecDumpNum(d, dFP);
- eexecDumpNum(op[k+1], fp[k+1]);
- d += op[k+1];
- dFP |= fp[k+1];
- }
- eexecDumpOp1(3);
- }
- nHints += nOps / 2;
- break;
- case 18: // hstemhm
- // ignored
- if (first) {
- cvtGlyphWidth(nOps & 1);
- first = gFalse;
- }
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 hstemhm", nOps);
- }
- nHints += nOps / 2;
- break;
- case 23: // vstemhm
- // ignored
- if (first) {
- cvtGlyphWidth(nOps & 1);
- first = gFalse;
- }
- if (nOps & 1) {
- error(-1, "Wrong number of args (%d) to Type 2 vstemhm", nOps);
- }
- nHints += nOps / 2;
- break;
- case 10: // callsubr
- case 11: // return
- case 16: // blend
- case 29: // callgsubr
- error(-1, "Unimplemented Type 2 charstring op: %d", s[i]);
- break;
- default:
- error(-1, "Illegal Type 2 charstring op: %d", s[i]);
- break;
- }
- ++i;
- nOps = 0;
- } else if (s[i] <= 246) {
- if (nOps < 48) {
- fp[nOps] = gFalse;
- op[nOps++] = (int)s[i] - 139;
- }
- ++i;
- } else if (s[i] <= 250) {
- if (nOps < 48) {
- fp[nOps] = gFalse;
- op[nOps++] = (((int)s[i] - 247) << 8) + (int)s[i+1] + 108;
- }
- i += 2;
- } else if (s[i] <= 254) {
- if (nOps < 48) {
- fp[nOps] = gFalse;
- op[nOps++] = -(((int)s[i] - 251) << 8) - (int)s[i+1] - 108;
- }
- i += 2;
- } else {
- x = (s[i+1] << 24) | (s[i+2] << 16) | (s[i+3] << 8) | s[i+4];
- if (x & 0x80000000)
- x |= -1 << 31;
- if (nOps < 48) {
- fp[nOps] = gTrue;
- op[nOps++] = (double)x / 65536.0;
- }
- i += 5;
- }
- }
-
- // charstring encryption
- r2 = 4330;
- for (i = 0; i < charBuf->getLength(); ++i) {
- byte = charBuf->getChar(i) ^ (r2 >> 8);
- charBuf->setChar(i, byte);
- r2 = (byte + r2) * 52845 + 22719;
- }
-}
-
-void Type1CFontFile::cvtGlyphWidth(GBool useOp) {
- double w;
- GBool wFP;
- int i;
-
- if (useOp) {
- w = nominalWidthX + op[0];
- wFP = nominalWidthXFP | fp[0];
- for (i = 1; i < nOps; ++i) {
- op[i-1] = op[i];
- fp[i-1] = fp[i];
- }
- --nOps;
- } else {
- w = defaultWidthX;
- wFP = defaultWidthXFP;
- }
- eexecDumpNum(0, gFalse);
- eexecDumpNum(w, wFP);
- eexecDumpOp1(13);
-}
-
-void Type1CFontFile::eexecDumpNum(double x, GBool fpA) {
- Guchar buf[12];
- int y, n;
-
- n = 0;
- if (fpA) {
- if (x >= -32768 && x < 32768) {
- y = (int)(x * 256.0);
- buf[0] = 255;
- buf[1] = (Guchar)(y >> 24);
- buf[2] = (Guchar)(y >> 16);
- buf[3] = (Guchar)(y >> 8);
- buf[4] = (Guchar)y;
- buf[5] = 255;
- buf[6] = 0;
- buf[7] = 0;
- buf[8] = 1;
- buf[9] = 0;
- buf[10] = 12;
- buf[11] = 12;
- n = 12;
- } else {
- error(-1, "Type 2 fixed point constant out of range");
- }
- } else {
- y = (int)x;
- if (y >= -107 && y <= 107) {
- buf[0] = (Guchar)(y + 139);
- n = 1;
- } else if (y > 107 && y <= 1131) {
- y -= 108;
- buf[0] = (Guchar)((y >> 8) + 247);
- buf[1] = (Guchar)(y & 0xff);
- n = 2;
- } else if (y < -107 && y >= -1131) {
- y = -y - 108;
- buf[0] = (Guchar)((y >> 8) + 251);
- buf[1] = (Guchar)(y & 0xff);
- n = 2;
- } else {
- buf[0] = 255;
- buf[1] = (Guchar)(y >> 24);
- buf[2] = (Guchar)(y >> 16);
- buf[3] = (Guchar)(y >> 8);
- buf[4] = (Guchar)y;
- n = 5;
- }
- }
- charBuf->append((char *)buf, n);
-}
-
-void Type1CFontFile::eexecDumpOp1(int opA) {
- charBuf->append((char)opA);
-}
-
-void Type1CFontFile::eexecDumpOp2(int opA) {
- charBuf->append((char)12);
- charBuf->append((char)opA);
-}
-
-void Type1CFontFile::eexecWriteCharstring(const Guchar *s, int n) {
- Guchar x;
- int i;
-
- // eexec encryption
- for (i = 0; i < n; ++i) {
- x = s[i] ^ (r1 >> 8);
- r1 = (x + r1) * 52845 + 22719;
- (*outputFunc)(outputStream, &hexChars[x >> 4], 1);
- (*outputFunc)(outputStream, &hexChars[x & 0x0f], 1);
- line += 2;
- if (line == 64) {
- (*outputFunc)(outputStream, "\n", 1);
- line = 0;
- }
- }
-}
-
-void Type1CFontFile::getDeltaInt(char *buf, const char *key, const double *opA,
- int n) {
- int x, i;
-
- sprintf(buf, "/%s [", key);
- buf += strlen(buf);
- x = 0;
- for (i = 0; i < n; ++i) {
- x += (int)opA[i];
- sprintf(buf, "%s%d", i > 0 ? " " : "", x);
- buf += strlen(buf);
- }
- sprintf(buf, "] def\n");
-}
-
-void Type1CFontFile::getDeltaReal(char *buf, const char *key, const double *opA,
- int n) {
- double x;
- int i;
-
- sprintf(buf, "/%s [", key);
- buf += strlen(buf);
- x = 0;
- for (i = 0; i < n; ++i) {
- x += opA[i];
- sprintf(buf, "%s%g", i > 0 ? " " : "", x);
- buf += strlen(buf);
- }
- sprintf(buf, "] def\n");
-}
-
-int Type1CFontFile::getIndexLen(Guchar *indexPtr) {
- return (int)getWord(indexPtr, 2);
-}
-
-Guchar *Type1CFontFile::getIndexValPtr(Guchar *indexPtr, int i) {
- int n, offSize;
- Guchar *idxStartPtr;
-
- n = (int)getWord(indexPtr, 2);
- offSize = indexPtr[2];
- idxStartPtr = indexPtr + 3 + (n + 1) * offSize - 1;
- return idxStartPtr + getWord(indexPtr + 3 + i * offSize, offSize);
-}
-
-Guchar *Type1CFontFile::getIndexEnd(Guchar *indexPtr) {
- int n, offSize;
- Guchar *idxStartPtr;
-
- n = (int)getWord(indexPtr, 2);
- offSize = indexPtr[2];
- idxStartPtr = indexPtr + 3 + (n + 1) * offSize - 1;
- return idxStartPtr + getWord(indexPtr + 3 + n * offSize, offSize);
-}
-
-Guint Type1CFontFile::getWord(Guchar *ptr, int size) {
- Guint x;
- int i;
-
- x = 0;
- for (i = 0; i < size; ++i) {
- x = (x << 8) + *ptr++;
- }
- return x;
-}
-
-double Type1CFontFile::getNum(Guchar **ptr, GBool *isFP) {
- static char nybChars[16] = "0123456789.ee -";
- int b0, b, nyb0, nyb1;
- double x;
- char buf[65];
- int i;
-
- x = 0;
- *isFP = gFalse;
- b0 = (*ptr)[0];
- if (b0 < 28) {
- x = 0;
- } else if (b0 == 28) {
- x = ((*ptr)[1] << 8) + (*ptr)[2];
- *ptr += 3;
- } else if (b0 == 29) {
- x = ((*ptr)[1] << 24) + ((*ptr)[2] << 16) + ((*ptr)[3] << 8) + (*ptr)[4];
- *ptr += 5;
- } else if (b0 == 30) {
- *ptr += 1;
- i = 0;
- do {
- b = *(*ptr)++;
- nyb0 = b >> 4;
- nyb1 = b & 0x0f;
- if (nyb0 == 0xf) {
- break;
- }
- buf[i++] = nybChars[nyb0];
- if (i == 64) {
- break;
- }
- if (nyb0 == 0xc) {
- buf[i++] = '-';
- }
- if (i == 64) {
- break;
- }
- if (nyb1 == 0xf) {
- break;
- }
- buf[i++] = nybChars[nyb1];
- if (i == 64) {
- break;
- }
- if (nyb1 == 0xc) {
- buf[i++] = '-';
- }
- } while (i < 64);
- buf[i] = '\0';
- x = atof(buf);
- *isFP = gTrue;
- } else if (b0 == 31) {
- x = 0;
- } else if (b0 < 247) {
- x = b0 - 139;
- *ptr += 1;
- } else if (b0 < 251) {
- x = ((b0 - 247) << 8) + (*ptr)[1] + 108;
- *ptr += 2;
- } else {
- x = -((b0 - 251) << 8) - (*ptr)[1] - 108;
- *ptr += 2;
- }
- return x;
-}
-
-char *Type1CFontFile::getString(int sid, char *buf) {
- Guchar *idxPtr0, *idxPtr1;
- int n;
-
- if (sid < 391) {
- strcpy(buf, type1CStdStrings[sid]);
- } else {
- sid -= 391;
- idxPtr0 = getIndexValPtr(stringIdxPtr, sid);
- idxPtr1 = getIndexValPtr(stringIdxPtr, sid + 1);
- if ((n = idxPtr1 - idxPtr0) > 255) {
- n = 255;
- }
- strncpy(buf, (char *)idxPtr0, n);
- buf[n] = '\0';
- }
- return buf;
-}
-
-//------------------------------------------------------------------------
-// TrueTypeFontFile
-//------------------------------------------------------------------------
-
-//
-// Terminology
-// -----------
-//
-// character code = number used as an element of a text string
-//
-// character name = glyph name = name for a particular glyph within a
-// font
-//
-// glyph index = position (within some internal table in the font)
-// where the instructions to draw a particular glyph are
-// stored
-//
-// Type 1 fonts
-// ------------
-//
-// Type 1 fonts contain:
-//
-// Encoding: array of glyph names, maps char codes to glyph names
-//
-// Encoding[charCode] = charName
-//
-// CharStrings: dictionary of instructions, keyed by character names,
-// maps character name to glyph data
-//
-// CharStrings[charName] = glyphData
-//
-// TrueType fonts
-// --------------
-//
-// TrueType fonts contain:
-//
-// 'cmap' table: mapping from character code to glyph index; there may
-// be multiple cmaps in a TrueType font
-//
-// cmap[charCode] = glyphIdx
-//
-// 'post' table: mapping from glyph index to glyph name
-//
-// post[glyphIdx] = glyphName
-//
-// Type 42 fonts
-// -------------
-//
-// Type 42 fonts contain:
-//
-// Encoding: array of glyph names, maps char codes to glyph names
-//
-// Encoding[charCode] = charName
-//
-// CharStrings: dictionary of glyph indexes, keyed by character names,
-// maps character name to glyph index
-//
-// CharStrings[charName] = glyphIdx
-//
-
-struct TTFontTableHdr {
- char tag[4];
- Guint checksum;
- Guint offset;
- Guint length;
-};
-
-struct T42Table {
- const char *tag; // 4-byte tag
- GBool required; // required by the TrueType spec?
-};
-
-// TrueType tables to be embedded in Type 42 fonts.
-// NB: the table names must be in alphabetical order here.
-#define nT42Tables 11
-static T42Table t42Tables[nT42Tables] = {
- { "cvt ", gTrue },
- { "fpgm", gTrue },
- { "glyf", gTrue },
- { "head", gTrue },
- { "hhea", gTrue },
- { "hmtx", gTrue },
- { "loca", gTrue },
- { "maxp", gTrue },
- { "prep", gTrue },
- { "vhea", gFalse },
- { "vmtx", gFalse }
-};
-#define t42HeadTable 3
-#define t42LocaTable 6
-#define t42GlyfTable 2
-
-// Glyph names in some arbitrary standard that Apple uses for their
-// TrueType fonts.
-static const char *macGlyphNames[258] = {
- ".notdef",
- "null",
- "CR",
- "space",
- "exclam",
- "quotedbl",
- "numbersign",
- "dollar",
- "percent",
- "ampersand",
- "quotesingle",
- "parenleft",
- "parenright",
- "asterisk",
- "plus",
- "comma",
- "hyphen",
- "period",
- "slash",
- "zero",
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "colon",
- "semicolon",
- "less",
- "equal",
- "greater",
- "question",
- "at",
- "A",
- "B",
- "C",
- "D",
- "E",
- "F",
- "G",
- "H",
- "I",
- "J",
- "K",
- "L",
- "M",
- "N",
- "O",
- "P",
- "Q",
- "R",
- "S",
- "T",
- "U",
- "V",
- "W",
- "X",
- "Y",
- "Z",
- "bracketleft",
- "backslash",
- "bracketright",
- "asciicircum",
- "underscore",
- "grave",
- "a",
- "b",
- "c",
- "d",
- "e",
- "f",
- "g",
- "h",
- "i",
- "j",
- "k",
- "l",
- "m",
- "n",
- "o",
- "p",
- "q",
- "r",
- "s",
- "t",
- "u",
- "v",
- "w",
- "x",
- "y",
- "z",
- "braceleft",
- "bar",
- "braceright",
- "asciitilde",
- "Adieresis",
- "Aring",
- "Ccedilla",
- "Eacute",
- "Ntilde",
- "Odieresis",
- "Udieresis",
- "aacute",
- "agrave",
- "acircumflex",
- "adieresis",
- "atilde",
- "aring",
- "ccedilla",
- "eacute",
- "egrave",
- "ecircumflex",
- "edieresis",
- "iacute",
- "igrave",
- "icircumflex",
- "idieresis",
- "ntilde",
- "oacute",
- "ograve",
- "ocircumflex",
- "odieresis",
- "otilde",
- "uacute",
- "ugrave",
- "ucircumflex",
- "udieresis",
- "dagger",
- "degree",
- "cent",
- "sterling",
- "section",
- "bullet",
- "paragraph",
- "germandbls",
- "registered",
- "copyright",
- "trademark",
- "acute",
- "dieresis",
- "notequal",
- "AE",
- "Oslash",
- "infinity",
- "plusminus",
- "lessequal",
- "greaterequal",
- "yen",
- "mu1",
- "partialdiff",
- "summation",
- "product",
- "pi",
- "integral",
- "ordfeminine",
- "ordmasculine",
- "Ohm",
- "ae",
- "oslash",
- "questiondown",
- "exclamdown",
- "logicalnot",
- "radical",
- "florin",
- "approxequal",
- "increment",
- "guillemotleft",
- "guillemotright",
- "ellipsis",
- "nbspace",
- "Agrave",
- "Atilde",
- "Otilde",
- "OE",
- "oe",
- "endash",
- "emdash",
- "quotedblleft",
- "quotedblright",
- "quoteleft",
- "quoteright",
- "divide",
- "lozenge",
- "ydieresis",
- "Ydieresis",
- "fraction",
- "currency",
- "guilsinglleft",
- "guilsinglright",
- "fi",
- "fl",
- "daggerdbl",
- "periodcentered",
- "quotesinglbase",
- "quotedblbase",
- "perthousand",
- "Acircumflex",
- "Ecircumflex",
- "Aacute",
- "Edieresis",
- "Egrave",
- "Iacute",
- "Icircumflex",
- "Idieresis",
- "Igrave",
- "Oacute",
- "Ocircumflex",
- "applelogo",
- "Ograve",
- "Uacute",
- "Ucircumflex",
- "Ugrave",
- "dotlessi",
- "circumflex",
- "tilde",
- "overscore",
- "breve",
- "dotaccent",
- "ring",
- "cedilla",
- "hungarumlaut",
- "ogonek",
- "caron",
- "Lslash",
- "lslash",
- "Scaron",
- "scaron",
- "Zcaron",
- "zcaron",
- "brokenbar",
- "Eth",
- "eth",
- "Yacute",
- "yacute",
- "Thorn",
- "thorn",
- "minus",
- "multiply",
- "onesuperior",
- "twosuperior",
- "threesuperior",
- "onehalf",
- "onequarter",
- "threequarters",
- "franc",
- "Gbreve",
- "gbreve",
- "Idot",
- "Scedilla",
- "scedilla",
- "Cacute",
- "cacute",
- "Ccaron",
- "ccaron",
- "dmacron"
-};
-
-enum T42FontIndexMode {
- t42FontModeUnicode,
- t42FontModeCharCode,
- t42FontModeCharCodeOffset,
- t42FontModeMacRoman
-};
-
-TrueTypeFontFile::TrueTypeFontFile(const char *fileA, int lenA) {
- int pos, i, idx, n, length;
- Guint size, startPos, endPos;
-
- file = fileA;
- len = lenA;
-
- encoding = NULL;
-
- // read table directory
- nTables = getUShort(4);
- tableHdrs = (TTFontTableHdr *)gmalloc(nTables * sizeof(TTFontTableHdr));
- pos = 12;
- for (i = 0; i < nTables; ++i) {
- tableHdrs[i].tag[0] = getByte(pos+0);
- tableHdrs[i].tag[1] = getByte(pos+1);
- tableHdrs[i].tag[2] = getByte(pos+2);
- tableHdrs[i].tag[3] = getByte(pos+3);
- tableHdrs[i].checksum = getULong(pos+4);
- tableHdrs[i].offset = getULong(pos+8);
- tableHdrs[i].length = getULong(pos+12);
- pos += 16;
- }
-
- // check for tables that are required by both the TrueType spec
- // and the Type 42 spec
- if (seekTable("head") < 0 ||
- seekTable("hhea") < 0 ||
- seekTable("loca") < 0 ||
- seekTable("maxp") < 0 ||
- seekTable("glyf") < 0 ||
- seekTable("hmtx") < 0) {
- error(-1, "TrueType font file is missing a required table");
- return;
- }
-
- // some embedded TrueType fonts have an incorrect (too small) cmap
- // table size
- idx = seekTableIdx("cmap");
- if (idx >= 0) {
- pos = tableHdrs[idx].offset;
- n = getUShort(pos + 2);
- size = (Guint)(4 + 8 * n);
- for (i = 0; i < n; ++i) {
- startPos = getULong(pos + 4 + 8*i + 4);
- length = getUShort(pos + startPos + 2);
- endPos = startPos + length;
- if (endPos > size) {
- size = endPos;
- }
- }
- if ((mungedCmapSize = size > tableHdrs[idx].length)) {
-#if 0 // don't bother printing this error message - it's too common
- error(-1, "Bad cmap table size in TrueType font");
-#endif
- tableHdrs[idx].length = size;
- }
- } else {
- mungedCmapSize = gFalse;
- }
-
- // read the 'head' table
- pos = seekTable("head");
- bbox[0] = getShort(pos + 36);
- bbox[1] = getShort(pos + 38);
- bbox[2] = getShort(pos + 40);
- bbox[3] = getShort(pos + 42);
- locaFmt = getShort(pos + 50);
-
- // read the 'maxp' table
- pos = seekTable("maxp");
- nGlyphs = getUShort(pos + 4);
-}
-
-TrueTypeFontFile::~TrueTypeFontFile() {
- int i;
-
- if (encoding) {
- for (i = 0; i < 256; ++i) {
- gfree(encoding[i]);
- }
- gfree(encoding);
- }
- gfree(tableHdrs);
-}
-
-const char *TrueTypeFontFile::getName() {
- return NULL;
-}
-
-char **TrueTypeFontFile::getEncoding() {
- int cmap[256];
- int nCmaps, cmapPlatform, cmapEncoding, cmapFmt;
- int cmapLen, cmapOffset, cmapFirst;
- int segCnt, segStart, segEnd, segDelta, segOffset;
- int pos, i, j, k;
- Guint fmt;
- GString *s;
- int stringIdx, stringPos, n;
-
- if (encoding) {
- return encoding;
- }
-
- //----- construct the (char code) -> (glyph idx) mapping
-
- // map everything to the missing glyph
- for (i = 0; i < 256; ++i) {
- cmap[i] = 0;
- }
-
- // look for the 'cmap' table
- if ((pos = seekTable("cmap")) >= 0) {
- nCmaps = getUShort(pos+2);
-
- // if the font has a Windows-symbol cmap, use it;
- // otherwise, use the first cmap in the table
- for (i = 0; i < nCmaps; ++i) {
- cmapPlatform = getUShort(pos + 4 + 8*i);
- cmapEncoding = getUShort(pos + 4 + 8*i + 2);
- if (cmapPlatform == 3 && cmapEncoding == 0) {
- break;
- }
- }
- if (i >= nCmaps) {
- i = 0;
- cmapPlatform = getUShort(pos + 4);
- cmapEncoding = getUShort(pos + 4 + 2);
- }
- pos += getULong(pos + 4 + 8*i + 4);
-
- // read the cmap
- cmapFmt = getUShort(pos);
- switch (cmapFmt) {
- case 0: // byte encoding table (Apple standard)
- cmapLen = getUShort(pos + 2);
- for (i = 0; i < cmapLen && i < 256; ++i) {
- cmap[i] = getByte(pos + 6 + i);
- }
- break;
- case 4: // segment mapping to delta values (Microsoft standard)
- if (cmapPlatform == 3 && cmapEncoding == 0) {
- // Windows-symbol uses char codes 0xf000 - 0xf0ff
- cmapOffset = 0xf000;
- } else {
- cmapOffset = 0;
- }
- segCnt = getUShort(pos + 6) / 2;
- for (i = 0; i < segCnt; ++i) {
- segEnd = getUShort(pos + 14 + 2*i);
- segStart = getUShort(pos + 16 + 2*segCnt + 2*i);
- segDelta = getUShort(pos + 16 + 4*segCnt + 2*i);
- segOffset = getUShort(pos + 16 + 6*segCnt + 2*i);
- if (segStart - cmapOffset <= 0xff &&
- segEnd - cmapOffset >= 0) {
- for (j = (segStart - cmapOffset >= 0) ? segStart : cmapOffset;
- j <= segEnd && j - cmapOffset <= 0xff;
- ++j) {
- if (segOffset == 0) {
- k = (j + segDelta) & 0xffff;
- } else {
- k = getUShort(pos + 16 + 6*segCnt + 2*i +
- segOffset + 2 * (j - segStart));
- if (k != 0) {
- k = (k + segDelta) & 0xffff;
- }
- }
- cmap[j - cmapOffset] = k;
- }
- }
- }
- break;
- case 6: // trimmed table mapping
- cmapFirst = getUShort(pos + 6);
- cmapLen = getUShort(pos + 8);
- for (i = cmapFirst; i < 256 && i < cmapFirst + cmapLen; ++i) {
- cmap[i] = getUShort(pos + 10 + 2*i);
- }
- break;
- default:
- error(-1, "Unimplemented cmap format (%d) in TrueType font file",
- cmapFmt);
- break;
- }
- }
-
- //----- construct the (glyph idx) -> (glyph name) mapping
- //----- and compute the (char code) -> (glyph name) mapping
-
- encoding = (char **)gmalloc(256 * sizeof(char *));
- for (i = 0; i < 256; ++i) {
- encoding[i] = NULL;
- }
-
- if ((pos = seekTable("post")) >= 0) {
- fmt = getULong(pos);
-
- // Apple font
- if (fmt == 0x00010000) {
- for (i = 0; i < 256; ++i) {
- j = (cmap[i] < 258) ? cmap[i] : 0;
- encoding[i] = copyString(macGlyphNames[j]);
- }
-
- // Microsoft font
- } else if (fmt == 0x00020000) {
- stringIdx = 0;
- stringPos = pos + 34 + 2*nGlyphs;
- for (i = 0; i < 256; ++i) {
- if (cmap[i] < nGlyphs) {
- j = getUShort(pos + 34 + 2 * cmap[i]);
- if (j < 258) {
- encoding[i] = copyString(macGlyphNames[j]);
- } else {
- j -= 258;
- if (j != stringIdx) {
- for (stringIdx = 0, stringPos = pos + 34 + 2*nGlyphs;
- stringIdx < j;
- ++stringIdx, stringPos += 1 + getByte(stringPos)) ;
- }
- n = getByte(stringPos);
- s = new GString(file + stringPos + 1, n);
- encoding[i] = copyString(s->getCString());
- delete s;
- ++stringIdx;
- stringPos += 1 + n;
- }
- } else {
- encoding[i] = copyString(macGlyphNames[0]);
- }
- }
-
- // Apple subset
- } else if (fmt == 0x000280000) {
- for (i = 0; i < 256; ++i) {
- if (cmap[i] < nGlyphs) {
- j = i + getChar(pos + 32 + cmap[i]);
- } else {
- j = 0;
- }
- encoding[i] = copyString(macGlyphNames[j]);
- }
-
- // Ugh, just assume the Apple glyph set
- } else {
- for (i = 0; i < 256; ++i) {
- j = (cmap[i] < 258) ? cmap[i] : 0;
- encoding[i] = copyString(macGlyphNames[j]);
- }
- }
-
- // no "post" table: assume the Apple glyph set
- } else {
- for (i = 0; i < 256; ++i) {
- j = (cmap[i] < 258) ? cmap[i] : 0;
- encoding[i] = copyString(macGlyphNames[j]);
- }
- }
-
- return encoding;
-}
-
-void TrueTypeFontFile::convertToType42(const char *name, const char **encodingA,
- CharCodeToUnicode *toUnicode,
- GBool pdfFontHasEncoding,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- char buf[512];
-
- // write the header
- sprintf(buf, "%%!PS-TrueTypeFont-%g\n", getFixed(0));
- (*outputFunc)(outputStream, buf, strlen(buf));
-
- // begin the font dictionary
- (*outputFunc)(outputStream, "10 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, name, strlen(name));
- (*outputFunc)(outputStream, " def\n", 5);
- (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
- bbox[0], bbox[1], bbox[2], bbox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
-
- // write the guts of the dictionary
- cvtEncoding(encodingA, pdfFontHasEncoding, outputFunc, outputStream);
- cvtCharStrings(encodingA, toUnicode, pdfFontHasEncoding,
- outputFunc, outputStream);
- cvtSfnts(outputFunc, outputStream, NULL);
-
- // end the dictionary and define the font
- (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
-}
-
-void TrueTypeFontFile::convertToCIDType2(const char *name, const Gushort *cidMap,
- int nCIDs,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- char buf[512];
- Gushort cid;
- int i, j, k;
-
- // write the header
- sprintf(buf, "%%!PS-TrueTypeFont-%g\n", getFixed(0));
- (*outputFunc)(outputStream, buf, strlen(buf));
-
- // begin the font dictionary
- (*outputFunc)(outputStream, "20 dict begin\n", 14);
- (*outputFunc)(outputStream, "/CIDFontName /", 14);
- (*outputFunc)(outputStream, name, strlen(name));
- (*outputFunc)(outputStream, " def\n", 5);
- (*outputFunc)(outputStream, "/CIDFontType 2 def\n", 19);
- (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
- (*outputFunc)(outputStream, "/CIDSystemInfo 3 dict dup begin\n", 32);
- (*outputFunc)(outputStream, " /Registry (Adobe) def\n", 24);
- (*outputFunc)(outputStream, " /Ordering (Identity) def\n", 27);
- (*outputFunc)(outputStream, " /Supplement 0 def\n", 20);
- (*outputFunc)(outputStream, " end def\n", 10);
- (*outputFunc)(outputStream, "/GDBytes 2 def\n", 15);
- if (cidMap) {
- sprintf(buf, "/CIDCount %d def\n", nCIDs);
- (*outputFunc)(outputStream, buf, strlen(buf));
- if (nCIDs > 32767) {
- (*outputFunc)(outputStream, "/CIDMap [", 9);
- for (i = 0; i < nCIDs; i += 32768 - 16) {
- (*outputFunc)(outputStream, "<\n", 2);
- for (j = 0; j < 32768 - 16 && i+j < nCIDs; j += 16) {
- (*outputFunc)(outputStream, " ", 2);
- for (k = 0; k < 16 && i+j+k < nCIDs; ++k) {
- cid = cidMap[i+j+k];
- sprintf(buf, "%02x%02x", (cid >> 8) & 0xff, cid & 0xff);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "\n", 1);
- }
- (*outputFunc)(outputStream, " >", 3);
- }
- (*outputFunc)(outputStream, "\n", 1);
- (*outputFunc)(outputStream, "] def\n", 6);
- } else {
- (*outputFunc)(outputStream, "/CIDMap <\n", 10);
- for (i = 0; i < nCIDs; i += 16) {
- (*outputFunc)(outputStream, " ", 2);
- for (j = 0; j < 16 && i+j < nCIDs; ++j) {
- cid = cidMap[i+j];
- sprintf(buf, "%02x%02x", (cid >> 8) & 0xff, cid & 0xff);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "\n", 1);
- }
- (*outputFunc)(outputStream, "> def\n", 6);
- }
- } else {
- // direct mapping - just fill the string(s) with s[i]=i
- sprintf(buf, "/CIDCount %d def\n", nGlyphs);
- (*outputFunc)(outputStream, buf, strlen(buf));
- if (nGlyphs > 32767) {
- (*outputFunc)(outputStream, "/CIDMap [\n", 10);
- for (i = 0; i < nGlyphs; i += 32767) {
- j = nGlyphs - i < 32767 ? nGlyphs - i : 32767;
- sprintf(buf, " %d string 0 1 %d {\n", 2 * j, j - 1);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, " 2 copy dup 2 mul exch %d add -8 bitshift put\n", i);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, " 1 index exch dup 2 mul 1 add exch %d add"
- " 255 and put\n", i);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, " } for\n", 8);
- }
- (*outputFunc)(outputStream, "] def\n", 6);
- } else {
- sprintf(buf, "/CIDMap %d string\n", 2 * nGlyphs);
- (*outputFunc)(outputStream, buf, strlen(buf));
- sprintf(buf, " 0 1 %d {\n", nGlyphs - 1);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream,
- " 2 copy dup 2 mul exch -8 bitshift put\n", 42);
- (*outputFunc)(outputStream,
- " 1 index exch dup 2 mul 1 add exch 255 and put\n", 50);
- (*outputFunc)(outputStream, " } for\n", 8);
- (*outputFunc)(outputStream, "def\n", 4);
- }
- }
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
- bbox[0], bbox[1], bbox[2], bbox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
- (*outputFunc)(outputStream, "/Encoding [] readonly def\n", 26);
- (*outputFunc)(outputStream, "/CharStrings 1 dict dup begin\n", 30);
- (*outputFunc)(outputStream, " /.notdef 0 def\n", 17);
- (*outputFunc)(outputStream, " end readonly def\n", 19);
-
- // write the guts of the dictionary
- cvtSfnts(outputFunc, outputStream, NULL);
-
- // end the dictionary and define the font
- (*outputFunc)(outputStream,
- "CIDFontName currentdict end /CIDFont defineresource pop\n",
- 56);
-}
-
-void TrueTypeFontFile::convertToType0(const char *name, const Gushort *cidMap,
- int nCIDs,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- char buf[512];
- GString *sfntsName;
- int n, i, j;
-
- // write the Type 42 sfnts array
- sfntsName = (new GString(name))->append("_sfnts");
- cvtSfnts(outputFunc, outputStream, sfntsName);
- delete sfntsName;
-
- // write the descendant Type 42 fonts
- n = cidMap ? nCIDs : nGlyphs;
- for (i = 0; i < n; i += 256) {
- (*outputFunc)(outputStream, "10 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, name, strlen(name));
- sprintf(buf, "_%02x def\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
- bbox[0], bbox[1], bbox[2], bbox[3]);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
- (*outputFunc)(outputStream, "/sfnts ", 7);
- (*outputFunc)(outputStream, name, strlen(name));
- (*outputFunc)(outputStream, "_sfnts def\n", 11);
- (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
- for (j = 0; j < 256 && i+j < n; ++j) {
- sprintf(buf, "dup %d /c%02x put\n", j, j);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "readonly def\n", 13);
- (*outputFunc)(outputStream, "/CharStrings 257 dict dup begin\n", 32);
- (*outputFunc)(outputStream, "/.notdef 0 def\n", 15);
- for (j = 0; j < 256 && i+j < n; ++j) {
- sprintf(buf, "/c%02x %d def\n", j, cidMap ? cidMap[i+j] : i+j);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "end readonly def\n", 17);
- (*outputFunc)(outputStream,
- "FontName currentdict end definefont pop\n", 40);
- }
-
- // write the Type 0 parent font
- (*outputFunc)(outputStream, "16 dict begin\n", 14);
- (*outputFunc)(outputStream, "/FontName /", 11);
- (*outputFunc)(outputStream, name, strlen(name));
- (*outputFunc)(outputStream, " def\n", 5);
- (*outputFunc)(outputStream, "/FontType 0 def\n", 16);
- (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
- (*outputFunc)(outputStream, "/FMapType 2 def\n", 16);
- (*outputFunc)(outputStream, "/Encoding [\n", 12);
- for (i = 0; i < n; i += 256) {
- sprintf(buf, "%d\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "] def\n", 6);
- (*outputFunc)(outputStream, "/FDepVector [\n", 14);
- for (i = 0; i < n; i += 256) {
- (*outputFunc)(outputStream, "/", 1);
- (*outputFunc)(outputStream, name, strlen(name));
- sprintf(buf, "_%02x findfont\n", i >> 8);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- (*outputFunc)(outputStream, "] def\n", 6);
- (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
-}
-
-int TrueTypeFontFile::getByte(int pos) {
- if (pos < 0 || pos >= len) {
- return 0;
- }
- return file[pos] & 0xff;
-}
-
-int TrueTypeFontFile::getChar(int pos) {
- int x;
-
- if (pos < 0 || pos >= len) {
- return 0;
- }
- x = file[pos] & 0xff;
- if (x & 0x80)
- x |= 0xffffff00;
- return x;
-}
-
-int TrueTypeFontFile::getUShort(int pos) {
- int x;
-
- if (pos < 0 || pos+1 >= len) {
- return 0;
- }
- x = file[pos] & 0xff;
- x = (x << 8) + (file[pos+1] & 0xff);
- return x;
-}
-
-int TrueTypeFontFile::getShort(int pos) {
- int x;
-
- if (pos < 0 || pos+1 >= len) {
- return 0;
- }
- x = file[pos] & 0xff;
- x = (x << 8) + (file[pos+1] & 0xff);
- if (x & 0x8000)
- x |= 0xffff0000;
- return x;
-}
-
-Guint TrueTypeFontFile::getULong(int pos) {
- int x;
-
- if (pos < 0 || pos+3 >= len) {
- return 0;
- }
- x = file[pos] & 0xff;
- x = (x << 8) + (file[pos+1] & 0xff);
- x = (x << 8) + (file[pos+2] & 0xff);
- x = (x << 8) + (file[pos+3] & 0xff);
- return x;
-}
-
-double TrueTypeFontFile::getFixed(int pos) {
- int x, y;
-
- x = getShort(pos);
- y = getUShort(pos+2);
- return (double)x + (double)y / 65536;
-}
-
-int TrueTypeFontFile::seekTable(const char *tag) {
- int i;
-
- for (i = 0; i < nTables; ++i) {
- if (!strncmp(tableHdrs[i].tag, tag, 4)) {
- return tableHdrs[i].offset;
- }
- }
- return -1;
-}
-
-int TrueTypeFontFile::seekTableIdx(const char *tag) {
- int i;
-
- for (i = 0; i < nTables; ++i) {
- if (!strncmp(tableHdrs[i].tag, tag, 4)) {
- return i;
- }
- }
- return -1;
-}
-
-void TrueTypeFontFile::cvtEncoding(const char **encodingA, GBool pdfFontHasEncoding,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- const char *name;
- char buf[64];
- int i;
-
- (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
- if (pdfFontHasEncoding) {
- for (i = 0; i < 256; ++i) {
- if (!(name = encodingA[i])) {
- name = ".notdef";
- }
- sprintf(buf, "dup %d /", i);
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, name, strlen(name));
- (*outputFunc)(outputStream, " put\n", 5);
- }
- } else {
- for (i = 0; i < 256; ++i) {
- sprintf(buf, "dup %d /c%02x put\n", i, i);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- }
- (*outputFunc)(outputStream, "readonly def\n", 13);
-}
-
-void TrueTypeFontFile::cvtCharStrings(const char **encodingA,
- CharCodeToUnicode *toUnicode,
- GBool pdfFontHasEncoding,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- int unicodeCmap, macRomanCmap, msSymbolCmap;
- int nCmaps, cmapPlatform, cmapEncoding, cmapFmt, cmapOffset;
- T42FontIndexMode mode;
- const char *name;
- char buf[64], buf2[16];
- Unicode u;
- int pos, i, j, k;
-
- // always define '.notdef'
- (*outputFunc)(outputStream, "/CharStrings 256 dict dup begin\n", 32);
- (*outputFunc)(outputStream, "/.notdef 0 def\n", 15);
-
- // if there's no 'cmap' table, punt
- if ((pos = seekTable("cmap")) < 0) {
- goto err;
- }
-
- // To match up with the Adobe-defined behaviour, we choose a cmap
- // like this:
- // 1. If the PDF font has an encoding:
- // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
- // and use the Unicode indexes, not the char codes.
- // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
- // and reverse map the char names through MacRomanEncoding to
- // get char codes.
- // 2. If the PDF font does not have an encoding:
- // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
- // and use char codes directly.
- // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
- // and use (0xf000 + char code).
- // 3. If none of these rules apply, use the first cmap and hope for
- // the best (this shouldn't happen).
- nCmaps = getUShort(pos+2);
- unicodeCmap = macRomanCmap = msSymbolCmap = -1;
- cmapOffset = 0;
- for (i = 0; i < nCmaps; ++i) {
- cmapPlatform = getUShort(pos + 4 + 8*i);
- cmapEncoding = getUShort(pos + 4 + 8*i + 2);
- if (cmapPlatform == 3 && cmapEncoding == 1) {
- unicodeCmap = i;
- } else if (cmapPlatform == 1 && cmapEncoding == 0) {
- macRomanCmap = i;
- } else if (cmapPlatform == 3 && cmapEncoding == 0) {
- msSymbolCmap = i;
- }
- }
- i = 0;
- mode = t42FontModeCharCode;
- if (pdfFontHasEncoding) {
- if (unicodeCmap >= 0) {
- i = unicodeCmap;
- mode = t42FontModeUnicode;
- } else if (macRomanCmap >= 0) {
- i = macRomanCmap;
- mode = t42FontModeMacRoman;
- }
- } else {
- if (macRomanCmap >= 0) {
- i = macRomanCmap;
- mode = t42FontModeCharCode;
- } else if (msSymbolCmap >= 0) {
- i = msSymbolCmap;
- mode = t42FontModeCharCodeOffset;
- cmapOffset = 0xf000;
- }
- }
- cmapPlatform = getUShort(pos + 4 + 8*i);
- cmapEncoding = getUShort(pos + 4 + 8*i + 2);
- pos += getULong(pos + 4 + 8*i + 4);
- cmapFmt = getUShort(pos);
- if (cmapFmt != 0 && cmapFmt != 4 && cmapFmt != 6) {
- error(-1, "Unimplemented cmap format (%d) in TrueType font file",
- cmapFmt);
- goto err;
- }
-
- // map char name to glyph index:
- // 1. use encoding to map name to char code
- // 2. use cmap to map char code to glyph index
- j = 0; // make gcc happy
- for (i = 0; i < 256; ++i) {
- if (pdfFontHasEncoding) {
- name = encodingA[i];
- } else {
- sprintf(buf2, "c%02x", i);
- name = buf2;
- }
- if (name && strcmp(name, ".notdef")) {
- switch (mode) {
- case t42FontModeUnicode:
- toUnicode->mapToUnicode((CharCode)i, &u, 1);
- j = (int)u;
- break;
- case t42FontModeCharCode:
- j = i;
- break;
- case t42FontModeCharCodeOffset:
- j = cmapOffset + i;
- break;
- case t42FontModeMacRoman:
- j = globalParams->getMacRomanCharCode(name);
- break;
- }
- // note: Distiller (maybe Adobe's PS interpreter in general)
- // doesn't like TrueType fonts that have CharStrings entries
- // which point to nonexistent glyphs, hence the (k < nGlyphs)
- // test
- if ((k = getCmapEntry(cmapFmt, pos, j)) > 0 &&
- k < nGlyphs) {
- (*outputFunc)(outputStream, "/", 1);
- (*outputFunc)(outputStream, name, strlen(name));
- sprintf(buf, " %d def\n", k);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- }
- }
-
- err:
- (*outputFunc)(outputStream, "end readonly def\n", 17);
-}
-
-int TrueTypeFontFile::getCmapEntry(int cmapFmt, int pos, int code) {
- int cmapLen, cmapFirst;
- int segCnt, segEnd, segStart, segDelta, segOffset;
- int a, b, m, i;
-
- switch (cmapFmt) {
- case 0: // byte encoding table (Apple standard)
- cmapLen = getUShort(pos + 2);
- if (code >= cmapLen) {
- return 0;
- }
- return getByte(pos + 6 + code);
-
- case 4: // segment mapping to delta values (Microsoft standard)
- segCnt = getUShort(pos + 6) / 2;
- a = -1;
- b = segCnt - 1;
- segEnd = getUShort(pos + 14 + 2*b);
- if (code > segEnd) {
- // malformed font -- the TrueType spec requires the last segEnd
- // to be 0xffff
- return 0;
- }
- // invariant: seg[a].end < code <= seg[b].end
- while (b - a > 1) {
- m = (a + b) / 2;
- segEnd = getUShort(pos + 14 + 2*m);
- if (segEnd < code) {
- a = m;
- } else {
- b = m;
- }
- }
- segStart = getUShort(pos + 16 + 2*segCnt + 2*b);
- segDelta = getUShort(pos + 16 + 4*segCnt + 2*b);
- segOffset = getUShort(pos + 16 + 6*segCnt + 2*b);
- if (segOffset == 0) {
- i = (code + segDelta) & 0xffff;
- } else {
- i = getUShort(pos + 16 + 6*segCnt + 2*b +
- segOffset + 2 * (code - segStart));
- if (i != 0) {
- i = (i + segDelta) & 0xffff;
- }
- }
- return i;
-
- case 6: // trimmed table mapping
- cmapFirst = getUShort(pos + 6);
- cmapLen = getUShort(pos + 8);
- if (code < cmapFirst || code >= cmapFirst + cmapLen) {
- return 0;
- }
- return getUShort(pos + 10 + 2*(code - cmapFirst));
-
- default:
- // shouldn't happen - this is checked earlier
- break;
- }
- return 0;
-}
-
-void TrueTypeFontFile::cvtSfnts(FontFileOutputFunc outputFunc,
- void *outputStream, GString *name) {
- TTFontTableHdr newTableHdrs[nT42Tables];
- char tableDir[12 + nT42Tables*16];
- char headTable[54];
- int *origLocaTable;
- char *locaTable;
- int nNewTables;
- Guint checksum;
- int pos, glyfPos, length, glyphLength, pad;
- int i, j, k;
-
- // construct the 'head' table, zero out the font checksum
- memcpy(headTable, file + seekTable("head"), 54);
- headTable[8] = headTable[9] = headTable[10] = headTable[11] = (char)0;
-
- // read the original 'loca' table and construct the new one
- // (pad each glyph out to a multiple of 4 bytes)
- origLocaTable = (int *)gmalloc((nGlyphs + 1) * sizeof(int));
- pos = seekTable("loca");
- for (i = 0; i <= nGlyphs; ++i) {
- if (locaFmt) {
- origLocaTable[i] = getULong(pos + 4*i);
- } else {
- origLocaTable[i] = 2 * getUShort(pos + 2*i);
- }
- }
- locaTable = (char *)gmalloc((nGlyphs + 1) * (locaFmt ? 4 : 2));
- if (locaFmt) {
- locaTable[0] = locaTable[1] = locaTable[2] = locaTable[3] = 0;
- } else {
- locaTable[0] = locaTable[1] = 0;
- }
- pos = 0;
- for (i = 1; i <= nGlyphs; ++i) {
- length = origLocaTable[i] - origLocaTable[i-1];
- if (length & 3) {
- length += 4 - (length & 3);
- }
- pos += length;
- if (locaFmt) {
- locaTable[4*i ] = (char)(pos >> 24);
- locaTable[4*i+1] = (char)(pos >> 16);
- locaTable[4*i+2] = (char)(pos >> 8);
- locaTable[4*i+3] = (char) pos;
- } else {
- locaTable[2*i ] = (char)(pos >> 9);
- locaTable[2*i+1] = (char)(pos >> 1);
- }
- }
-
- // count the number of tables
- nNewTables = 0;
- for (i = 0; i < nT42Tables; ++i) {
- if (t42Tables[i].required ||
- seekTable(t42Tables[i].tag) >= 0) {
- ++nNewTables;
- }
- }
-
- // construct the new table headers, including table checksums
- // (pad each table out to a multiple of 4 bytes)
- pos = 12 + nNewTables*16;
- k = 0;
- for (i = 0; i < nT42Tables; ++i) {
- length = -1;
- checksum = 0; // make gcc happy
- if (i == t42HeadTable) {
- length = 54;
- checksum = computeTableChecksum(headTable, 54);
- } else if (i == t42LocaTable) {
- length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
- checksum = computeTableChecksum(locaTable, length);
- } else if (i == t42GlyfTable) {
- length = 0;
- checksum = 0;
- glyfPos = seekTable("glyf");
- for (j = 0; j < nGlyphs; ++j) {
- glyphLength = origLocaTable[j+1] - origLocaTable[j];
- pad = (glyphLength & 3) ? 4 - (glyphLength & 3) : 0;
- length += glyphLength + pad;
- checksum += computeTableChecksum(file + glyfPos + origLocaTable[j],
- glyphLength);
- }
- } else {
- if ((j = seekTableIdx(t42Tables[i].tag)) >= 0) {
- length = tableHdrs[j].length;
- checksum = computeTableChecksum(file + tableHdrs[j].offset, length);
- } else if (t42Tables[i].required) {
- error(-1, "Embedded TrueType font is missing a required table ('%s')",
- t42Tables[i].tag);
- length = 0;
- checksum = 0;
- }
- }
- if (length >= 0) {
- strncpy(newTableHdrs[k].tag, t42Tables[i].tag, 4);
- newTableHdrs[k].checksum = checksum;
- newTableHdrs[k].offset = pos;
- newTableHdrs[k].length = length;
- pad = (length & 3) ? 4 - (length & 3) : 0;
- pos += length + pad;
- ++k;
- }
- }
-
- // construct the table directory
- tableDir[0] = 0x00; // sfnt version
- tableDir[1] = 0x01;
- tableDir[2] = 0x00;
- tableDir[3] = 0x00;
- tableDir[4] = 0; // numTables
- tableDir[5] = nNewTables;
- tableDir[6] = 0; // searchRange
- tableDir[7] = (char)128;
- tableDir[8] = 0; // entrySelector
- tableDir[9] = 3;
- tableDir[10] = 0; // rangeShift
- tableDir[11] = (char)(16 * nNewTables - 128);
- pos = 12;
- for (i = 0; i < nNewTables; ++i) {
- tableDir[pos ] = newTableHdrs[i].tag[0];
- tableDir[pos+ 1] = newTableHdrs[i].tag[1];
- tableDir[pos+ 2] = newTableHdrs[i].tag[2];
- tableDir[pos+ 3] = newTableHdrs[i].tag[3];
- tableDir[pos+ 4] = (char)(newTableHdrs[i].checksum >> 24);
- tableDir[pos+ 5] = (char)(newTableHdrs[i].checksum >> 16);
- tableDir[pos+ 6] = (char)(newTableHdrs[i].checksum >> 8);
- tableDir[pos+ 7] = (char) newTableHdrs[i].checksum;
- tableDir[pos+ 8] = (char)(newTableHdrs[i].offset >> 24);
- tableDir[pos+ 9] = (char)(newTableHdrs[i].offset >> 16);
- tableDir[pos+10] = (char)(newTableHdrs[i].offset >> 8);
- tableDir[pos+11] = (char) newTableHdrs[i].offset;
- tableDir[pos+12] = (char)(newTableHdrs[i].length >> 24);
- tableDir[pos+13] = (char)(newTableHdrs[i].length >> 16);
- tableDir[pos+14] = (char)(newTableHdrs[i].length >> 8);
- tableDir[pos+15] = (char) newTableHdrs[i].length;
- pos += 16;
- }
-
- // compute the font checksum and store it in the head table
- checksum = computeTableChecksum(tableDir, 12 + nNewTables*16);
- for (i = 0; i < nNewTables; ++i) {
- checksum += newTableHdrs[i].checksum;
- }
- checksum = 0xb1b0afba - checksum; // because the TrueType spec says so
- headTable[ 8] = (char)(checksum >> 24);
- headTable[ 9] = (char)(checksum >> 16);
- headTable[10] = (char)(checksum >> 8);
- headTable[11] = (char) checksum;
-
- // start the sfnts array
- if (name) {
- (*outputFunc)(outputStream, "/", 1);
- (*outputFunc)(outputStream, name->getCString(), name->getLength());
- (*outputFunc)(outputStream, " [\n", 3);
- } else {
- (*outputFunc)(outputStream, "/sfnts [\n", 9);
- }
-
- // write the table directory
- dumpString(tableDir, 12 + nNewTables*16, outputFunc, outputStream);
-
- // write the tables
- for (i = 0; i < nNewTables; ++i) {
- if (i == t42HeadTable) {
- dumpString(headTable, 54, outputFunc, outputStream);
- } else if (i == t42LocaTable) {
- length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
- dumpString(locaTable, length, outputFunc, outputStream);
- } else if (i == t42GlyfTable) {
- glyfPos = seekTable("glyf");
- for (j = 0; j < nGlyphs; ++j) {
- length = origLocaTable[j+1] - origLocaTable[j];
- if (length > 0) {
- dumpString(file + glyfPos + origLocaTable[j], length,
- outputFunc, outputStream);
- }
- }
- } else {
- // length == 0 means the table is missing and the error was
- // already reported during the construction of the table
- // headers
- if ((length = newTableHdrs[i].length) > 0) {
- dumpString(file + seekTable(t42Tables[i].tag), length,
- outputFunc, outputStream);
- }
- }
- }
-
- // end the sfnts array
- (*outputFunc)(outputStream, "] def\n", 6);
-
- gfree(origLocaTable);
- gfree(locaTable);
-}
-
-void TrueTypeFontFile::dumpString(const char *s, int length,
- FontFileOutputFunc outputFunc,
- void *outputStream) {
- char buf[64];
- int pad, i, j;
-
- (*outputFunc)(outputStream, "<", 1);
- for (i = 0; i < length; i += 32) {
- for (j = 0; j < 32 && i+j < length; ++j) {
- sprintf(buf, "%02X", s[i+j] & 0xff);
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- if (i % (65536 - 32) == 65536 - 64) {
- (*outputFunc)(outputStream, ">\n<", 3);
- } else if (i+32 < length) {
- (*outputFunc)(outputStream, "\n", 1);
- }
- }
- if (length & 3) {
- pad = 4 - (length & 3);
- for (i = 0; i < pad; ++i) {
- (*outputFunc)(outputStream, "00", 2);
- }
- }
- // add an extra zero byte because the Adobe Type 42 spec says so
- (*outputFunc)(outputStream, "00>\n", 4);
-}
-
-Guint TrueTypeFontFile::computeTableChecksum(const char *data, int length) {
- Guint checksum, word;
- int i;
-
- checksum = 0;
- for (i = 0; i+3 < length; i += 4) {
- word = ((data[i ] & 0xff) << 24) +
- ((data[i+1] & 0xff) << 16) +
- ((data[i+2] & 0xff) << 8) +
- (data[i+3] & 0xff);
- checksum += word;
- }
- if (length & 3) {
- word = 0;
- i = length & ~3;
- switch (length & 3) {
- case 3:
- word |= (data[i+2] & 0xff) << 8;
- case 2:
- word |= (data[i+1] & 0xff) << 16;
- case 1:
- word |= (data[i ] & 0xff) << 24;
- break;
- }
- checksum += word;
- }
- return checksum;
-}
-
-void TrueTypeFontFile::writeTTF(FILE *out) {
- static char cmapTab[20] = {
- 0, 0, // table version number
- 0, 1, // number of encoding tables
- 0, 1, // platform ID
- 0, 0, // encoding ID
- 0, 0, 0, 12, // offset of subtable
- 0, 0, // subtable format
- 0, 1, // subtable length
- 0, 1, // subtable version
- 0, // map char 0 -> glyph 0
- 0 // pad to multiple of four bytes
- };
- static char nameTab[8] = {
- 0, 0, // format
- 0, 0, // number of name records
- 0, 6, // offset to start of string storage
- 0, 0 // pad to multiple of four bytes
- };
- static char postTab[32] = {
- 0, 1, 0, 0, // format
- 0, 0, 0, 0, // italic angle
- 0, 0, // underline position
- 0, 0, // underline thickness
- 0, 0, 0, 0, // fixed pitch
- 0, 0, 0, 0, // min Type 42 memory
- 0, 0, 0, 0, // max Type 42 memory
- 0, 0, 0, 0, // min Type 1 memory
- 0, 0, 0, 0 // max Type 1 memory
- };
- GBool haveCmap, haveName, havePost;
- GBool dirCmap, dirName, dirPost;
- int nNewTables, nAllTables, pad;
- char *tableDir;
- Guint t, pos;
- int i, j;
-
- // check for missing tables
- haveCmap = seekTable("cmap") >= 0;
- haveName = seekTable("name") >= 0;
- havePost = seekTable("post") >= 0;
- nNewTables = (haveCmap ? 0 : 1) + (haveName ? 0 : 1) + (havePost ? 0 : 1);
- if (!nNewTables && !mungedCmapSize) {
- // none are missing - write the TTF file as is
- fwrite(file, 1, len, out);
- return;
- }
-
- // construct the new table directory
- nAllTables = nTables + nNewTables;
- tableDir = (char *)gmalloc(12 + nAllTables * 16);
- memcpy(tableDir, file, 12 + nTables * 16);
- tableDir[4] = (char)((nAllTables >> 8) & 0xff);
- tableDir[5] = (char)(nAllTables & 0xff);
- for (i = -1, t = (Guint)nAllTables; t; ++i, t >>= 1) ;
- t = 1 << (4 + i);
- tableDir[6] = (char)((t >> 8) & 0xff);
- tableDir[7] = (char)(t & 0xff);
- tableDir[8] = (char)((i >> 8) & 0xff);
- tableDir[9] = (char)(i & 0xff);
- t = nAllTables * 16 - t;
- tableDir[10] = (char)((t >> 8) & 0xff);
- tableDir[11] = (char)(t & 0xff);
- dirCmap = haveCmap;
- dirName = haveName;
- dirPost = havePost;
- j = 0;
- pad = (len & 3) ? 4 - (len & 3) : 0;
- pos = len + pad + 16 * nNewTables;
- for (i = 0; i < nTables; ++i) {
- if (!dirCmap && strncmp(tableHdrs[i].tag, "cmap", 4) > 0) {
- tableDir[12 + 16*j ] = 'c';
- tableDir[12 + 16*j + 1] = 'm';
- tableDir[12 + 16*j + 2] = 'a';
- tableDir[12 + 16*j + 3] = 'p';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(cmapTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(cmapTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(cmapTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(cmapTab) & 0xff);
- pos += sizeof(cmapTab);
- ++j;
- dirCmap = gTrue;
- }
- if (!dirName && strncmp(tableHdrs[i].tag, "name", 4) > 0) {
- tableDir[12 + 16*j ] = 'n';
- tableDir[12 + 16*j + 1] = 'a';
- tableDir[12 + 16*j + 2] = 'm';
- tableDir[12 + 16*j + 3] = 'e';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(nameTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(nameTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(nameTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(nameTab) & 0xff);
- pos += sizeof(nameTab);
- ++j;
- dirName = gTrue;
- }
- if (!dirName && strncmp(tableHdrs[i].tag, "post", 4) > 0) {
- tableDir[12 + 16*j ] = 'p';
- tableDir[12 + 16*j + 1] = 'o';
- tableDir[12 + 16*j + 2] = 's';
- tableDir[12 + 16*j + 3] = 't';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(postTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(postTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(postTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(postTab) & 0xff);
- pos += sizeof(postTab);
- ++j;
- dirPost = gTrue;
- }
- tableDir[12 + 16*j ] = tableHdrs[i].tag[0];
- tableDir[12 + 16*j + 1] = tableHdrs[i].tag[1];
- tableDir[12 + 16*j + 2] = tableHdrs[i].tag[2];
- tableDir[12 + 16*j + 3] = tableHdrs[i].tag[3];
- tableDir[12 + 16*j + 4] = (char)((tableHdrs[i].checksum >> 24) & 0xff);
- tableDir[12 + 16*j + 5] = (char)((tableHdrs[i].checksum >> 16) & 0xff);
- tableDir[12 + 16*j + 6] = (char)((tableHdrs[i].checksum >> 8) & 0xff);
- tableDir[12 + 16*j + 7] = (char)( tableHdrs[i].checksum & 0xff);
- t = tableHdrs[i].offset + nNewTables * 16;
- tableDir[12 + 16*j + 8] = (char)((t >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((t >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((t >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( t & 0xff);
- tableDir[12 + 16*j + 12] = (char)((tableHdrs[i].length >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((tableHdrs[i].length >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((tableHdrs[i].length >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( tableHdrs[i].length & 0xff);
- ++j;
- }
- if (!dirCmap) {
- tableDir[12 + 16*j ] = 'c';
- tableDir[12 + 16*j + 1] = 'm';
- tableDir[12 + 16*j + 2] = 'a';
- tableDir[12 + 16*j + 3] = 'p';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(cmapTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(cmapTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(cmapTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(cmapTab) & 0xff);
- pos += sizeof(cmapTab);
- ++j;
- dirCmap = gTrue;
- }
- if (!dirName) {
- tableDir[12 + 16*j ] = 'n';
- tableDir[12 + 16*j + 1] = 'a';
- tableDir[12 + 16*j + 2] = 'm';
- tableDir[12 + 16*j + 3] = 'e';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(nameTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(nameTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(nameTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(nameTab) & 0xff);
- pos += sizeof(nameTab);
- ++j;
- dirName = gTrue;
- }
- if (!dirPost) {
- tableDir[12 + 16*j ] = 'p';
- tableDir[12 + 16*j + 1] = 'o';
- tableDir[12 + 16*j + 2] = 's';
- tableDir[12 + 16*j + 3] = 't';
- tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
- tableDir[12 + 16*j + 5] = (char)0;
- tableDir[12 + 16*j + 6] = (char)0;
- tableDir[12 + 16*j + 7] = (char)0;
- tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
- tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
- tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
- tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
- tableDir[12 + 16*j + 12] = (char)((sizeof(postTab) >> 24) & 0xff);
- tableDir[12 + 16*j + 13] = (char)((sizeof(postTab) >> 16) & 0xff);
- tableDir[12 + 16*j + 14] = (char)((sizeof(postTab) >> 8) & 0xff);
- tableDir[12 + 16*j + 15] = (char)( sizeof(postTab) & 0xff);
- pos += sizeof(postTab);
- ++j;
- dirPost = gTrue;
- }
-
- // write the table directory
- fwrite(tableDir, 1, 12 + 16 * nAllTables, out);
-
- // write the original tables
- fwrite(file + 12 + 16*nTables, 1, len - (12 + 16*nTables), out);
-
- // write the new tables
- for (i = 0; i < pad; ++i) {
- fputc((char)0, out);
- }
- if (!haveCmap) {
- fwrite(cmapTab, 1, sizeof(cmapTab), out);
- }
- if (!haveName) {
- fwrite(nameTab, 1, sizeof(nameTab), out);
- }
- if (!havePost) {
- fwrite(postTab, 1, sizeof(postTab), out);
- }
-
- gfree(tableDir);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/FontFile.cpp b/filters/kword/pdf/xpdf/xpdf/FontFile.cpp
new file mode 100644
index 000000000..8a6597b08
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/FontFile.cpp
@@ -0,0 +1,3883 @@
+//========================================================================
+//
+// FontFile.cpp
+//
+// Copyright 1999-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <math.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "CharCodeToUnicode.h"
+#include "FontEncodingTables.h"
+#include "FontFile.h"
+
+#include "CompactFontTables.h"
+
+//------------------------------------------------------------------------
+
+static inline const char *nextLine(const char *line, const char *end) {
+ while (line < end && *line != '\n' && *line != '\r')
+ ++line;
+ while (line < end && *line == '\n' || *line == '\r')
+ ++line;
+ return line;
+}
+
+static const char hexChars[17] = "0123456789ABCDEF";
+
+//------------------------------------------------------------------------
+// FontFile
+//------------------------------------------------------------------------
+
+FontFile::FontFile() {
+}
+
+FontFile::~FontFile() {
+}
+
+//------------------------------------------------------------------------
+// Type1FontFile
+//------------------------------------------------------------------------
+
+Type1FontFile::Type1FontFile(const char *file, int len) {
+ const char *line, *line1;
+ char *p, *p2;
+ GBool haveEncoding;
+ char buf[256];
+ char c;
+ int n, code, i, j;
+
+ name = NULL;
+ encoding = (char **)gmalloc(256 * sizeof(char *));
+ for (i = 0; i < 256; ++i) {
+ encoding[i] = NULL;
+ }
+ haveEncoding = gFalse;
+
+ for (i = 1, line = file;
+ i <= 100 && line < file + len && !haveEncoding;
+ ++i) {
+
+ // get font name
+ if (!strncmp(line, "/FontName", 9)) {
+ strncpy(buf, line, 255);
+ buf[255] = '\0';
+ if ((p = strchr(buf+9, '/')) &&
+ (p = strtok(p+1, " \t\n\r"))) {
+ name = copyString(p);
+ }
+ line = nextLine(line, file + len);
+
+ // get encoding
+ } else if (!strncmp(line, "/Encoding StandardEncoding def", 30)) {
+ for (j = 0; j < 256; ++j) {
+ if (standardEncoding[j]) {
+ encoding[j] = copyString(standardEncoding[j]);
+ }
+ }
+ haveEncoding = gTrue;
+ } else if (!strncmp(line, "/Encoding 256 array", 19)) {
+ for (j = 0; j < 300; ++j) {
+ line1 = nextLine(line, file + len);
+ if ((n = line1 - line) > 255) {
+ n = 255;
+ }
+ strncpy(buf, line, n);
+ buf[n] = '\0';
+ for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
+ if (!strncmp(p, "dup", 3)) {
+ for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
+ for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
+ if (*p2) {
+ c = *p2;
+ *p2 = '\0';
+ if ((code = atoi(p)) < 256) {
+ *p2 = c;
+ for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
+ if (*p == '/') {
+ ++p;
+ for (p2 = p; *p2 && *p2 != ' ' && *p2 != '\t'; ++p2) ;
+ *p2 = '\0';
+ encoding[code] = copyString(p);
+ }
+ }
+ }
+ } else {
+ if (strtok(buf, " \t") &&
+ (p = strtok(NULL, " \t\n\r")) && !strcmp(p, "def")) {
+ break;
+ }
+ }
+ line = line1;
+ }
+ //~ check for getinterval/putinterval junk
+ haveEncoding = gTrue;
+
+ } else {
+ line = nextLine(line, file + len);
+ }
+ }
+}
+
+Type1FontFile::~Type1FontFile() {
+ int i;
+
+ if (name) {
+ gfree(name);
+ }
+ for (i = 0; i < 256; ++i) {
+ gfree(encoding[i]);
+ }
+ gfree(encoding);
+}
+
+//------------------------------------------------------------------------
+// Type1CFontFile
+//------------------------------------------------------------------------
+
+struct Type1CTopDict {
+ int version;
+ int notice;
+ int copyright;
+ int fullName;
+ int familyName;
+ int weight;
+ int isFixedPitch;
+ double italicAngle;
+ double underlinePosition;
+ double underlineThickness;
+ int paintType;
+ int charstringType;
+ double fontMatrix[6];
+ int uniqueID;
+ double fontBBox[4];
+ double strokeWidth;
+ int charset;
+ int encoding;
+ int charStrings;
+ int privateSize;
+ int privateOffset;
+
+ //----- CIDFont entries
+ int registry;
+ int ordering;
+ int supplement;
+ int fdArrayOffset;
+ int fdSelectOffset;
+};
+
+struct Type1CPrivateDict {
+ GString *dictData;
+ int subrsOffset;
+ double defaultWidthX;
+ GBool defaultWidthXFP;
+ double nominalWidthX;
+ GBool nominalWidthXFP;
+};
+
+Type1CFontFile::Type1CFontFile(const char *fileA, int lenA) {
+ Guchar *nameIdxPtr, *idxPtr0, *idxPtr1;
+
+ file = fileA;
+ len = lenA;
+ name = NULL;
+ encoding = NULL;
+
+ // some tools embed Type 1C fonts with an extra whitespace char at
+ // the beginning
+ if (file[0] != '\x01') {
+ ++file;
+ }
+
+ // read header
+ topOffSize = file[3] & 0xff;
+
+ // read name index (first font only)
+ nameIdxPtr = (Guchar *)file + (file[2] & 0xff);
+ idxPtr0 = getIndexValPtr(nameIdxPtr, 0);
+ idxPtr1 = getIndexValPtr(nameIdxPtr, 1);
+ name = new GString((char *)idxPtr0, idxPtr1 - idxPtr0);
+
+ topDictIdxPtr = getIndexEnd(nameIdxPtr);
+ stringIdxPtr = getIndexEnd(topDictIdxPtr);
+ gsubrIdxPtr = getIndexEnd(stringIdxPtr);
+}
+
+Type1CFontFile::~Type1CFontFile() {
+ int i;
+
+ delete name;
+ if (encoding) {
+ for (i = 0; i < 256; ++i) {
+ gfree(encoding[i]);
+ }
+ gfree(encoding);
+ }
+}
+
+const char *Type1CFontFile::getName() {
+ return name->getCString();
+}
+
+char **Type1CFontFile::getEncoding() {
+ if (!encoding) {
+ readNameAndEncoding();
+ }
+ return encoding;
+}
+
+void Type1CFontFile::readNameAndEncoding() {
+ char buf[256];
+ Guchar *idxPtr0, *idxPtr1, *ptr;
+ int nGlyphs;
+ int nCodes, nRanges, nLeft, nSups;
+ Gushort *glyphNames;
+ int charset, enc, charstrings;
+ int encFormat;
+ int c, sid;
+ double x;
+ GBool isFP;
+ int key;
+ int i, j;
+
+ encoding = (char **)gmalloc(256 * sizeof(char *));
+ for (i = 0; i < 256; ++i) {
+ encoding[i] = NULL;
+ }
+
+ // read top dict (first font only)
+ idxPtr0 = getIndexValPtr(topDictIdxPtr, 0);
+ idxPtr1 = getIndexValPtr(topDictIdxPtr, 1);
+ charset = enc = charstrings = 0;
+ i = 0;
+ ptr = idxPtr0;
+ while (ptr < idxPtr1) {
+ if (*ptr <= 27 || *ptr == 31) {
+ key = *ptr++;
+ if (key == 0x0c) {
+ key = (key << 8) | *ptr++;
+ }
+ if (key == 0x0f) { // charset
+ charset = (int)op[0];
+ } else if (key == 0x10) { // encoding
+ enc = (int)op[0];
+ } else if (key == 0x11) { // charstrings
+ charstrings = (int)op[0];
+ }
+ i = 0;
+ } else {
+ x = getNum(&ptr, &isFP);
+ if (i < 48) {
+ op[i++] = x;
+ }
+ }
+ }
+
+ // get number of glyphs from charstrings index
+ nGlyphs = getIndexLen((Guchar *)file + charstrings);
+
+ // read charset (GID -> name mapping)
+ glyphNames = readCharset(charset, nGlyphs);
+
+ // read encoding (GID -> code mapping)
+ if (enc == 0) {
+ for (i = 0; i < 256; ++i) {
+ if (standardEncoding[i]) {
+ encoding[i] = copyString(standardEncoding[i]);
+ }
+ }
+ } else if (enc == 1) {
+ for (i = 0; i < 256; ++i) {
+ if (expertEncoding[i]) {
+ encoding[i] = copyString(expertEncoding[i]);
+ }
+ }
+ } else {
+ ptr = (Guchar *)file + enc;
+ encFormat = *ptr++;
+ if ((encFormat & 0x7f) == 0) {
+ nCodes = 1 + *ptr++;
+ if (nCodes > nGlyphs) {
+ nCodes = nGlyphs;
+ }
+ for (i = 1; i < nCodes; ++i) {
+ c = *ptr++;
+ encoding[c] = copyString(getString(glyphNames[i], buf));
+ }
+ } else if ((encFormat & 0x7f) == 1) {
+ nRanges = *ptr++;
+ nCodes = 1;
+ for (i = 0; i < nRanges; ++i) {
+ c = *ptr++;
+ nLeft = *ptr++;
+ for (j = 0; j <= nLeft && nCodes < nGlyphs; ++j) {
+ encoding[c] = copyString(getString(glyphNames[nCodes], buf));
+ ++nCodes;
+ ++c;
+ }
+ }
+ }
+ if (encFormat & 0x80) {
+ nSups = *ptr++;
+ for (i = 0; i < nSups; ++i) {
+ c = *ptr++;
+ sid = getWord(ptr, 2);
+ ptr += 2;
+ encoding[c] = copyString(getString(sid, buf));
+ }
+ }
+ }
+
+ if (charset > 2) {
+ gfree(glyphNames);
+ }
+}
+
+void Type1CFontFile::convertToType1(FontFileOutputFunc outputFuncA,
+ void *outputStreamA) {
+ Type1CTopDict dict;
+ Type1CPrivateDict privateDict;
+ char buf[512], eBuf[256];
+ Guchar *idxPtr0, *idxPtr1, *subrsIdxPtr, *charStringsIdxPtr, *ptr;
+ int nGlyphs, nCodes, nRanges, nLeft, nSups;
+ Gushort *glyphNames;
+ int encFormat, nSubrs, nCharStrings;
+ int c, sid;
+ int i, j, n;
+
+ outputFunc = outputFuncA;
+ outputStream = outputStreamA;
+
+ // read top dict (first font only)
+ readTopDict(&dict);
+
+ // get global subrs
+ //~ ... global subrs are unimplemented
+
+ // write header and font dictionary, up to encoding
+ (*outputFunc)(outputStream, "%!FontType1-1.0: ", 17);
+ (*outputFunc)(outputStream, name->getCString(), name->getLength());
+ if (dict.version != 0) {
+ getString(dict.version, buf);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ (*outputFunc)(outputStream, "11 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontInfo 10 dict dup begin\n", 28);
+ if (dict.version != 0) {
+ (*outputFunc)(outputStream, "/version (", 10);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.notice != 0) {
+ getString(dict.notice, buf);
+ (*outputFunc)(outputStream, "/Notice (", 9);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.copyright != 0) {
+ getString(dict.copyright, buf);
+ (*outputFunc)(outputStream, "/Copyright (", 12);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.fullName != 0) {
+ getString(dict.fullName, buf);
+ (*outputFunc)(outputStream, "/FullName (", 11);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.familyName != 0) {
+ getString(dict.familyName, buf);
+ (*outputFunc)(outputStream, "/FamilyName (", 13);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.weight != 0) {
+ getString(dict.weight, buf);
+ (*outputFunc)(outputStream, "/Weight (", 9);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") readonly def\n", 15);
+ }
+ if (dict.isFixedPitch) {
+ (*outputFunc)(outputStream, "/isFixedPitch true def\n", 23);
+ } else {
+ (*outputFunc)(outputStream, "/isFixedPitch false def\n", 24);
+ }
+ sprintf(buf, "/ItalicAngle %g def\n", dict.italicAngle);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/UnderlinePosition %g def\n", dict.underlinePosition);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/UnderlineThickness %g def\n", dict.underlineThickness);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "end readonly def\n", 17);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, name->getCString(), name->getLength());
+ (*outputFunc)(outputStream, " def\n", 5);
+ sprintf(buf, "/PaintType %d def\n", dict.paintType);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
+ sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] readonly def\n",
+ dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
+ dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/FontBBox [%g %g %g %g] readonly def\n",
+ dict.fontBBox[0], dict.fontBBox[1],
+ dict.fontBBox[2], dict.fontBBox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ if (dict.uniqueID != 0) {
+ sprintf(buf, "/UniqueID %d def\n", dict.uniqueID);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+
+ // get number of glyphs from charstrings index
+ nGlyphs = getIndexLen((Guchar *)file + dict.charStrings);
+
+ // read charset
+ glyphNames = readCharset(dict.charset, nGlyphs);
+
+ // read encoding (glyph -> code mapping), write Type 1 encoding
+ (*outputFunc)(outputStream, "/Encoding ", 10);
+ if (dict.encoding == 0) {
+ (*outputFunc)(outputStream, "StandardEncoding def\n", 21);
+ } else {
+ (*outputFunc)(outputStream, "256 array\n", 10);
+ (*outputFunc)(outputStream,
+ "0 1 255 {1 index exch /.notdef put} for\n", 40);
+ if (dict.encoding == 1) {
+ for (i = 0; i < 256; ++i) {
+ if (expertEncoding[i]) {
+ sprintf(buf, "dup %d /%s put\n", i, expertEncoding[i]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ }
+ } else {
+ ptr = (Guchar *)file + dict.encoding;
+ encFormat = *ptr++;
+ if ((encFormat & 0x7f) == 0) {
+ nCodes = 1 + *ptr++;
+ if (nCodes > nGlyphs) {
+ nCodes = nGlyphs;
+ }
+ for (i = 1; i < nCodes; ++i) {
+ c = *ptr++;
+ sprintf(buf, "dup %d /", c);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ getString(glyphNames[i], buf);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, " put\n", 5);
+ }
+ } else if ((encFormat & 0x7f) == 1) {
+ nRanges = *ptr++;
+ nCodes = 1;
+ for (i = 0; i < nRanges; ++i) {
+ c = *ptr++;
+ nLeft = *ptr++;
+ for (j = 0; j <= nLeft && nCodes < nGlyphs; ++j) {
+ sprintf(buf, "dup %d /", c);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ getString(glyphNames[nCodes], buf);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, " put\n", 5);
+ ++nCodes;
+ ++c;
+ }
+ }
+ }
+ if (encFormat & 0x80) {
+ nSups = *ptr++;
+ for (i = 0; i < nSups; ++i) {
+ c = *ptr++;
+ sid = getWord(ptr, 2);
+ ptr += 2;
+ sprintf(buf, "dup %d /", c);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ getString(sid, buf);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, " put\n", 5);
+ }
+ }
+ }
+ (*outputFunc)(outputStream, "readonly def\n", 13);
+ }
+ (*outputFunc)(outputStream, "currentdict end\n", 16);
+
+ // start the binary section
+ (*outputFunc)(outputStream, "currentfile eexec\n", 18);
+ r1 = 55665;
+ line = 0;
+
+ // get private dictionary
+ eexecWrite("\x83\xca\x73\xd5");
+ eexecWrite("dup /Private 32 dict dup begin\n");
+ eexecWrite("/RD {string currentfile exch readstring pop} executeonly def\n");
+ eexecWrite("/ND {noaccess def} executeonly def\n");
+ eexecWrite("/NP {noaccess put} executeonly def\n");
+ eexecWrite("/MinFeature {16 16} ND\n");
+ readPrivateDict(&privateDict, dict.privateOffset, dict.privateSize);
+ eexecWrite(privateDict.dictData->getCString());
+ defaultWidthX = privateDict.defaultWidthX;
+ defaultWidthXFP = privateDict.defaultWidthXFP;
+ nominalWidthX = privateDict.nominalWidthX;
+ nominalWidthXFP = privateDict.nominalWidthXFP;
+
+ // get subrs
+ if (privateDict.subrsOffset != 0) {
+ subrsIdxPtr = (Guchar *)file + dict.privateOffset +
+ privateDict.subrsOffset;
+ nSubrs = getIndexLen(subrsIdxPtr);
+ sprintf(eBuf, "/Subrs %d array\n", nSubrs);
+ eexecWrite(eBuf);
+ idxPtr1 = getIndexValPtr(subrsIdxPtr, 0);
+ for (i = 0; i < nSubrs; ++i) {
+ idxPtr0 = idxPtr1;
+ idxPtr1 = getIndexValPtr(subrsIdxPtr, i+1);
+ n = idxPtr1 - idxPtr0;
+#if 1 //~ Type 2 subrs are unimplemented
+ error(-1, "Unimplemented Type 2 subrs");
+#else
+ sprintf(eBuf, "dup %d %d RD ", i, n);
+ eexecWrite(eBuf);
+ eexecCvtGlyph(idxPtr0, n);
+ eexecWrite(" NP\n");
+#endif
+ }
+ eexecWrite("ND\n");
+ }
+
+ // get CharStrings
+ charStringsIdxPtr = (Guchar *)file + dict.charStrings;
+ nCharStrings = getIndexLen(charStringsIdxPtr);
+ sprintf(eBuf, "2 index /CharStrings %d dict dup begin\n", nCharStrings);
+ eexecWrite(eBuf);
+ idxPtr1 = getIndexValPtr(charStringsIdxPtr, 0);
+ for (i = 0; i < nCharStrings; ++i) {
+ idxPtr0 = idxPtr1;
+ idxPtr1 = getIndexValPtr(charStringsIdxPtr, i+1);
+ n = idxPtr1 - idxPtr0;
+ eexecCvtGlyph(getString(glyphNames[i], buf), idxPtr0, n);
+ }
+ eexecWrite("end\n");
+ eexecWrite("end\n");
+ eexecWrite("readonly put\n");
+ eexecWrite("noaccess put\n");
+ eexecWrite("dup /FontName get exch definefont pop\n");
+ eexecWrite("mark currentfile closefile\n");
+
+ // trailer
+ if (line > 0) {
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+ for (i = 0; i < 8; ++i) {
+ (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65);
+ }
+ (*outputFunc)(outputStream, "cleartomark\n", 12);
+
+ // clean up
+ delete privateDict.dictData;
+ if (dict.charset > 2) {
+ gfree(glyphNames);
+ }
+}
+
+void Type1CFontFile::convertToCIDType0(const char *psName,
+ FontFileOutputFunc outputFuncA,
+ void *outputStreamA) {
+ Type1CTopDict dict;
+ Type1CPrivateDict *privateDicts;
+ GString *charStrings;
+ int *charStringOffsets;
+ Gushort *charset;
+ int *cidMap;
+ Guchar *fdSelect;
+ Guchar *charStringsIdxPtr, *fdArrayIdx, *idxPtr0, *idxPtr1, *ptr;
+ char buf[512], buf2[16];
+ int nGlyphs, nCIDs, gdBytes, nFDs;
+ int fdSelectFmt, nRanges, gid0, gid1, fd, offset;
+ int key;
+ double x;
+ GBool isFP;
+ int i, j, k, n;
+
+ outputFunc = outputFuncA;
+ outputStream = outputStreamA;
+
+ (*outputFunc)(outputStream, "/CIDInit /ProcSet findresource begin\n", 37);
+
+ // read top dict (first font only)
+ readTopDict(&dict);
+
+ // read the FDArray dictionaries and Private dictionaries
+ if (dict.fdArrayOffset == 0) {
+ nFDs = 1;
+ privateDicts = (Type1CPrivateDict *)
+ gmalloc(nFDs * sizeof(Type1CPrivateDict));
+ privateDicts[0].dictData = new GString();
+ privateDicts[0].subrsOffset = 0;
+ privateDicts[0].defaultWidthX = 0;
+ privateDicts[0].defaultWidthXFP = gFalse;
+ privateDicts[0].nominalWidthX = 0;
+ privateDicts[0].nominalWidthXFP = gFalse;
+ } else {
+ fdArrayIdx = (Guchar *)file + dict.fdArrayOffset;
+ nFDs = getIndexLen(fdArrayIdx);
+ privateDicts = (Type1CPrivateDict *)
+ gmalloc(nFDs * sizeof(Type1CPrivateDict));
+ idxPtr1 = getIndexValPtr(fdArrayIdx, 0);
+ for (i = 0; i < nFDs; ++i) {
+ privateDicts[i].dictData = NULL;
+ idxPtr0 = idxPtr1;
+ idxPtr1 = getIndexValPtr(fdArrayIdx, i + 1);
+ ptr = idxPtr0;
+ j = 0;
+ while (ptr < idxPtr1) {
+ if (*ptr <= 27 || *ptr == 31) {
+ key = *ptr++;
+ if (key == 0x0c) {
+ key = (key << 8) | *ptr++;
+ }
+ if (key == 0x0012) {
+ readPrivateDict(&privateDicts[i], (int)op[1], (int)op[0]);
+ }
+ j = 0;
+ } else {
+ x = getNum(&ptr, &isFP);
+ if (j < 48) {
+ op[j] = x;
+ fp[j++] = isFP;
+ }
+ }
+ }
+ if (!privateDicts[i].dictData) {
+ privateDicts[i].dictData = new GString();
+ privateDicts[i].subrsOffset = 0;
+ privateDicts[i].defaultWidthX = 0;
+ privateDicts[i].defaultWidthXFP = gFalse;
+ privateDicts[i].nominalWidthX = 0;
+ privateDicts[i].nominalWidthXFP = gFalse;
+ }
+ }
+ }
+
+ // get the glyph count
+ charStringsIdxPtr = (Guchar *)file + dict.charStrings;
+ nGlyphs = getIndexLen(charStringsIdxPtr);
+
+ // read the FDSelect table
+ fdSelect = (Guchar *)gmalloc(nGlyphs);
+ if (dict.fdSelectOffset == 0) {
+ for (i = 0; i < nGlyphs; ++i) {
+ fdSelect[i] = 0;
+ }
+ } else {
+ ptr = (Guchar *)file + dict.fdSelectOffset;
+ fdSelectFmt = *ptr++;
+ if (fdSelectFmt == 0) {
+ memcpy(fdSelect, ptr, nGlyphs);
+ } else if (fdSelectFmt == 3) {
+ nRanges = getWord(ptr, 2);
+ ptr += 2;
+ gid0 = getWord(ptr, 2);
+ ptr += 2;
+ for (i = 1; i <= nRanges; ++i) {
+ fd = *ptr++;
+ gid1 = getWord(ptr, 2);
+ ptr += 2;
+ for (j = gid0; j < gid1; ++j) {
+ fdSelect[j] = fd;
+ }
+ gid0 = gid1;
+ }
+ } else {
+ error(-1, "Unknown FDSelect table format in CID font");
+ for (i = 0; i < nGlyphs; ++i) {
+ fdSelect[i] = 0;
+ }
+ }
+ }
+
+ // read the charset, compute the CID-to-GID mapping
+ charset = readCharset(dict.charset, nGlyphs);
+ nCIDs = 0;
+ for (i = 0; i < nGlyphs; ++i) {
+ if (charset[i] >= nCIDs) {
+ nCIDs = charset[i] + 1;
+ }
+ }
+ cidMap = (int *)gmalloc(nCIDs * sizeof(int));
+ for (i = 0; i < nCIDs; ++i) {
+ cidMap[i] = -1;
+ }
+ for (i = 0; i < nGlyphs; ++i) {
+ cidMap[charset[i]] = i;
+ }
+
+ // build the charstrings
+ charStrings = new GString();
+ charStringOffsets = (int *)gmalloc((nCIDs + 1) * sizeof(int));
+ for (i = 0; i < nCIDs; ++i) {
+ charStringOffsets[i] = charStrings->getLength();
+ if (cidMap[i] >= 0) {
+ idxPtr0 = getIndexValPtr(charStringsIdxPtr, cidMap[i]);
+ idxPtr1 = getIndexValPtr(charStringsIdxPtr, cidMap[i]+1);
+ n = idxPtr1 - idxPtr0;
+ j = fdSelect[cidMap[i]];
+ defaultWidthX = privateDicts[j].defaultWidthX;
+ defaultWidthXFP = privateDicts[j].defaultWidthXFP;
+ nominalWidthX = privateDicts[j].nominalWidthX;
+ nominalWidthXFP = privateDicts[j].nominalWidthXFP;
+ cvtGlyph(idxPtr0, n);
+ charStrings->append(charBuf);
+ delete charBuf;
+ }
+ }
+ charStringOffsets[nCIDs] = charStrings->getLength();
+
+ // compute gdBytes = number of bytes needed for charstring offsets
+ // (offset size needs to account for the charstring offset table,
+ // with a worst case of five bytes per entry, plus the charstrings
+ // themselves)
+ i = (nCIDs + 1) * 5 + charStrings->getLength();
+ if (i < 0x100) {
+ gdBytes = 1;
+ } else if (i < 0x10000) {
+ gdBytes = 2;
+ } else if (i < 0x1000000) {
+ gdBytes = 3;
+ } else {
+ gdBytes = 4;
+ }
+
+ // begin the font dictionary
+ (*outputFunc)(outputStream, "20 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/CIDFontName /", 14);
+ (*outputFunc)(outputStream, psName, strlen(psName));
+ (*outputFunc)(outputStream, " def\n", 5);
+ (*outputFunc)(outputStream, "/CIDFontType 0 def\n", 19);
+ (*outputFunc)(outputStream, "/CIDSystemInfo 3 dict dup begin\n", 32);
+ if (dict.registry > 0 && dict.ordering > 0) {
+ getString(dict.registry, buf);
+ (*outputFunc)(outputStream, " /Registry (", 13);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") def\n", 6);
+ getString(dict.ordering, buf);
+ (*outputFunc)(outputStream, " /Ordering (", 13);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, ") def\n", 6);
+ } else {
+ (*outputFunc)(outputStream, " /Registry (Adobe) def\n", 24);
+ (*outputFunc)(outputStream, " /Ordering (Identity) def\n", 27);
+ }
+ sprintf(buf, " /Supplement %d def\n", dict.supplement);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "end def\n", 8);
+ sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] def\n",
+ dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
+ dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/FontBBox [%g %g %g %g] def\n",
+ dict.fontBBox[0], dict.fontBBox[1],
+ dict.fontBBox[2], dict.fontBBox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FontInfo 1 dict dup begin\n", 27);
+ (*outputFunc)(outputStream, " /FSType 8 def\n", 16);
+ (*outputFunc)(outputStream, "end def\n", 8);
+
+ // CIDFont-specific entries
+ sprintf(buf, "/CIDCount %d def\n", nCIDs);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FDBytes 1 def\n", 15);
+ sprintf(buf, "/GDBytes %d def\n", gdBytes);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/CIDMapOffset 0 def\n", 20);
+ if (dict.paintType != 0) {
+ sprintf(buf, "/PaintType %d def\n", dict.paintType);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+
+ // FDArray entry
+ sprintf(buf, "/FDArray %d array\n", nFDs);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ for (i = 0; i < nFDs; ++i) {
+ sprintf(buf, "dup %d 10 dict begin\n", i);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ sprintf(buf, "/PaintType %d def\n", dict.paintType);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/Private 32 dict begin\n", 23);
+ (*outputFunc)(outputStream, privateDicts[i].dictData->getCString(),
+ privateDicts[i].dictData->getLength());
+ (*outputFunc)(outputStream, "currentdict end def\n", 20);
+ (*outputFunc)(outputStream, "currentdict end put\n", 20);
+ }
+ (*outputFunc)(outputStream, "def\n", 4);
+
+ //~ need to deal with subrs
+
+ // start the binary section
+ offset = (nCIDs + 1) * (1 + gdBytes);
+ sprintf(buf, "(Hex) %d StartData\n",
+ offset + charStrings->getLength());
+ (*outputFunc)(outputStream, buf, strlen(buf));
+
+ // write the charstring offset (CIDMap) table
+ for (i = 0; i <= nCIDs; i += 6) {
+ for (j = 0; j < 6 && i+j <= nCIDs; ++j) {
+ if (i+j < nCIDs && cidMap[i+j] >= 0) {
+ buf[0] = (char)fdSelect[cidMap[i+j]];
+ } else {
+ buf[0] = (char)0;
+ }
+ n = offset + charStringOffsets[i+j];
+ for (k = gdBytes; k >= 1; --k) {
+ buf[k] = (char)(n & 0xff);
+ n >>= 8;
+ }
+ for (k = 0; k <= gdBytes; ++k) {
+ sprintf(buf2, "%02x", buf[k] & 0xff);
+ (*outputFunc)(outputStream, buf2, 2);
+ }
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+
+ // write the charstring data
+ n = charStrings->getLength();
+ for (i = 0; i < n; i += 32) {
+ for (j = 0; j < 32 && i+j < n; ++j) {
+ sprintf(buf, "%02x", charStrings->getChar(i+j) & 0xff);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ if (i + 32 >= n) {
+ (*outputFunc)(outputStream, ">", 1);
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+
+ for (i = 0; i < nFDs; ++i) {
+ delete privateDicts[i].dictData;
+ }
+ gfree(privateDicts);
+ gfree(cidMap);
+ gfree(charset);
+ gfree(charStringOffsets);
+ delete charStrings;
+ gfree(fdSelect);
+}
+
+void Type1CFontFile::convertToType0(const char *psName,
+ FontFileOutputFunc outputFuncA,
+ void *outputStreamA) {
+ Type1CTopDict dict;
+ Type1CPrivateDict *privateDicts;
+ Gushort *charset;
+ int *cidMap;
+ Guchar *fdSelect;
+ Guchar *charStringsIdxPtr, *fdArrayIdx, *idxPtr0, *idxPtr1, *ptr;
+ char buf[512];
+ char eBuf[256];
+ int nGlyphs, nCIDs, nFDs;
+ int fdSelectFmt, nRanges, gid0, gid1, fd;
+ int key;
+ double x;
+ GBool isFP;
+ int i, j, n;
+
+ outputFunc = outputFuncA;
+ outputStream = outputStreamA;
+
+ // read top dict (first font only)
+ readTopDict(&dict);
+
+ // read the FDArray dictionaries and Private dictionaries
+ if (dict.fdArrayOffset == 0) {
+ nFDs = 1;
+ privateDicts = (Type1CPrivateDict *)
+ gmalloc(nFDs * sizeof(Type1CPrivateDict));
+ privateDicts[0].dictData = new GString();
+ privateDicts[0].subrsOffset = 0;
+ privateDicts[0].defaultWidthX = 0;
+ privateDicts[0].defaultWidthXFP = gFalse;
+ privateDicts[0].nominalWidthX = 0;
+ privateDicts[0].nominalWidthXFP = gFalse;
+ } else {
+ fdArrayIdx = (Guchar *)file + dict.fdArrayOffset;
+ nFDs = getIndexLen(fdArrayIdx);
+ privateDicts = (Type1CPrivateDict *)
+ gmalloc(nFDs * sizeof(Type1CPrivateDict));
+ idxPtr1 = getIndexValPtr(fdArrayIdx, 0);
+ for (i = 0; i < nFDs; ++i) {
+ privateDicts[i].dictData = NULL;
+ idxPtr0 = idxPtr1;
+ idxPtr1 = getIndexValPtr(fdArrayIdx, i + 1);
+ ptr = idxPtr0;
+ j = 0;
+ while (ptr < idxPtr1) {
+ if (*ptr <= 27 || *ptr == 31) {
+ key = *ptr++;
+ if (key == 0x0c) {
+ key = (key << 8) | *ptr++;
+ }
+ if (key == 0x0012) {
+ readPrivateDict(&privateDicts[i], (int)op[1], (int)op[0]);
+ }
+ j = 0;
+ } else {
+ x = getNum(&ptr, &isFP);
+ if (j < 48) {
+ op[j] = x;
+ fp[j++] = isFP;
+ }
+ }
+ }
+ if (!privateDicts[i].dictData) {
+ privateDicts[i].dictData = new GString();
+ privateDicts[i].subrsOffset = 0;
+ privateDicts[i].defaultWidthX = 0;
+ privateDicts[i].defaultWidthXFP = gFalse;
+ privateDicts[i].nominalWidthX = 0;
+ privateDicts[i].nominalWidthXFP = gFalse;
+ }
+ }
+ }
+
+ // get the glyph count
+ charStringsIdxPtr = (Guchar *)file + dict.charStrings;
+ nGlyphs = getIndexLen(charStringsIdxPtr);
+
+ // read the FDSelect table
+ fdSelect = (Guchar *)gmalloc(nGlyphs);
+ if (dict.fdSelectOffset == 0) {
+ for (i = 0; i < nGlyphs; ++i) {
+ fdSelect[i] = 0;
+ }
+ } else {
+ ptr = (Guchar *)file + dict.fdSelectOffset;
+ fdSelectFmt = *ptr++;
+ if (fdSelectFmt == 0) {
+ memcpy(fdSelect, ptr, nGlyphs);
+ } else if (fdSelectFmt == 3) {
+ nRanges = getWord(ptr, 2);
+ ptr += 2;
+ gid0 = getWord(ptr, 2);
+ ptr += 2;
+ for (i = 1; i <= nRanges; ++i) {
+ fd = *ptr++;
+ gid1 = getWord(ptr, 2);
+ ptr += 2;
+ for (j = gid0; j < gid1; ++j) {
+ fdSelect[j] = fd;
+ }
+ gid0 = gid1;
+ }
+ } else {
+ error(-1, "Unknown FDSelect table format in CID font");
+ for (i = 0; i < nGlyphs; ++i) {
+ fdSelect[i] = 0;
+ }
+ }
+ }
+
+ // read the charset, compute the CID-to-GID mapping
+ charset = readCharset(dict.charset, nGlyphs);
+ nCIDs = 0;
+ for (i = 0; i < nGlyphs; ++i) {
+ if (charset[i] >= nCIDs) {
+ nCIDs = charset[i] + 1;
+ }
+ }
+ cidMap = (int *)gmalloc(nCIDs * sizeof(int));
+ for (i = 0; i < nCIDs; ++i) {
+ cidMap[i] = -1;
+ }
+ for (i = 0; i < nGlyphs; ++i) {
+ cidMap[charset[i]] = i;
+ }
+
+ // write the descendant Type 1 fonts
+ for (i = 0; i < nCIDs; i += 256) {
+
+ //~ this assumes that all CIDs in this block have the same FD --
+ //~ to handle multiple FDs correctly, need to somehow divide the
+ //~ font up by FD
+ fd = 0;
+ for (j = 0; j < 256 && i+j < nCIDs; ++j) {
+ if (cidMap[i+j] >= 0) {
+ fd = fdSelect[cidMap[i+j]];
+ break;
+ }
+ }
+
+ // font dictionary (unencrypted section)
+ (*outputFunc)(outputStream, "16 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, psName, strlen(psName));
+ sprintf(buf, "_%02x def\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FontType 1 def\n", 16);
+ sprintf(buf, "/FontMatrix [%g %g %g %g %g %g] def\n",
+ dict.fontMatrix[0], dict.fontMatrix[1], dict.fontMatrix[2],
+ dict.fontMatrix[3], dict.fontMatrix[4], dict.fontMatrix[5]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/FontBBox [%g %g %g %g] def\n",
+ dict.fontBBox[0], dict.fontBBox[1],
+ dict.fontBBox[2], dict.fontBBox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, "/PaintType %d def\n", dict.paintType);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ if (dict.paintType != 0) {
+ sprintf(buf, "/StrokeWidth %g def\n", dict.strokeWidth);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
+ for (j = 0; j < 256 && i+j < nCIDs; ++j) {
+ sprintf(buf, "dup %d /c%02x put\n", j, j);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "readonly def\n", 13);
+ (*outputFunc)(outputStream, "currentdict end\n", 16);
+
+ // start the binary section
+ (*outputFunc)(outputStream, "currentfile eexec\n", 18);
+ r1 = 55665;
+ line = 0;
+
+ // start the private dictionary
+ eexecWrite("\x83\xca\x73\xd5");
+ eexecWrite("dup /Private 32 dict dup begin\n");
+ eexecWrite("/RD {string currentfile exch readstring pop} executeonly def\n");
+ eexecWrite("/ND {noaccess def} executeonly def\n");
+ eexecWrite("/NP {noaccess put} executeonly def\n");
+ eexecWrite("/MinFeature {16 16} ND\n");
+ eexecWrite(privateDicts[fd].dictData->getCString());
+ defaultWidthX = privateDicts[fd].defaultWidthX;
+ defaultWidthXFP = privateDicts[fd].defaultWidthXFP;
+ nominalWidthX = privateDicts[fd].nominalWidthX;
+ nominalWidthXFP = privateDicts[fd].nominalWidthXFP;
+
+ // start the CharStrings
+ sprintf(eBuf, "2 index /CharStrings 256 dict dup begin\n");
+ eexecWrite(eBuf);
+
+ // write the .notdef CharString
+ idxPtr0 = getIndexValPtr(charStringsIdxPtr, 0);
+ idxPtr1 = getIndexValPtr(charStringsIdxPtr, 1);
+ n = idxPtr1 - idxPtr0;
+ eexecCvtGlyph(".notdef", idxPtr0, n);
+
+ // write the CharStrings
+ for (j = 0; j < 256 && i+j < nCIDs; ++j) {
+ if (cidMap[i+j] >= 0) {
+ idxPtr0 = getIndexValPtr(charStringsIdxPtr, cidMap[i+j]);
+ idxPtr1 = getIndexValPtr(charStringsIdxPtr, cidMap[i+j]+1);
+ n = idxPtr1 - idxPtr0;
+ sprintf(buf, "c%02x", j);
+ eexecCvtGlyph(buf, idxPtr0, n);
+ }
+ }
+ eexecWrite("end\n");
+ eexecWrite("end\n");
+ eexecWrite("readonly put\n");
+ eexecWrite("noaccess put\n");
+ eexecWrite("dup /FontName get exch definefont pop\n");
+ eexecWrite("mark currentfile closefile\n");
+
+ // trailer
+ if (line > 0) {
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+ for (j = 0; j < 8; ++j) {
+ (*outputFunc)(outputStream, "0000000000000000000000000000000000000000000000000000000000000000\n", 65);
+ }
+ (*outputFunc)(outputStream, "cleartomark\n", 12);
+ }
+
+ // write the Type 0 parent font
+ (*outputFunc)(outputStream, "16 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, psName, strlen(psName));
+ (*outputFunc)(outputStream, " def\n", 5);
+ (*outputFunc)(outputStream, "/FontType 0 def\n", 16);
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ (*outputFunc)(outputStream, "/FMapType 2 def\n", 16);
+ (*outputFunc)(outputStream, "/Encoding [\n", 12);
+ for (i = 0; i < nCIDs; i += 256) {
+ sprintf(buf, "%d\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "] def\n", 6);
+ (*outputFunc)(outputStream, "/FDepVector [\n", 14);
+ for (i = 0; i < nCIDs; i += 256) {
+ (*outputFunc)(outputStream, "/", 1);
+ (*outputFunc)(outputStream, psName, strlen(psName));
+ sprintf(buf, "_%02x findfont\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "] def\n", 6);
+ (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
+
+ // clean up
+ for (i = 0; i < nFDs; ++i) {
+ delete privateDicts[i].dictData;
+ }
+ gfree(privateDicts);
+ gfree(cidMap);
+ gfree(charset);
+ gfree(fdSelect);
+}
+
+void Type1CFontFile::readTopDict(Type1CTopDict *dict) {
+ Guchar *idxPtr0, *idxPtr1, *ptr;
+ double x;
+ GBool isFP;
+ int key;
+ int i;
+
+ idxPtr0 = getIndexValPtr(topDictIdxPtr, 0);
+ idxPtr1 = getIndexValPtr(topDictIdxPtr, 1);
+ dict->version = 0;
+ dict->notice = 0;
+ dict->copyright = 0;
+ dict->fullName = 0;
+ dict->familyName = 0;
+ dict->weight = 0;
+ dict->isFixedPitch = 0;
+ dict->italicAngle = 0;
+ dict->underlinePosition = -100;
+ dict->underlineThickness = 50;
+ dict->paintType = 0;
+ dict->charstringType = 2;
+ dict->fontMatrix[0] = 0.001;
+ dict->fontMatrix[1] = 0;
+ dict->fontMatrix[2] = 0;
+ dict->fontMatrix[3] = 0.001;
+ dict->fontMatrix[4] = 0;
+ dict->fontMatrix[5] = 0;
+ dict->uniqueID = 0;
+ dict->fontBBox[0] = 0;
+ dict->fontBBox[1] = 0;
+ dict->fontBBox[2] = 0;
+ dict->fontBBox[3] = 0;
+ dict->strokeWidth = 0;
+ dict->charset = 0;
+ dict->encoding = 0;
+ dict->charStrings = 0;
+ dict->privateSize = 0;
+ dict->privateOffset = 0;
+ dict->registry = 0;
+ dict->ordering = 0;
+ dict->supplement = 0;
+ dict->fdArrayOffset = 0;
+ dict->fdSelectOffset = 0;
+ i = 0;
+ ptr = idxPtr0;
+ while (ptr < idxPtr1) {
+ if (*ptr <= 27 || *ptr == 31) {
+ key = *ptr++;
+ if (key == 0x0c) {
+ key = (key << 8) | *ptr++;
+ }
+ switch (key) {
+ case 0x0000: dict->version = (int)op[0]; break;
+ case 0x0001: dict->notice = (int)op[0]; break;
+ case 0x0c00: dict->copyright = (int)op[0]; break;
+ case 0x0002: dict->fullName = (int)op[0]; break;
+ case 0x0003: dict->familyName = (int)op[0]; break;
+ case 0x0004: dict->weight = (int)op[0]; break;
+ case 0x0c01: dict->isFixedPitch = (int)op[0]; break;
+ case 0x0c02: dict->italicAngle = op[0]; break;
+ case 0x0c03: dict->underlinePosition = op[0]; break;
+ case 0x0c04: dict->underlineThickness = op[0]; break;
+ case 0x0c05: dict->paintType = (int)op[0]; break;
+ case 0x0c06: dict->charstringType = (int)op[0]; break;
+ case 0x0c07: dict->fontMatrix[0] = op[0];
+ dict->fontMatrix[1] = op[1];
+ dict->fontMatrix[2] = op[2];
+ dict->fontMatrix[3] = op[3];
+ dict->fontMatrix[4] = op[4];
+ dict->fontMatrix[5] = op[5]; break;
+ case 0x000d: dict->uniqueID = (int)op[0]; break;
+ case 0x0005: dict->fontBBox[0] = op[0];
+ dict->fontBBox[1] = op[1];
+ dict->fontBBox[2] = op[2];
+ dict->fontBBox[3] = op[3]; break;
+ case 0x0c08: dict->strokeWidth = op[0]; break;
+ case 0x000f: dict->charset = (int)op[0]; break;
+ case 0x0010: dict->encoding = (int)op[0]; break;
+ case 0x0011: dict->charStrings = (int)op[0]; break;
+ case 0x0012: dict->privateSize = (int)op[0];
+ dict->privateOffset = (int)op[1]; break;
+ case 0x0c1e: dict->registry = (int)op[0];
+ dict->ordering = (int)op[1];
+ dict->supplement = (int)op[2]; break;
+ case 0x0c24: dict->fdArrayOffset = (int)op[0]; break;
+ case 0x0c25: dict->fdSelectOffset = (int)op[0]; break;
+ }
+ i = 0;
+ } else {
+ x = getNum(&ptr, &isFP);
+ if (i < 48) {
+ op[i] = x;
+ fp[i++] = isFP;
+ }
+ }
+ }
+}
+
+void Type1CFontFile::readPrivateDict(Type1CPrivateDict *privateDict,
+ int offset, int size) {
+ Guchar *idxPtr0, *idxPtr1, *ptr;
+ char eBuf[256];
+ int key;
+ double x;
+ GBool isFP;
+ int i;
+
+ privateDict->dictData = new GString();
+ privateDict->subrsOffset = 0;
+ privateDict->defaultWidthX = 0;
+ privateDict->defaultWidthXFP = gFalse;
+ privateDict->nominalWidthX = 0;
+ privateDict->nominalWidthXFP = gFalse;
+ idxPtr0 = (Guchar *)file + offset;
+ idxPtr1 = idxPtr0 + size;
+ ptr = idxPtr0;
+ i = 0;
+ while (ptr < idxPtr1) {
+ if (*ptr <= 27 || *ptr == 31) {
+ key = *ptr++;
+ if (key == 0x0c) {
+ key = (key << 8) | *ptr++;
+ }
+ switch (key) {
+ case 0x0006:
+ getDeltaInt(eBuf, "BlueValues", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0007:
+ getDeltaInt(eBuf, "OtherBlues", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0008:
+ getDeltaInt(eBuf, "FamilyBlues", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0009:
+ getDeltaInt(eBuf, "FamilyOtherBlues", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c09:
+ sprintf(eBuf, "/BlueScale %g def\n", op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0a:
+ sprintf(eBuf, "/BlueShift %d def\n", (int)op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0b:
+ sprintf(eBuf, "/BlueFuzz %d def\n", (int)op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x000a:
+ sprintf(eBuf, "/StdHW [%g] def\n", op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x000b:
+ sprintf(eBuf, "/StdVW [%g] def\n", op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0c:
+ getDeltaReal(eBuf, "StemSnapH", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0d:
+ getDeltaReal(eBuf, "StemSnapV", op, i);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0e:
+ sprintf(eBuf, "/ForceBold %s def\n", op[0] ? "true" : "false");
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c0f:
+ sprintf(eBuf, "/ForceBoldThreshold %g def\n", op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c11:
+ sprintf(eBuf, "/LanguageGroup %d def\n", (int)op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c12:
+ sprintf(eBuf, "/ExpansionFactor %g def\n", op[0]);
+ privateDict->dictData->append(eBuf);
+ break;
+ case 0x0c13:
+ error(-1, "Got Type 1C InitialRandomSeed");
+ break;
+ case 0x0013:
+ privateDict->subrsOffset = (int)op[0];
+ break;
+ case 0x0014:
+ privateDict->defaultWidthX = op[0];
+ privateDict->defaultWidthXFP = fp[0];
+ break;
+ case 0x0015:
+ privateDict->nominalWidthX = op[0];
+ privateDict->nominalWidthXFP = fp[0];
+ break;
+ default:
+ error(-1, "Unknown Type 1C private dict entry %04x", key);
+ break;
+ }
+ i = 0;
+ } else {
+ x = getNum(&ptr, &isFP);
+ if (i < 48) {
+ op[i] = x;
+ fp[i++] = isFP;
+ }
+ }
+ }
+}
+
+Gushort *Type1CFontFile::readCharset(int charset, int nGlyphs) {
+ Gushort *glyphNames;
+ Guchar *ptr;
+ int charsetFormat, c;
+ int nLeft, i, j;
+
+ if (charset == 0) {
+ glyphNames = type1CISOAdobeCharset;
+ } else if (charset == 1) {
+ glyphNames = type1CExpertCharset;
+ } else if (charset == 2) {
+ glyphNames = type1CExpertSubsetCharset;
+ } else {
+ glyphNames = (Gushort *)gmalloc(nGlyphs * sizeof(Gushort));
+ glyphNames[0] = 0;
+ ptr = (Guchar *)file + charset;
+ charsetFormat = *ptr++;
+ if (charsetFormat == 0) {
+ for (i = 1; i < nGlyphs; ++i) {
+ glyphNames[i] = getWord(ptr, 2);
+ ptr += 2;
+ }
+ } else if (charsetFormat == 1) {
+ i = 1;
+ while (i < nGlyphs) {
+ c = getWord(ptr, 2);
+ ptr += 2;
+ nLeft = *ptr++;
+ for (j = 0; j <= nLeft && i < nGlyphs; ++j) {
+ glyphNames[i++] = c++;
+ }
+ }
+ } else if (charsetFormat == 2) {
+ i = 1;
+ while (i < nGlyphs) {
+ c = getWord(ptr, 2);
+ ptr += 2;
+ nLeft = getWord(ptr, 2);
+ ptr += 2;
+ for (j = 0; j <= nLeft && i < nGlyphs; ++j) {
+ glyphNames[i++] = c++;
+ }
+ }
+ }
+ }
+ return glyphNames;
+}
+
+void Type1CFontFile::eexecWrite(const char *s) {
+ const Guchar *p;
+ Guchar x;
+
+ for (p = (const Guchar *)s; *p; ++p) {
+ x = *p ^ (r1 >> 8);
+ r1 = (x + r1) * 52845 + 22719;
+ (*outputFunc)(outputStream, &hexChars[x >> 4], 1);
+ (*outputFunc)(outputStream, &hexChars[x & 0x0f], 1);
+ line += 2;
+ if (line == 64) {
+ (*outputFunc)(outputStream, "\n", 1);
+ line = 0;
+ }
+ }
+}
+
+void Type1CFontFile::eexecCvtGlyph(const char *glyphName, const Guchar *s, int n) {
+ char eBuf[256];
+
+ cvtGlyph(s, n);
+ sprintf(eBuf, "/%s %d RD ", glyphName, charBuf->getLength());
+ eexecWrite(eBuf);
+ eexecWriteCharstring((Guchar *)charBuf->getCString(), charBuf->getLength());
+ eexecWrite(" ND\n");
+ delete charBuf;
+}
+
+void Type1CFontFile::cvtGlyph(const Guchar *s, int n) {
+ int nHints;
+ int x;
+ GBool first = gTrue;
+ double d, dx, dy;
+ GBool dFP;
+ Gushort r2;
+ Guchar byte;
+ int i, k;
+
+ charBuf = new GString();
+ charBuf->append((char)73);
+ charBuf->append((char)58);
+ charBuf->append((char)147);
+ charBuf->append((char)134);
+
+ i = 0;
+ nOps = 0;
+ nHints = 0;
+ while (i < n) {
+ if (s[i] == 12) {
+ switch (s[i+1]) {
+ case 0: // dotsection (should be Type 1 only?)
+ // ignored
+ break;
+ case 34: // hflex
+ if (nOps != 7) {
+ error(-1, "Wrong number of args (%d) to Type 2 hflex", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpOp1(8);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[5], fp[5]);
+ eexecDumpNum(-op[2], fp[2]);
+ eexecDumpNum(op[6], fp[6]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpOp1(8);
+ break;
+ case 35: // flex
+ if (nOps != 13) {
+ error(-1, "Wrong number of args (%d) to Type 2 flex", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpNum(op[5], fp[5]);
+ eexecDumpOp1(8);
+ eexecDumpNum(op[6], fp[6]);
+ eexecDumpNum(op[7], fp[7]);
+ eexecDumpNum(op[8], fp[8]);
+ eexecDumpNum(op[9], fp[9]);
+ eexecDumpNum(op[10], fp[10]);
+ eexecDumpNum(op[11], fp[11]);
+ eexecDumpOp1(8);
+ break;
+ case 36: // hflex1
+ if (nOps != 9) {
+ error(-1, "Wrong number of args (%d) to Type 2 hflex1", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpOp1(8);
+ eexecDumpNum(op[5], fp[5]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[6], fp[6]);
+ eexecDumpNum(op[7], fp[7]);
+ eexecDumpNum(op[8], fp[8]);
+ eexecDumpNum(-(op[1] + op[3] + op[7]), fp[1] | fp[3] | fp[7]);
+ eexecDumpOp1(8);
+ break;
+ case 37: // flex1
+ if (nOps != 11) {
+ error(-1, "Wrong number of args (%d) to Type 2 flex1", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpNum(op[5], fp[5]);
+ eexecDumpOp1(8);
+ eexecDumpNum(op[6], fp[6]);
+ eexecDumpNum(op[7], fp[7]);
+ eexecDumpNum(op[8], fp[8]);
+ eexecDumpNum(op[9], fp[9]);
+ dx = op[0] + op[2] + op[4] + op[6] + op[8];
+ dy = op[1] + op[3] + op[5] + op[7] + op[9];
+ if (fabs(dx) > fabs(dy)) {
+ eexecDumpNum(op[10], fp[10]);
+ eexecDumpNum(-dy, fp[1] | fp[3] | fp[5] | fp[7] | fp[9]);
+ } else {
+ eexecDumpNum(-dx, fp[0] | fp[2] | fp[4] | fp[6] | fp[8]);
+ eexecDumpNum(op[10], fp[10]);
+ }
+ eexecDumpOp1(8);
+ break;
+ case 3: // and
+ case 4: // or
+ case 5: // not
+ case 8: // store
+ case 9: // abs
+ case 10: // add
+ case 11: // sub
+ case 12: // div
+ case 13: // load
+ case 14: // neg
+ case 15: // eq
+ case 18: // drop
+ case 20: // put
+ case 21: // get
+ case 22: // ifelse
+ case 23: // random
+ case 24: // mul
+ case 26: // sqrt
+ case 27: // dup
+ case 28: // exch
+ case 29: // index
+ case 30: // roll
+ error(-1, "Unimplemented Type 2 charstring op: 12.%d", s[i+1]);
+ break;
+ default:
+ error(-1, "Illegal Type 2 charstring op: 12.%d", s[i+1]);
+ break;
+ }
+ i += 2;
+ nOps = 0;
+ } else if (s[i] == 19) { // hintmask
+ // ignored
+ if (first) {
+ cvtGlyphWidth(nOps == 1);
+ first = gFalse;
+ }
+ if (nOps > 0) {
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 hintmask/vstemhm",
+ nOps);
+ }
+ nHints += nOps / 2;
+ }
+ i += 1 + ((nHints + 7) >> 3);
+ nOps = 0;
+ } else if (s[i] == 20) { // cntrmask
+ // ignored
+ if (first) {
+ cvtGlyphWidth(nOps == 1);
+ first = gFalse;
+ }
+ if (nOps > 0) {
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 cntrmask/vstemhm",
+ nOps);
+ }
+ nHints += nOps / 2;
+ }
+ i += 1 + ((nHints + 7) >> 3);
+ nOps = 0;
+ } else if (s[i] == 28) {
+ x = (s[i+1] << 8) + s[i+2];
+ if (x & 0x8000) {
+ x |= -1 << 15;
+ }
+ if (nOps < 48) {
+ fp[nOps] = gFalse;
+ op[nOps++] = x;
+ }
+ i += 3;
+ } else if (s[i] <= 31) {
+ switch (s[i]) {
+ case 4: // vmoveto
+ if (first) {
+ cvtGlyphWidth(nOps == 2);
+ first = gFalse;
+ }
+ if (nOps != 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 vmoveto", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpOp1(4);
+ break;
+ case 5: // rlineto
+ if (nOps < 2 || nOps % 2 != 0) {
+ error(-1, "Wrong number of args (%d) to Type 2 rlineto", nOps);
+ }
+ for (k = 0; k < nOps; k += 2) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpOp1(5);
+ }
+ break;
+ case 6: // hlineto
+ if (nOps < 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 hlineto", nOps);
+ }
+ for (k = 0; k < nOps; ++k) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpOp1((k & 1) ? 7 : 6);
+ }
+ break;
+ case 7: // vlineto
+ if (nOps < 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 vlineto", nOps);
+ }
+ for (k = 0; k < nOps; ++k) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpOp1((k & 1) ? 6 : 7);
+ }
+ break;
+ case 8: // rrcurveto
+ if (nOps < 6 || nOps % 6 != 0) {
+ error(-1, "Wrong number of args (%d) to Type 2 rrcurveto", nOps);
+ }
+ for (k = 0; k < nOps; k += 6) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ eexecDumpNum(op[k+5], fp[k+5]);
+ eexecDumpOp1(8);
+ }
+ break;
+ case 14: // endchar / seac
+ if (first) {
+ cvtGlyphWidth(nOps == 1 || nOps == 5);
+ first = gFalse;
+ }
+ if (nOps == 4) {
+ eexecDumpNum(0, 0);
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpOp2(6);
+ } else if (nOps == 0) {
+ eexecDumpOp1(14);
+ } else {
+ error(-1, "Wrong number of args (%d) to Type 2 endchar", nOps);
+ }
+ break;
+ case 21: // rmoveto
+ if (first) {
+ cvtGlyphWidth(nOps == 3);
+ first = gFalse;
+ }
+ if (nOps != 2) {
+ error(-1, "Wrong number of args (%d) to Type 2 rmoveto", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpOp1(21);
+ break;
+ case 22: // hmoveto
+ if (first) {
+ cvtGlyphWidth(nOps == 2);
+ first = gFalse;
+ }
+ if (nOps != 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 hmoveto", nOps);
+ }
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpOp1(22);
+ break;
+ case 24: // rcurveline
+ if (nOps < 8 || (nOps - 2) % 6 != 0) {
+ error(-1, "Wrong number of args (%d) to Type 2 rcurveline", nOps);
+ }
+ for (k = 0; k < nOps - 2; k += 6) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ eexecDumpNum(op[k+5], fp[k+5]);
+ eexecDumpOp1(8);
+ }
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k]);
+ eexecDumpOp1(5);
+ break;
+ case 25: // rlinecurve
+ if (nOps < 8 || (nOps - 6) % 2 != 0) {
+ error(-1, "Wrong number of args (%d) to Type 2 rlinecurve", nOps);
+ }
+ for (k = 0; k < nOps - 6; k += 2) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k]);
+ eexecDumpOp1(5);
+ }
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ eexecDumpNum(op[k+5], fp[k+5]);
+ eexecDumpOp1(8);
+ break;
+ case 26: // vvcurveto
+ if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
+ error(-1, "Wrong number of args (%d) to Type 2 vvcurveto", nOps);
+ }
+ if (nOps % 2 == 1) {
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpOp1(8);
+ k = 5;
+ } else {
+ k = 0;
+ }
+ for (; k < nOps; k += 4) {
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpOp1(8);
+ }
+ break;
+ case 27: // hhcurveto
+ if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
+ error(-1, "Wrong number of args (%d) to Type 2 hhcurveto", nOps);
+ }
+ if (nOps % 2 == 1) {
+ eexecDumpNum(op[1], fp[1]);
+ eexecDumpNum(op[0], fp[0]);
+ eexecDumpNum(op[2], fp[2]);
+ eexecDumpNum(op[3], fp[3]);
+ eexecDumpNum(op[4], fp[4]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpOp1(8);
+ k = 5;
+ } else {
+ k = 0;
+ }
+ for (; k < nOps; k += 4) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpOp1(8);
+ }
+ break;
+ case 30: // vhcurveto
+ if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
+ error(-1, "Wrong number of args (%d) to Type 2 vhcurveto", nOps);
+ }
+ for (k = 0; k < nOps && k != nOps-5; k += 4) {
+ if (k % 8 == 0) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpOp1(30);
+ } else {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpOp1(31);
+ }
+ }
+ if (k == nOps-5) {
+ if (k % 8 == 0) {
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ } else {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ }
+ eexecDumpOp1(8);
+ }
+ break;
+ case 31: // hvcurveto
+ if (nOps < 4 || !(nOps % 4 == 0 || (nOps-1) % 4 == 0)) {
+ error(-1, "Wrong number of args (%d) to Type 2 hvcurveto", nOps);
+ }
+ for (k = 0; k < nOps && k != nOps-5; k += 4) {
+ if (k % 8 == 0) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpOp1(31);
+ } else {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpOp1(30);
+ }
+ }
+ if (k == nOps-5) {
+ if (k % 8 == 0) {
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ } else {
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(op[k], fp[k]);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ eexecDumpNum(op[k+2], fp[k+2]);
+ eexecDumpNum(op[k+3], fp[k+3]);
+ eexecDumpNum(op[k+4], fp[k+4]);
+ }
+ eexecDumpOp1(8);
+ }
+ break;
+ case 1: // hstem
+ if (first) {
+ cvtGlyphWidth(nOps & 1);
+ first = gFalse;
+ }
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 hstem", nOps);
+ }
+ d = 0;
+ dFP = gFalse;
+ for (k = 0; k < nOps; k += 2) {
+ if (op[k+1] < 0) {
+ d += op[k] + op[k+1];
+ dFP |= fp[k] | fp[k+1];
+ eexecDumpNum(d, dFP);
+ eexecDumpNum(-op[k+1], fp[k+1]);
+ } else {
+ d += op[k];
+ dFP |= fp[k];
+ eexecDumpNum(d, dFP);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ d += op[k+1];
+ dFP |= fp[k+1];
+ }
+ eexecDumpOp1(1);
+ }
+ nHints += nOps / 2;
+ break;
+ case 3: // vstem
+ if (first) {
+ cvtGlyphWidth(nOps & 1);
+ first = gFalse;
+ }
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 vstem", nOps);
+ }
+ d = 0;
+ dFP = gFalse;
+ for (k = 0; k < nOps; k += 2) {
+ if (op[k+1] < 0) {
+ d += op[k] + op[k+1];
+ dFP |= fp[k] | fp[k+1];
+ eexecDumpNum(d, dFP);
+ eexecDumpNum(-op[k+1], fp[k+1]);
+ } else {
+ d += op[k];
+ dFP |= fp[k];
+ eexecDumpNum(d, dFP);
+ eexecDumpNum(op[k+1], fp[k+1]);
+ d += op[k+1];
+ dFP |= fp[k+1];
+ }
+ eexecDumpOp1(3);
+ }
+ nHints += nOps / 2;
+ break;
+ case 18: // hstemhm
+ // ignored
+ if (first) {
+ cvtGlyphWidth(nOps & 1);
+ first = gFalse;
+ }
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 hstemhm", nOps);
+ }
+ nHints += nOps / 2;
+ break;
+ case 23: // vstemhm
+ // ignored
+ if (first) {
+ cvtGlyphWidth(nOps & 1);
+ first = gFalse;
+ }
+ if (nOps & 1) {
+ error(-1, "Wrong number of args (%d) to Type 2 vstemhm", nOps);
+ }
+ nHints += nOps / 2;
+ break;
+ case 10: // callsubr
+ case 11: // return
+ case 16: // blend
+ case 29: // callgsubr
+ error(-1, "Unimplemented Type 2 charstring op: %d", s[i]);
+ break;
+ default:
+ error(-1, "Illegal Type 2 charstring op: %d", s[i]);
+ break;
+ }
+ ++i;
+ nOps = 0;
+ } else if (s[i] <= 246) {
+ if (nOps < 48) {
+ fp[nOps] = gFalse;
+ op[nOps++] = (int)s[i] - 139;
+ }
+ ++i;
+ } else if (s[i] <= 250) {
+ if (nOps < 48) {
+ fp[nOps] = gFalse;
+ op[nOps++] = (((int)s[i] - 247) << 8) + (int)s[i+1] + 108;
+ }
+ i += 2;
+ } else if (s[i] <= 254) {
+ if (nOps < 48) {
+ fp[nOps] = gFalse;
+ op[nOps++] = -(((int)s[i] - 251) << 8) - (int)s[i+1] - 108;
+ }
+ i += 2;
+ } else {
+ x = (s[i+1] << 24) | (s[i+2] << 16) | (s[i+3] << 8) | s[i+4];
+ if (x & 0x80000000)
+ x |= -1 << 31;
+ if (nOps < 48) {
+ fp[nOps] = gTrue;
+ op[nOps++] = (double)x / 65536.0;
+ }
+ i += 5;
+ }
+ }
+
+ // charstring encryption
+ r2 = 4330;
+ for (i = 0; i < charBuf->getLength(); ++i) {
+ byte = charBuf->getChar(i) ^ (r2 >> 8);
+ charBuf->setChar(i, byte);
+ r2 = (byte + r2) * 52845 + 22719;
+ }
+}
+
+void Type1CFontFile::cvtGlyphWidth(GBool useOp) {
+ double w;
+ GBool wFP;
+ int i;
+
+ if (useOp) {
+ w = nominalWidthX + op[0];
+ wFP = nominalWidthXFP | fp[0];
+ for (i = 1; i < nOps; ++i) {
+ op[i-1] = op[i];
+ fp[i-1] = fp[i];
+ }
+ --nOps;
+ } else {
+ w = defaultWidthX;
+ wFP = defaultWidthXFP;
+ }
+ eexecDumpNum(0, gFalse);
+ eexecDumpNum(w, wFP);
+ eexecDumpOp1(13);
+}
+
+void Type1CFontFile::eexecDumpNum(double x, GBool fpA) {
+ Guchar buf[12];
+ int y, n;
+
+ n = 0;
+ if (fpA) {
+ if (x >= -32768 && x < 32768) {
+ y = (int)(x * 256.0);
+ buf[0] = 255;
+ buf[1] = (Guchar)(y >> 24);
+ buf[2] = (Guchar)(y >> 16);
+ buf[3] = (Guchar)(y >> 8);
+ buf[4] = (Guchar)y;
+ buf[5] = 255;
+ buf[6] = 0;
+ buf[7] = 0;
+ buf[8] = 1;
+ buf[9] = 0;
+ buf[10] = 12;
+ buf[11] = 12;
+ n = 12;
+ } else {
+ error(-1, "Type 2 fixed point constant out of range");
+ }
+ } else {
+ y = (int)x;
+ if (y >= -107 && y <= 107) {
+ buf[0] = (Guchar)(y + 139);
+ n = 1;
+ } else if (y > 107 && y <= 1131) {
+ y -= 108;
+ buf[0] = (Guchar)((y >> 8) + 247);
+ buf[1] = (Guchar)(y & 0xff);
+ n = 2;
+ } else if (y < -107 && y >= -1131) {
+ y = -y - 108;
+ buf[0] = (Guchar)((y >> 8) + 251);
+ buf[1] = (Guchar)(y & 0xff);
+ n = 2;
+ } else {
+ buf[0] = 255;
+ buf[1] = (Guchar)(y >> 24);
+ buf[2] = (Guchar)(y >> 16);
+ buf[3] = (Guchar)(y >> 8);
+ buf[4] = (Guchar)y;
+ n = 5;
+ }
+ }
+ charBuf->append((char *)buf, n);
+}
+
+void Type1CFontFile::eexecDumpOp1(int opA) {
+ charBuf->append((char)opA);
+}
+
+void Type1CFontFile::eexecDumpOp2(int opA) {
+ charBuf->append((char)12);
+ charBuf->append((char)opA);
+}
+
+void Type1CFontFile::eexecWriteCharstring(const Guchar *s, int n) {
+ Guchar x;
+ int i;
+
+ // eexec encryption
+ for (i = 0; i < n; ++i) {
+ x = s[i] ^ (r1 >> 8);
+ r1 = (x + r1) * 52845 + 22719;
+ (*outputFunc)(outputStream, &hexChars[x >> 4], 1);
+ (*outputFunc)(outputStream, &hexChars[x & 0x0f], 1);
+ line += 2;
+ if (line == 64) {
+ (*outputFunc)(outputStream, "\n", 1);
+ line = 0;
+ }
+ }
+}
+
+void Type1CFontFile::getDeltaInt(char *buf, const char *key, const double *opA,
+ int n) {
+ int x, i;
+
+ sprintf(buf, "/%s [", key);
+ buf += strlen(buf);
+ x = 0;
+ for (i = 0; i < n; ++i) {
+ x += (int)opA[i];
+ sprintf(buf, "%s%d", i > 0 ? " " : "", x);
+ buf += strlen(buf);
+ }
+ sprintf(buf, "] def\n");
+}
+
+void Type1CFontFile::getDeltaReal(char *buf, const char *key, const double *opA,
+ int n) {
+ double x;
+ int i;
+
+ sprintf(buf, "/%s [", key);
+ buf += strlen(buf);
+ x = 0;
+ for (i = 0; i < n; ++i) {
+ x += opA[i];
+ sprintf(buf, "%s%g", i > 0 ? " " : "", x);
+ buf += strlen(buf);
+ }
+ sprintf(buf, "] def\n");
+}
+
+int Type1CFontFile::getIndexLen(Guchar *indexPtr) {
+ return (int)getWord(indexPtr, 2);
+}
+
+Guchar *Type1CFontFile::getIndexValPtr(Guchar *indexPtr, int i) {
+ int n, offSize;
+ Guchar *idxStartPtr;
+
+ n = (int)getWord(indexPtr, 2);
+ offSize = indexPtr[2];
+ idxStartPtr = indexPtr + 3 + (n + 1) * offSize - 1;
+ return idxStartPtr + getWord(indexPtr + 3 + i * offSize, offSize);
+}
+
+Guchar *Type1CFontFile::getIndexEnd(Guchar *indexPtr) {
+ int n, offSize;
+ Guchar *idxStartPtr;
+
+ n = (int)getWord(indexPtr, 2);
+ offSize = indexPtr[2];
+ idxStartPtr = indexPtr + 3 + (n + 1) * offSize - 1;
+ return idxStartPtr + getWord(indexPtr + 3 + n * offSize, offSize);
+}
+
+Guint Type1CFontFile::getWord(Guchar *ptr, int size) {
+ Guint x;
+ int i;
+
+ x = 0;
+ for (i = 0; i < size; ++i) {
+ x = (x << 8) + *ptr++;
+ }
+ return x;
+}
+
+double Type1CFontFile::getNum(Guchar **ptr, GBool *isFP) {
+ static char nybChars[16] = "0123456789.ee -";
+ int b0, b, nyb0, nyb1;
+ double x;
+ char buf[65];
+ int i;
+
+ x = 0;
+ *isFP = gFalse;
+ b0 = (*ptr)[0];
+ if (b0 < 28) {
+ x = 0;
+ } else if (b0 == 28) {
+ x = ((*ptr)[1] << 8) + (*ptr)[2];
+ *ptr += 3;
+ } else if (b0 == 29) {
+ x = ((*ptr)[1] << 24) + ((*ptr)[2] << 16) + ((*ptr)[3] << 8) + (*ptr)[4];
+ *ptr += 5;
+ } else if (b0 == 30) {
+ *ptr += 1;
+ i = 0;
+ do {
+ b = *(*ptr)++;
+ nyb0 = b >> 4;
+ nyb1 = b & 0x0f;
+ if (nyb0 == 0xf) {
+ break;
+ }
+ buf[i++] = nybChars[nyb0];
+ if (i == 64) {
+ break;
+ }
+ if (nyb0 == 0xc) {
+ buf[i++] = '-';
+ }
+ if (i == 64) {
+ break;
+ }
+ if (nyb1 == 0xf) {
+ break;
+ }
+ buf[i++] = nybChars[nyb1];
+ if (i == 64) {
+ break;
+ }
+ if (nyb1 == 0xc) {
+ buf[i++] = '-';
+ }
+ } while (i < 64);
+ buf[i] = '\0';
+ x = atof(buf);
+ *isFP = gTrue;
+ } else if (b0 == 31) {
+ x = 0;
+ } else if (b0 < 247) {
+ x = b0 - 139;
+ *ptr += 1;
+ } else if (b0 < 251) {
+ x = ((b0 - 247) << 8) + (*ptr)[1] + 108;
+ *ptr += 2;
+ } else {
+ x = -((b0 - 251) << 8) - (*ptr)[1] - 108;
+ *ptr += 2;
+ }
+ return x;
+}
+
+char *Type1CFontFile::getString(int sid, char *buf) {
+ Guchar *idxPtr0, *idxPtr1;
+ int n;
+
+ if (sid < 391) {
+ strcpy(buf, type1CStdStrings[sid]);
+ } else {
+ sid -= 391;
+ idxPtr0 = getIndexValPtr(stringIdxPtr, sid);
+ idxPtr1 = getIndexValPtr(stringIdxPtr, sid + 1);
+ if ((n = idxPtr1 - idxPtr0) > 255) {
+ n = 255;
+ }
+ strncpy(buf, (char *)idxPtr0, n);
+ buf[n] = '\0';
+ }
+ return buf;
+}
+
+//------------------------------------------------------------------------
+// TrueTypeFontFile
+//------------------------------------------------------------------------
+
+//
+// Terminology
+// -----------
+//
+// character code = number used as an element of a text string
+//
+// character name = glyph name = name for a particular glyph within a
+// font
+//
+// glyph index = position (within some internal table in the font)
+// where the instructions to draw a particular glyph are
+// stored
+//
+// Type 1 fonts
+// ------------
+//
+// Type 1 fonts contain:
+//
+// Encoding: array of glyph names, maps char codes to glyph names
+//
+// Encoding[charCode] = charName
+//
+// CharStrings: dictionary of instructions, keyed by character names,
+// maps character name to glyph data
+//
+// CharStrings[charName] = glyphData
+//
+// TrueType fonts
+// --------------
+//
+// TrueType fonts contain:
+//
+// 'cmap' table: mapping from character code to glyph index; there may
+// be multiple cmaps in a TrueType font
+//
+// cmap[charCode] = glyphIdx
+//
+// 'post' table: mapping from glyph index to glyph name
+//
+// post[glyphIdx] = glyphName
+//
+// Type 42 fonts
+// -------------
+//
+// Type 42 fonts contain:
+//
+// Encoding: array of glyph names, maps char codes to glyph names
+//
+// Encoding[charCode] = charName
+//
+// CharStrings: dictionary of glyph indexes, keyed by character names,
+// maps character name to glyph index
+//
+// CharStrings[charName] = glyphIdx
+//
+
+struct TTFontTableHdr {
+ char tag[4];
+ Guint checksum;
+ Guint offset;
+ Guint length;
+};
+
+struct T42Table {
+ const char *tag; // 4-byte tag
+ GBool required; // required by the TrueType spec?
+};
+
+// TrueType tables to be embedded in Type 42 fonts.
+// NB: the table names must be in alphabetical order here.
+#define nT42Tables 11
+static T42Table t42Tables[nT42Tables] = {
+ { "cvt ", gTrue },
+ { "fpgm", gTrue },
+ { "glyf", gTrue },
+ { "head", gTrue },
+ { "hhea", gTrue },
+ { "hmtx", gTrue },
+ { "loca", gTrue },
+ { "maxp", gTrue },
+ { "prep", gTrue },
+ { "vhea", gFalse },
+ { "vmtx", gFalse }
+};
+#define t42HeadTable 3
+#define t42LocaTable 6
+#define t42GlyfTable 2
+
+// Glyph names in some arbitrary standard that Apple uses for their
+// TrueType fonts.
+static const char *macGlyphNames[258] = {
+ ".notdef",
+ "null",
+ "CR",
+ "space",
+ "exclam",
+ "quotedbl",
+ "numbersign",
+ "dollar",
+ "percent",
+ "ampersand",
+ "quotesingle",
+ "parenleft",
+ "parenright",
+ "asterisk",
+ "plus",
+ "comma",
+ "hyphen",
+ "period",
+ "slash",
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "colon",
+ "semicolon",
+ "less",
+ "equal",
+ "greater",
+ "question",
+ "at",
+ "A",
+ "B",
+ "C",
+ "D",
+ "E",
+ "F",
+ "G",
+ "H",
+ "I",
+ "J",
+ "K",
+ "L",
+ "M",
+ "N",
+ "O",
+ "P",
+ "Q",
+ "R",
+ "S",
+ "T",
+ "U",
+ "V",
+ "W",
+ "X",
+ "Y",
+ "Z",
+ "bracketleft",
+ "backslash",
+ "bracketright",
+ "asciicircum",
+ "underscore",
+ "grave",
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+ "g",
+ "h",
+ "i",
+ "j",
+ "k",
+ "l",
+ "m",
+ "n",
+ "o",
+ "p",
+ "q",
+ "r",
+ "s",
+ "t",
+ "u",
+ "v",
+ "w",
+ "x",
+ "y",
+ "z",
+ "braceleft",
+ "bar",
+ "braceright",
+ "asciitilde",
+ "Adieresis",
+ "Aring",
+ "Ccedilla",
+ "Eacute",
+ "Ntilde",
+ "Odieresis",
+ "Udieresis",
+ "aacute",
+ "agrave",
+ "acircumflex",
+ "adieresis",
+ "atilde",
+ "aring",
+ "ccedilla",
+ "eacute",
+ "egrave",
+ "ecircumflex",
+ "edieresis",
+ "iacute",
+ "igrave",
+ "icircumflex",
+ "idieresis",
+ "ntilde",
+ "oacute",
+ "ograve",
+ "ocircumflex",
+ "odieresis",
+ "otilde",
+ "uacute",
+ "ugrave",
+ "ucircumflex",
+ "udieresis",
+ "dagger",
+ "degree",
+ "cent",
+ "sterling",
+ "section",
+ "bullet",
+ "paragraph",
+ "germandbls",
+ "registered",
+ "copyright",
+ "trademark",
+ "acute",
+ "dieresis",
+ "notequal",
+ "AE",
+ "Oslash",
+ "infinity",
+ "plusminus",
+ "lessequal",
+ "greaterequal",
+ "yen",
+ "mu1",
+ "partialdiff",
+ "summation",
+ "product",
+ "pi",
+ "integral",
+ "ordfeminine",
+ "ordmasculine",
+ "Ohm",
+ "ae",
+ "oslash",
+ "questiondown",
+ "exclamdown",
+ "logicalnot",
+ "radical",
+ "florin",
+ "approxequal",
+ "increment",
+ "guillemotleft",
+ "guillemotright",
+ "ellipsis",
+ "nbspace",
+ "Agrave",
+ "Atilde",
+ "Otilde",
+ "OE",
+ "oe",
+ "endash",
+ "emdash",
+ "quotedblleft",
+ "quotedblright",
+ "quoteleft",
+ "quoteright",
+ "divide",
+ "lozenge",
+ "ydieresis",
+ "Ydieresis",
+ "fraction",
+ "currency",
+ "guilsinglleft",
+ "guilsinglright",
+ "fi",
+ "fl",
+ "daggerdbl",
+ "periodcentered",
+ "quotesinglbase",
+ "quotedblbase",
+ "perthousand",
+ "Acircumflex",
+ "Ecircumflex",
+ "Aacute",
+ "Edieresis",
+ "Egrave",
+ "Iacute",
+ "Icircumflex",
+ "Idieresis",
+ "Igrave",
+ "Oacute",
+ "Ocircumflex",
+ "applelogo",
+ "Ograve",
+ "Uacute",
+ "Ucircumflex",
+ "Ugrave",
+ "dotlessi",
+ "circumflex",
+ "tilde",
+ "overscore",
+ "breve",
+ "dotaccent",
+ "ring",
+ "cedilla",
+ "hungarumlaut",
+ "ogonek",
+ "caron",
+ "Lslash",
+ "lslash",
+ "Scaron",
+ "scaron",
+ "Zcaron",
+ "zcaron",
+ "brokenbar",
+ "Eth",
+ "eth",
+ "Yacute",
+ "yacute",
+ "Thorn",
+ "thorn",
+ "minus",
+ "multiply",
+ "onesuperior",
+ "twosuperior",
+ "threesuperior",
+ "onehalf",
+ "onequarter",
+ "threequarters",
+ "franc",
+ "Gbreve",
+ "gbreve",
+ "Idot",
+ "Scedilla",
+ "scedilla",
+ "Cacute",
+ "cacute",
+ "Ccaron",
+ "ccaron",
+ "dmacron"
+};
+
+enum T42FontIndexMode {
+ t42FontModeUnicode,
+ t42FontModeCharCode,
+ t42FontModeCharCodeOffset,
+ t42FontModeMacRoman
+};
+
+TrueTypeFontFile::TrueTypeFontFile(const char *fileA, int lenA) {
+ int pos, i, idx, n, length;
+ Guint size, startPos, endPos;
+
+ file = fileA;
+ len = lenA;
+
+ encoding = NULL;
+
+ // read table directory
+ nTables = getUShort(4);
+ tableHdrs = (TTFontTableHdr *)gmalloc(nTables * sizeof(TTFontTableHdr));
+ pos = 12;
+ for (i = 0; i < nTables; ++i) {
+ tableHdrs[i].tag[0] = getByte(pos+0);
+ tableHdrs[i].tag[1] = getByte(pos+1);
+ tableHdrs[i].tag[2] = getByte(pos+2);
+ tableHdrs[i].tag[3] = getByte(pos+3);
+ tableHdrs[i].checksum = getULong(pos+4);
+ tableHdrs[i].offset = getULong(pos+8);
+ tableHdrs[i].length = getULong(pos+12);
+ pos += 16;
+ }
+
+ // check for tables that are required by both the TrueType spec
+ // and the Type 42 spec
+ if (seekTable("head") < 0 ||
+ seekTable("hhea") < 0 ||
+ seekTable("loca") < 0 ||
+ seekTable("maxp") < 0 ||
+ seekTable("glyf") < 0 ||
+ seekTable("hmtx") < 0) {
+ error(-1, "TrueType font file is missing a required table");
+ return;
+ }
+
+ // some embedded TrueType fonts have an incorrect (too small) cmap
+ // table size
+ idx = seekTableIdx("cmap");
+ if (idx >= 0) {
+ pos = tableHdrs[idx].offset;
+ n = getUShort(pos + 2);
+ size = (Guint)(4 + 8 * n);
+ for (i = 0; i < n; ++i) {
+ startPos = getULong(pos + 4 + 8*i + 4);
+ length = getUShort(pos + startPos + 2);
+ endPos = startPos + length;
+ if (endPos > size) {
+ size = endPos;
+ }
+ }
+ if ((mungedCmapSize = size > tableHdrs[idx].length)) {
+#if 0 // don't bother printing this error message - it's too common
+ error(-1, "Bad cmap table size in TrueType font");
+#endif
+ tableHdrs[idx].length = size;
+ }
+ } else {
+ mungedCmapSize = gFalse;
+ }
+
+ // read the 'head' table
+ pos = seekTable("head");
+ bbox[0] = getShort(pos + 36);
+ bbox[1] = getShort(pos + 38);
+ bbox[2] = getShort(pos + 40);
+ bbox[3] = getShort(pos + 42);
+ locaFmt = getShort(pos + 50);
+
+ // read the 'maxp' table
+ pos = seekTable("maxp");
+ nGlyphs = getUShort(pos + 4);
+}
+
+TrueTypeFontFile::~TrueTypeFontFile() {
+ int i;
+
+ if (encoding) {
+ for (i = 0; i < 256; ++i) {
+ gfree(encoding[i]);
+ }
+ gfree(encoding);
+ }
+ gfree(tableHdrs);
+}
+
+const char *TrueTypeFontFile::getName() {
+ return NULL;
+}
+
+char **TrueTypeFontFile::getEncoding() {
+ int cmap[256];
+ int nCmaps, cmapPlatform, cmapEncoding, cmapFmt;
+ int cmapLen, cmapOffset, cmapFirst;
+ int segCnt, segStart, segEnd, segDelta, segOffset;
+ int pos, i, j, k;
+ Guint fmt;
+ GString *s;
+ int stringIdx, stringPos, n;
+
+ if (encoding) {
+ return encoding;
+ }
+
+ //----- construct the (char code) -> (glyph idx) mapping
+
+ // map everything to the missing glyph
+ for (i = 0; i < 256; ++i) {
+ cmap[i] = 0;
+ }
+
+ // look for the 'cmap' table
+ if ((pos = seekTable("cmap")) >= 0) {
+ nCmaps = getUShort(pos+2);
+
+ // if the font has a Windows-symbol cmap, use it;
+ // otherwise, use the first cmap in the table
+ for (i = 0; i < nCmaps; ++i) {
+ cmapPlatform = getUShort(pos + 4 + 8*i);
+ cmapEncoding = getUShort(pos + 4 + 8*i + 2);
+ if (cmapPlatform == 3 && cmapEncoding == 0) {
+ break;
+ }
+ }
+ if (i >= nCmaps) {
+ i = 0;
+ cmapPlatform = getUShort(pos + 4);
+ cmapEncoding = getUShort(pos + 4 + 2);
+ }
+ pos += getULong(pos + 4 + 8*i + 4);
+
+ // read the cmap
+ cmapFmt = getUShort(pos);
+ switch (cmapFmt) {
+ case 0: // byte encoding table (Apple standard)
+ cmapLen = getUShort(pos + 2);
+ for (i = 0; i < cmapLen && i < 256; ++i) {
+ cmap[i] = getByte(pos + 6 + i);
+ }
+ break;
+ case 4: // segment mapping to delta values (Microsoft standard)
+ if (cmapPlatform == 3 && cmapEncoding == 0) {
+ // Windows-symbol uses char codes 0xf000 - 0xf0ff
+ cmapOffset = 0xf000;
+ } else {
+ cmapOffset = 0;
+ }
+ segCnt = getUShort(pos + 6) / 2;
+ for (i = 0; i < segCnt; ++i) {
+ segEnd = getUShort(pos + 14 + 2*i);
+ segStart = getUShort(pos + 16 + 2*segCnt + 2*i);
+ segDelta = getUShort(pos + 16 + 4*segCnt + 2*i);
+ segOffset = getUShort(pos + 16 + 6*segCnt + 2*i);
+ if (segStart - cmapOffset <= 0xff &&
+ segEnd - cmapOffset >= 0) {
+ for (j = (segStart - cmapOffset >= 0) ? segStart : cmapOffset;
+ j <= segEnd && j - cmapOffset <= 0xff;
+ ++j) {
+ if (segOffset == 0) {
+ k = (j + segDelta) & 0xffff;
+ } else {
+ k = getUShort(pos + 16 + 6*segCnt + 2*i +
+ segOffset + 2 * (j - segStart));
+ if (k != 0) {
+ k = (k + segDelta) & 0xffff;
+ }
+ }
+ cmap[j - cmapOffset] = k;
+ }
+ }
+ }
+ break;
+ case 6: // trimmed table mapping
+ cmapFirst = getUShort(pos + 6);
+ cmapLen = getUShort(pos + 8);
+ for (i = cmapFirst; i < 256 && i < cmapFirst + cmapLen; ++i) {
+ cmap[i] = getUShort(pos + 10 + 2*i);
+ }
+ break;
+ default:
+ error(-1, "Unimplemented cmap format (%d) in TrueType font file",
+ cmapFmt);
+ break;
+ }
+ }
+
+ //----- construct the (glyph idx) -> (glyph name) mapping
+ //----- and compute the (char code) -> (glyph name) mapping
+
+ encoding = (char **)gmalloc(256 * sizeof(char *));
+ for (i = 0; i < 256; ++i) {
+ encoding[i] = NULL;
+ }
+
+ if ((pos = seekTable("post")) >= 0) {
+ fmt = getULong(pos);
+
+ // Apple font
+ if (fmt == 0x00010000) {
+ for (i = 0; i < 256; ++i) {
+ j = (cmap[i] < 258) ? cmap[i] : 0;
+ encoding[i] = copyString(macGlyphNames[j]);
+ }
+
+ // Microsoft font
+ } else if (fmt == 0x00020000) {
+ stringIdx = 0;
+ stringPos = pos + 34 + 2*nGlyphs;
+ for (i = 0; i < 256; ++i) {
+ if (cmap[i] < nGlyphs) {
+ j = getUShort(pos + 34 + 2 * cmap[i]);
+ if (j < 258) {
+ encoding[i] = copyString(macGlyphNames[j]);
+ } else {
+ j -= 258;
+ if (j != stringIdx) {
+ for (stringIdx = 0, stringPos = pos + 34 + 2*nGlyphs;
+ stringIdx < j;
+ ++stringIdx, stringPos += 1 + getByte(stringPos)) ;
+ }
+ n = getByte(stringPos);
+ s = new GString(file + stringPos + 1, n);
+ encoding[i] = copyString(s->getCString());
+ delete s;
+ ++stringIdx;
+ stringPos += 1 + n;
+ }
+ } else {
+ encoding[i] = copyString(macGlyphNames[0]);
+ }
+ }
+
+ // Apple subset
+ } else if (fmt == 0x000280000) {
+ for (i = 0; i < 256; ++i) {
+ if (cmap[i] < nGlyphs) {
+ j = i + getChar(pos + 32 + cmap[i]);
+ } else {
+ j = 0;
+ }
+ encoding[i] = copyString(macGlyphNames[j]);
+ }
+
+ // Ugh, just assume the Apple glyph set
+ } else {
+ for (i = 0; i < 256; ++i) {
+ j = (cmap[i] < 258) ? cmap[i] : 0;
+ encoding[i] = copyString(macGlyphNames[j]);
+ }
+ }
+
+ // no "post" table: assume the Apple glyph set
+ } else {
+ for (i = 0; i < 256; ++i) {
+ j = (cmap[i] < 258) ? cmap[i] : 0;
+ encoding[i] = copyString(macGlyphNames[j]);
+ }
+ }
+
+ return encoding;
+}
+
+void TrueTypeFontFile::convertToType42(const char *name, const char **encodingA,
+ CharCodeToUnicode *toUnicode,
+ GBool pdfFontHasEncoding,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ char buf[512];
+
+ // write the header
+ sprintf(buf, "%%!PS-TrueTypeFont-%g\n", getFixed(0));
+ (*outputFunc)(outputStream, buf, strlen(buf));
+
+ // begin the font dictionary
+ (*outputFunc)(outputStream, "10 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, name, strlen(name));
+ (*outputFunc)(outputStream, " def\n", 5);
+ (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
+ bbox[0], bbox[1], bbox[2], bbox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
+
+ // write the guts of the dictionary
+ cvtEncoding(encodingA, pdfFontHasEncoding, outputFunc, outputStream);
+ cvtCharStrings(encodingA, toUnicode, pdfFontHasEncoding,
+ outputFunc, outputStream);
+ cvtSfnts(outputFunc, outputStream, NULL);
+
+ // end the dictionary and define the font
+ (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
+}
+
+void TrueTypeFontFile::convertToCIDType2(const char *name, const Gushort *cidMap,
+ int nCIDs,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ char buf[512];
+ Gushort cid;
+ int i, j, k;
+
+ // write the header
+ sprintf(buf, "%%!PS-TrueTypeFont-%g\n", getFixed(0));
+ (*outputFunc)(outputStream, buf, strlen(buf));
+
+ // begin the font dictionary
+ (*outputFunc)(outputStream, "20 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/CIDFontName /", 14);
+ (*outputFunc)(outputStream, name, strlen(name));
+ (*outputFunc)(outputStream, " def\n", 5);
+ (*outputFunc)(outputStream, "/CIDFontType 2 def\n", 19);
+ (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
+ (*outputFunc)(outputStream, "/CIDSystemInfo 3 dict dup begin\n", 32);
+ (*outputFunc)(outputStream, " /Registry (Adobe) def\n", 24);
+ (*outputFunc)(outputStream, " /Ordering (Identity) def\n", 27);
+ (*outputFunc)(outputStream, " /Supplement 0 def\n", 20);
+ (*outputFunc)(outputStream, " end def\n", 10);
+ (*outputFunc)(outputStream, "/GDBytes 2 def\n", 15);
+ if (cidMap) {
+ sprintf(buf, "/CIDCount %d def\n", nCIDs);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ if (nCIDs > 32767) {
+ (*outputFunc)(outputStream, "/CIDMap [", 9);
+ for (i = 0; i < nCIDs; i += 32768 - 16) {
+ (*outputFunc)(outputStream, "<\n", 2);
+ for (j = 0; j < 32768 - 16 && i+j < nCIDs; j += 16) {
+ (*outputFunc)(outputStream, " ", 2);
+ for (k = 0; k < 16 && i+j+k < nCIDs; ++k) {
+ cid = cidMap[i+j+k];
+ sprintf(buf, "%02x%02x", (cid >> 8) & 0xff, cid & 0xff);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+ (*outputFunc)(outputStream, " >", 3);
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ (*outputFunc)(outputStream, "] def\n", 6);
+ } else {
+ (*outputFunc)(outputStream, "/CIDMap <\n", 10);
+ for (i = 0; i < nCIDs; i += 16) {
+ (*outputFunc)(outputStream, " ", 2);
+ for (j = 0; j < 16 && i+j < nCIDs; ++j) {
+ cid = cidMap[i+j];
+ sprintf(buf, "%02x%02x", (cid >> 8) & 0xff, cid & 0xff);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+ (*outputFunc)(outputStream, "> def\n", 6);
+ }
+ } else {
+ // direct mapping - just fill the string(s) with s[i]=i
+ sprintf(buf, "/CIDCount %d def\n", nGlyphs);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ if (nGlyphs > 32767) {
+ (*outputFunc)(outputStream, "/CIDMap [\n", 10);
+ for (i = 0; i < nGlyphs; i += 32767) {
+ j = nGlyphs - i < 32767 ? nGlyphs - i : 32767;
+ sprintf(buf, " %d string 0 1 %d {\n", 2 * j, j - 1);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, " 2 copy dup 2 mul exch %d add -8 bitshift put\n", i);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, " 1 index exch dup 2 mul 1 add exch %d add"
+ " 255 and put\n", i);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, " } for\n", 8);
+ }
+ (*outputFunc)(outputStream, "] def\n", 6);
+ } else {
+ sprintf(buf, "/CIDMap %d string\n", 2 * nGlyphs);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ sprintf(buf, " 0 1 %d {\n", nGlyphs - 1);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream,
+ " 2 copy dup 2 mul exch -8 bitshift put\n", 42);
+ (*outputFunc)(outputStream,
+ " 1 index exch dup 2 mul 1 add exch 255 and put\n", 50);
+ (*outputFunc)(outputStream, " } for\n", 8);
+ (*outputFunc)(outputStream, "def\n", 4);
+ }
+ }
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
+ bbox[0], bbox[1], bbox[2], bbox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
+ (*outputFunc)(outputStream, "/Encoding [] readonly def\n", 26);
+ (*outputFunc)(outputStream, "/CharStrings 1 dict dup begin\n", 30);
+ (*outputFunc)(outputStream, " /.notdef 0 def\n", 17);
+ (*outputFunc)(outputStream, " end readonly def\n", 19);
+
+ // write the guts of the dictionary
+ cvtSfnts(outputFunc, outputStream, NULL);
+
+ // end the dictionary and define the font
+ (*outputFunc)(outputStream,
+ "CIDFontName currentdict end /CIDFont defineresource pop\n",
+ 56);
+}
+
+void TrueTypeFontFile::convertToType0(const char *name, const Gushort *cidMap,
+ int nCIDs,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ char buf[512];
+ GString *sfntsName;
+ int n, i, j;
+
+ // write the Type 42 sfnts array
+ sfntsName = (new GString(name))->append("_sfnts");
+ cvtSfnts(outputFunc, outputStream, sfntsName);
+ delete sfntsName;
+
+ // write the descendant Type 42 fonts
+ n = cidMap ? nCIDs : nGlyphs;
+ for (i = 0; i < n; i += 256) {
+ (*outputFunc)(outputStream, "10 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, name, strlen(name));
+ sprintf(buf, "_%02x def\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/FontType 42 def\n", 17);
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ sprintf(buf, "/FontBBox [%d %d %d %d] def\n",
+ bbox[0], bbox[1], bbox[2], bbox[3]);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, "/PaintType 0 def\n", 17);
+ (*outputFunc)(outputStream, "/sfnts ", 7);
+ (*outputFunc)(outputStream, name, strlen(name));
+ (*outputFunc)(outputStream, "_sfnts def\n", 11);
+ (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
+ for (j = 0; j < 256 && i+j < n; ++j) {
+ sprintf(buf, "dup %d /c%02x put\n", j, j);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "readonly def\n", 13);
+ (*outputFunc)(outputStream, "/CharStrings 257 dict dup begin\n", 32);
+ (*outputFunc)(outputStream, "/.notdef 0 def\n", 15);
+ for (j = 0; j < 256 && i+j < n; ++j) {
+ sprintf(buf, "/c%02x %d def\n", j, cidMap ? cidMap[i+j] : i+j);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "end readonly def\n", 17);
+ (*outputFunc)(outputStream,
+ "FontName currentdict end definefont pop\n", 40);
+ }
+
+ // write the Type 0 parent font
+ (*outputFunc)(outputStream, "16 dict begin\n", 14);
+ (*outputFunc)(outputStream, "/FontName /", 11);
+ (*outputFunc)(outputStream, name, strlen(name));
+ (*outputFunc)(outputStream, " def\n", 5);
+ (*outputFunc)(outputStream, "/FontType 0 def\n", 16);
+ (*outputFunc)(outputStream, "/FontMatrix [1 0 0 1 0 0] def\n", 30);
+ (*outputFunc)(outputStream, "/FMapType 2 def\n", 16);
+ (*outputFunc)(outputStream, "/Encoding [\n", 12);
+ for (i = 0; i < n; i += 256) {
+ sprintf(buf, "%d\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "] def\n", 6);
+ (*outputFunc)(outputStream, "/FDepVector [\n", 14);
+ for (i = 0; i < n; i += 256) {
+ (*outputFunc)(outputStream, "/", 1);
+ (*outputFunc)(outputStream, name, strlen(name));
+ sprintf(buf, "_%02x findfont\n", i >> 8);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ (*outputFunc)(outputStream, "] def\n", 6);
+ (*outputFunc)(outputStream, "FontName currentdict end definefont pop\n", 40);
+}
+
+int TrueTypeFontFile::getByte(int pos) {
+ if (pos < 0 || pos >= len) {
+ return 0;
+ }
+ return file[pos] & 0xff;
+}
+
+int TrueTypeFontFile::getChar(int pos) {
+ int x;
+
+ if (pos < 0 || pos >= len) {
+ return 0;
+ }
+ x = file[pos] & 0xff;
+ if (x & 0x80)
+ x |= 0xffffff00;
+ return x;
+}
+
+int TrueTypeFontFile::getUShort(int pos) {
+ int x;
+
+ if (pos < 0 || pos+1 >= len) {
+ return 0;
+ }
+ x = file[pos] & 0xff;
+ x = (x << 8) + (file[pos+1] & 0xff);
+ return x;
+}
+
+int TrueTypeFontFile::getShort(int pos) {
+ int x;
+
+ if (pos < 0 || pos+1 >= len) {
+ return 0;
+ }
+ x = file[pos] & 0xff;
+ x = (x << 8) + (file[pos+1] & 0xff);
+ if (x & 0x8000)
+ x |= 0xffff0000;
+ return x;
+}
+
+Guint TrueTypeFontFile::getULong(int pos) {
+ int x;
+
+ if (pos < 0 || pos+3 >= len) {
+ return 0;
+ }
+ x = file[pos] & 0xff;
+ x = (x << 8) + (file[pos+1] & 0xff);
+ x = (x << 8) + (file[pos+2] & 0xff);
+ x = (x << 8) + (file[pos+3] & 0xff);
+ return x;
+}
+
+double TrueTypeFontFile::getFixed(int pos) {
+ int x, y;
+
+ x = getShort(pos);
+ y = getUShort(pos+2);
+ return (double)x + (double)y / 65536;
+}
+
+int TrueTypeFontFile::seekTable(const char *tag) {
+ int i;
+
+ for (i = 0; i < nTables; ++i) {
+ if (!strncmp(tableHdrs[i].tag, tag, 4)) {
+ return tableHdrs[i].offset;
+ }
+ }
+ return -1;
+}
+
+int TrueTypeFontFile::seekTableIdx(const char *tag) {
+ int i;
+
+ for (i = 0; i < nTables; ++i) {
+ if (!strncmp(tableHdrs[i].tag, tag, 4)) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+void TrueTypeFontFile::cvtEncoding(const char **encodingA, GBool pdfFontHasEncoding,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ const char *name;
+ char buf[64];
+ int i;
+
+ (*outputFunc)(outputStream, "/Encoding 256 array\n", 20);
+ if (pdfFontHasEncoding) {
+ for (i = 0; i < 256; ++i) {
+ if (!(name = encodingA[i])) {
+ name = ".notdef";
+ }
+ sprintf(buf, "dup %d /", i);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, name, strlen(name));
+ (*outputFunc)(outputStream, " put\n", 5);
+ }
+ } else {
+ for (i = 0; i < 256; ++i) {
+ sprintf(buf, "dup %d /c%02x put\n", i, i);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ }
+ (*outputFunc)(outputStream, "readonly def\n", 13);
+}
+
+void TrueTypeFontFile::cvtCharStrings(const char **encodingA,
+ CharCodeToUnicode *toUnicode,
+ GBool pdfFontHasEncoding,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ int unicodeCmap, macRomanCmap, msSymbolCmap;
+ int nCmaps, cmapPlatform, cmapEncoding, cmapFmt, cmapOffset;
+ T42FontIndexMode mode;
+ const char *name;
+ char buf[64], buf2[16];
+ Unicode u;
+ int pos, i, j, k;
+
+ // always define '.notdef'
+ (*outputFunc)(outputStream, "/CharStrings 256 dict dup begin\n", 32);
+ (*outputFunc)(outputStream, "/.notdef 0 def\n", 15);
+
+ // if there's no 'cmap' table, punt
+ if ((pos = seekTable("cmap")) < 0) {
+ goto err;
+ }
+
+ // To match up with the Adobe-defined behaviour, we choose a cmap
+ // like this:
+ // 1. If the PDF font has an encoding:
+ // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
+ // and use the Unicode indexes, not the char codes.
+ // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and reverse map the char names through MacRomanEncoding to
+ // get char codes.
+ // 2. If the PDF font does not have an encoding:
+ // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and use char codes directly.
+ // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
+ // and use (0xf000 + char code).
+ // 3. If none of these rules apply, use the first cmap and hope for
+ // the best (this shouldn't happen).
+ nCmaps = getUShort(pos+2);
+ unicodeCmap = macRomanCmap = msSymbolCmap = -1;
+ cmapOffset = 0;
+ for (i = 0; i < nCmaps; ++i) {
+ cmapPlatform = getUShort(pos + 4 + 8*i);
+ cmapEncoding = getUShort(pos + 4 + 8*i + 2);
+ if (cmapPlatform == 3 && cmapEncoding == 1) {
+ unicodeCmap = i;
+ } else if (cmapPlatform == 1 && cmapEncoding == 0) {
+ macRomanCmap = i;
+ } else if (cmapPlatform == 3 && cmapEncoding == 0) {
+ msSymbolCmap = i;
+ }
+ }
+ i = 0;
+ mode = t42FontModeCharCode;
+ if (pdfFontHasEncoding) {
+ if (unicodeCmap >= 0) {
+ i = unicodeCmap;
+ mode = t42FontModeUnicode;
+ } else if (macRomanCmap >= 0) {
+ i = macRomanCmap;
+ mode = t42FontModeMacRoman;
+ }
+ } else {
+ if (macRomanCmap >= 0) {
+ i = macRomanCmap;
+ mode = t42FontModeCharCode;
+ } else if (msSymbolCmap >= 0) {
+ i = msSymbolCmap;
+ mode = t42FontModeCharCodeOffset;
+ cmapOffset = 0xf000;
+ }
+ }
+ cmapPlatform = getUShort(pos + 4 + 8*i);
+ cmapEncoding = getUShort(pos + 4 + 8*i + 2);
+ pos += getULong(pos + 4 + 8*i + 4);
+ cmapFmt = getUShort(pos);
+ if (cmapFmt != 0 && cmapFmt != 4 && cmapFmt != 6) {
+ error(-1, "Unimplemented cmap format (%d) in TrueType font file",
+ cmapFmt);
+ goto err;
+ }
+
+ // map char name to glyph index:
+ // 1. use encoding to map name to char code
+ // 2. use cmap to map char code to glyph index
+ j = 0; // make gcc happy
+ for (i = 0; i < 256; ++i) {
+ if (pdfFontHasEncoding) {
+ name = encodingA[i];
+ } else {
+ sprintf(buf2, "c%02x", i);
+ name = buf2;
+ }
+ if (name && strcmp(name, ".notdef")) {
+ switch (mode) {
+ case t42FontModeUnicode:
+ toUnicode->mapToUnicode((CharCode)i, &u, 1);
+ j = (int)u;
+ break;
+ case t42FontModeCharCode:
+ j = i;
+ break;
+ case t42FontModeCharCodeOffset:
+ j = cmapOffset + i;
+ break;
+ case t42FontModeMacRoman:
+ j = globalParams->getMacRomanCharCode(name);
+ break;
+ }
+ // note: Distiller (maybe Adobe's PS interpreter in general)
+ // doesn't like TrueType fonts that have CharStrings entries
+ // which point to nonexistent glyphs, hence the (k < nGlyphs)
+ // test
+ if ((k = getCmapEntry(cmapFmt, pos, j)) > 0 &&
+ k < nGlyphs) {
+ (*outputFunc)(outputStream, "/", 1);
+ (*outputFunc)(outputStream, name, strlen(name));
+ sprintf(buf, " %d def\n", k);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ }
+ }
+
+ err:
+ (*outputFunc)(outputStream, "end readonly def\n", 17);
+}
+
+int TrueTypeFontFile::getCmapEntry(int cmapFmt, int pos, int code) {
+ int cmapLen, cmapFirst;
+ int segCnt, segEnd, segStart, segDelta, segOffset;
+ int a, b, m, i;
+
+ switch (cmapFmt) {
+ case 0: // byte encoding table (Apple standard)
+ cmapLen = getUShort(pos + 2);
+ if (code >= cmapLen) {
+ return 0;
+ }
+ return getByte(pos + 6 + code);
+
+ case 4: // segment mapping to delta values (Microsoft standard)
+ segCnt = getUShort(pos + 6) / 2;
+ a = -1;
+ b = segCnt - 1;
+ segEnd = getUShort(pos + 14 + 2*b);
+ if (code > segEnd) {
+ // malformed font -- the TrueType spec requires the last segEnd
+ // to be 0xffff
+ return 0;
+ }
+ // invariant: seg[a].end < code <= seg[b].end
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ segEnd = getUShort(pos + 14 + 2*m);
+ if (segEnd < code) {
+ a = m;
+ } else {
+ b = m;
+ }
+ }
+ segStart = getUShort(pos + 16 + 2*segCnt + 2*b);
+ segDelta = getUShort(pos + 16 + 4*segCnt + 2*b);
+ segOffset = getUShort(pos + 16 + 6*segCnt + 2*b);
+ if (segOffset == 0) {
+ i = (code + segDelta) & 0xffff;
+ } else {
+ i = getUShort(pos + 16 + 6*segCnt + 2*b +
+ segOffset + 2 * (code - segStart));
+ if (i != 0) {
+ i = (i + segDelta) & 0xffff;
+ }
+ }
+ return i;
+
+ case 6: // trimmed table mapping
+ cmapFirst = getUShort(pos + 6);
+ cmapLen = getUShort(pos + 8);
+ if (code < cmapFirst || code >= cmapFirst + cmapLen) {
+ return 0;
+ }
+ return getUShort(pos + 10 + 2*(code - cmapFirst));
+
+ default:
+ // shouldn't happen - this is checked earlier
+ break;
+ }
+ return 0;
+}
+
+void TrueTypeFontFile::cvtSfnts(FontFileOutputFunc outputFunc,
+ void *outputStream, GString *name) {
+ TTFontTableHdr newTableHdrs[nT42Tables];
+ char tableDir[12 + nT42Tables*16];
+ char headTable[54];
+ int *origLocaTable;
+ char *locaTable;
+ int nNewTables;
+ Guint checksum;
+ int pos, glyfPos, length, glyphLength, pad;
+ int i, j, k;
+
+ // construct the 'head' table, zero out the font checksum
+ memcpy(headTable, file + seekTable("head"), 54);
+ headTable[8] = headTable[9] = headTable[10] = headTable[11] = (char)0;
+
+ // read the original 'loca' table and construct the new one
+ // (pad each glyph out to a multiple of 4 bytes)
+ origLocaTable = (int *)gmalloc((nGlyphs + 1) * sizeof(int));
+ pos = seekTable("loca");
+ for (i = 0; i <= nGlyphs; ++i) {
+ if (locaFmt) {
+ origLocaTable[i] = getULong(pos + 4*i);
+ } else {
+ origLocaTable[i] = 2 * getUShort(pos + 2*i);
+ }
+ }
+ locaTable = (char *)gmalloc((nGlyphs + 1) * (locaFmt ? 4 : 2));
+ if (locaFmt) {
+ locaTable[0] = locaTable[1] = locaTable[2] = locaTable[3] = 0;
+ } else {
+ locaTable[0] = locaTable[1] = 0;
+ }
+ pos = 0;
+ for (i = 1; i <= nGlyphs; ++i) {
+ length = origLocaTable[i] - origLocaTable[i-1];
+ if (length & 3) {
+ length += 4 - (length & 3);
+ }
+ pos += length;
+ if (locaFmt) {
+ locaTable[4*i ] = (char)(pos >> 24);
+ locaTable[4*i+1] = (char)(pos >> 16);
+ locaTable[4*i+2] = (char)(pos >> 8);
+ locaTable[4*i+3] = (char) pos;
+ } else {
+ locaTable[2*i ] = (char)(pos >> 9);
+ locaTable[2*i+1] = (char)(pos >> 1);
+ }
+ }
+
+ // count the number of tables
+ nNewTables = 0;
+ for (i = 0; i < nT42Tables; ++i) {
+ if (t42Tables[i].required ||
+ seekTable(t42Tables[i].tag) >= 0) {
+ ++nNewTables;
+ }
+ }
+
+ // construct the new table headers, including table checksums
+ // (pad each table out to a multiple of 4 bytes)
+ pos = 12 + nNewTables*16;
+ k = 0;
+ for (i = 0; i < nT42Tables; ++i) {
+ length = -1;
+ checksum = 0; // make gcc happy
+ if (i == t42HeadTable) {
+ length = 54;
+ checksum = computeTableChecksum(headTable, 54);
+ } else if (i == t42LocaTable) {
+ length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
+ checksum = computeTableChecksum(locaTable, length);
+ } else if (i == t42GlyfTable) {
+ length = 0;
+ checksum = 0;
+ glyfPos = seekTable("glyf");
+ for (j = 0; j < nGlyphs; ++j) {
+ glyphLength = origLocaTable[j+1] - origLocaTable[j];
+ pad = (glyphLength & 3) ? 4 - (glyphLength & 3) : 0;
+ length += glyphLength + pad;
+ checksum += computeTableChecksum(file + glyfPos + origLocaTable[j],
+ glyphLength);
+ }
+ } else {
+ if ((j = seekTableIdx(t42Tables[i].tag)) >= 0) {
+ length = tableHdrs[j].length;
+ checksum = computeTableChecksum(file + tableHdrs[j].offset, length);
+ } else if (t42Tables[i].required) {
+ error(-1, "Embedded TrueType font is missing a required table ('%s')",
+ t42Tables[i].tag);
+ length = 0;
+ checksum = 0;
+ }
+ }
+ if (length >= 0) {
+ strncpy(newTableHdrs[k].tag, t42Tables[i].tag, 4);
+ newTableHdrs[k].checksum = checksum;
+ newTableHdrs[k].offset = pos;
+ newTableHdrs[k].length = length;
+ pad = (length & 3) ? 4 - (length & 3) : 0;
+ pos += length + pad;
+ ++k;
+ }
+ }
+
+ // construct the table directory
+ tableDir[0] = 0x00; // sfnt version
+ tableDir[1] = 0x01;
+ tableDir[2] = 0x00;
+ tableDir[3] = 0x00;
+ tableDir[4] = 0; // numTables
+ tableDir[5] = nNewTables;
+ tableDir[6] = 0; // searchRange
+ tableDir[7] = (char)128;
+ tableDir[8] = 0; // entrySelector
+ tableDir[9] = 3;
+ tableDir[10] = 0; // rangeShift
+ tableDir[11] = (char)(16 * nNewTables - 128);
+ pos = 12;
+ for (i = 0; i < nNewTables; ++i) {
+ tableDir[pos ] = newTableHdrs[i].tag[0];
+ tableDir[pos+ 1] = newTableHdrs[i].tag[1];
+ tableDir[pos+ 2] = newTableHdrs[i].tag[2];
+ tableDir[pos+ 3] = newTableHdrs[i].tag[3];
+ tableDir[pos+ 4] = (char)(newTableHdrs[i].checksum >> 24);
+ tableDir[pos+ 5] = (char)(newTableHdrs[i].checksum >> 16);
+ tableDir[pos+ 6] = (char)(newTableHdrs[i].checksum >> 8);
+ tableDir[pos+ 7] = (char) newTableHdrs[i].checksum;
+ tableDir[pos+ 8] = (char)(newTableHdrs[i].offset >> 24);
+ tableDir[pos+ 9] = (char)(newTableHdrs[i].offset >> 16);
+ tableDir[pos+10] = (char)(newTableHdrs[i].offset >> 8);
+ tableDir[pos+11] = (char) newTableHdrs[i].offset;
+ tableDir[pos+12] = (char)(newTableHdrs[i].length >> 24);
+ tableDir[pos+13] = (char)(newTableHdrs[i].length >> 16);
+ tableDir[pos+14] = (char)(newTableHdrs[i].length >> 8);
+ tableDir[pos+15] = (char) newTableHdrs[i].length;
+ pos += 16;
+ }
+
+ // compute the font checksum and store it in the head table
+ checksum = computeTableChecksum(tableDir, 12 + nNewTables*16);
+ for (i = 0; i < nNewTables; ++i) {
+ checksum += newTableHdrs[i].checksum;
+ }
+ checksum = 0xb1b0afba - checksum; // because the TrueType spec says so
+ headTable[ 8] = (char)(checksum >> 24);
+ headTable[ 9] = (char)(checksum >> 16);
+ headTable[10] = (char)(checksum >> 8);
+ headTable[11] = (char) checksum;
+
+ // start the sfnts array
+ if (name) {
+ (*outputFunc)(outputStream, "/", 1);
+ (*outputFunc)(outputStream, name->getCString(), name->getLength());
+ (*outputFunc)(outputStream, " [\n", 3);
+ } else {
+ (*outputFunc)(outputStream, "/sfnts [\n", 9);
+ }
+
+ // write the table directory
+ dumpString(tableDir, 12 + nNewTables*16, outputFunc, outputStream);
+
+ // write the tables
+ for (i = 0; i < nNewTables; ++i) {
+ if (i == t42HeadTable) {
+ dumpString(headTable, 54, outputFunc, outputStream);
+ } else if (i == t42LocaTable) {
+ length = (nGlyphs + 1) * (locaFmt ? 4 : 2);
+ dumpString(locaTable, length, outputFunc, outputStream);
+ } else if (i == t42GlyfTable) {
+ glyfPos = seekTable("glyf");
+ for (j = 0; j < nGlyphs; ++j) {
+ length = origLocaTable[j+1] - origLocaTable[j];
+ if (length > 0) {
+ dumpString(file + glyfPos + origLocaTable[j], length,
+ outputFunc, outputStream);
+ }
+ }
+ } else {
+ // length == 0 means the table is missing and the error was
+ // already reported during the construction of the table
+ // headers
+ if ((length = newTableHdrs[i].length) > 0) {
+ dumpString(file + seekTable(t42Tables[i].tag), length,
+ outputFunc, outputStream);
+ }
+ }
+ }
+
+ // end the sfnts array
+ (*outputFunc)(outputStream, "] def\n", 6);
+
+ gfree(origLocaTable);
+ gfree(locaTable);
+}
+
+void TrueTypeFontFile::dumpString(const char *s, int length,
+ FontFileOutputFunc outputFunc,
+ void *outputStream) {
+ char buf[64];
+ int pad, i, j;
+
+ (*outputFunc)(outputStream, "<", 1);
+ for (i = 0; i < length; i += 32) {
+ for (j = 0; j < 32 && i+j < length; ++j) {
+ sprintf(buf, "%02X", s[i+j] & 0xff);
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ if (i % (65536 - 32) == 65536 - 64) {
+ (*outputFunc)(outputStream, ">\n<", 3);
+ } else if (i+32 < length) {
+ (*outputFunc)(outputStream, "\n", 1);
+ }
+ }
+ if (length & 3) {
+ pad = 4 - (length & 3);
+ for (i = 0; i < pad; ++i) {
+ (*outputFunc)(outputStream, "00", 2);
+ }
+ }
+ // add an extra zero byte because the Adobe Type 42 spec says so
+ (*outputFunc)(outputStream, "00>\n", 4);
+}
+
+Guint TrueTypeFontFile::computeTableChecksum(const char *data, int length) {
+ Guint checksum, word;
+ int i;
+
+ checksum = 0;
+ for (i = 0; i+3 < length; i += 4) {
+ word = ((data[i ] & 0xff) << 24) +
+ ((data[i+1] & 0xff) << 16) +
+ ((data[i+2] & 0xff) << 8) +
+ (data[i+3] & 0xff);
+ checksum += word;
+ }
+ if (length & 3) {
+ word = 0;
+ i = length & ~3;
+ switch (length & 3) {
+ case 3:
+ word |= (data[i+2] & 0xff) << 8;
+ case 2:
+ word |= (data[i+1] & 0xff) << 16;
+ case 1:
+ word |= (data[i ] & 0xff) << 24;
+ break;
+ }
+ checksum += word;
+ }
+ return checksum;
+}
+
+void TrueTypeFontFile::writeTTF(FILE *out) {
+ static char cmapTab[20] = {
+ 0, 0, // table version number
+ 0, 1, // number of encoding tables
+ 0, 1, // platform ID
+ 0, 0, // encoding ID
+ 0, 0, 0, 12, // offset of subtable
+ 0, 0, // subtable format
+ 0, 1, // subtable length
+ 0, 1, // subtable version
+ 0, // map char 0 -> glyph 0
+ 0 // pad to multiple of four bytes
+ };
+ static char nameTab[8] = {
+ 0, 0, // format
+ 0, 0, // number of name records
+ 0, 6, // offset to start of string storage
+ 0, 0 // pad to multiple of four bytes
+ };
+ static char postTab[32] = {
+ 0, 1, 0, 0, // format
+ 0, 0, 0, 0, // italic angle
+ 0, 0, // underline position
+ 0, 0, // underline thickness
+ 0, 0, 0, 0, // fixed pitch
+ 0, 0, 0, 0, // min Type 42 memory
+ 0, 0, 0, 0, // max Type 42 memory
+ 0, 0, 0, 0, // min Type 1 memory
+ 0, 0, 0, 0 // max Type 1 memory
+ };
+ GBool haveCmap, haveName, havePost;
+ GBool dirCmap, dirName, dirPost;
+ int nNewTables, nAllTables, pad;
+ char *tableDir;
+ Guint t, pos;
+ int i, j;
+
+ // check for missing tables
+ haveCmap = seekTable("cmap") >= 0;
+ haveName = seekTable("name") >= 0;
+ havePost = seekTable("post") >= 0;
+ nNewTables = (haveCmap ? 0 : 1) + (haveName ? 0 : 1) + (havePost ? 0 : 1);
+ if (!nNewTables && !mungedCmapSize) {
+ // none are missing - write the TTF file as is
+ fwrite(file, 1, len, out);
+ return;
+ }
+
+ // construct the new table directory
+ nAllTables = nTables + nNewTables;
+ tableDir = (char *)gmalloc(12 + nAllTables * 16);
+ memcpy(tableDir, file, 12 + nTables * 16);
+ tableDir[4] = (char)((nAllTables >> 8) & 0xff);
+ tableDir[5] = (char)(nAllTables & 0xff);
+ for (i = -1, t = (Guint)nAllTables; t; ++i, t >>= 1) ;
+ t = 1 << (4 + i);
+ tableDir[6] = (char)((t >> 8) & 0xff);
+ tableDir[7] = (char)(t & 0xff);
+ tableDir[8] = (char)((i >> 8) & 0xff);
+ tableDir[9] = (char)(i & 0xff);
+ t = nAllTables * 16 - t;
+ tableDir[10] = (char)((t >> 8) & 0xff);
+ tableDir[11] = (char)(t & 0xff);
+ dirCmap = haveCmap;
+ dirName = haveName;
+ dirPost = havePost;
+ j = 0;
+ pad = (len & 3) ? 4 - (len & 3) : 0;
+ pos = len + pad + 16 * nNewTables;
+ for (i = 0; i < nTables; ++i) {
+ if (!dirCmap && strncmp(tableHdrs[i].tag, "cmap", 4) > 0) {
+ tableDir[12 + 16*j ] = 'c';
+ tableDir[12 + 16*j + 1] = 'm';
+ tableDir[12 + 16*j + 2] = 'a';
+ tableDir[12 + 16*j + 3] = 'p';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(cmapTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(cmapTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(cmapTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(cmapTab) & 0xff);
+ pos += sizeof(cmapTab);
+ ++j;
+ dirCmap = gTrue;
+ }
+ if (!dirName && strncmp(tableHdrs[i].tag, "name", 4) > 0) {
+ tableDir[12 + 16*j ] = 'n';
+ tableDir[12 + 16*j + 1] = 'a';
+ tableDir[12 + 16*j + 2] = 'm';
+ tableDir[12 + 16*j + 3] = 'e';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(nameTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(nameTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(nameTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(nameTab) & 0xff);
+ pos += sizeof(nameTab);
+ ++j;
+ dirName = gTrue;
+ }
+ if (!dirName && strncmp(tableHdrs[i].tag, "post", 4) > 0) {
+ tableDir[12 + 16*j ] = 'p';
+ tableDir[12 + 16*j + 1] = 'o';
+ tableDir[12 + 16*j + 2] = 's';
+ tableDir[12 + 16*j + 3] = 't';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(postTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(postTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(postTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(postTab) & 0xff);
+ pos += sizeof(postTab);
+ ++j;
+ dirPost = gTrue;
+ }
+ tableDir[12 + 16*j ] = tableHdrs[i].tag[0];
+ tableDir[12 + 16*j + 1] = tableHdrs[i].tag[1];
+ tableDir[12 + 16*j + 2] = tableHdrs[i].tag[2];
+ tableDir[12 + 16*j + 3] = tableHdrs[i].tag[3];
+ tableDir[12 + 16*j + 4] = (char)((tableHdrs[i].checksum >> 24) & 0xff);
+ tableDir[12 + 16*j + 5] = (char)((tableHdrs[i].checksum >> 16) & 0xff);
+ tableDir[12 + 16*j + 6] = (char)((tableHdrs[i].checksum >> 8) & 0xff);
+ tableDir[12 + 16*j + 7] = (char)( tableHdrs[i].checksum & 0xff);
+ t = tableHdrs[i].offset + nNewTables * 16;
+ tableDir[12 + 16*j + 8] = (char)((t >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((t >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((t >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( t & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((tableHdrs[i].length >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((tableHdrs[i].length >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((tableHdrs[i].length >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( tableHdrs[i].length & 0xff);
+ ++j;
+ }
+ if (!dirCmap) {
+ tableDir[12 + 16*j ] = 'c';
+ tableDir[12 + 16*j + 1] = 'm';
+ tableDir[12 + 16*j + 2] = 'a';
+ tableDir[12 + 16*j + 3] = 'p';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(cmapTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(cmapTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(cmapTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(cmapTab) & 0xff);
+ pos += sizeof(cmapTab);
+ ++j;
+ dirCmap = gTrue;
+ }
+ if (!dirName) {
+ tableDir[12 + 16*j ] = 'n';
+ tableDir[12 + 16*j + 1] = 'a';
+ tableDir[12 + 16*j + 2] = 'm';
+ tableDir[12 + 16*j + 3] = 'e';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(nameTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(nameTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(nameTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(nameTab) & 0xff);
+ pos += sizeof(nameTab);
+ ++j;
+ dirName = gTrue;
+ }
+ if (!dirPost) {
+ tableDir[12 + 16*j ] = 'p';
+ tableDir[12 + 16*j + 1] = 'o';
+ tableDir[12 + 16*j + 2] = 's';
+ tableDir[12 + 16*j + 3] = 't';
+ tableDir[12 + 16*j + 4] = (char)0; //~ should compute the checksum
+ tableDir[12 + 16*j + 5] = (char)0;
+ tableDir[12 + 16*j + 6] = (char)0;
+ tableDir[12 + 16*j + 7] = (char)0;
+ tableDir[12 + 16*j + 8] = (char)((pos >> 24) & 0xff);
+ tableDir[12 + 16*j + 9] = (char)((pos >> 16) & 0xff);
+ tableDir[12 + 16*j + 10] = (char)((pos >> 8) & 0xff);
+ tableDir[12 + 16*j + 11] = (char)( pos & 0xff);
+ tableDir[12 + 16*j + 12] = (char)((sizeof(postTab) >> 24) & 0xff);
+ tableDir[12 + 16*j + 13] = (char)((sizeof(postTab) >> 16) & 0xff);
+ tableDir[12 + 16*j + 14] = (char)((sizeof(postTab) >> 8) & 0xff);
+ tableDir[12 + 16*j + 15] = (char)( sizeof(postTab) & 0xff);
+ pos += sizeof(postTab);
+ ++j;
+ dirPost = gTrue;
+ }
+
+ // write the table directory
+ fwrite(tableDir, 1, 12 + 16 * nAllTables, out);
+
+ // write the original tables
+ fwrite(file + 12 + 16*nTables, 1, len - (12 + 16*nTables), out);
+
+ // write the new tables
+ for (i = 0; i < pad; ++i) {
+ fputc((char)0, out);
+ }
+ if (!haveCmap) {
+ fwrite(cmapTab, 1, sizeof(cmapTab), out);
+ }
+ if (!haveName) {
+ fwrite(nameTab, 1, sizeof(nameTab), out);
+ }
+ if (!havePost) {
+ fwrite(postTab, 1, sizeof(postTab), out);
+ }
+
+ gfree(tableDir);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Function.cc b/filters/kword/pdf/xpdf/xpdf/Function.cc
deleted file mode 100644
index e72d3d288..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Function.cc
+++ /dev/null
@@ -1,1521 +0,0 @@
-//========================================================================
-//
-// Function.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <math.h>
-#include "gmem.h"
-#include "Object.h"
-#include "Dict.h"
-#include "Stream.h"
-#include "Error.h"
-#include "Function.h"
-
-//------------------------------------------------------------------------
-// Function
-//------------------------------------------------------------------------
-
-Function::Function() {
-}
-
-Function::~Function() {
-}
-
-Function *Function::parse(Object *funcObj) {
- Function *func;
- Dict *dict;
- int funcType;
- Object obj1;
-
- if (funcObj->isStream()) {
- dict = funcObj->streamGetDict();
- } else if (funcObj->isDict()) {
- dict = funcObj->getDict();
- } else if (funcObj->isName("Identity")) {
- return new IdentityFunction();
- } else {
- error(-1, "Expected function dictionary or stream");
- return NULL;
- }
-
- if (!dict->lookup("FunctionType", &obj1)->isInt()) {
- error(-1, "Function type is missing or wrong type");
- obj1.free();
- return NULL;
- }
- funcType = obj1.getInt();
- obj1.free();
-
- if (funcType == 0) {
- func = new SampledFunction(funcObj, dict);
- } else if (funcType == 2) {
- func = new ExponentialFunction(funcObj, dict);
- } else if (funcType == 3) {
- func = new StitchingFunction(funcObj, dict);
- } else if (funcType == 4) {
- func = new PostScriptFunction(funcObj, dict);
- } else {
- error(-1, "Unimplemented function type (%d)", funcType);
- return NULL;
- }
- if (!func->isOk()) {
- delete func;
- return NULL;
- }
-
- return func;
-}
-
-GBool Function::init(Dict *dict) {
- Object obj1, obj2;
- int i;
-
- //----- Domain
- if (!dict->lookup("Domain", &obj1)->isArray()) {
- error(-1, "Function is missing domain");
- goto err2;
- }
- m = obj1.arrayGetLength() / 2;
- if (m > funcMaxInputs) {
- error(-1, "Functions with more than %d inputs are unsupported",
- funcMaxInputs);
- goto err2;
- }
- for (i = 0; i < m; ++i) {
- obj1.arrayGet(2*i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function domain array");
- goto err1;
- }
- domain[i][0] = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2*i+1, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function domain array");
- goto err1;
- }
- domain[i][1] = obj2.getNum();
- obj2.free();
- }
- obj1.free();
-
- //----- Range
- hasRange = gFalse;
- n = 0;
- if (dict->lookup("Range", &obj1)->isArray()) {
- hasRange = gTrue;
- n = obj1.arrayGetLength() / 2;
- if (n > funcMaxOutputs) {
- error(-1, "Functions with more than %d outputs are unsupported",
- funcMaxOutputs);
- goto err2;
- }
- for (i = 0; i < n; ++i) {
- obj1.arrayGet(2*i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function range array");
- goto err1;
- }
- range[i][0] = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2*i+1, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function range array");
- goto err1;
- }
- range[i][1] = obj2.getNum();
- obj2.free();
- }
- }
- obj1.free();
-
- return gTrue;
-
- err1:
- obj2.free();
- err2:
- obj1.free();
- return gFalse;
-}
-
-//------------------------------------------------------------------------
-// IdentityFunction
-//------------------------------------------------------------------------
-
-IdentityFunction::IdentityFunction() {
- int i;
-
- // fill these in with arbitrary values just in case they get used
- // somewhere
- m = funcMaxInputs;
- n = funcMaxOutputs;
- for (i = 0; i < funcMaxInputs; ++i) {
- domain[i][0] = 0;
- domain[i][1] = 1;
- }
- hasRange = gFalse;
-}
-
-IdentityFunction::~IdentityFunction() {
-}
-
-void IdentityFunction::transform(const double *in, double *out) const {
- int i;
-
- for (i = 0; i < funcMaxOutputs; ++i) {
- out[i] = in[i];
- }
-}
-
-//------------------------------------------------------------------------
-// SampledFunction
-//------------------------------------------------------------------------
-
-SampledFunction::SampledFunction(Object *funcObj, Dict *dict) {
- Stream *str;
- int nSamples, sampleBits;
- double sampleMul;
- Object obj1, obj2;
- Guint buf, bitMask;
- int bits;
- int s;
- int i;
-
- samples = NULL;
- ok = gFalse;
-
- //----- initialize the generic stuff
- if (!init(dict)) {
- goto err1;
- }
- if (!hasRange) {
- error(-1, "Type 0 function is missing range");
- goto err1;
- }
-
- //----- get the stream
- if (!funcObj->isStream()) {
- error(-1, "Type 0 function isn't a stream");
- goto err1;
- }
- str = funcObj->getStream();
-
- //----- Size
- if (!dict->lookup("Size", &obj1)->isArray() ||
- obj1.arrayGetLength() != m) {
- error(-1, "Function has missing or invalid size array");
- goto err2;
- }
- for (i = 0; i < m; ++i) {
- obj1.arrayGet(i, &obj2);
- if (!obj2.isInt()) {
- error(-1, "Illegal value in function size array");
- goto err3;
- }
- sampleSize[i] = obj2.getInt();
- obj2.free();
- }
- obj1.free();
-
- //----- BitsPerSample
- if (!dict->lookup("BitsPerSample", &obj1)->isInt()) {
- error(-1, "Function has missing or invalid BitsPerSample");
- goto err2;
- }
- sampleBits = obj1.getInt();
- sampleMul = 1.0 / (double)((1 << sampleBits) - 1);
- obj1.free();
-
- //----- Encode
- if (dict->lookup("Encode", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2*m) {
- for (i = 0; i < m; ++i) {
- obj1.arrayGet(2*i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function encode array");
- goto err3;
- }
- encode[i][0] = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2*i+1, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function encode array");
- goto err3;
- }
- encode[i][1] = obj2.getNum();
- obj2.free();
- }
- } else {
- for (i = 0; i < m; ++i) {
- encode[i][0] = 0;
- encode[i][1] = sampleSize[i] - 1;
- }
- }
- obj1.free();
-
- //----- Decode
- if (dict->lookup("Decode", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2*n) {
- for (i = 0; i < n; ++i) {
- obj1.arrayGet(2*i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function decode array");
- goto err3;
- }
- decode[i][0] = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2*i+1, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function decode array");
- goto err3;
- }
- decode[i][1] = obj2.getNum();
- obj2.free();
- }
- } else {
- for (i = 0; i < n; ++i) {
- decode[i][0] = range[i][0];
- decode[i][1] = range[i][1];
- }
- }
- obj1.free();
-
- //----- samples
- nSamples = n;
- for (i = 0; i < m; ++i)
- nSamples *= sampleSize[i];
- samples = (double *)gmalloc(nSamples * sizeof(double));
- buf = 0;
- bits = 0;
- bitMask = (1 << sampleBits) - 1;
- str->reset();
- for (i = 0; i < nSamples; ++i) {
- if (sampleBits == 8) {
- s = str->getChar();
- } else if (sampleBits == 16) {
- s = str->getChar();
- s = (s << 8) + str->getChar();
- } else if (sampleBits == 32) {
- s = str->getChar();
- s = (s << 8) + str->getChar();
- s = (s << 8) + str->getChar();
- s = (s << 8) + str->getChar();
- } else {
- while (bits < sampleBits) {
- buf = (buf << 8) | (str->getChar() & 0xff);
- bits += 8;
- }
- s = (buf >> (bits - sampleBits)) & bitMask;
- bits -= sampleBits;
- }
- samples[i] = (double)s * sampleMul;
- }
- str->close();
-
- ok = gTrue;
- return;
-
- err3:
- obj2.free();
- err2:
- obj1.free();
- err1:
- return;
-}
-
-SampledFunction::~SampledFunction() {
- if (samples) {
- gfree(samples);
- }
-}
-
-SampledFunction::SampledFunction(const SampledFunction *func) {
- int nSamples, i;
-
- memcpy(this, func, sizeof(SampledFunction));
-
- nSamples = n;
- for (i = 0; i < m; ++i) {
- nSamples *= sampleSize[i];
- }
- samples = (double *)gmalloc(nSamples * sizeof(double));
- memcpy(samples, func->samples, nSamples * sizeof(double));
-}
-
-void SampledFunction::transform(const double *in, double *out) const {
- double x;
- int e[2][funcMaxInputs];
- double efrac[funcMaxInputs];
- double s0[1 << funcMaxInputs], s1[1 << funcMaxInputs];
- int i, j, k, idx;
-
- // map input values into sample array
- for (i = 0; i < m; ++i) {
- x = ((in[i] - domain[i][0]) / (domain[i][1] - domain[i][0])) *
- (encode[i][1] - encode[i][0]) + encode[i][0];
- if (x < 0) {
- x = 0;
- } else if (x > sampleSize[i] - 1) {
- x = sampleSize[i] - 1;
- }
- e[0][i] = (int)floor(x);
- e[1][i] = (int)ceil(x);
- efrac[i] = x - e[0][i];
- }
-
- // for each output, do m-linear interpolation
- for (i = 0; i < n; ++i) {
-
- // pull 2^m values out of the sample array
- for (j = 0; j < (1<<m); ++j) {
- idx = e[j & 1][m - 1];
- for (k = m - 2; k >= 0; --k) {
- idx = idx * sampleSize[k] + e[(j >> k) & 1][k];
- }
- idx = idx * n + i;
- s0[j] = samples[idx];
- }
-
- // do m sets of interpolations
- for (j = 0; j < m; ++j) {
- for (k = 0; k < (1 << (m - j)); k += 2) {
- s1[k >> 1] = (1 - efrac[j]) * s0[k] + efrac[j] * s0[k+1];
- }
- memcpy(s0, s1, (1 << (m - j - 1)) * sizeof(double));
- }
-
- // map output value to range
- out[i] = s0[0] * (decode[i][1] - decode[i][0]) + decode[i][0];
- if (out[i] < range[i][0]) {
- out[i] = range[i][0];
- } else if (out[i] > range[i][1]) {
- out[i] = range[i][1];
- }
- }
-}
-
-//------------------------------------------------------------------------
-// ExponentialFunction
-//------------------------------------------------------------------------
-
-ExponentialFunction::ExponentialFunction(Object */*funcObj*/, Dict *dict) {
- Object obj1, obj2;
- GBool hasN;
- int i;
-
- ok = gFalse;
-
- //----- initialize the generic stuff
- if (!init(dict)) {
- goto err1;
- }
- if (m != 1) {
- error(-1, "Exponential function with more than one input");
- goto err1;
- }
- hasN = hasRange;
-
- //----- default values
- for (i = 0; i < funcMaxOutputs; ++i) {
- c0[i] = 0;
- c1[i] = 1;
- }
-
- //----- C0
- if (dict->lookup("C0", &obj1)->isArray()) {
- if (!hasN) {
- n = obj1.arrayGetLength();
- hasN = gTrue;
- } else if (obj1.arrayGetLength() != n) {
- error(-1, "Function's C0 array is wrong length");
- goto err2;
- }
- for (i = 0; i < n; ++i) {
- obj1.arrayGet(i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function C0 array");
- goto err3;
- }
- c0[i] = obj2.getNum();
- obj2.free();
- }
- }
- obj1.free();
-
- //----- C1
- if (dict->lookup("C1", &obj1)->isArray()) {
- if (!hasN) {
- n = obj1.arrayGetLength();
- hasN = gTrue;
- } else if (obj1.arrayGetLength() != n) {
- error(-1, "Function's C1 array is wrong length");
- goto err2;
- }
- for (i = 0; i < n; ++i) {
- obj1.arrayGet(i, &obj2);
- if (!obj2.isNum()) {
- error(-1, "Illegal value in function C1 array");
- goto err3;
- }
- c1[i] = obj2.getNum();
- obj2.free();
- }
- }
- obj1.free();
-
- //----- N (exponent)
- if (!dict->lookup("N", &obj1)->isNum()) {
- error(-1, "Function has missing or invalid N");
- goto err2;
- }
- e = obj1.getNum();
- obj1.free();
-
- // this isn't supposed to happen, but I've run into (broken) PDF
- // files where it does
- if (!hasN) {
- error(-1, "Exponential function does not define number of output values");
- n = 1;
- }
-
- ok = gTrue;
- return;
-
- err3:
- obj2.free();
- err2:
- obj1.free();
- err1:
- return;
-}
-
-ExponentialFunction::~ExponentialFunction() {
-}
-
-ExponentialFunction::ExponentialFunction(const ExponentialFunction *func) {
- memcpy(this, func, sizeof(ExponentialFunction));
-}
-
-void ExponentialFunction::transform(const double *in, double *out) const {
- double x;
- int i;
-
- if (in[0] < domain[0][0]) {
- x = domain[0][0];
- } else if (in[0] > domain[0][1]) {
- x = domain[0][1];
- } else {
- x = in[0];
- }
- for (i = 0; i < n; ++i) {
- out[i] = c0[i] + pow(x, e) * (c1[i] - c0[i]);
- if (hasRange) {
- if (out[i] < range[i][0]) {
- out[i] = range[i][0];
- } else if (out[i] > range[i][1]) {
- out[i] = range[i][1];
- }
- }
- }
- return;
-}
-
-//------------------------------------------------------------------------
-// StitchingFunction
-//------------------------------------------------------------------------
-
-StitchingFunction::StitchingFunction(Object */*funcObj*/, Dict *dict) {
- Object obj1, obj2;
- int i;
-
- ok = gFalse;
- funcs = NULL;
- bounds = NULL;
- encode = NULL;
-
- //----- initialize the generic stuff
- if (!init(dict)) {
- goto err1;
- }
- if (m != 1) {
- error(-1, "Stitching function with more than one input");
- goto err1;
- }
-
- //----- Functions
- if (!dict->lookup("Functions", &obj1)->isArray()) {
- error(-1, "Missing 'Functions' entry in stitching function");
- goto err1;
- }
- k = obj1.arrayGetLength();
- funcs = (Function **)gmalloc(k * sizeof(Function *));
- bounds = (double *)gmalloc((k + 1) * sizeof(double));
- encode = (double *)gmalloc(2 * k * sizeof(double));
- for (i = 0; i < k; ++i) {
- funcs[i] = NULL;
- }
- for (i = 0; i < k; ++i) {
- if (!(funcs[i] = Function::parse(obj1.arrayGet(i, &obj2)))) {
- goto err2;
- }
- if (i > 0 && (funcs[i]->getInputSize() != 1 ||
- funcs[i]->getOutputSize() != funcs[0]->getOutputSize())) {
- error(-1, "Incompatible subfunctions in stitching function");
- goto err2;
- }
- obj2.free();
- }
- obj1.free();
-
- //----- Bounds
- if (!dict->lookup("Bounds", &obj1)->isArray() ||
- obj1.arrayGetLength() != k - 1) {
- error(-1, "Missing or invalid 'Bounds' entry in stitching function");
- goto err1;
- }
- bounds[0] = domain[0][0];
- for (i = 1; i < k; ++i) {
- if (!obj1.arrayGet(i - 1, &obj2)->isNum()) {
- error(-1, "Invalid type in 'Bounds' array in stitching function");
- goto err2;
- }
- bounds[i] = obj2.getNum();
- obj2.free();
- }
- bounds[k] = domain[0][1];
- obj1.free();
-
- //----- Encode
- if (!dict->lookup("Encode", &obj1)->isArray() ||
- obj1.arrayGetLength() != 2 * k) {
- error(-1, "Missing or invalid 'Encode' entry in stitching function");
- goto err1;
- }
- for (i = 0; i < 2 * k; ++i) {
- if (!obj1.arrayGet(i, &obj2)->isNum()) {
- error(-1, "Invalid type in 'Encode' array in stitching function");
- goto err2;
- }
- encode[i] = obj2.getNum();
- obj2.free();
- }
- obj1.free();
-
- ok = gTrue;
- return;
-
- err2:
- obj2.free();
- err1:
- obj1.free();
-}
-
-StitchingFunction::StitchingFunction(const StitchingFunction *func) {
- k = func->k;
- funcs = (Function **)gmalloc(k * sizeof(Function *));
- memcpy(funcs, func->funcs, k * sizeof(Function *));
- bounds = (double *)gmalloc((k + 1) * sizeof(double));
- memcpy(bounds, func->bounds, (k + 1) * sizeof(double));
- encode = (double *)gmalloc(2 * k * sizeof(double));
- memcpy(encode, func->encode, 2 * k * sizeof(double));
- ok = gTrue;
-}
-
-StitchingFunction::~StitchingFunction() {
- int i;
-
- for (i = 0; i < k; ++i) {
- if (funcs[i]) {
- delete funcs[i];
- }
- }
- gfree(funcs);
- gfree(bounds);
- gfree(encode);
-}
-
-void StitchingFunction::transform(const double *in, double *out) const {
- double x;
- int i;
-
- if (in[0] < domain[0][0]) {
- x = domain[0][0];
- } else if (in[0] > domain[0][1]) {
- x = domain[0][1];
- } else {
- x = in[0];
- }
- for (i = 0; i < k - 1; ++i) {
- if (x < bounds[i+1]) {
- break;
- }
- }
- x = encode[2*i] + ((x - bounds[i]) / (bounds[i+1] - bounds[i])) *
- (encode[2*i+1] - encode[2*i]);
- funcs[i]->transform(&x, out);
-}
-
-//------------------------------------------------------------------------
-// PostScriptFunction
-//------------------------------------------------------------------------
-
-enum PSOp {
- psOpAbs,
- psOpAdd,
- psOpAnd,
- psOpAtan,
- psOpBitshift,
- psOpCeiling,
- psOpCopy,
- psOpCos,
- psOpCvi,
- psOpCvr,
- psOpDiv,
- psOpDup,
- psOpEq,
- psOpExch,
- psOpExp,
- psOpFalse,
- psOpFloor,
- psOpGe,
- psOpGt,
- psOpIdiv,
- psOpIndex,
- psOpLe,
- psOpLn,
- psOpLog,
- psOpLt,
- psOpMod,
- psOpMul,
- psOpNe,
- psOpNeg,
- psOpNot,
- psOpOr,
- psOpPop,
- psOpRoll,
- psOpRound,
- psOpSin,
- psOpSqrt,
- psOpSub,
- psOpTrue,
- psOpTruncate,
- psOpXor,
- psOpIf,
- psOpIfelse,
- psOpReturn
-};
-
-// Note: 'if' and 'ifelse' are parsed separately.
-// The rest are listed here in alphabetical order.
-// The index in this table is equivalent to the entry in PSOp.
-const char *psOpNames[] = {
- "abs",
- "add",
- "and",
- "atan",
- "bitshift",
- "ceiling",
- "copy",
- "cos",
- "cvi",
- "cvr",
- "div",
- "dup",
- "eq",
- "exch",
- "exp",
- "false",
- "floor",
- "ge",
- "gt",
- "idiv",
- "index",
- "le",
- "ln",
- "log",
- "lt",
- "mod",
- "mul",
- "ne",
- "neg",
- "not",
- "or",
- "pop",
- "roll",
- "round",
- "sin",
- "sqrt",
- "sub",
- "true",
- "truncate",
- "xor"
-};
-
-#define nPSOps (sizeof(psOpNames) / sizeof(char *))
-
-enum PSObjectType {
- psBool,
- psInt,
- psReal,
- psOperator,
- psBlock
-};
-
-// In the code array, 'if'/'ifelse' operators take up three slots
-// plus space for the code in the subclause(s).
-//
-// +---------------------------------+
-// | psOperator: psOpIf / psOpIfelse |
-// +---------------------------------+
-// | psBlock: ptr=<A> |
-// +---------------------------------+
-// | psBlock: ptr=<B> |
-// +---------------------------------+
-// | if clause |
-// | ... |
-// | psOperator: psOpReturn |
-// +---------------------------------+
-// <A> | else clause |
-// | ... |
-// | psOperator: psOpReturn |
-// +---------------------------------+
-// <B> | ... |
-//
-// For 'if', pointer <A> is present in the code stream but unused.
-
-struct PSObject {
- PSObjectType type;
- union {
- GBool booln; // boolean (stack only)
- int intg; // integer (stack and code)
- double real; // real (stack and code)
- PSOp op; // operator (code only)
- int blk; // if/ifelse block pointer (code only)
- };
-};
-
-#define psStackSize 100
-
-class PSStack {
-public:
-
- PSStack() { sp = psStackSize; }
- void pushBool(GBool booln);
- void pushInt(int intg);
- void pushReal(double real);
- GBool popBool();
- int popInt();
- double popNum();
- GBool empty() { return sp == psStackSize; }
- GBool topIsInt() { return sp < psStackSize && stack[sp].type == psInt; }
- GBool topTwoAreInts()
- { return sp < psStackSize - 1 &&
- stack[sp].type == psInt &&
- stack[sp+1].type == psInt; }
- GBool topIsReal() { return sp < psStackSize && stack[sp].type == psReal; }
- GBool topTwoAreNums()
- { return sp < psStackSize - 1 &&
- (stack[sp].type == psInt || stack[sp].type == psReal) &&
- (stack[sp+1].type == psInt || stack[sp+1].type == psReal); }
- void copy(int n);
- void roll(int n, int j);
- void index(int i);
- void pop();
-
-private:
-
- GBool checkOverflow(int n = 1);
- GBool checkUnderflow();
- GBool checkType(PSObjectType t1, PSObjectType t2);
-
- PSObject stack[psStackSize];
- int sp;
-};
-
-GBool PSStack::checkOverflow(int n) {
- if (sp - n < 0) {
- error(-1, "Stack overflow in PostScript function");
- return gFalse;
- }
- return gTrue;
-}
-
-GBool PSStack::checkUnderflow() {
- if (sp == psStackSize) {
- error(-1, "Stack underflow in PostScript function");
- return gFalse;
- }
- return gTrue;
-}
-
-GBool PSStack::checkType(PSObjectType t1, PSObjectType t2) {
- if (stack[sp].type != t1 && stack[sp].type != t2) {
- error(-1, "Type mismatch in PostScript function");
- return gFalse;
- }
- return gTrue;
-}
-
-void PSStack::pushBool(GBool booln) {
- if (checkOverflow()) {
- stack[--sp].type = psBool;
- stack[sp].booln = booln;
- }
-}
-
-void PSStack::pushInt(int intg) {
- if (checkOverflow()) {
- stack[--sp].type = psInt;
- stack[sp].intg = intg;
- }
-}
-
-void PSStack::pushReal(double real) {
- if (checkOverflow()) {
- stack[--sp].type = psReal;
- stack[sp].real = real;
- }
-}
-
-GBool PSStack::popBool() {
- if (checkUnderflow() && checkType(psBool, psBool)) {
- return stack[sp++].booln;
- }
- return gFalse;
-}
-
-int PSStack::popInt() {
- if (checkUnderflow() && checkType(psInt, psInt)) {
- return stack[sp++].intg;
- }
- return 0;
-}
-
-double PSStack::popNum() {
- double ret;
-
- if (checkUnderflow() && checkType(psInt, psReal)) {
- ret = (stack[sp].type == psInt) ? (double)stack[sp].intg : stack[sp].real;
- ++sp;
- return ret;
- }
- return 0;
-}
-
-void PSStack::copy(int n) {
- int i;
-
- if (!checkOverflow(n)) {
- return;
- }
- for (i = sp + n - 1; i <= sp; ++i) {
- stack[i - n] = stack[i];
- }
- sp -= n;
-}
-
-void PSStack::roll(int n, int j) {
- PSObject obj;
- int i, k;
-
- if (j >= 0) {
- j %= n;
- } else {
- j = -j % n;
- if (j != 0) {
- j = n - j;
- }
- }
- if (n <= 0 || j == 0) {
- return;
- }
- for (i = 0; i < j; ++i) {
- obj = stack[sp];
- for (k = sp; k < sp + n - 1; ++k) {
- stack[k] = stack[k+1];
- }
- stack[sp + n - 1] = obj;
- }
-}
-
-void PSStack::index(int i) {
- if (!checkOverflow()) {
- return;
- }
- --sp;
- stack[sp] = stack[sp + 1 + i];
-}
-
-void PSStack::pop() {
- if (!checkUnderflow()) {
- return;
- }
- ++sp;
-}
-
-PostScriptFunction::PostScriptFunction(Object *funcObj, Dict *dict) {
- Stream *str;
- int codePtr;
- GString *tok;
-
- code = NULL;
- codeSize = 0;
- ok = gFalse;
-
- //----- initialize the generic stuff
- if (!init(dict)) {
- goto err1;
- }
- if (!hasRange) {
- error(-1, "Type 4 function is missing range");
- goto err1;
- }
-
- //----- get the stream
- if (!funcObj->isStream()) {
- error(-1, "Type 4 function isn't a stream");
- goto err1;
- }
- str = funcObj->getStream();
-
- //----- parse the function
- str->reset();
- if (!(tok = getToken(str)) || tok->cmp("{")) {
- error(-1, "Expected '{' at start of PostScript function");
- if (tok) {
- delete tok;
- }
- goto err1;
- }
- delete tok;
- codePtr = 0;
- if (!parseCode(str, &codePtr)) {
- goto err2;
- }
- str->close();
-
- ok = gTrue;
-
- err2:
- str->close();
- err1:
- return;
-}
-
-PostScriptFunction::PostScriptFunction(const PostScriptFunction *func) {
- memcpy(this, func, sizeof(PostScriptFunction));
- code = (PSObject *)gmalloc(codeSize * sizeof(PSObject));
- memcpy(code, func->code, codeSize * sizeof(PSObject));
-}
-
-PostScriptFunction::~PostScriptFunction() {
- gfree(code);
-}
-
-void PostScriptFunction::transform(const double *in, double *out) const {
- PSStack *stack;
- int i;
-
- stack = new PSStack();
- for (i = 0; i < m; ++i) {
- //~ may need to check for integers here
- stack->pushReal(in[i]);
- }
- exec(stack, 0);
- for (i = n - 1; i >= 0; --i) {
- out[i] = stack->popNum();
- if (out[i] < range[i][0]) {
- out[i] = range[i][0];
- } else if (out[i] > range[i][1]) {
- out[i] = range[i][1];
- }
- }
- // if (!stack->empty()) {
- // error(-1, "Extra values on stack at end of PostScript function");
- // }
- delete stack;
-}
-
-GBool PostScriptFunction::parseCode(Stream *str, int *codePtr) {
- GString *tok;
- char *p;
- GBool isReal;
- int opPtr, elsePtr;
- int a, b, mid, cmp;
-
- while (1) {
- if (!(tok = getToken(str))) {
- error(-1, "Unexpected end of PostScript function stream");
- return gFalse;
- }
- p = tok->getCString();
- if (isdigit(*p) || *p == '.' || *p == '-') {
- isReal = gFalse;
- for (++p; *p; ++p) {
- if (*p == '.') {
- isReal = gTrue;
- break;
- }
- }
- resizeCode(*codePtr);
- if (isReal) {
- code[*codePtr].type = psReal;
- code[*codePtr].real = atof(tok->getCString());
- } else {
- code[*codePtr].type = psInt;
- code[*codePtr].intg = atoi(tok->getCString());
- }
- ++*codePtr;
- delete tok;
- } else if (!tok->cmp("{")) {
- delete tok;
- opPtr = *codePtr;
- *codePtr += 3;
- resizeCode(opPtr + 2);
- if (!parseCode(str, codePtr)) {
- return gFalse;
- }
- if (!(tok = getToken(str))) {
- error(-1, "Unexpected end of PostScript function stream");
- return gFalse;
- }
- if (!tok->cmp("{")) {
- elsePtr = *codePtr;
- if (!parseCode(str, codePtr)) {
- return gFalse;
- }
- delete tok;
- if (!(tok = getToken(str))) {
- error(-1, "Unexpected end of PostScript function stream");
- return gFalse;
- }
- } else {
- elsePtr = -1;
- }
- if (!tok->cmp("if")) {
- if (elsePtr >= 0) {
- error(-1, "Got 'if' operator with two blocks in PostScript function");
- return gFalse;
- }
- code[opPtr].type = psOperator;
- code[opPtr].op = psOpIf;
- code[opPtr+2].type = psBlock;
- code[opPtr+2].blk = *codePtr;
- } else if (!tok->cmp("ifelse")) {
- if (elsePtr < 0) {
- error(-1, "Got 'ifelse' operator with one blocks in PostScript function");
- return gFalse;
- }
- code[opPtr].type = psOperator;
- code[opPtr].op = psOpIfelse;
- code[opPtr+1].type = psBlock;
- code[opPtr+1].blk = elsePtr;
- code[opPtr+2].type = psBlock;
- code[opPtr+2].blk = *codePtr;
- } else {
- error(-1, "Expected if/ifelse operator in PostScript function");
- delete tok;
- return gFalse;
- }
- delete tok;
- } else if (!tok->cmp("}")) {
- delete tok;
- resizeCode(*codePtr);
- code[*codePtr].type = psOperator;
- code[*codePtr].op = psOpReturn;
- ++*codePtr;
- break;
- } else {
- a = -1;
- b = nPSOps;
- // invariant: psOpNames[a] < tok < psOpNames[b]
- while (b - a > 1) {
- mid = (a + b) / 2;
- cmp = tok->cmp(psOpNames[mid]);
- if (cmp > 0) {
- a = mid;
- } else if (cmp < 0) {
- b = mid;
- } else {
- a = b = mid;
- }
- }
- if (cmp != 0) {
- error(-1, "Unknown operator '%s' in PostScript function",
- tok->getCString());
- delete tok;
- return gFalse;
- }
- delete tok;
- resizeCode(*codePtr);
- code[*codePtr].type = psOperator;
- code[*codePtr].op = (PSOp)a;
- ++*codePtr;
- }
- }
- return gTrue;
-}
-
-GString *PostScriptFunction::getToken(Stream *str) {
- GString *s;
- int c;
-
- s = new GString();
- do {
- c = str->getChar();
- } while (c != EOF && isspace(c));
- if (c == '{' || c == '}') {
- s->append((char)c);
- } else if (isdigit(c) || c == '.' || c == '-') {
- while (1) {
- s->append((char)c);
- c = str->lookChar();
- if (c == EOF || !(isdigit(c) || c == '.' || c == '-')) {
- break;
- }
- str->getChar();
- }
- } else {
- while (1) {
- s->append((char)c);
- c = str->lookChar();
- if (c == EOF || !isalnum(c)) {
- break;
- }
- str->getChar();
- }
- }
- return s;
-}
-
-void PostScriptFunction::resizeCode(int newSize) {
- if (newSize >= codeSize) {
- codeSize += 64;
- code = (PSObject *)grealloc(code, codeSize * sizeof(PSObject));
- }
-}
-
-void PostScriptFunction::exec(PSStack *stack, int codePtr) const {
- int i1, i2;
- double r1, r2;
- GBool b1, b2;
-
- while (1) {
- switch (code[codePtr].type) {
- case psInt:
- stack->pushInt(code[codePtr++].intg);
- break;
- case psReal:
- stack->pushReal(code[codePtr++].real);
- break;
- case psOperator:
- switch (code[codePtr++].op) {
- case psOpAbs:
- if (stack->topIsInt()) {
- stack->pushInt(abs(stack->popInt()));
- } else {
- stack->pushReal(fabs(stack->popNum()));
- }
- break;
- case psOpAdd:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 + i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushReal(r1 + r2);
- }
- break;
- case psOpAnd:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 & i2);
- } else {
- b2 = stack->popBool();
- b1 = stack->popBool();
- stack->pushReal(b1 && b2);
- }
- break;
- case psOpAtan:
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushReal(atan2(r1, r2));
- break;
- case psOpBitshift:
- i2 = stack->popInt();
- i1 = stack->popInt();
- if (i2 > 0) {
- stack->pushInt(i1 << i2);
- } else if (i2 < 0) {
- stack->pushInt((int)((Guint)i1 >> i2));
- } else {
- stack->pushInt(i1);
- }
- break;
- case psOpCeiling:
- if (!stack->topIsInt()) {
- stack->pushReal(ceil(stack->popNum()));
- }
- break;
- case psOpCopy:
- stack->copy(stack->popInt());
- break;
- case psOpCos:
- stack->pushReal(cos(stack->popNum()));
- break;
- case psOpCvi:
- if (!stack->topIsInt()) {
- stack->pushInt((int)stack->popNum());
- }
- break;
- case psOpCvr:
- if (!stack->topIsReal()) {
- stack->pushReal(stack->popNum());
- }
- break;
- case psOpDiv:
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushReal(r1 / r2);
- break;
- case psOpDup:
- stack->copy(1);
- break;
- case psOpEq:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 == i2);
- } else if (stack->topTwoAreNums()) {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 == r2);
- } else {
- b2 = stack->popBool();
- b1 = stack->popBool();
- stack->pushBool(b1 == b2);
- }
- break;
- case psOpExch:
- stack->roll(2, 1);
- break;
- case psOpExp:
- r2 = stack->popInt();
- r1 = stack->popInt();
- stack->pushReal(pow(r1, r2));
- break;
- case psOpFalse:
- stack->pushBool(gFalse);
- break;
- case psOpFloor:
- if (!stack->topIsInt()) {
- stack->pushReal(floor(stack->popNum()));
- }
- break;
- case psOpGe:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 >= i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 >= r2);
- }
- break;
- case psOpGt:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 > i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 > r2);
- }
- break;
- case psOpIdiv:
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 / i2);
- break;
- case psOpIndex:
- stack->index(stack->popInt());
- break;
- case psOpLe:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 <= i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 <= r2);
- }
- break;
- case psOpLn:
- stack->pushReal(log(stack->popNum()));
- break;
- case psOpLog:
- stack->pushReal(log10(stack->popNum()));
- break;
- case psOpLt:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 < i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 < r2);
- }
- break;
- case psOpMod:
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 % i2);
- break;
- case psOpMul:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- //~ should check for out-of-range, and push a real instead
- stack->pushInt(i1 * i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushReal(r1 * r2);
- }
- break;
- case psOpNe:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushBool(i1 != i2);
- } else if (stack->topTwoAreNums()) {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushBool(r1 != r2);
- } else {
- b2 = stack->popBool();
- b1 = stack->popBool();
- stack->pushBool(b1 != b2);
- }
- break;
- case psOpNeg:
- if (stack->topIsInt()) {
- stack->pushInt(-stack->popInt());
- } else {
- stack->pushReal(-stack->popNum());
- }
- break;
- case psOpNot:
- if (stack->topIsInt()) {
- stack->pushInt(~stack->popInt());
- } else {
- stack->pushReal(!stack->popBool());
- }
- break;
- case psOpOr:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 | i2);
- } else {
- b2 = stack->popBool();
- b1 = stack->popBool();
- stack->pushReal(b1 || b2);
- }
- break;
- case psOpPop:
- stack->pop();
- break;
- case psOpRoll:
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->roll(i1, i2);
- break;
- case psOpRound:
- if (!stack->topIsInt()) {
- r1 = stack->popNum();
- stack->pushReal((r1 >= 0) ? floor(r1 + 0.5) : ceil(r1 - 0.5));
- }
- break;
- case psOpSin:
- stack->pushReal(cos(stack->popNum()));
- break;
- case psOpSqrt:
- stack->pushReal(sqrt(stack->popNum()));
- break;
- case psOpSub:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 - i2);
- } else {
- r2 = stack->popNum();
- r1 = stack->popNum();
- stack->pushReal(r1 - r2);
- }
- break;
- case psOpTrue:
- stack->pushBool(gTrue);
- break;
- case psOpTruncate:
- if (!stack->topIsInt()) {
- r1 = stack->popNum();
- stack->pushReal((r1 >= 0) ? floor(r1) : ceil(r1));
- }
- break;
- case psOpXor:
- if (stack->topTwoAreInts()) {
- i2 = stack->popInt();
- i1 = stack->popInt();
- stack->pushInt(i1 ^ i2);
- } else {
- b2 = stack->popBool();
- b1 = stack->popBool();
- stack->pushReal(b1 ^ b2);
- }
- break;
- case psOpIf:
- b1 = stack->popBool();
- if (b1) {
- exec(stack, codePtr + 2);
- }
- codePtr = code[codePtr + 1].blk;
- break;
- case psOpIfelse:
- b1 = stack->popBool();
- if (b1) {
- exec(stack, codePtr + 2);
- } else {
- exec(stack, code[codePtr].blk);
- }
- codePtr = code[codePtr + 1].blk;
- break;
- case psOpReturn:
- return;
- }
- break;
- default:
- error(-1, "Internal: bad object in PostScript function code");
- break;
- }
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Function.cpp b/filters/kword/pdf/xpdf/xpdf/Function.cpp
new file mode 100644
index 000000000..84e27d197
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Function.cpp
@@ -0,0 +1,1521 @@
+//========================================================================
+//
+// Function.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <math.h>
+#include "gmem.h"
+#include "Object.h"
+#include "Dict.h"
+#include "Stream.h"
+#include "Error.h"
+#include "Function.h"
+
+//------------------------------------------------------------------------
+// Function
+//------------------------------------------------------------------------
+
+Function::Function() {
+}
+
+Function::~Function() {
+}
+
+Function *Function::parse(Object *funcObj) {
+ Function *func;
+ Dict *dict;
+ int funcType;
+ Object obj1;
+
+ if (funcObj->isStream()) {
+ dict = funcObj->streamGetDict();
+ } else if (funcObj->isDict()) {
+ dict = funcObj->getDict();
+ } else if (funcObj->isName("Identity")) {
+ return new IdentityFunction();
+ } else {
+ error(-1, "Expected function dictionary or stream");
+ return NULL;
+ }
+
+ if (!dict->lookup("FunctionType", &obj1)->isInt()) {
+ error(-1, "Function type is missing or wrong type");
+ obj1.free();
+ return NULL;
+ }
+ funcType = obj1.getInt();
+ obj1.free();
+
+ if (funcType == 0) {
+ func = new SampledFunction(funcObj, dict);
+ } else if (funcType == 2) {
+ func = new ExponentialFunction(funcObj, dict);
+ } else if (funcType == 3) {
+ func = new StitchingFunction(funcObj, dict);
+ } else if (funcType == 4) {
+ func = new PostScriptFunction(funcObj, dict);
+ } else {
+ error(-1, "Unimplemented function type (%d)", funcType);
+ return NULL;
+ }
+ if (!func->isOk()) {
+ delete func;
+ return NULL;
+ }
+
+ return func;
+}
+
+GBool Function::init(Dict *dict) {
+ Object obj1, obj2;
+ int i;
+
+ //----- Domain
+ if (!dict->lookup("Domain", &obj1)->isArray()) {
+ error(-1, "Function is missing domain");
+ goto err2;
+ }
+ m = obj1.arrayGetLength() / 2;
+ if (m > funcMaxInputs) {
+ error(-1, "Functions with more than %d inputs are unsupported",
+ funcMaxInputs);
+ goto err2;
+ }
+ for (i = 0; i < m; ++i) {
+ obj1.arrayGet(2*i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function domain array");
+ goto err1;
+ }
+ domain[i][0] = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2*i+1, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function domain array");
+ goto err1;
+ }
+ domain[i][1] = obj2.getNum();
+ obj2.free();
+ }
+ obj1.free();
+
+ //----- Range
+ hasRange = gFalse;
+ n = 0;
+ if (dict->lookup("Range", &obj1)->isArray()) {
+ hasRange = gTrue;
+ n = obj1.arrayGetLength() / 2;
+ if (n > funcMaxOutputs) {
+ error(-1, "Functions with more than %d outputs are unsupported",
+ funcMaxOutputs);
+ goto err2;
+ }
+ for (i = 0; i < n; ++i) {
+ obj1.arrayGet(2*i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function range array");
+ goto err1;
+ }
+ range[i][0] = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2*i+1, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function range array");
+ goto err1;
+ }
+ range[i][1] = obj2.getNum();
+ obj2.free();
+ }
+ }
+ obj1.free();
+
+ return gTrue;
+
+ err1:
+ obj2.free();
+ err2:
+ obj1.free();
+ return gFalse;
+}
+
+//------------------------------------------------------------------------
+// IdentityFunction
+//------------------------------------------------------------------------
+
+IdentityFunction::IdentityFunction() {
+ int i;
+
+ // fill these in with arbitrary values just in case they get used
+ // somewhere
+ m = funcMaxInputs;
+ n = funcMaxOutputs;
+ for (i = 0; i < funcMaxInputs; ++i) {
+ domain[i][0] = 0;
+ domain[i][1] = 1;
+ }
+ hasRange = gFalse;
+}
+
+IdentityFunction::~IdentityFunction() {
+}
+
+void IdentityFunction::transform(const double *in, double *out) const {
+ int i;
+
+ for (i = 0; i < funcMaxOutputs; ++i) {
+ out[i] = in[i];
+ }
+}
+
+//------------------------------------------------------------------------
+// SampledFunction
+//------------------------------------------------------------------------
+
+SampledFunction::SampledFunction(Object *funcObj, Dict *dict) {
+ Stream *str;
+ int nSamples, sampleBits;
+ double sampleMul;
+ Object obj1, obj2;
+ Guint buf, bitMask;
+ int bits;
+ int s;
+ int i;
+
+ samples = NULL;
+ ok = gFalse;
+
+ //----- initialize the generic stuff
+ if (!init(dict)) {
+ goto err1;
+ }
+ if (!hasRange) {
+ error(-1, "Type 0 function is missing range");
+ goto err1;
+ }
+
+ //----- get the stream
+ if (!funcObj->isStream()) {
+ error(-1, "Type 0 function isn't a stream");
+ goto err1;
+ }
+ str = funcObj->getStream();
+
+ //----- Size
+ if (!dict->lookup("Size", &obj1)->isArray() ||
+ obj1.arrayGetLength() != m) {
+ error(-1, "Function has missing or invalid size array");
+ goto err2;
+ }
+ for (i = 0; i < m; ++i) {
+ obj1.arrayGet(i, &obj2);
+ if (!obj2.isInt()) {
+ error(-1, "Illegal value in function size array");
+ goto err3;
+ }
+ sampleSize[i] = obj2.getInt();
+ obj2.free();
+ }
+ obj1.free();
+
+ //----- BitsPerSample
+ if (!dict->lookup("BitsPerSample", &obj1)->isInt()) {
+ error(-1, "Function has missing or invalid BitsPerSample");
+ goto err2;
+ }
+ sampleBits = obj1.getInt();
+ sampleMul = 1.0 / (double)((1 << sampleBits) - 1);
+ obj1.free();
+
+ //----- Encode
+ if (dict->lookup("Encode", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2*m) {
+ for (i = 0; i < m; ++i) {
+ obj1.arrayGet(2*i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function encode array");
+ goto err3;
+ }
+ encode[i][0] = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2*i+1, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function encode array");
+ goto err3;
+ }
+ encode[i][1] = obj2.getNum();
+ obj2.free();
+ }
+ } else {
+ for (i = 0; i < m; ++i) {
+ encode[i][0] = 0;
+ encode[i][1] = sampleSize[i] - 1;
+ }
+ }
+ obj1.free();
+
+ //----- Decode
+ if (dict->lookup("Decode", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2*n) {
+ for (i = 0; i < n; ++i) {
+ obj1.arrayGet(2*i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function decode array");
+ goto err3;
+ }
+ decode[i][0] = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2*i+1, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function decode array");
+ goto err3;
+ }
+ decode[i][1] = obj2.getNum();
+ obj2.free();
+ }
+ } else {
+ for (i = 0; i < n; ++i) {
+ decode[i][0] = range[i][0];
+ decode[i][1] = range[i][1];
+ }
+ }
+ obj1.free();
+
+ //----- samples
+ nSamples = n;
+ for (i = 0; i < m; ++i)
+ nSamples *= sampleSize[i];
+ samples = (double *)gmalloc(nSamples * sizeof(double));
+ buf = 0;
+ bits = 0;
+ bitMask = (1 << sampleBits) - 1;
+ str->reset();
+ for (i = 0; i < nSamples; ++i) {
+ if (sampleBits == 8) {
+ s = str->getChar();
+ } else if (sampleBits == 16) {
+ s = str->getChar();
+ s = (s << 8) + str->getChar();
+ } else if (sampleBits == 32) {
+ s = str->getChar();
+ s = (s << 8) + str->getChar();
+ s = (s << 8) + str->getChar();
+ s = (s << 8) + str->getChar();
+ } else {
+ while (bits < sampleBits) {
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bits += 8;
+ }
+ s = (buf >> (bits - sampleBits)) & bitMask;
+ bits -= sampleBits;
+ }
+ samples[i] = (double)s * sampleMul;
+ }
+ str->close();
+
+ ok = gTrue;
+ return;
+
+ err3:
+ obj2.free();
+ err2:
+ obj1.free();
+ err1:
+ return;
+}
+
+SampledFunction::~SampledFunction() {
+ if (samples) {
+ gfree(samples);
+ }
+}
+
+SampledFunction::SampledFunction(const SampledFunction *func) {
+ int nSamples, i;
+
+ memcpy(this, func, sizeof(SampledFunction));
+
+ nSamples = n;
+ for (i = 0; i < m; ++i) {
+ nSamples *= sampleSize[i];
+ }
+ samples = (double *)gmalloc(nSamples * sizeof(double));
+ memcpy(samples, func->samples, nSamples * sizeof(double));
+}
+
+void SampledFunction::transform(const double *in, double *out) const {
+ double x;
+ int e[2][funcMaxInputs];
+ double efrac[funcMaxInputs];
+ double s0[1 << funcMaxInputs], s1[1 << funcMaxInputs];
+ int i, j, k, idx;
+
+ // map input values into sample array
+ for (i = 0; i < m; ++i) {
+ x = ((in[i] - domain[i][0]) / (domain[i][1] - domain[i][0])) *
+ (encode[i][1] - encode[i][0]) + encode[i][0];
+ if (x < 0) {
+ x = 0;
+ } else if (x > sampleSize[i] - 1) {
+ x = sampleSize[i] - 1;
+ }
+ e[0][i] = (int)floor(x);
+ e[1][i] = (int)ceil(x);
+ efrac[i] = x - e[0][i];
+ }
+
+ // for each output, do m-linear interpolation
+ for (i = 0; i < n; ++i) {
+
+ // pull 2^m values out of the sample array
+ for (j = 0; j < (1<<m); ++j) {
+ idx = e[j & 1][m - 1];
+ for (k = m - 2; k >= 0; --k) {
+ idx = idx * sampleSize[k] + e[(j >> k) & 1][k];
+ }
+ idx = idx * n + i;
+ s0[j] = samples[idx];
+ }
+
+ // do m sets of interpolations
+ for (j = 0; j < m; ++j) {
+ for (k = 0; k < (1 << (m - j)); k += 2) {
+ s1[k >> 1] = (1 - efrac[j]) * s0[k] + efrac[j] * s0[k+1];
+ }
+ memcpy(s0, s1, (1 << (m - j - 1)) * sizeof(double));
+ }
+
+ // map output value to range
+ out[i] = s0[0] * (decode[i][1] - decode[i][0]) + decode[i][0];
+ if (out[i] < range[i][0]) {
+ out[i] = range[i][0];
+ } else if (out[i] > range[i][1]) {
+ out[i] = range[i][1];
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// ExponentialFunction
+//------------------------------------------------------------------------
+
+ExponentialFunction::ExponentialFunction(Object */*funcObj*/, Dict *dict) {
+ Object obj1, obj2;
+ GBool hasN;
+ int i;
+
+ ok = gFalse;
+
+ //----- initialize the generic stuff
+ if (!init(dict)) {
+ goto err1;
+ }
+ if (m != 1) {
+ error(-1, "Exponential function with more than one input");
+ goto err1;
+ }
+ hasN = hasRange;
+
+ //----- default values
+ for (i = 0; i < funcMaxOutputs; ++i) {
+ c0[i] = 0;
+ c1[i] = 1;
+ }
+
+ //----- C0
+ if (dict->lookup("C0", &obj1)->isArray()) {
+ if (!hasN) {
+ n = obj1.arrayGetLength();
+ hasN = gTrue;
+ } else if (obj1.arrayGetLength() != n) {
+ error(-1, "Function's C0 array is wrong length");
+ goto err2;
+ }
+ for (i = 0; i < n; ++i) {
+ obj1.arrayGet(i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function C0 array");
+ goto err3;
+ }
+ c0[i] = obj2.getNum();
+ obj2.free();
+ }
+ }
+ obj1.free();
+
+ //----- C1
+ if (dict->lookup("C1", &obj1)->isArray()) {
+ if (!hasN) {
+ n = obj1.arrayGetLength();
+ hasN = gTrue;
+ } else if (obj1.arrayGetLength() != n) {
+ error(-1, "Function's C1 array is wrong length");
+ goto err2;
+ }
+ for (i = 0; i < n; ++i) {
+ obj1.arrayGet(i, &obj2);
+ if (!obj2.isNum()) {
+ error(-1, "Illegal value in function C1 array");
+ goto err3;
+ }
+ c1[i] = obj2.getNum();
+ obj2.free();
+ }
+ }
+ obj1.free();
+
+ //----- N (exponent)
+ if (!dict->lookup("N", &obj1)->isNum()) {
+ error(-1, "Function has missing or invalid N");
+ goto err2;
+ }
+ e = obj1.getNum();
+ obj1.free();
+
+ // this isn't supposed to happen, but I've run into (broken) PDF
+ // files where it does
+ if (!hasN) {
+ error(-1, "Exponential function does not define number of output values");
+ n = 1;
+ }
+
+ ok = gTrue;
+ return;
+
+ err3:
+ obj2.free();
+ err2:
+ obj1.free();
+ err1:
+ return;
+}
+
+ExponentialFunction::~ExponentialFunction() {
+}
+
+ExponentialFunction::ExponentialFunction(const ExponentialFunction *func) {
+ memcpy(this, func, sizeof(ExponentialFunction));
+}
+
+void ExponentialFunction::transform(const double *in, double *out) const {
+ double x;
+ int i;
+
+ if (in[0] < domain[0][0]) {
+ x = domain[0][0];
+ } else if (in[0] > domain[0][1]) {
+ x = domain[0][1];
+ } else {
+ x = in[0];
+ }
+ for (i = 0; i < n; ++i) {
+ out[i] = c0[i] + pow(x, e) * (c1[i] - c0[i]);
+ if (hasRange) {
+ if (out[i] < range[i][0]) {
+ out[i] = range[i][0];
+ } else if (out[i] > range[i][1]) {
+ out[i] = range[i][1];
+ }
+ }
+ }
+ return;
+}
+
+//------------------------------------------------------------------------
+// StitchingFunction
+//------------------------------------------------------------------------
+
+StitchingFunction::StitchingFunction(Object */*funcObj*/, Dict *dict) {
+ Object obj1, obj2;
+ int i;
+
+ ok = gFalse;
+ funcs = NULL;
+ bounds = NULL;
+ encode = NULL;
+
+ //----- initialize the generic stuff
+ if (!init(dict)) {
+ goto err1;
+ }
+ if (m != 1) {
+ error(-1, "Stitching function with more than one input");
+ goto err1;
+ }
+
+ //----- Functions
+ if (!dict->lookup("Functions", &obj1)->isArray()) {
+ error(-1, "Missing 'Functions' entry in stitching function");
+ goto err1;
+ }
+ k = obj1.arrayGetLength();
+ funcs = (Function **)gmalloc(k * sizeof(Function *));
+ bounds = (double *)gmalloc((k + 1) * sizeof(double));
+ encode = (double *)gmalloc(2 * k * sizeof(double));
+ for (i = 0; i < k; ++i) {
+ funcs[i] = NULL;
+ }
+ for (i = 0; i < k; ++i) {
+ if (!(funcs[i] = Function::parse(obj1.arrayGet(i, &obj2)))) {
+ goto err2;
+ }
+ if (i > 0 && (funcs[i]->getInputSize() != 1 ||
+ funcs[i]->getOutputSize() != funcs[0]->getOutputSize())) {
+ error(-1, "Incompatible subfunctions in stitching function");
+ goto err2;
+ }
+ obj2.free();
+ }
+ obj1.free();
+
+ //----- Bounds
+ if (!dict->lookup("Bounds", &obj1)->isArray() ||
+ obj1.arrayGetLength() != k - 1) {
+ error(-1, "Missing or invalid 'Bounds' entry in stitching function");
+ goto err1;
+ }
+ bounds[0] = domain[0][0];
+ for (i = 1; i < k; ++i) {
+ if (!obj1.arrayGet(i - 1, &obj2)->isNum()) {
+ error(-1, "Invalid type in 'Bounds' array in stitching function");
+ goto err2;
+ }
+ bounds[i] = obj2.getNum();
+ obj2.free();
+ }
+ bounds[k] = domain[0][1];
+ obj1.free();
+
+ //----- Encode
+ if (!dict->lookup("Encode", &obj1)->isArray() ||
+ obj1.arrayGetLength() != 2 * k) {
+ error(-1, "Missing or invalid 'Encode' entry in stitching function");
+ goto err1;
+ }
+ for (i = 0; i < 2 * k; ++i) {
+ if (!obj1.arrayGet(i, &obj2)->isNum()) {
+ error(-1, "Invalid type in 'Encode' array in stitching function");
+ goto err2;
+ }
+ encode[i] = obj2.getNum();
+ obj2.free();
+ }
+ obj1.free();
+
+ ok = gTrue;
+ return;
+
+ err2:
+ obj2.free();
+ err1:
+ obj1.free();
+}
+
+StitchingFunction::StitchingFunction(const StitchingFunction *func) {
+ k = func->k;
+ funcs = (Function **)gmalloc(k * sizeof(Function *));
+ memcpy(funcs, func->funcs, k * sizeof(Function *));
+ bounds = (double *)gmalloc((k + 1) * sizeof(double));
+ memcpy(bounds, func->bounds, (k + 1) * sizeof(double));
+ encode = (double *)gmalloc(2 * k * sizeof(double));
+ memcpy(encode, func->encode, 2 * k * sizeof(double));
+ ok = gTrue;
+}
+
+StitchingFunction::~StitchingFunction() {
+ int i;
+
+ for (i = 0; i < k; ++i) {
+ if (funcs[i]) {
+ delete funcs[i];
+ }
+ }
+ gfree(funcs);
+ gfree(bounds);
+ gfree(encode);
+}
+
+void StitchingFunction::transform(const double *in, double *out) const {
+ double x;
+ int i;
+
+ if (in[0] < domain[0][0]) {
+ x = domain[0][0];
+ } else if (in[0] > domain[0][1]) {
+ x = domain[0][1];
+ } else {
+ x = in[0];
+ }
+ for (i = 0; i < k - 1; ++i) {
+ if (x < bounds[i+1]) {
+ break;
+ }
+ }
+ x = encode[2*i] + ((x - bounds[i]) / (bounds[i+1] - bounds[i])) *
+ (encode[2*i+1] - encode[2*i]);
+ funcs[i]->transform(&x, out);
+}
+
+//------------------------------------------------------------------------
+// PostScriptFunction
+//------------------------------------------------------------------------
+
+enum PSOp {
+ psOpAbs,
+ psOpAdd,
+ psOpAnd,
+ psOpAtan,
+ psOpBitshift,
+ psOpCeiling,
+ psOpCopy,
+ psOpCos,
+ psOpCvi,
+ psOpCvr,
+ psOpDiv,
+ psOpDup,
+ psOpEq,
+ psOpExch,
+ psOpExp,
+ psOpFalse,
+ psOpFloor,
+ psOpGe,
+ psOpGt,
+ psOpIdiv,
+ psOpIndex,
+ psOpLe,
+ psOpLn,
+ psOpLog,
+ psOpLt,
+ psOpMod,
+ psOpMul,
+ psOpNe,
+ psOpNeg,
+ psOpNot,
+ psOpOr,
+ psOpPop,
+ psOpRoll,
+ psOpRound,
+ psOpSin,
+ psOpSqrt,
+ psOpSub,
+ psOpTrue,
+ psOpTruncate,
+ psOpXor,
+ psOpIf,
+ psOpIfelse,
+ psOpReturn
+};
+
+// Note: 'if' and 'ifelse' are parsed separately.
+// The rest are listed here in alphabetical order.
+// The index in this table is equivalent to the entry in PSOp.
+const char *psOpNames[] = {
+ "abs",
+ "add",
+ "and",
+ "atan",
+ "bitshift",
+ "ceiling",
+ "copy",
+ "cos",
+ "cvi",
+ "cvr",
+ "div",
+ "dup",
+ "eq",
+ "exch",
+ "exp",
+ "false",
+ "floor",
+ "ge",
+ "gt",
+ "idiv",
+ "index",
+ "le",
+ "ln",
+ "log",
+ "lt",
+ "mod",
+ "mul",
+ "ne",
+ "neg",
+ "not",
+ "or",
+ "pop",
+ "roll",
+ "round",
+ "sin",
+ "sqrt",
+ "sub",
+ "true",
+ "truncate",
+ "xor"
+};
+
+#define nPSOps (sizeof(psOpNames) / sizeof(char *))
+
+enum PSObjectType {
+ psBool,
+ psInt,
+ psReal,
+ psOperator,
+ psBlock
+};
+
+// In the code array, 'if'/'ifelse' operators take up three slots
+// plus space for the code in the subclause(s).
+//
+// +---------------------------------+
+// | psOperator: psOpIf / psOpIfelse |
+// +---------------------------------+
+// | psBlock: ptr=<A> |
+// +---------------------------------+
+// | psBlock: ptr=<B> |
+// +---------------------------------+
+// | if clause |
+// | ... |
+// | psOperator: psOpReturn |
+// +---------------------------------+
+// <A> | else clause |
+// | ... |
+// | psOperator: psOpReturn |
+// +---------------------------------+
+// <B> | ... |
+//
+// For 'if', pointer <A> is present in the code stream but unused.
+
+struct PSObject {
+ PSObjectType type;
+ union {
+ GBool booln; // boolean (stack only)
+ int intg; // integer (stack and code)
+ double real; // real (stack and code)
+ PSOp op; // operator (code only)
+ int blk; // if/ifelse block pointer (code only)
+ };
+};
+
+#define psStackSize 100
+
+class PSStack {
+public:
+
+ PSStack() { sp = psStackSize; }
+ void pushBool(GBool booln);
+ void pushInt(int intg);
+ void pushReal(double real);
+ GBool popBool();
+ int popInt();
+ double popNum();
+ GBool empty() { return sp == psStackSize; }
+ GBool topIsInt() { return sp < psStackSize && stack[sp].type == psInt; }
+ GBool topTwoAreInts()
+ { return sp < psStackSize - 1 &&
+ stack[sp].type == psInt &&
+ stack[sp+1].type == psInt; }
+ GBool topIsReal() { return sp < psStackSize && stack[sp].type == psReal; }
+ GBool topTwoAreNums()
+ { return sp < psStackSize - 1 &&
+ (stack[sp].type == psInt || stack[sp].type == psReal) &&
+ (stack[sp+1].type == psInt || stack[sp+1].type == psReal); }
+ void copy(int n);
+ void roll(int n, int j);
+ void index(int i);
+ void pop();
+
+private:
+
+ GBool checkOverflow(int n = 1);
+ GBool checkUnderflow();
+ GBool checkType(PSObjectType t1, PSObjectType t2);
+
+ PSObject stack[psStackSize];
+ int sp;
+};
+
+GBool PSStack::checkOverflow(int n) {
+ if (sp - n < 0) {
+ error(-1, "Stack overflow in PostScript function");
+ return gFalse;
+ }
+ return gTrue;
+}
+
+GBool PSStack::checkUnderflow() {
+ if (sp == psStackSize) {
+ error(-1, "Stack underflow in PostScript function");
+ return gFalse;
+ }
+ return gTrue;
+}
+
+GBool PSStack::checkType(PSObjectType t1, PSObjectType t2) {
+ if (stack[sp].type != t1 && stack[sp].type != t2) {
+ error(-1, "Type mismatch in PostScript function");
+ return gFalse;
+ }
+ return gTrue;
+}
+
+void PSStack::pushBool(GBool booln) {
+ if (checkOverflow()) {
+ stack[--sp].type = psBool;
+ stack[sp].booln = booln;
+ }
+}
+
+void PSStack::pushInt(int intg) {
+ if (checkOverflow()) {
+ stack[--sp].type = psInt;
+ stack[sp].intg = intg;
+ }
+}
+
+void PSStack::pushReal(double real) {
+ if (checkOverflow()) {
+ stack[--sp].type = psReal;
+ stack[sp].real = real;
+ }
+}
+
+GBool PSStack::popBool() {
+ if (checkUnderflow() && checkType(psBool, psBool)) {
+ return stack[sp++].booln;
+ }
+ return gFalse;
+}
+
+int PSStack::popInt() {
+ if (checkUnderflow() && checkType(psInt, psInt)) {
+ return stack[sp++].intg;
+ }
+ return 0;
+}
+
+double PSStack::popNum() {
+ double ret;
+
+ if (checkUnderflow() && checkType(psInt, psReal)) {
+ ret = (stack[sp].type == psInt) ? (double)stack[sp].intg : stack[sp].real;
+ ++sp;
+ return ret;
+ }
+ return 0;
+}
+
+void PSStack::copy(int n) {
+ int i;
+
+ if (!checkOverflow(n)) {
+ return;
+ }
+ for (i = sp + n - 1; i <= sp; ++i) {
+ stack[i - n] = stack[i];
+ }
+ sp -= n;
+}
+
+void PSStack::roll(int n, int j) {
+ PSObject obj;
+ int i, k;
+
+ if (j >= 0) {
+ j %= n;
+ } else {
+ j = -j % n;
+ if (j != 0) {
+ j = n - j;
+ }
+ }
+ if (n <= 0 || j == 0) {
+ return;
+ }
+ for (i = 0; i < j; ++i) {
+ obj = stack[sp];
+ for (k = sp; k < sp + n - 1; ++k) {
+ stack[k] = stack[k+1];
+ }
+ stack[sp + n - 1] = obj;
+ }
+}
+
+void PSStack::index(int i) {
+ if (!checkOverflow()) {
+ return;
+ }
+ --sp;
+ stack[sp] = stack[sp + 1 + i];
+}
+
+void PSStack::pop() {
+ if (!checkUnderflow()) {
+ return;
+ }
+ ++sp;
+}
+
+PostScriptFunction::PostScriptFunction(Object *funcObj, Dict *dict) {
+ Stream *str;
+ int codePtr;
+ GString *tok;
+
+ code = NULL;
+ codeSize = 0;
+ ok = gFalse;
+
+ //----- initialize the generic stuff
+ if (!init(dict)) {
+ goto err1;
+ }
+ if (!hasRange) {
+ error(-1, "Type 4 function is missing range");
+ goto err1;
+ }
+
+ //----- get the stream
+ if (!funcObj->isStream()) {
+ error(-1, "Type 4 function isn't a stream");
+ goto err1;
+ }
+ str = funcObj->getStream();
+
+ //----- parse the function
+ str->reset();
+ if (!(tok = getToken(str)) || tok->cmp("{")) {
+ error(-1, "Expected '{' at start of PostScript function");
+ if (tok) {
+ delete tok;
+ }
+ goto err1;
+ }
+ delete tok;
+ codePtr = 0;
+ if (!parseCode(str, &codePtr)) {
+ goto err2;
+ }
+ str->close();
+
+ ok = gTrue;
+
+ err2:
+ str->close();
+ err1:
+ return;
+}
+
+PostScriptFunction::PostScriptFunction(const PostScriptFunction *func) {
+ memcpy(this, func, sizeof(PostScriptFunction));
+ code = (PSObject *)gmalloc(codeSize * sizeof(PSObject));
+ memcpy(code, func->code, codeSize * sizeof(PSObject));
+}
+
+PostScriptFunction::~PostScriptFunction() {
+ gfree(code);
+}
+
+void PostScriptFunction::transform(const double *in, double *out) const {
+ PSStack *stack;
+ int i;
+
+ stack = new PSStack();
+ for (i = 0; i < m; ++i) {
+ //~ may need to check for integers here
+ stack->pushReal(in[i]);
+ }
+ exec(stack, 0);
+ for (i = n - 1; i >= 0; --i) {
+ out[i] = stack->popNum();
+ if (out[i] < range[i][0]) {
+ out[i] = range[i][0];
+ } else if (out[i] > range[i][1]) {
+ out[i] = range[i][1];
+ }
+ }
+ // if (!stack->empty()) {
+ // error(-1, "Extra values on stack at end of PostScript function");
+ // }
+ delete stack;
+}
+
+GBool PostScriptFunction::parseCode(Stream *str, int *codePtr) {
+ GString *tok;
+ char *p;
+ GBool isReal;
+ int opPtr, elsePtr;
+ int a, b, mid, cmp;
+
+ while (1) {
+ if (!(tok = getToken(str))) {
+ error(-1, "Unexpected end of PostScript function stream");
+ return gFalse;
+ }
+ p = tok->getCString();
+ if (isdigit(*p) || *p == '.' || *p == '-') {
+ isReal = gFalse;
+ for (++p; *p; ++p) {
+ if (*p == '.') {
+ isReal = gTrue;
+ break;
+ }
+ }
+ resizeCode(*codePtr);
+ if (isReal) {
+ code[*codePtr].type = psReal;
+ code[*codePtr].real = atof(tok->getCString());
+ } else {
+ code[*codePtr].type = psInt;
+ code[*codePtr].intg = atoi(tok->getCString());
+ }
+ ++*codePtr;
+ delete tok;
+ } else if (!tok->cmp("{")) {
+ delete tok;
+ opPtr = *codePtr;
+ *codePtr += 3;
+ resizeCode(opPtr + 2);
+ if (!parseCode(str, codePtr)) {
+ return gFalse;
+ }
+ if (!(tok = getToken(str))) {
+ error(-1, "Unexpected end of PostScript function stream");
+ return gFalse;
+ }
+ if (!tok->cmp("{")) {
+ elsePtr = *codePtr;
+ if (!parseCode(str, codePtr)) {
+ return gFalse;
+ }
+ delete tok;
+ if (!(tok = getToken(str))) {
+ error(-1, "Unexpected end of PostScript function stream");
+ return gFalse;
+ }
+ } else {
+ elsePtr = -1;
+ }
+ if (!tok->cmp("if")) {
+ if (elsePtr >= 0) {
+ error(-1, "Got 'if' operator with two blocks in PostScript function");
+ return gFalse;
+ }
+ code[opPtr].type = psOperator;
+ code[opPtr].op = psOpIf;
+ code[opPtr+2].type = psBlock;
+ code[opPtr+2].blk = *codePtr;
+ } else if (!tok->cmp("ifelse")) {
+ if (elsePtr < 0) {
+ error(-1, "Got 'ifelse' operator with one blocks in PostScript function");
+ return gFalse;
+ }
+ code[opPtr].type = psOperator;
+ code[opPtr].op = psOpIfelse;
+ code[opPtr+1].type = psBlock;
+ code[opPtr+1].blk = elsePtr;
+ code[opPtr+2].type = psBlock;
+ code[opPtr+2].blk = *codePtr;
+ } else {
+ error(-1, "Expected if/ifelse operator in PostScript function");
+ delete tok;
+ return gFalse;
+ }
+ delete tok;
+ } else if (!tok->cmp("}")) {
+ delete tok;
+ resizeCode(*codePtr);
+ code[*codePtr].type = psOperator;
+ code[*codePtr].op = psOpReturn;
+ ++*codePtr;
+ break;
+ } else {
+ a = -1;
+ b = nPSOps;
+ // invariant: psOpNames[a] < tok < psOpNames[b]
+ while (b - a > 1) {
+ mid = (a + b) / 2;
+ cmp = tok->cmp(psOpNames[mid]);
+ if (cmp > 0) {
+ a = mid;
+ } else if (cmp < 0) {
+ b = mid;
+ } else {
+ a = b = mid;
+ }
+ }
+ if (cmp != 0) {
+ error(-1, "Unknown operator '%s' in PostScript function",
+ tok->getCString());
+ delete tok;
+ return gFalse;
+ }
+ delete tok;
+ resizeCode(*codePtr);
+ code[*codePtr].type = psOperator;
+ code[*codePtr].op = (PSOp)a;
+ ++*codePtr;
+ }
+ }
+ return gTrue;
+}
+
+GString *PostScriptFunction::getToken(Stream *str) {
+ GString *s;
+ int c;
+
+ s = new GString();
+ do {
+ c = str->getChar();
+ } while (c != EOF && isspace(c));
+ if (c == '{' || c == '}') {
+ s->append((char)c);
+ } else if (isdigit(c) || c == '.' || c == '-') {
+ while (1) {
+ s->append((char)c);
+ c = str->lookChar();
+ if (c == EOF || !(isdigit(c) || c == '.' || c == '-')) {
+ break;
+ }
+ str->getChar();
+ }
+ } else {
+ while (1) {
+ s->append((char)c);
+ c = str->lookChar();
+ if (c == EOF || !isalnum(c)) {
+ break;
+ }
+ str->getChar();
+ }
+ }
+ return s;
+}
+
+void PostScriptFunction::resizeCode(int newSize) {
+ if (newSize >= codeSize) {
+ codeSize += 64;
+ code = (PSObject *)grealloc(code, codeSize * sizeof(PSObject));
+ }
+}
+
+void PostScriptFunction::exec(PSStack *stack, int codePtr) const {
+ int i1, i2;
+ double r1, r2;
+ GBool b1, b2;
+
+ while (1) {
+ switch (code[codePtr].type) {
+ case psInt:
+ stack->pushInt(code[codePtr++].intg);
+ break;
+ case psReal:
+ stack->pushReal(code[codePtr++].real);
+ break;
+ case psOperator:
+ switch (code[codePtr++].op) {
+ case psOpAbs:
+ if (stack->topIsInt()) {
+ stack->pushInt(abs(stack->popInt()));
+ } else {
+ stack->pushReal(fabs(stack->popNum()));
+ }
+ break;
+ case psOpAdd:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 + i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushReal(r1 + r2);
+ }
+ break;
+ case psOpAnd:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 & i2);
+ } else {
+ b2 = stack->popBool();
+ b1 = stack->popBool();
+ stack->pushReal(b1 && b2);
+ }
+ break;
+ case psOpAtan:
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushReal(atan2(r1, r2));
+ break;
+ case psOpBitshift:
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ if (i2 > 0) {
+ stack->pushInt(i1 << i2);
+ } else if (i2 < 0) {
+ stack->pushInt((int)((Guint)i1 >> i2));
+ } else {
+ stack->pushInt(i1);
+ }
+ break;
+ case psOpCeiling:
+ if (!stack->topIsInt()) {
+ stack->pushReal(ceil(stack->popNum()));
+ }
+ break;
+ case psOpCopy:
+ stack->copy(stack->popInt());
+ break;
+ case psOpCos:
+ stack->pushReal(cos(stack->popNum()));
+ break;
+ case psOpCvi:
+ if (!stack->topIsInt()) {
+ stack->pushInt((int)stack->popNum());
+ }
+ break;
+ case psOpCvr:
+ if (!stack->topIsReal()) {
+ stack->pushReal(stack->popNum());
+ }
+ break;
+ case psOpDiv:
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushReal(r1 / r2);
+ break;
+ case psOpDup:
+ stack->copy(1);
+ break;
+ case psOpEq:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 == i2);
+ } else if (stack->topTwoAreNums()) {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 == r2);
+ } else {
+ b2 = stack->popBool();
+ b1 = stack->popBool();
+ stack->pushBool(b1 == b2);
+ }
+ break;
+ case psOpExch:
+ stack->roll(2, 1);
+ break;
+ case psOpExp:
+ r2 = stack->popInt();
+ r1 = stack->popInt();
+ stack->pushReal(pow(r1, r2));
+ break;
+ case psOpFalse:
+ stack->pushBool(gFalse);
+ break;
+ case psOpFloor:
+ if (!stack->topIsInt()) {
+ stack->pushReal(floor(stack->popNum()));
+ }
+ break;
+ case psOpGe:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 >= i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 >= r2);
+ }
+ break;
+ case psOpGt:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 > i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 > r2);
+ }
+ break;
+ case psOpIdiv:
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 / i2);
+ break;
+ case psOpIndex:
+ stack->index(stack->popInt());
+ break;
+ case psOpLe:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 <= i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 <= r2);
+ }
+ break;
+ case psOpLn:
+ stack->pushReal(log(stack->popNum()));
+ break;
+ case psOpLog:
+ stack->pushReal(log10(stack->popNum()));
+ break;
+ case psOpLt:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 < i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 < r2);
+ }
+ break;
+ case psOpMod:
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 % i2);
+ break;
+ case psOpMul:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ //~ should check for out-of-range, and push a real instead
+ stack->pushInt(i1 * i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushReal(r1 * r2);
+ }
+ break;
+ case psOpNe:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushBool(i1 != i2);
+ } else if (stack->topTwoAreNums()) {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushBool(r1 != r2);
+ } else {
+ b2 = stack->popBool();
+ b1 = stack->popBool();
+ stack->pushBool(b1 != b2);
+ }
+ break;
+ case psOpNeg:
+ if (stack->topIsInt()) {
+ stack->pushInt(-stack->popInt());
+ } else {
+ stack->pushReal(-stack->popNum());
+ }
+ break;
+ case psOpNot:
+ if (stack->topIsInt()) {
+ stack->pushInt(~stack->popInt());
+ } else {
+ stack->pushReal(!stack->popBool());
+ }
+ break;
+ case psOpOr:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 | i2);
+ } else {
+ b2 = stack->popBool();
+ b1 = stack->popBool();
+ stack->pushReal(b1 || b2);
+ }
+ break;
+ case psOpPop:
+ stack->pop();
+ break;
+ case psOpRoll:
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->roll(i1, i2);
+ break;
+ case psOpRound:
+ if (!stack->topIsInt()) {
+ r1 = stack->popNum();
+ stack->pushReal((r1 >= 0) ? floor(r1 + 0.5) : ceil(r1 - 0.5));
+ }
+ break;
+ case psOpSin:
+ stack->pushReal(cos(stack->popNum()));
+ break;
+ case psOpSqrt:
+ stack->pushReal(sqrt(stack->popNum()));
+ break;
+ case psOpSub:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 - i2);
+ } else {
+ r2 = stack->popNum();
+ r1 = stack->popNum();
+ stack->pushReal(r1 - r2);
+ }
+ break;
+ case psOpTrue:
+ stack->pushBool(gTrue);
+ break;
+ case psOpTruncate:
+ if (!stack->topIsInt()) {
+ r1 = stack->popNum();
+ stack->pushReal((r1 >= 0) ? floor(r1) : ceil(r1));
+ }
+ break;
+ case psOpXor:
+ if (stack->topTwoAreInts()) {
+ i2 = stack->popInt();
+ i1 = stack->popInt();
+ stack->pushInt(i1 ^ i2);
+ } else {
+ b2 = stack->popBool();
+ b1 = stack->popBool();
+ stack->pushReal(b1 ^ b2);
+ }
+ break;
+ case psOpIf:
+ b1 = stack->popBool();
+ if (b1) {
+ exec(stack, codePtr + 2);
+ }
+ codePtr = code[codePtr + 1].blk;
+ break;
+ case psOpIfelse:
+ b1 = stack->popBool();
+ if (b1) {
+ exec(stack, codePtr + 2);
+ } else {
+ exec(stack, code[codePtr].blk);
+ }
+ codePtr = code[codePtr + 1].blk;
+ break;
+ case psOpReturn:
+ return;
+ }
+ break;
+ default:
+ error(-1, "Internal: bad object in PostScript function code");
+ break;
+ }
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Gfx.cc b/filters/kword/pdf/xpdf/xpdf/Gfx.cc
deleted file mode 100644
index 7948d78ae..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Gfx.cc
+++ /dev/null
@@ -1,2782 +0,0 @@
-//========================================================================
-//
-// Gfx.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stddef.h>
-#include <string.h>
-#include <math.h>
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "CharTypes.h"
-#include "Object.h"
-#include "Array.h"
-#include "Dict.h"
-#include "Stream.h"
-#include "Lexer.h"
-#include "Parser.h"
-#include "GfxFont.h"
-#include "GfxState.h"
-#include "OutputDev.h"
-#include "Page.h"
-#include "Error.h"
-#include "Gfx.h"
-
-// the MSVC math.h doesn't define this
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
-
-//------------------------------------------------------------------------
-// constants
-//------------------------------------------------------------------------
-
-// Max number of splits along the t axis for an axial shading fill.
-#define axialMaxSplits 256
-
-// Max delta allowed in any color component for an axial shading fill.
-#define axialColorDelta (1 / 256.0)
-
-// Max number of splits along the t axis for a radial shading fill.
-#define radialMaxSplits 256
-
-// Max delta allowed in any color component for a radial shading fill.
-#define radialColorDelta (1 / 256.0)
-
-//------------------------------------------------------------------------
-// Operator table
-//------------------------------------------------------------------------
-
-Operator Gfx::opTab[] = {
- {"\"", 3, {tchkNum, tchkNum, tchkString},
- &Gfx::opMoveSetShowText},
- {"'", 1, {tchkString},
- &Gfx::opMoveShowText},
- {"B", 0, {tchkNone},
- &Gfx::opFillStroke},
- {"B*", 0, {tchkNone},
- &Gfx::opEOFillStroke},
- {"BDC", 2, {tchkName, tchkProps},
- &Gfx::opBeginMarkedContent},
- {"BI", 0, {tchkNone},
- &Gfx::opBeginImage},
- {"BMC", 1, {tchkName},
- &Gfx::opBeginMarkedContent},
- {"BT", 0, {tchkNone},
- &Gfx::opBeginText},
- {"BX", 0, {tchkNone},
- &Gfx::opBeginIgnoreUndef},
- {"CS", 1, {tchkName},
- &Gfx::opSetStrokeColorSpace},
- {"DP", 2, {tchkName, tchkProps},
- &Gfx::opMarkPoint},
- {"Do", 1, {tchkName},
- &Gfx::opXObject},
- {"EI", 0, {tchkNone},
- &Gfx::opEndImage},
- {"EMC", 0, {tchkNone},
- &Gfx::opEndMarkedContent},
- {"ET", 0, {tchkNone},
- &Gfx::opEndText},
- {"EX", 0, {tchkNone},
- &Gfx::opEndIgnoreUndef},
- {"F", 0, {tchkNone},
- &Gfx::opFill},
- {"G", 1, {tchkNum},
- &Gfx::opSetStrokeGray},
- {"ID", 0, {tchkNone},
- &Gfx::opImageData},
- {"J", 1, {tchkInt},
- &Gfx::opSetLineCap},
- {"K", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opSetStrokeCMYKColor},
- {"M", 1, {tchkNum},
- &Gfx::opSetMiterLimit},
- {"MP", 1, {tchkName},
- &Gfx::opMarkPoint},
- {"Q", 0, {tchkNone},
- &Gfx::opRestore},
- {"RG", 3, {tchkNum, tchkNum, tchkNum},
- &Gfx::opSetStrokeRGBColor},
- {"S", 0, {tchkNone},
- &Gfx::opStroke},
- {"SC", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opSetStrokeColor},
- {"SCN", -5, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
- tchkSCN},
- &Gfx::opSetStrokeColorN},
- {"T*", 0, {tchkNone},
- &Gfx::opTextNextLine},
- {"TD", 2, {tchkNum, tchkNum},
- &Gfx::opTextMoveSet},
- {"TJ", 1, {tchkArray},
- &Gfx::opShowSpaceText},
- {"TL", 1, {tchkNum},
- &Gfx::opSetTextLeading},
- {"Tc", 1, {tchkNum},
- &Gfx::opSetCharSpacing},
- {"Td", 2, {tchkNum, tchkNum},
- &Gfx::opTextMove},
- {"Tf", 2, {tchkName, tchkNum},
- &Gfx::opSetFont},
- {"Tj", 1, {tchkString},
- &Gfx::opShowText},
- {"Tm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
- tchkNum, tchkNum},
- &Gfx::opSetTextMatrix},
- {"Tr", 1, {tchkInt},
- &Gfx::opSetTextRender},
- {"Ts", 1, {tchkNum},
- &Gfx::opSetTextRise},
- {"Tw", 1, {tchkNum},
- &Gfx::opSetWordSpacing},
- {"Tz", 1, {tchkNum},
- &Gfx::opSetHorizScaling},
- {"W", 0, {tchkNone},
- &Gfx::opClip},
- {"W*", 0, {tchkNone},
- &Gfx::opEOClip},
- {"b", 0, {tchkNone},
- &Gfx::opCloseFillStroke},
- {"b*", 0, {tchkNone},
- &Gfx::opCloseEOFillStroke},
- {"c", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
- tchkNum, tchkNum},
- &Gfx::opCurveTo},
- {"cm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
- tchkNum, tchkNum},
- &Gfx::opConcat},
- {"cs", 1, {tchkName},
- &Gfx::opSetFillColorSpace},
- {"d", 2, {tchkArray, tchkNum},
- &Gfx::opSetDash},
- {"d0", 2, {tchkNum, tchkNum},
- &Gfx::opSetCharWidth},
- {"d1", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
- tchkNum, tchkNum},
- &Gfx::opSetCacheDevice},
- {"f", 0, {tchkNone},
- &Gfx::opFill},
- {"f*", 0, {tchkNone},
- &Gfx::opEOFill},
- {"g", 1, {tchkNum},
- &Gfx::opSetFillGray},
- {"gs", 1, {tchkName},
- &Gfx::opSetExtGState},
- {"h", 0, {tchkNone},
- &Gfx::opClosePath},
- {"i", 1, {tchkNum},
- &Gfx::opSetFlat},
- {"j", 1, {tchkInt},
- &Gfx::opSetLineJoin},
- {"k", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opSetFillCMYKColor},
- {"l", 2, {tchkNum, tchkNum},
- &Gfx::opLineTo},
- {"m", 2, {tchkNum, tchkNum},
- &Gfx::opMoveTo},
- {"n", 0, {tchkNone},
- &Gfx::opEndPath},
- {"q", 0, {tchkNone},
- &Gfx::opSave},
- {"re", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opRectangle},
- {"rg", 3, {tchkNum, tchkNum, tchkNum},
- &Gfx::opSetFillRGBColor},
- {"ri", 1, {tchkName},
- &Gfx::opSetRenderingIntent},
- {"s", 0, {tchkNone},
- &Gfx::opCloseStroke},
- {"sc", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opSetFillColor},
- {"scn", -5, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
- tchkSCN},
- &Gfx::opSetFillColorN},
- {"sh", 1, {tchkName},
- &Gfx::opShFill},
- {"v", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opCurveTo1},
- {"w", 1, {tchkNum},
- &Gfx::opSetLineWidth},
- {"y", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
- &Gfx::opCurveTo2},
-};
-
-#define numOps (sizeof(opTab) / sizeof(Operator))
-
-//------------------------------------------------------------------------
-// GfxResources
-//------------------------------------------------------------------------
-
-GfxResources::GfxResources(XRef *xref, Dict *resDict, GfxResources *nextA) {
- Object obj1;
-
- if (resDict) {
-
- // build font dictionary
- fonts = NULL;
- resDict->lookup("Font", &obj1);
- if (obj1.isDict()) {
- fonts = new GfxFontDict(xref, obj1.getDict());
- }
- obj1.free();
-
- // get XObject dictionary
- resDict->lookup("XObject", &xObjDict);
-
- // get color space dictionary
- resDict->lookup("ColorSpace", &colorSpaceDict);
-
- // get pattern dictionary
- resDict->lookup("Pattern", &patternDict);
-
- // get shading dictionary
- resDict->lookup("Shading", &shadingDict);
-
- // get graphics state parameter dictionary
- resDict->lookup("ExtGState", &gStateDict);
-
- } else {
- fonts = NULL;
- xObjDict.initNull();
- colorSpaceDict.initNull();
- patternDict.initNull();
- gStateDict.initNull();
- }
-
- next = nextA;
-}
-
-GfxResources::~GfxResources() {
- if (fonts) {
- delete fonts;
- }
- xObjDict.free();
- colorSpaceDict.free();
- patternDict.free();
- shadingDict.free();
- gStateDict.free();
-}
-
-GfxFont *GfxResources::lookupFont(char *name) {
- GfxFont *font;
- GfxResources *resPtr;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->fonts) {
- if ((font = resPtr->fonts->lookup(name)))
- return font;
- }
- }
- error(-1, "Unknown font tag '%s'", name);
- return NULL;
-}
-
-GBool GfxResources::lookupXObject(char *name, Object *obj) {
- GfxResources *resPtr;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->xObjDict.isDict()) {
- if (!resPtr->xObjDict.dictLookup(name, obj)->isNull())
- return gTrue;
- obj->free();
- }
- }
- error(-1, "XObject '%s' is unknown", name);
- return gFalse;
-}
-
-GBool GfxResources::lookupXObjectNF(char *name, Object *obj) {
- GfxResources *resPtr;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->xObjDict.isDict()) {
- if (!resPtr->xObjDict.dictLookupNF(name, obj)->isNull())
- return gTrue;
- obj->free();
- }
- }
- error(-1, "XObject '%s' is unknown", name);
- return gFalse;
-}
-
-void GfxResources::lookupColorSpace(char *name, Object *obj) {
- GfxResources *resPtr;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->colorSpaceDict.isDict()) {
- if (!resPtr->colorSpaceDict.dictLookup(name, obj)->isNull()) {
- return;
- }
- obj->free();
- }
- }
- obj->initNull();
-}
-
-GfxPattern *GfxResources::lookupPattern(char *name) {
- GfxResources *resPtr;
- GfxPattern *pattern;
- Object obj;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->patternDict.isDict()) {
- if (!resPtr->patternDict.dictLookup(name, &obj)->isNull()) {
- pattern = GfxPattern::parse(&obj);
- obj.free();
- return pattern;
- }
- obj.free();
- }
- }
- error(-1, "Unknown pattern '%s'", name);
- return NULL;
-}
-
-GfxShading *GfxResources::lookupShading(char *name) {
- GfxResources *resPtr;
- GfxShading *shading;
- Object obj;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->shadingDict.isDict()) {
- if (!resPtr->shadingDict.dictLookup(name, &obj)->isNull()) {
- shading = GfxShading::parse(&obj);
- obj.free();
- return shading;
- }
- obj.free();
- }
- }
- error(-1, "Unknown shading '%s'", name);
- return NULL;
-}
-
-GBool GfxResources::lookupGState(char *name, Object *obj) {
- GfxResources *resPtr;
-
- for (resPtr = this; resPtr; resPtr = resPtr->next) {
- if (resPtr->gStateDict.isDict()) {
- if (!resPtr->gStateDict.dictLookup(name, obj)->isNull()) {
- return gTrue;
- }
- obj->free();
- }
- }
- error(-1, "ExtGState '%s' is unknown", name);
- return gFalse;
-}
-
-//------------------------------------------------------------------------
-// Gfx
-//------------------------------------------------------------------------
-
-Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, double dpi,
- PDFRectangle *box, GBool crop, PDFRectangle *cropBox, int rotate,
- GBool (*abortCheckCbkA)(void *data),
- void *abortCheckCbkDataA) {
- int i;
-
- xref = xrefA;
- subPage = gFalse;
- printCommands = globalParams->getPrintCommands();
-
- // start the resource stack
- res = new GfxResources(xref, resDict, NULL);
-
- // initialize
- out = outA;
- state = new GfxState(dpi, box, rotate, out->upsideDown());
- fontChanged = gFalse;
- clip = clipNone;
- ignoreUndef = 0;
- out->startPage(pageNum, state);
- out->setDefaultCTM(state->getCTM());
- out->updateAll(state);
- for (i = 0; i < 6; ++i) {
- baseMatrix[i] = state->getCTM()[i];
- }
- abortCheckCbk = abortCheckCbkA;
- abortCheckCbkData = abortCheckCbkDataA;
-
- // set crop box
- if (crop) {
- state->moveTo(cropBox->x1, cropBox->y1);
- state->lineTo(cropBox->x2, cropBox->y1);
- state->lineTo(cropBox->x2, cropBox->y2);
- state->lineTo(cropBox->x1, cropBox->y2);
- state->closePath();
- state->clip();
- out->clip(state);
- state->clearPath();
- }
-}
-
-Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict,
- PDFRectangle *box, GBool crop, PDFRectangle *cropBox,
- GBool (*abortCheckCbkA)(void *data),
- void *abortCheckCbkDataA) {
- int i;
-
- xref = xrefA;
- subPage = gTrue;
- printCommands = globalParams->getPrintCommands();
-
- // start the resource stack
- res = new GfxResources(xref, resDict, NULL);
-
- // initialize
- out = outA;
- state = new GfxState(72, box, 0, gFalse);
- fontChanged = gFalse;
- clip = clipNone;
- ignoreUndef = 0;
- for (i = 0; i < 6; ++i) {
- baseMatrix[i] = state->getCTM()[i];
- }
- abortCheckCbk = abortCheckCbkA;
- abortCheckCbkData = abortCheckCbkDataA;
-
- // set crop box
- if (crop) {
- state->moveTo(cropBox->x1, cropBox->y1);
- state->lineTo(cropBox->x2, cropBox->y1);
- state->lineTo(cropBox->x2, cropBox->y2);
- state->lineTo(cropBox->x1, cropBox->y2);
- state->closePath();
- state->clip();
- out->clip(state);
- state->clearPath();
- }
-}
-
-Gfx::~Gfx() {
- while (state->hasSaves()) {
- state = state->restore();
- out->restoreState(state);
- }
- if (!subPage) {
- out->endPage();
- }
- while (res) {
- popResources();
- }
- if (state) {
- delete state;
- }
-}
-
-void Gfx::display(Object *obj, GBool topLevel) {
- Object obj2;
- int i;
-
- if (obj->isArray()) {
- for (i = 0; i < obj->arrayGetLength(); ++i) {
- obj->arrayGet(i, &obj2);
- if (!obj2.isStream()) {
- error(-1, "Weird page contents");
- obj2.free();
- return;
- }
- obj2.free();
- }
- } else if (!obj->isStream()) {
- error(-1, "Weird page contents");
- return;
- }
- parser = new Parser(xref, new Lexer(xref, obj));
- go(topLevel);
- delete parser;
- parser = NULL;
-}
-
-void Gfx::go(GBool topLevel) {
- Object obj;
- Object args[maxArgs];
- int numArgs, i;
- int lastAbortCheck;
-
- // scan a sequence of objects
- updateLevel = lastAbortCheck = 0;
- numArgs = 0;
- parser->getObj(&obj);
- while (!obj.isEOF()) {
-
- // got a command - execute it
- if (obj.isCmd()) {
- if (printCommands) {
- obj.print(stdout);
- for (i = 0; i < numArgs; ++i) {
- printf(" ");
- args[i].print(stdout);
- }
- printf("\n");
- fflush(stdout);
- }
- execOp(&obj, args, numArgs);
- obj.free();
- for (i = 0; i < numArgs; ++i)
- args[i].free();
- numArgs = 0;
-
- // periodically update display
- if (++updateLevel >= 20000) {
- out->dump();
- updateLevel = 0;
- }
-
- // check for an abort
- if (abortCheckCbk) {
- if (updateLevel - lastAbortCheck > 10) {
- if ((*abortCheckCbk)(abortCheckCbkData)) {
- break;
- }
- lastAbortCheck = updateLevel;
- }
- }
-
- // got an argument - save it
- } else if (numArgs < maxArgs) {
- args[numArgs++] = obj;
-
- // too many arguments - something is wrong
- } else {
- error(getPos(), "Too many args in content stream");
- if (printCommands) {
- printf("throwing away arg: ");
- obj.print(stdout);
- printf("\n");
- fflush(stdout);
- }
- obj.free();
- }
-
- // grab the next object
- parser->getObj(&obj);
- }
- obj.free();
-
- // args at end with no command
- if (numArgs > 0) {
- error(getPos(), "Leftover args in content stream");
- if (printCommands) {
- printf("%d leftovers:", numArgs);
- for (i = 0; i < numArgs; ++i) {
- printf(" ");
- args[i].print(stdout);
- }
- printf("\n");
- fflush(stdout);
- }
- for (i = 0; i < numArgs; ++i)
- args[i].free();
- }
-
- // update display
- if (topLevel && updateLevel > 0) {
- out->dump();
- }
-}
-
-void Gfx::execOp(Object *cmd, Object args[], int numArgs) {
- Operator *op;
- const char *name;
- int i;
-
- // find operator
- name = cmd->getCmd();
- if (!(op = findOp(name))) {
- if (ignoreUndef == 0)
- error(getPos(), "Unknown operator '%s'", name);
- return;
- }
-
- // type check args
- if (op->numArgs >= 0) {
- if (numArgs != op->numArgs) {
- error(getPos(), "Wrong number (%d) of args to '%s' operator",
- numArgs, name);
- return;
- }
- } else {
- if (numArgs > -op->numArgs) {
- error(getPos(), "Too many (%d) args to '%s' operator",
- numArgs, name);
- return;
- }
- }
- for (i = 0; i < numArgs; ++i) {
- if (!checkArg(&args[i], op->tchk[i])) {
- error(getPos(), "Arg #%d to '%s' operator is wrong type (%s)",
- i, name, args[i].getTypeName());
- return;
- }
- }
-
- // do it
- (this->*op->func)(args, numArgs);
-}
-
-Operator *Gfx::findOp(const char *name) {
- int a, b, m, cmp;
-
- a = -1;
- b = numOps;
- // invariant: opTab[a] < name < opTab[b]
- while (b - a > 1) {
- m = (a + b) / 2;
- cmp = strcmp(opTab[m].name, name);
- if (cmp < 0)
- a = m;
- else if (cmp > 0)
- b = m;
- else
- a = b = m;
- }
- if (cmp != 0)
- return NULL;
- return &opTab[a];
-}
-
-GBool Gfx::checkArg(Object *arg, TchkType type) {
- switch (type) {
- case tchkBool: return arg->isBool();
- case tchkInt: return arg->isInt();
- case tchkNum: return arg->isNum();
- case tchkString: return arg->isString();
- case tchkName: return arg->isName();
- case tchkArray: return arg->isArray();
- case tchkProps: return arg->isDict() || arg->isName();
- case tchkSCN: return arg->isNum() || arg->isName();
- case tchkNone: return gFalse;
- }
- return gFalse;
-}
-
-int Gfx::getPos() {
- return parser ? parser->getPos() : -1;
-}
-
-//------------------------------------------------------------------------
-// graphics state operators
-//------------------------------------------------------------------------
-
-void Gfx::opSave(Object /*args*/[], int /*numArgs*/) {
- out->saveState(state);
- state = state->save();
-}
-
-void Gfx::opRestore(Object /*args*/[], int /*numArgs*/) {
- state = state->restore();
- out->restoreState(state);
-}
-
-void Gfx::opConcat(Object args[], int /*numArgs*/) {
- state->concatCTM(args[0].getNum(), args[1].getNum(),
- args[2].getNum(), args[3].getNum(),
- args[4].getNum(), args[5].getNum());
- out->updateCTM(state, args[0].getNum(), args[1].getNum(),
- args[2].getNum(), args[3].getNum(),
- args[4].getNum(), args[5].getNum());
- fontChanged = gTrue;
-}
-
-void Gfx::opSetDash(Object args[], int /*numArgs*/) {
- Array *a;
- int length;
- Object obj;
- double *dash;
- int i;
-
- a = args[0].getArray();
- length = a->getLength();
- if (length == 0) {
- dash = NULL;
- } else {
- dash = (double *)gmalloc(length * sizeof(double));
- for (i = 0; i < length; ++i) {
- dash[i] = a->get(i, &obj)->getNum();
- obj.free();
- }
- }
- state->setLineDash(dash, length, args[1].getNum());
- out->updateLineDash(state);
-}
-
-void Gfx::opSetFlat(Object args[], int /*numArgs*/) {
- state->setFlatness((int)args[0].getNum());
- out->updateFlatness(state);
-}
-
-void Gfx::opSetLineJoin(Object args[], int /*numArgs*/) {
- state->setLineJoin(args[0].getInt());
- out->updateLineJoin(state);
-}
-
-void Gfx::opSetLineCap(Object args[], int /*numArgs*/) {
- state->setLineCap(args[0].getInt());
- out->updateLineCap(state);
-}
-
-void Gfx::opSetMiterLimit(Object args[], int /*numArgs*/) {
- state->setMiterLimit(args[0].getNum());
- out->updateMiterLimit(state);
-}
-
-void Gfx::opSetLineWidth(Object args[], int /*numArgs*/) {
- state->setLineWidth(args[0].getNum());
- out->updateLineWidth(state);
-}
-
-void Gfx::opSetExtGState(Object args[], int /*numArgs*/) {
- Object obj1, obj2;
-
- if (!res->lookupGState(args[0].getName(), &obj1)) {
- return;
- }
- if (!obj1.isDict()) {
- error(getPos(), "ExtGState '%s' is wrong type", args[0].getName());
- obj1.free();
- return;
- }
- if (obj1.dictLookup("ca", &obj2)->isNum()) {
- state->setFillOpacity(obj2.getNum());
- out->updateFillOpacity(state);
- }
- obj2.free();
- if (obj1.dictLookup("CA", &obj2)->isNum()) {
- state->setStrokeOpacity(obj2.getNum());
- out->updateStrokeOpacity(state);
- }
- obj2.free();
- obj1.free();
-}
-
-void Gfx::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/) {
-}
-
-//------------------------------------------------------------------------
-// color operators
-//------------------------------------------------------------------------
-
-void Gfx::opSetFillGray(Object args[], int /*numArgs*/) {
- GfxColor color;
-
- state->setFillPattern(NULL);
- state->setFillColorSpace(new GfxDeviceGrayColorSpace());
- color.c[0] = args[0].getNum();
- state->setFillColor(&color);
- out->updateFillColor(state);
-}
-
-void Gfx::opSetStrokeGray(Object args[], int /*numArgs*/) {
- GfxColor color;
-
- state->setStrokePattern(NULL);
- state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
- color.c[0] = args[0].getNum();
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
-}
-
-void Gfx::opSetFillCMYKColor(Object args[], int /*numArgs*/) {
- GfxColor color;
- int i;
-
- state->setFillPattern(NULL);
- state->setFillColorSpace(new GfxDeviceCMYKColorSpace());
- for (i = 0; i < 4; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
-}
-
-void Gfx::opSetStrokeCMYKColor(Object args[], int /*numArgs*/) {
- GfxColor color;
- int i;
-
- state->setStrokePattern(NULL);
- state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace());
- for (i = 0; i < 4; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
-}
-
-void Gfx::opSetFillRGBColor(Object args[], int /*numArgs*/) {
- GfxColor color;
- int i;
-
- state->setFillPattern(NULL);
- state->setFillColorSpace(new GfxDeviceRGBColorSpace());
- for (i = 0; i < 3; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
-}
-
-void Gfx::opSetStrokeRGBColor(Object args[], int /*numArgs*/) {
- GfxColor color;
- int i;
-
- state->setStrokePattern(NULL);
- state->setStrokeColorSpace(new GfxDeviceRGBColorSpace());
- for (i = 0; i < 3; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
-}
-
-void Gfx::opSetFillColorSpace(Object args[], int /*numArgs*/) {
- Object obj;
- GfxColorSpace *colorSpace;
- GfxColor color;
- int i;
-
- state->setFillPattern(NULL);
- res->lookupColorSpace(args[0].getName(), &obj);
- if (obj.isNull()) {
- colorSpace = GfxColorSpace::parse(&args[0]);
- } else {
- colorSpace = GfxColorSpace::parse(&obj);
- }
- obj.free();
- if (colorSpace) {
- state->setFillColorSpace(colorSpace);
- } else {
- error(getPos(), "Bad color space (fill)");
- }
- for (i = 0; i < gfxColorMaxComps; ++i) {
- color.c[i] = 0;
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
-}
-
-void Gfx::opSetStrokeColorSpace(Object args[], int /*numArgs*/) {
- Object obj;
- GfxColorSpace *colorSpace;
- GfxColor color;
- int i;
-
- state->setStrokePattern(NULL);
- res->lookupColorSpace(args[0].getName(), &obj);
- if (obj.isNull()) {
- colorSpace = GfxColorSpace::parse(&args[0]);
- } else {
- colorSpace = GfxColorSpace::parse(&obj);
- }
- obj.free();
- if (colorSpace) {
- state->setStrokeColorSpace(colorSpace);
- } else {
- error(getPos(), "Bad color space (stroke)");
- }
- for (i = 0; i < gfxColorMaxComps; ++i) {
- color.c[i] = 0;
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
-}
-
-void Gfx::opSetFillColor(Object args[], int numArgs) {
- GfxColor color;
- int i;
-
- state->setFillPattern(NULL);
- for (i = 0; i < numArgs; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
-}
-
-void Gfx::opSetStrokeColor(Object args[], int numArgs) {
- GfxColor color;
- int i;
-
- state->setStrokePattern(NULL);
- for (i = 0; i < numArgs; ++i) {
- color.c[i] = args[i].getNum();
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
-}
-
-void Gfx::opSetFillColorN(Object args[], int numArgs) {
- GfxColor color;
- GfxPattern *pattern;
- int i;
-
- if (state->getFillColorSpace()->getMode() == csPattern) {
- if (numArgs > 1) {
- for (i = 0; i < numArgs && i < 4; ++i) {
- if (args[i].isNum()) {
- color.c[i] = args[i].getNum();
- }
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
- }
- if (args[numArgs-1].isName() &&
- (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
- state->setFillPattern(pattern);
- }
-
- } else {
- state->setFillPattern(NULL);
- for (i = 0; i < numArgs && i < 4; ++i) {
- if (args[i].isNum()) {
- color.c[i] = args[i].getNum();
- }
- }
- state->setFillColor(&color);
- out->updateFillColor(state);
- }
-}
-
-void Gfx::opSetStrokeColorN(Object args[], int numArgs) {
- GfxColor color;
- GfxPattern *pattern;
- int i;
-
- if (state->getStrokeColorSpace()->getMode() == csPattern) {
- if (numArgs > 1) {
- for (i = 0; i < numArgs && i < 4; ++i) {
- if (args[i].isNum()) {
- color.c[i] = args[i].getNum();
- }
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
- }
- if (args[numArgs-1].isName() &&
- (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
- state->setStrokePattern(pattern);
- }
-
- } else {
- state->setStrokePattern(NULL);
- for (i = 0; i < numArgs && i < 4; ++i) {
- if (args[i].isNum()) {
- color.c[i] = args[i].getNum();
- }
- }
- state->setStrokeColor(&color);
- out->updateStrokeColor(state);
- }
-}
-
-//------------------------------------------------------------------------
-// path segment operators
-//------------------------------------------------------------------------
-
-void Gfx::opMoveTo(Object args[], int /*numArgs*/) {
- state->moveTo(args[0].getNum(), args[1].getNum());
-}
-
-void Gfx::opLineTo(Object args[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- error(getPos(), "No current point in lineto");
- return;
- }
- state->lineTo(args[0].getNum(), args[1].getNum());
-}
-
-void Gfx::opCurveTo(Object args[], int /*numArgs*/) {
- double x1, y1, x2, y2, x3, y3;
-
- if (!state->isCurPt()) {
- error(getPos(), "No current point in curveto");
- return;
- }
- x1 = args[0].getNum();
- y1 = args[1].getNum();
- x2 = args[2].getNum();
- y2 = args[3].getNum();
- x3 = args[4].getNum();
- y3 = args[5].getNum();
- state->curveTo(x1, y1, x2, y2, x3, y3);
-}
-
-void Gfx::opCurveTo1(Object args[], int /*numArgs*/) {
- double x1, y1, x2, y2, x3, y3;
-
- if (!state->isCurPt()) {
- error(getPos(), "No current point in curveto1");
- return;
- }
- x1 = state->getCurX();
- y1 = state->getCurY();
- x2 = args[0].getNum();
- y2 = args[1].getNum();
- x3 = args[2].getNum();
- y3 = args[3].getNum();
- state->curveTo(x1, y1, x2, y2, x3, y3);
-}
-
-void Gfx::opCurveTo2(Object args[], int /*numArgs*/) {
- double x1, y1, x2, y2, x3, y3;
-
- if (!state->isCurPt()) {
- error(getPos(), "No current point in curveto2");
- return;
- }
- x1 = args[0].getNum();
- y1 = args[1].getNum();
- x2 = args[2].getNum();
- y2 = args[3].getNum();
- x3 = x2;
- y3 = y2;
- state->curveTo(x1, y1, x2, y2, x3, y3);
-}
-
-void Gfx::opRectangle(Object args[], int /*numArgs*/) {
- double x, y, w, h;
-
- x = args[0].getNum();
- y = args[1].getNum();
- w = args[2].getNum();
- h = args[3].getNum();
- state->moveTo(x, y);
- state->lineTo(x + w, y);
- state->lineTo(x + w, y + h);
- state->lineTo(x, y + h);
- state->closePath();
-}
-
-void Gfx::opClosePath(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- error(getPos(), "No current point in closepath");
- return;
- }
- state->closePath();
-}
-
-//------------------------------------------------------------------------
-// path painting operators
-//------------------------------------------------------------------------
-
-void Gfx::opEndPath(Object /*args*/[], int /*numArgs*/) {
- doEndPath();
-}
-
-void Gfx::opStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in stroke");
- return;
- }
- if (state->isPath())
- out->stroke(state);
- doEndPath();
-}
-
-void Gfx::opCloseStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in closepath/stroke");
- return;
- }
- if (state->isPath()) {
- state->closePath();
- out->stroke(state);
- }
- doEndPath();
-}
-
-void Gfx::opFill(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in fill");
- return;
- }
- if (state->isPath()) {
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gFalse);
- } else {
- out->fill(state);
- }
- }
- doEndPath();
-}
-
-void Gfx::opEOFill(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in eofill");
- return;
- }
- if (state->isPath()) {
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gTrue);
- } else {
- out->eoFill(state);
- }
- }
- doEndPath();
-}
-
-void Gfx::opFillStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in fill/stroke");
- return;
- }
- if (state->isPath()) {
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gFalse);
- } else {
- out->fill(state);
- }
- out->stroke(state);
- }
- doEndPath();
-}
-
-void Gfx::opCloseFillStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in closepath/fill/stroke");
- return;
- }
- if (state->isPath()) {
- state->closePath();
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gFalse);
- } else {
- out->fill(state);
- }
- out->stroke(state);
- }
- doEndPath();
-}
-
-void Gfx::opEOFillStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in eofill/stroke");
- return;
- }
- if (state->isPath()) {
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gTrue);
- } else {
- out->eoFill(state);
- }
- out->stroke(state);
- }
- doEndPath();
-}
-
-void Gfx::opCloseEOFillStroke(Object /*args*/[], int /*numArgs*/) {
- if (!state->isCurPt()) {
- //error(getPos(), "No path in closepath/eofill/stroke");
- return;
- }
- if (state->isPath()) {
- state->closePath();
- if (state->getFillColorSpace()->getMode() == csPattern) {
- doPatternFill(gTrue);
- } else {
- out->eoFill(state);
- }
- out->stroke(state);
- }
- doEndPath();
-}
-
-void Gfx::doPatternFill(GBool eoFill) {
- GfxPatternColorSpace *patCS;
- GfxPattern *pattern;
- GfxTilingPattern *tPat;
- const GfxColorSpace *cs;
- double xMin, yMin, xMax, yMax, x, y, x1, y1;
- double cxMin, cyMin, cxMax, cyMax;
- int xi0, yi0, xi1, yi1, xi, yi;
- const double *ctm;
- double *btm, *ptm;
- double m[6], ictm[6], m1[6], imb[6];
- double det;
- double xstep, ystep;
- int i;
-
- // this is a bit of a kludge -- patterns can be really slow, so we
- // skip them if we're only doing text extraction, since they almost
- // certainly don't contain any text
- if (!out->needNonText()) {
- return;
- }
-
- // get color space
- patCS = (GfxPatternColorSpace *)state->getFillColorSpace();
-
- // get pattern
- if (!(pattern = state->getFillPattern())) {
- return;
- }
- if (pattern->getType() != 1) {
- return;
- }
- tPat = (GfxTilingPattern *)pattern;
-
- // construct a (pattern space) -> (current space) transform matrix
- ctm = state->getCTM();
- btm = baseMatrix;
- ptm = tPat->getMatrix();
- // iCTM = invert CTM
- det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
- ictm[0] = ctm[3] * det;
- ictm[1] = -ctm[1] * det;
- ictm[2] = -ctm[2] * det;
- ictm[3] = ctm[0] * det;
- ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
- ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
- // m1 = PTM * BTM = PTM * base transform matrix
- m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2];
- m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3];
- m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2];
- m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3];
- m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4];
- m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5];
- // m = m1 * iCTM = (PTM * BTM) * (iCTM)
- m[0] = m1[0] * ictm[0] + m1[1] * ictm[2];
- m[1] = m1[0] * ictm[1] + m1[1] * ictm[3];
- m[2] = m1[2] * ictm[0] + m1[3] * ictm[2];
- m[3] = m1[2] * ictm[1] + m1[3] * ictm[3];
- m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4];
- m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5];
-
- // construct a (base space) -> (pattern space) transform matrix
- det = 1 / (m1[0] * m1[3] - m1[1] * m1[2]);
- imb[0] = m1[3] * det;
- imb[1] = -m1[1] * det;
- imb[2] = -m1[2] * det;
- imb[3] = m1[0] * det;
- imb[4] = (m1[2] * m1[5] - m1[3] * m1[4]) * det;
- imb[5] = (m1[1] * m1[4] - m1[0] * m1[5]) * det;
-
- // save current graphics state
- out->saveState(state);
- state = state->save();
-
- // set underlying color space (for uncolored tiling patterns)
- if (tPat->getPaintType() == 2 && (cs = patCS->getUnder())) {
- state->setFillColorSpace(cs->copy());
- } else {
- state->setFillColorSpace(new GfxDeviceGrayColorSpace());
- }
- state->setFillPattern(NULL);
- out->updateFillColor(state);
-
- // clip to current path
- state->clip();
- if (eoFill) {
- out->eoClip(state);
- } else {
- out->clip(state);
- }
- state->clearPath();
-
- // transform clip region bbox to pattern space
- state->getClipBBox(&cxMin, &cyMin, &cxMax, &cyMax);
- xMin = xMax = cxMin * imb[0] + cyMin * imb[2] + imb[4];
- yMin = yMax = cxMin * imb[1] + cyMin * imb[3] + imb[5];
- x1 = cxMin * imb[0] + cyMax * imb[2] + imb[4];
- y1 = cxMin * imb[1] + cyMax * imb[3] + imb[5];
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
- x1 = cxMax * imb[0] + cyMin * imb[2] + imb[4];
- y1 = cxMax * imb[1] + cyMin * imb[3] + imb[5];
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
- x1 = cxMax * imb[0] + cyMax * imb[2] + imb[4];
- y1 = cxMax * imb[1] + cyMax * imb[3] + imb[5];
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
-
- // draw the pattern
- //~ this should treat negative steps differently -- start at right/top
- //~ edge instead of left/bottom (?)
- xstep = fabs(tPat->getXStep());
- ystep = fabs(tPat->getYStep());
- xi0 = (int)floor(xMin / xstep);
- xi1 = (int)ceil(xMax / xstep);
- yi0 = (int)floor(yMin / ystep);
- yi1 = (int)ceil(yMax / ystep);
- for (i = 0; i < 4; ++i) {
- m1[i] = m[i];
- }
- for (yi = yi0; yi < yi1; ++yi) {
- for (xi = xi0; xi < xi1; ++xi) {
- x = xi * xstep;
- y = yi * ystep;
- m1[4] = x * m[0] + y * m[2] + m[4];
- m1[5] = x * m[1] + y * m[3] + m[5];
- doForm1(tPat->getContentStream(), tPat->getResDict(),
- m1, tPat->getBBox());
- }
- }
-
- // restore graphics state
- state = state->restore();
- out->restoreState(state);
-}
-
-void Gfx::opShFill(Object args[], int /*numArgs*/) {
- GfxShading *shading;
- double xMin, yMin, xMax, yMax;
-
- if (!(shading = res->lookupShading(args[0].getName()))) {
- return;
- }
-
- // save current graphics state
- out->saveState(state);
- state = state->save();
-
- // clip to bbox
- if (shading->getHasBBox()) {
- shading->getBBox(&xMin, &yMin, &xMax, &yMax);
- state->moveTo(xMin, yMin);
- state->lineTo(xMax, yMin);
- state->lineTo(xMax, yMax);
- state->lineTo(xMin, yMax);
- state->closePath();
- state->clip();
- out->clip(state);
- state->clearPath();
- }
-
- // set the color space
- state->setFillColorSpace(shading->getColorSpace()->copy());
-
- // do shading type-specific operations
- switch (shading->getType()) {
- case 2:
- doAxialShFill((GfxAxialShading *)shading);
- break;
- case 3:
- doRadialShFill((GfxRadialShading *)shading);
- break;
- }
-
- // restore graphics state
- state = state->restore();
- out->restoreState(state);
-
- delete shading;
-}
-
-void Gfx::doAxialShFill(GfxAxialShading *shading) {
- double xMin, yMin, xMax, yMax;
- double x0, y0, x1, y1;
- double dx, dy, mul;
- double tMin, tMax, t, tx, ty;
- double s[4], sMin, sMax, tmp;
- double ux0, uy0, ux1, uy1, vx0, vy0, vx1, vy1;
- double t0, t1, tt;
- double ta[axialMaxSplits + 1];
- int next[axialMaxSplits + 1];
- GfxColor color0, color1;
- int nComps;
- int i, j, k, kk;
-
- // get the clip region bbox
- state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
-
- // compute min and max t values, based on the four corners of the
- // clip region bbox
- shading->getCoords(&x0, &y0, &x1, &y1);
- dx = x1 - x0;
- dy = y1 - y0;
- mul = 1 / (dx * dx + dy * dy);
- tMin = tMax = ((xMin - x0) * dx + (yMin - y0) * dy) * mul;
- t = ((xMin - x0) * dx + (yMax - y0) * dy) * mul;
- if (t < tMin) {
- tMin = t;
- } else if (t > tMax) {
- tMax = t;
- }
- t = ((xMax - x0) * dx + (yMin - y0) * dy) * mul;
- if (t < tMin) {
- tMin = t;
- } else if (t > tMax) {
- tMax = t;
- }
- t = ((xMax - x0) * dx + (yMax - y0) * dy) * mul;
- if (t < tMin) {
- tMin = t;
- } else if (t > tMax) {
- tMax = t;
- }
- if (tMin < 0 && !shading->getExtend0()) {
- tMin = 0;
- }
- if (tMax > 1 && !shading->getExtend1()) {
- tMax = 1;
- }
-
- // get the function domain
- t0 = shading->getDomain0();
- t1 = shading->getDomain1();
-
- // Traverse the t axis and do the shading.
- //
- // For each point (tx, ty) on the t axis, consider a line through
- // that point perpendicular to the t axis:
- //
- // x(s) = tx + s * -dy --> s = (x - tx) / -dy
- // y(s) = ty + s * dx --> s = (y - ty) / dx
- //
- // Then look at the intersection of this line with the bounding box
- // (xMin, yMin, xMax, yMax). In the general case, there are four
- // intersection points:
- //
- // s0 = (xMin - tx) / -dy
- // s1 = (xMax - tx) / -dy
- // s2 = (yMin - ty) / dx
- // s3 = (yMax - ty) / dx
- //
- // and we want the middle two s values.
- //
- // In the case where dx = 0, take s0 and s1; in the case where dy =
- // 0, take s2 and s3.
- //
- // Each filled polygon is bounded by two of these line segments
- // perpdendicular to the t axis.
- //
- // The t axis is bisected into smaller regions until the color
- // difference across a region is small enough, and then the region
- // is painted with a single color.
-
- // set up
- nComps = shading->getColorSpace()->getNComps();
- ta[0] = tMin;
- ta[axialMaxSplits] = tMax;
- next[0] = axialMaxSplits;
-
- // compute the color at t = tMin
- if (tMin < 0) {
- tt = t0;
- } else if (tMin > 1) {
- tt = t1;
- } else {
- tt = t0 + (t1 - t0) * tMin;
- }
- shading->getColor(tt, &color0);
-
- // compute the coordinates of the point on the t axis at t = tMin;
- // then compute the intersection of the perpendicular line with the
- // bounding box
- tx = x0 + tMin * dx;
- ty = y0 + tMin * dy;
- if (dx == 0 && dy == 0) {
- sMin = sMax = 0;
- } if (dx == 0) {
- sMin = (xMin - tx) / -dy;
- sMax = (xMax - tx) / -dy;
- if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
- } else if (dy == 0) {
- sMin = (yMin - ty) / dx;
- sMax = (yMax - ty) / dx;
- if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
- } else {
- s[0] = (yMin - ty) / dx;
- s[1] = (yMax - ty) / dx;
- s[2] = (xMin - tx) / -dy;
- s[3] = (xMax - tx) / -dy;
- for (j = 0; j < 3; ++j) {
- kk = j;
- for (k = j + 1; k < 4; ++k) {
- if (s[k] < s[kk]) {
- kk = k;
- }
- }
- tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
- }
- sMin = s[1];
- sMax = s[2];
- }
- ux0 = tx - sMin * dy;
- uy0 = ty + sMin * dx;
- vx0 = tx - sMax * dy;
- vy0 = ty + sMax * dx;
-
- i = 0;
- while (i < axialMaxSplits) {
-
- // bisect until color difference is small enough or we hit the
- // bisection limit
- j = next[i];
- while (j > i + 1) {
- if (ta[j] < 0) {
- tt = t0;
- } else if (ta[j] > 1) {
- tt = t1;
- } else {
- tt = t0 + (t1 - t0) * ta[j];
- }
- shading->getColor(tt, &color1);
- for (k = 0; k < nComps; ++k) {
- if (fabs(color1.c[k] - color0.c[k]) > axialColorDelta) {
- break;
- }
- }
- if (k == nComps) {
- break;
- }
- k = (i + j) / 2;
- ta[k] = 0.5 * (ta[i] + ta[j]);
- next[i] = k;
- next[k] = j;
- j = k;
- }
-
- // use the average of the colors of the two sides of the region
- for (k = 0; k < nComps; ++k) {
- color0.c[k] = 0.5 * (color0.c[k] + color1.c[k]);
- }
-
- // compute the coordinates of the point on the t axis; then
- // compute the intersection of the perpendicular line with the
- // bounding box
- tx = x0 + ta[j] * dx;
- ty = y0 + ta[j] * dy;
- if (dx == 0 && dy == 0) {
- sMin = sMax = 0;
- } if (dx == 0) {
- sMin = (xMin - tx) / -dy;
- sMax = (xMax - tx) / -dy;
- if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
- } else if (dy == 0) {
- sMin = (yMin - ty) / dx;
- sMax = (yMax - ty) / dx;
- if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
- } else {
- s[0] = (yMin - ty) / dx;
- s[1] = (yMax - ty) / dx;
- s[2] = (xMin - tx) / -dy;
- s[3] = (xMax - tx) / -dy;
- for (j = 0; j < 3; ++j) {
- kk = j;
- for (k = j + 1; k < 4; ++k) {
- if (s[k] < s[kk]) {
- kk = k;
- }
- }
- tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
- }
- sMin = s[1];
- sMax = s[2];
- }
- ux1 = tx - sMin * dy;
- uy1 = ty + sMin * dx;
- vx1 = tx - sMax * dy;
- vy1 = ty + sMax * dx;
-
- // set the color
- state->setFillColor(&color0);
- out->updateFillColor(state);
-
- // fill the region
- state->moveTo(ux0, uy0);
- state->lineTo(vx0, vy0);
- state->lineTo(vx1, vy1);
- state->lineTo(ux1, uy1);
- state->closePath();
- out->fill(state);
- state->clearPath();
-
- // set up for next region
- ux0 = ux1;
- uy0 = uy1;
- vx0 = vx1;
- vy0 = vy1;
- color0 = color1;
- i = next[i];
- }
-}
-
-void Gfx::doRadialShFill(GfxRadialShading *shading) {
- double sMin, sMax, xMin, yMin, xMax, yMax;
- double x0, y0, r0, x1, y1, r1, t0, t1;
- int nComps;
- GfxColor colorA, colorB;
- double xa, ya, xb, yb, ra, rb;
- double ta, tb, sa, sb;
- int ia, ib, k, n;
- const double *ctm;
- double angle, t;
-
- // get the shading info
- shading->getCoords(&x0, &y0, &r0, &x1, &y1, &r1);
- t0 = shading->getDomain0();
- t1 = shading->getDomain1();
- nComps = shading->getColorSpace()->getNComps();
-
- // compute the (possibly extended) s range
- sMin = 0;
- sMax = 1;
- if (shading->getExtend0()) {
- if (r0 < r1) {
- // extend the smaller end
- sMin = -r0 / (r1 - r0);
- } else {
- // extend the larger end
- //~ this computes the diagonal of the bounding box -- we should
- //~ really compute the intersection of the moving/expanding
- //~ circles with each of the four corners and look for the max
- //~ radius
- state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
- sMin = (sqrt((xMax - xMin) * (xMax - xMin) +
- (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
- if (sMin > 0) {
- sMin = 0;
- } else if (sMin < -20) {
- // sanity check
- sMin = -20;
- }
- }
- }
- if (shading->getExtend1()) {
- if (r1 < r0) {
- // extend the smaller end
- sMax = -r0 / (r1 - r0);
- } else if (r1 > r0) {
- // extend the larger end
- state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
- sMax = (sqrt((xMax - xMin) * (xMax - xMin) +
- (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
- if (sMax < 1) {
- sMin = 1;
- } else if (sMax > 20) {
- // sanity check
- sMax = 20;
- }
- }
- }
-
- // compute the number of steps into which circles must be divided to
- // achieve a curve flatness of 0.1 pixel in device space for the
- // largest circle (note that "device space" is 72 dpi when generating
- // PostScript, hence the relatively small 0.1 pixel accuracy)
- ctm = state->getCTM();
- t = fabs(ctm[0]);
- if (fabs(ctm[1]) > t) {
- t = fabs(ctm[1]);
- }
- if (fabs(ctm[2]) > t) {
- t = fabs(ctm[2]);
- }
- if (fabs(ctm[3]) > t) {
- t = fabs(ctm[3]);
- }
- if (r0 > r1) {
- t *= r0;
- } else {
- t *= r1;
- }
- if (t < 1) {
- n = 3;
- } else {
- n = (int)(M_PI / acos(1 - 0.1 / t));
- if (n < 3) {
- n = 3;
- } else if (n > 200) {
- n = 200;
- }
- }
-
- // Traverse the t axis and do the shading.
- //
- // This generates and fills a series of rings. Each ring is defined
- // by two circles:
- // sa, ta, xa, ya, ra, colorA
- // sb, tb, xb, yb, rb, colorB
- //
- // The s/t axis is divided into radialMaxSplits parts; these parts
- // are combined as much as possible while respecting the
- // radialColorDelta parameter.
-
- // setup for the start circle
- ia = 0;
- sa = sMin;
- ta = t0 + sa * (t1 - t0);
- xa = x0 + sa * (x1 - x0);
- ya = y0 + sa * (y1 - y0);
- ra = r0 + sa * (r1 - r0);
- if (ta < t0) {
- shading->getColor(t0, &colorA);
- } else if (ta > t1) {
- shading->getColor(t1, &colorA);
- } else {
- shading->getColor(ta, &colorA);
- }
-
- while (ia < radialMaxSplits) {
-
- // go as far along the t axis (toward t1) as we can, such that the
- // color difference is within the tolerance (radialColorDelta) --
- // this uses bisection (between the current value, t, and t1),
- // limited to radialMaxSplits points along the t axis
- ib = radialMaxSplits;
- sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
- tb = t0 + sb * (t1 - t0);
- if (tb < t0) {
- shading->getColor(t0, &colorB);
- } else if (tb > t1) {
- shading->getColor(t1, &colorB);
- } else {
- shading->getColor(tb, &colorB);
- }
- while (ib - ia > 1) {
- for (k = 0; k < nComps; ++k) {
- if (fabs(colorB.c[k] - colorA.c[k]) > radialColorDelta) {
- break;
- }
- }
- if (k == nComps) {
- break;
- }
- ib = (ia + ib) / 2;
- sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
- tb = t0 + sb * (t1 - t0);
- if (tb < t0) {
- shading->getColor(t0, &colorB);
- } else if (tb > t1) {
- shading->getColor(t1, &colorB);
- } else {
- shading->getColor(tb, &colorB);
- }
- }
-
- // compute center and radius of the circle
- xb = x0 + sb * (x1 - x0);
- yb = y0 + sb * (y1 - y0);
- rb = r0 + sb * (r1 - r0);
-
- // use the average of the colors at the two circles
- for (k = 0; k < nComps; ++k) {
- colorA.c[k] = 0.5 * (colorA.c[k] + colorB.c[k]);
- }
- state->setFillColor(&colorA);
- out->updateFillColor(state);
-
- // construct path for first circle
- state->moveTo(xa + ra, ya);
- for (k = 1; k < n; ++k) {
- angle = ((double)k / (double)n) * 2 * M_PI;
- state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
- }
- state->closePath();
-
- // construct and append path for second circle
- state->moveTo(xb + rb, yb);
- for (k = 1; k < n; ++k) {
- angle = ((double)k / (double)n) * 2 * M_PI;
- state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
- }
- state->closePath();
-
- // fill the ring
- out->eoFill(state);
- state->clearPath();
-
- // step to the next value of t
- ia = ib;
- sa = sb;
- ta = tb;
- xa = xb;
- ya = yb;
- ra = rb;
- colorA = colorB;
- }
-}
-
-void Gfx::doEndPath() {
- if (state->isPath() && clip != clipNone) {
- state->clip();
- if (clip == clipNormal) {
- out->clip(state);
- } else {
- out->eoClip(state);
- }
- }
- clip = clipNone;
- state->clearPath();
-}
-
-//------------------------------------------------------------------------
-// path clipping operators
-//------------------------------------------------------------------------
-
-void Gfx::opClip(Object /*args*/[], int /*numArgs*/) {
- clip = clipNormal;
-}
-
-void Gfx::opEOClip(Object /*args*/[], int /*numArgs*/) {
- clip = clipEO;
-}
-
-//------------------------------------------------------------------------
-// text object operators
-//------------------------------------------------------------------------
-
-void Gfx::opBeginText(Object /*args*/[], int /*numArgs*/) {
- state->setTextMat(1, 0, 0, 1, 0, 0);
- state->textMoveTo(0, 0);
- out->updateTextMat(state);
- out->updateTextPos(state);
- fontChanged = gTrue;
-}
-
-void Gfx::opEndText(Object /*args*/[], int /*numArgs*/) {
-}
-
-//------------------------------------------------------------------------
-// text state operators
-//------------------------------------------------------------------------
-
-void Gfx::opSetCharSpacing(Object args[], int /*numArgs*/) {
- state->setCharSpace(args[0].getNum());
- out->updateCharSpace(state);
-}
-
-void Gfx::opSetFont(Object args[], int /*numArgs*/) {
- GfxFont *font;
-
- if (!(font = res->lookupFont(args[0].getName()))) {
- return;
- }
- if (printCommands) {
- printf(" font: tag=%s name='%s' %g\n",
- font->getTag()->getCString(),
- font->getName() ? font->getName()->getCString() : "???",
- args[1].getNum());
- fflush(stdout);
- }
- state->setFont(font, args[1].getNum());
- fontChanged = gTrue;
-}
-
-void Gfx::opSetTextLeading(Object args[], int /*numArgs*/) {
- state->setLeading(args[0].getNum());
-}
-
-void Gfx::opSetTextRender(Object args[], int /*numArgs*/) {
- state->setRender(args[0].getInt());
- out->updateRender(state);
-}
-
-void Gfx::opSetTextRise(Object args[], int /*numArgs*/) {
- state->setRise(args[0].getNum());
- out->updateRise(state);
-}
-
-void Gfx::opSetWordSpacing(Object args[], int /*numArgs*/) {
- state->setWordSpace(args[0].getNum());
- out->updateWordSpace(state);
-}
-
-void Gfx::opSetHorizScaling(Object args[], int /*numArgs*/) {
- state->setHorizScaling(args[0].getNum());
- out->updateHorizScaling(state);
- fontChanged = gTrue;
-}
-
-//------------------------------------------------------------------------
-// text positioning operators
-//------------------------------------------------------------------------
-
-void Gfx::opTextMove(Object args[], int /*numArgs*/) {
- double tx, ty;
-
- tx = state->getLineX() + args[0].getNum();
- ty = state->getLineY() + args[1].getNum();
- state->textMoveTo(tx, ty);
- out->updateTextPos(state);
-}
-
-void Gfx::opTextMoveSet(Object args[], int /*numArgs*/) {
- double tx, ty;
-
- tx = state->getLineX() + args[0].getNum();
- ty = args[1].getNum();
- state->setLeading(-ty);
- ty += state->getLineY();
- state->textMoveTo(tx, ty);
- out->updateTextPos(state);
-}
-
-void Gfx::opSetTextMatrix(Object args[], int /*numArgs*/) {
- state->setTextMat(args[0].getNum(), args[1].getNum(),
- args[2].getNum(), args[3].getNum(),
- args[4].getNum(), args[5].getNum());
- state->textMoveTo(0, 0);
- out->updateTextMat(state);
- out->updateTextPos(state);
- fontChanged = gTrue;
-}
-
-void Gfx::opTextNextLine(Object /*args*/[], int /*numArgs*/) {
- double tx, ty;
-
- tx = state->getLineX();
- ty = state->getLineY() - state->getLeading();
- state->textMoveTo(tx, ty);
- out->updateTextPos(state);
-}
-
-//------------------------------------------------------------------------
-// text string operators
-//------------------------------------------------------------------------
-
-void Gfx::opShowText(Object args[], int /*numArgs*/) {
- if (!state->getFont()) {
- error(getPos(), "No font in show");
- return;
- }
- doShowText(args[0].getString());
-}
-
-void Gfx::opMoveShowText(Object args[], int /*numArgs*/) {
- double tx, ty;
-
- if (!state->getFont()) {
- error(getPos(), "No font in move/show");
- return;
- }
- tx = state->getLineX();
- ty = state->getLineY() - state->getLeading();
- state->textMoveTo(tx, ty);
- out->updateTextPos(state);
- doShowText(args[0].getString());
-}
-
-void Gfx::opMoveSetShowText(Object args[], int /*numArgs*/) {
- double tx, ty;
-
- if (!state->getFont()) {
- error(getPos(), "No font in move/set/show");
- return;
- }
- state->setWordSpace(args[0].getNum());
- state->setCharSpace(args[1].getNum());
- tx = state->getLineX();
- ty = state->getLineY() - state->getLeading();
- state->textMoveTo(tx, ty);
- out->updateWordSpace(state);
- out->updateCharSpace(state);
- out->updateTextPos(state);
- doShowText(args[2].getString());
-}
-
-void Gfx::opShowSpaceText(Object args[], int /*numArgs*/) {
- Array *a;
- Object obj;
- int wMode;
- int i;
-
- if (!state->getFont()) {
- error(getPos(), "No font in show/space");
- return;
- }
- wMode = state->getFont()->getWMode();
- a = args[0].getArray();
- for (i = 0; i < a->getLength(); ++i) {
- a->get(i, &obj);
- if (obj.isNum()) {
- if (wMode) {
- state->textShift(0, -obj.getNum() * 0.001 * state->getFontSize());
- } else {
- state->textShift(-obj.getNum() * 0.001 * state->getFontSize(), 0);
- }
- out->updateTextShift(state, obj.getNum());
- } else if (obj.isString()) {
- doShowText(obj.getString());
- } else {
- error(getPos(), "Element of show/space array must be number or string");
- }
- obj.free();
- }
-}
-
-void Gfx::doShowText(GString *s) {
- GfxFont *font;
- int wMode;
- double riseX, riseY;
- CharCode code;
- Unicode u[8];
- double x, y, dx, dy, dx2, dy2, curX, curY, tdx, tdy;
- double originX, originY, tOriginX, tOriginY;
- double oldCTM[6], newCTM[6];
- const double *mat;
- Object charProc;
- Dict *resDict;
- Parser *oldParser;
- char *p;
- int len, n, uLen, nChars, nSpaces, i;
-
- if (fontChanged) {
- out->updateFont(state);
- fontChanged = gFalse;
- }
- font = state->getFont();
- wMode = font->getWMode();
-
- if (out->useDrawChar()) {
- out->beginString(state, s);
- }
-
- // handle a Type 3 char
- if (font->getType() == fontType3 && out->interpretType3Chars()) {
- mat = state->getCTM();
- for (i = 0; i < 6; ++i) {
- oldCTM[i] = mat[i];
- }
- mat = state->getTextMat();
- newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2];
- newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3];
- newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2];
- newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3];
- mat = font->getFontMatrix();
- newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2];
- newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3];
- newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2];
- newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3];
- newCTM[0] *= state->getFontSize();
- newCTM[3] *= state->getFontSize();
- newCTM[0] *= state->getHorizScaling();
- newCTM[2] *= state->getHorizScaling();
- state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
- curX = state->getCurX();
- curY = state->getCurY();
- oldParser = parser;
- p = s->getCString();
- len = s->getLength();
- while (len > 0) {
- n = font->getNextChar(p, len, &code,
- u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
- &dx, &dy, &originX, &originY);
- dx = dx * state->getFontSize() + state->getCharSpace();
- if (n == 1 && *p == ' ') {
- dx += state->getWordSpace();
- }
- dx *= state->getHorizScaling();
- dy *= state->getFontSize();
- state->textTransformDelta(dx, dy, &tdx, &tdy);
- state->transform(curX + riseX, curY + riseY, &x, &y);
- out->saveState(state);
- state = state->save();
- state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y);
- //~ out->updateCTM(???)
- if (!out->beginType3Char(state, code, u, uLen)) {
- ((Gfx8BitFont *)font)->getCharProc(code, &charProc);
- if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
- pushResources(resDict);
- }
- if (charProc.isStream()) {
- display(&charProc, gFalse);
- } else {
- error(getPos(), "Missing or bad Type3 CharProc entry");
- }
- out->endType3Char(state);
- if (resDict) {
- popResources();
- }
- charProc.free();
- }
- state = state->restore();
- out->restoreState(state);
- // GfxState::restore() does *not* restore the current position,
- // so we track it here with (curX, curY)
- curX += tdx;
- curY += tdy;
- state->moveTo(curX, curY);
- p += n;
- len -= n;
- }
- parser = oldParser;
-
- } else if (out->useDrawChar()) {
- state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
- p = s->getCString();
- len = s->getLength();
- while (len > 0) {
- n = font->getNextChar(p, len, &code,
- u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
- &dx, &dy, &originX, &originY);
- if (wMode) {
- dx *= state->getFontSize();
- dy = dy * state->getFontSize() + state->getCharSpace();
- if (n == 1 && *p == ' ') {
- dy += state->getWordSpace();
- }
- } else {
- dx = dx * state->getFontSize() + state->getCharSpace();
- if (n == 1 && *p == ' ') {
- dx += state->getWordSpace();
- }
- dx *= state->getHorizScaling();
- dy *= state->getFontSize();
- }
- state->textTransformDelta(dx, dy, &tdx, &tdy);
- originX *= state->getFontSize();
- originY *= state->getFontSize();
- state->textTransformDelta(originX, originY, &tOriginX, &tOriginY);
- out->drawChar(state, state->getCurX() + riseX, state->getCurY() + riseY,
- tdx, tdy, tOriginX, tOriginY, code, u, uLen);
- state->shift(tdx, tdy);
- p += n;
- len -= n;
- }
-
- } else {
- dx = dy = 0;
- p = s->getCString();
- len = s->getLength();
- nChars = nSpaces = 0;
- while (len > 0) {
- n = font->getNextChar(p, len, &code,
- u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
- &dx2, &dy2, &originX, &originY);
- dx += dx2;
- dy += dy2;
- if (n == 1 && *p == ' ') {
- ++nSpaces;
- }
- ++nChars;
- p += n;
- len -= n;
- }
- if (wMode) {
- dx *= state->getFontSize();
- dy = dy * state->getFontSize()
- + nChars * state->getCharSpace()
- + nSpaces * state->getWordSpace();
- } else {
- dx = dx * state->getFontSize()
- + nChars * state->getCharSpace()
- + nSpaces * state->getWordSpace();
- dx *= state->getHorizScaling();
- dy *= state->getFontSize();
- }
- state->textTransformDelta(dx, dy, &tdx, &tdy);
- out->drawString(state, s);
- state->shift(tdx, tdy);
- }
-
- if (out->useDrawChar()) {
- out->endString(state);
- }
-
- updateLevel += 10 * s->getLength();
-}
-
-//------------------------------------------------------------------------
-// XObject operators
-//------------------------------------------------------------------------
-
-void Gfx::opXObject(Object args[], int /*numArgs*/) {
- Object obj1, obj2, obj3, refObj;
-#ifdef OPI_SUPPORT
- Object opiDict;
-#endif
-
- if (!res->lookupXObject(args[0].getName(), &obj1)) {
- return;
- }
- if (!obj1.isStream()) {
- error(getPos(), "XObject '%s' is wrong type", args[0].getName());
- obj1.free();
- return;
- }
-#ifdef OPI_SUPPORT
- obj1.streamGetDict()->lookup("OPI", &opiDict);
- if (opiDict.isDict()) {
- out->opiBegin(state, opiDict.getDict());
- }
-#endif
- obj1.streamGetDict()->lookup("Subtype", &obj2);
- if (obj2.isName("Image")) {
- res->lookupXObjectNF(args[0].getName(), &refObj);
- doImage(&refObj, obj1.getStream(), gFalse);
- refObj.free();
- } else if (obj2.isName("Form")) {
- doForm(&obj1);
- } else if (obj2.isName("PS")) {
- obj1.streamGetDict()->lookup("Level1", &obj3);
- out->psXObject(obj1.getStream(),
- obj3.isStream() ? obj3.getStream() : (Stream *)NULL);
- } else if (obj2.isName()) {
- error(getPos(), "Unknown XObject subtype '%s'", obj2.getName());
- } else {
- error(getPos(), "XObject subtype is missing or wrong type");
- }
- obj2.free();
-#ifdef OPI_SUPPORT
- if (opiDict.isDict()) {
- out->opiEnd(state, opiDict.getDict());
- }
- opiDict.free();
-#endif
- obj1.free();
-}
-
-void Gfx::doImage(Object *ref, Stream *str, GBool inlineImg) {
- Dict *dict;
- int width, height;
- int bits;
- GBool mask;
- GBool invert;
- GfxColorSpace *colorSpace;
- GfxImageColorMap *colorMap;
- Object maskObj;
- GBool haveMask;
- int maskColors[2*gfxColorMaxComps];
- Object obj1, obj2;
- int i;
-
- // get stream dict
- dict = str->getDict();
-
- // get size
- dict->lookup("Width", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("W", &obj1);
- }
- if (!obj1.isInt())
- goto err2;
- width = obj1.getInt();
- obj1.free();
- dict->lookup("Height", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("H", &obj1);
- }
- if (!obj1.isInt())
- goto err2;
- height = obj1.getInt();
- obj1.free();
-
- // image or mask?
- dict->lookup("ImageMask", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("IM", &obj1);
- }
- mask = gFalse;
- if (obj1.isBool())
- mask = obj1.getBool();
- else if (!obj1.isNull())
- goto err2;
- obj1.free();
-
- // bit depth
- dict->lookup("BitsPerComponent", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("BPC", &obj1);
- }
- if (!obj1.isInt())
- goto err2;
- bits = obj1.getInt();
- obj1.free();
-
- // display a mask
- if (mask) {
-
- // check for inverted mask
- if (bits != 1)
- goto err1;
- invert = gFalse;
- dict->lookup("Decode", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("D", &obj1);
- }
- if (obj1.isArray()) {
- obj1.arrayGet(0, &obj2);
- if (obj2.isInt() && obj2.getInt() == 1)
- invert = gTrue;
- obj2.free();
- } else if (!obj1.isNull()) {
- goto err2;
- }
- obj1.free();
-
- // draw it
- out->drawImageMask(state, ref, str, width, height, invert, inlineImg);
-
- } else {
-
- // get color space and color map
- dict->lookup("ColorSpace", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("CS", &obj1);
- }
- if (obj1.isName()) {
- res->lookupColorSpace(obj1.getName(), &obj2);
- if (!obj2.isNull()) {
- obj1.free();
- obj1 = obj2;
- } else {
- obj2.free();
- }
- }
- colorSpace = GfxColorSpace::parse(&obj1);
- obj1.free();
- if (!colorSpace) {
- goto err1;
- }
- dict->lookup("Decode", &obj1);
- if (obj1.isNull()) {
- obj1.free();
- dict->lookup("D", &obj1);
- }
- colorMap = new GfxImageColorMap(bits, &obj1, colorSpace);
- obj1.free();
- if (!colorMap->isOk()) {
- delete colorMap;
- goto err1;
- }
-
- // get the mask
- haveMask = gFalse;
- dict->lookup("Mask", &maskObj);
- if (maskObj.isArray()) {
- for (i = 0;
- i < maskObj.arrayGetLength() && i < 2*gfxColorMaxComps;
- ++i) {
- maskObj.arrayGet(i, &obj1);
- maskColors[i] = obj1.getInt();
- obj1.free();
- }
- haveMask = gTrue;
- }
-
- // draw it
- out->drawImage(state, ref, str, width, height, colorMap,
- haveMask ? maskColors : (int *)NULL, inlineImg);
- delete colorMap;
-
- maskObj.free();
- }
-
- if ((i = width * height) > 1000) {
- i = 1000;
- }
- updateLevel += i;
-
- return;
-
- err2:
- obj1.free();
- err1:
- error(getPos(), "Bad image parameters");
-}
-
-void Gfx::doForm(Object *str) {
- Dict *dict;
- Object matrixObj, bboxObj;
- double m[6], bbox[6];
- Object resObj;
- Dict *resDict;
- Object obj1;
- int i;
-
- // get stream dict
- dict = str->streamGetDict();
-
- // check form type
- dict->lookup("FormType", &obj1);
- if (!(obj1.isInt() && obj1.getInt() == 1)) {
- error(getPos(), "Unknown form type");
- }
- obj1.free();
-
- // get bounding box
- dict->lookup("BBox", &bboxObj);
- if (!bboxObj.isArray()) {
- matrixObj.free();
- bboxObj.free();
- error(getPos(), "Bad form bounding box");
- return;
- }
- for (i = 0; i < 4; ++i) {
- bboxObj.arrayGet(i, &obj1);
- bbox[i] = obj1.getNum();
- obj1.free();
- }
- bboxObj.free();
-
- // get matrix
- dict->lookup("Matrix", &matrixObj);
- if (matrixObj.isArray()) {
- for (i = 0; i < 6; ++i) {
- matrixObj.arrayGet(i, &obj1);
- m[i] = obj1.getNum();
- obj1.free();
- }
- } else {
- m[0] = 1; m[1] = 0;
- m[2] = 0; m[3] = 1;
- m[4] = 0; m[5] = 0;
- }
- matrixObj.free();
-
- // get resources
- dict->lookup("Resources", &resObj);
- resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
-
- // draw it
- doForm1(str, resDict, m, bbox);
-
- resObj.free();
-}
-
-void Gfx::doAnnot(Object *str, double xMin, double yMin,
- double xMax, double yMax) {
- Dict *dict, *resDict;
- Object matrixObj, bboxObj, resObj;
- Object obj1;
- double m[6], bbox[6], ictm[6];
- const double *ctm;
- double formX0, formY0, formX1, formY1;
- double annotX0, annotY0, annotX1, annotY1;
- double det, x, y, sx, sy;
- int i;
-
- // get stream dict
- dict = str->streamGetDict();
-
- // get the form bounding box
- dict->lookup("BBox", &bboxObj);
- if (!bboxObj.isArray()) {
- bboxObj.free();
- error(getPos(), "Bad form bounding box");
- return;
- }
- for (i = 0; i < 4; ++i) {
- bboxObj.arrayGet(i, &obj1);
- bbox[i] = obj1.getNum();
- obj1.free();
- }
- bboxObj.free();
-
- // get the form matrix
- dict->lookup("Matrix", &matrixObj);
- if (matrixObj.isArray()) {
- for (i = 0; i < 6; ++i) {
- matrixObj.arrayGet(i, &obj1);
- m[i] = obj1.getNum();
- obj1.free();
- }
- } else {
- m[0] = 1; m[1] = 0;
- m[2] = 0; m[3] = 1;
- m[4] = 0; m[5] = 0;
- }
- matrixObj.free();
-
- // transform the form bbox from form space to user space
- formX0 = bbox[0] * m[0] + bbox[1] * m[2] + m[4];
- formY0 = bbox[0] * m[1] + bbox[1] * m[3] + m[5];
- formX1 = bbox[2] * m[0] + bbox[3] * m[2] + m[4];
- formY1 = bbox[2] * m[1] + bbox[3] * m[3] + m[5];
-
- // transform the annotation bbox from default user space to user
- // space: (bbox * baseMatrix) * iCTM
- ctm = state->getCTM();
- det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
- ictm[0] = ctm[3] * det;
- ictm[1] = -ctm[1] * det;
- ictm[2] = -ctm[2] * det;
- ictm[3] = ctm[0] * det;
- ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
- ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
- x = baseMatrix[0] * xMin + baseMatrix[2] * yMin + baseMatrix[4];
- y = baseMatrix[1] * xMin + baseMatrix[3] * yMin + baseMatrix[5];
- annotX0 = ictm[0] * x + ictm[2] * y + ictm[4];
- annotY0 = ictm[1] * x + ictm[3] * y + ictm[5];
- x = baseMatrix[0] * xMax + baseMatrix[2] * yMax + baseMatrix[4];
- y = baseMatrix[1] * xMax + baseMatrix[3] * yMax + baseMatrix[5];
- annotX1 = ictm[0] * x + ictm[2] * y + ictm[4];
- annotY1 = ictm[1] * x + ictm[3] * y + ictm[5];
-
- // swap min/max coords
- if (formX0 > formX1) {
- x = formX0; formX0 = formX1; formX1 = x;
- }
- if (formY0 > formY1) {
- y = formY0; formY0 = formY1; formY1 = y;
- }
- if (annotX0 > annotX1) {
- x = annotX0; annotX0 = annotX1; annotX1 = x;
- }
- if (annotY0 > annotY1) {
- y = annotY0; annotY0 = annotY1; annotY1 = y;
- }
-
- // scale the form to fit the annotation bbox
- if (formX1 == formX0) {
- // this shouldn't happen
- sx = 1;
- } else {
- sx = (annotX1 - annotX0) / (formX1 - formX0);
- }
- if (formY1 == formY0) {
- // this shouldn't happen
- sy = 1;
- } else {
- sy = (annotY1 - annotY0) / (formY1 - formY0);
- }
- m[0] *= sx;
- m[2] *= sx;
- m[4] = (m[4] - formX0) * sx + annotX0;
- m[1] *= sy;
- m[3] *= sy;
- m[5] = (m[5] - formY0) * sy + annotY0;
-
- // get resources
- dict->lookup("Resources", &resObj);
- resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
-
- // draw it
- doForm1(str, resDict, m, bbox);
-
- resObj.free();
- bboxObj.free();
-}
-
-void Gfx::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox) {
- Parser *oldParser;
- double oldBaseMatrix[6];
- int i;
-
- // push new resources on stack
- pushResources(resDict);
-
- // save current graphics state
- out->saveState(state);
- state = state->save();
-
- // save current parser
- oldParser = parser;
-
- // set form transformation matrix
- state->concatCTM(matrix[0], matrix[1], matrix[2],
- matrix[3], matrix[4], matrix[5]);
- out->updateCTM(state, matrix[0], matrix[1], matrix[2],
- matrix[3], matrix[4], matrix[5]);
-
- // set new base matrix
- for (i = 0; i < 6; ++i) {
- oldBaseMatrix[i] = baseMatrix[i];
- baseMatrix[i] = state->getCTM()[i];
- }
-
- // set form bounding box
- state->moveTo(bbox[0], bbox[1]);
- state->lineTo(bbox[2], bbox[1]);
- state->lineTo(bbox[2], bbox[3]);
- state->lineTo(bbox[0], bbox[3]);
- state->closePath();
- state->clip();
- out->clip(state);
- state->clearPath();
-
- // draw the form
- display(str, gFalse);
-
- // restore base matrix
- for (i = 0; i < 6; ++i) {
- baseMatrix[i] = oldBaseMatrix[i];
- }
-
- // restore parser
- parser = oldParser;
-
- // restore graphics state
- state = state->restore();
- out->restoreState(state);
-
- // pop resource stack
- popResources();
-
- return;
-}
-
-void Gfx::pushResources(Dict *resDict) {
- res = new GfxResources(xref, resDict, res);
-}
-
-void Gfx::popResources() {
- GfxResources *resPtr;
-
- resPtr = res->getNext();
- delete res;
- res = resPtr;
-}
-
-//------------------------------------------------------------------------
-// in-line image operators
-//------------------------------------------------------------------------
-
-void Gfx::opBeginImage(Object /*args*/[], int /*numArgs*/) {
- Stream *str;
- int c1, c2;
-
- // build dict/stream
- str = buildImageStream();
-
- // display the image
- if (str) {
- doImage(NULL, str, gTrue);
-
- // skip 'EI' tag
- c1 = str->getBaseStream()->getChar();
- c2 = str->getBaseStream()->getChar();
- while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) {
- c1 = c2;
- c2 = str->getBaseStream()->getChar();
- }
- delete str;
- }
-}
-
-Stream *Gfx::buildImageStream() {
- Object dict;
- Object obj;
- char *key;
- Stream *str;
-
- // build dictionary
- dict.initDict(xref);
- parser->getObj(&obj);
- while (!obj.isCmd("ID") && !obj.isEOF()) {
- if (!obj.isName()) {
- error(getPos(), "Inline image dictionary key must be a name object");
- obj.free();
- } else {
- key = copyString(obj.getName());
- obj.free();
- parser->getObj(&obj);
- if (obj.isEOF() || obj.isError()) {
- gfree(key);
- break;
- }
- dict.dictAdd(key, &obj);
- }
- parser->getObj(&obj);
- }
- if (obj.isEOF()) {
- error(getPos(), "End of file in inline image");
- obj.free();
- dict.free();
- return NULL;
- }
- obj.free();
-
- // make stream
- str = new EmbedStream(parser->getStream(), &dict);
- str = str->addFilters(&dict);
-
- return str;
-}
-
-void Gfx::opImageData(Object /*args*/[], int /*numArgs*/) {
- error(getPos(), "Internal: got 'ID' operator");
-}
-
-void Gfx::opEndImage(Object /*args*/[], int /*numArgs*/) {
- error(getPos(), "Internal: got 'EI' operator");
-}
-
-//------------------------------------------------------------------------
-// type 3 font operators
-//------------------------------------------------------------------------
-
-void Gfx::opSetCharWidth(Object args[], int /*numArgs*/) {
- out->type3D0(state, args[0].getNum(), args[1].getNum());
-}
-
-void Gfx::opSetCacheDevice(Object args[], int /*numArgs*/) {
- out->type3D1(state, args[0].getNum(), args[1].getNum(),
- args[2].getNum(), args[3].getNum(),
- args[4].getNum(), args[5].getNum());
-}
-
-//------------------------------------------------------------------------
-// compatibility operators
-//------------------------------------------------------------------------
-
-void Gfx::opBeginIgnoreUndef(Object /*args*/[], int /*numArgs*/) {
- ++ignoreUndef;
-}
-
-void Gfx::opEndIgnoreUndef(Object /*args*/[], int /*numArgs*/) {
- if (ignoreUndef > 0)
- --ignoreUndef;
-}
-
-//------------------------------------------------------------------------
-// marked content operators
-//------------------------------------------------------------------------
-
-void Gfx::opBeginMarkedContent(Object args[], int numArgs) {
- if (printCommands) {
- printf(" marked content: %s ", args[0].getName());
- if (numArgs == 2)
- args[2].print(stdout);
- printf("\n");
- fflush(stdout);
- }
-}
-
-void Gfx::opEndMarkedContent(Object /*args*/[], int /*numArgs*/) {
-}
-
-void Gfx::opMarkPoint(Object args[], int numArgs) {
- if (printCommands) {
- printf(" mark point: %s ", args[0].getName());
- if (numArgs == 2)
- args[2].print(stdout);
- printf("\n");
- fflush(stdout);
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Gfx.cpp b/filters/kword/pdf/xpdf/xpdf/Gfx.cpp
new file mode 100644
index 000000000..cb6b47831
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Gfx.cpp
@@ -0,0 +1,2782 @@
+//========================================================================
+//
+// Gfx.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stddef.h>
+#include <string.h>
+#include <math.h>
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "CharTypes.h"
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Stream.h"
+#include "Lexer.h"
+#include "Parser.h"
+#include "GfxFont.h"
+#include "GfxState.h"
+#include "OutputDev.h"
+#include "Page.h"
+#include "Error.h"
+#include "Gfx.h"
+
+// the MSVC math.h doesn't define this
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+//------------------------------------------------------------------------
+// constants
+//------------------------------------------------------------------------
+
+// Max number of splits along the t axis for an axial shading fill.
+#define axialMaxSplits 256
+
+// Max delta allowed in any color component for an axial shading fill.
+#define axialColorDelta (1 / 256.0)
+
+// Max number of splits along the t axis for a radial shading fill.
+#define radialMaxSplits 256
+
+// Max delta allowed in any color component for a radial shading fill.
+#define radialColorDelta (1 / 256.0)
+
+//------------------------------------------------------------------------
+// Operator table
+//------------------------------------------------------------------------
+
+Operator Gfx::opTab[] = {
+ {"\"", 3, {tchkNum, tchkNum, tchkString},
+ &Gfx::opMoveSetShowText},
+ {"'", 1, {tchkString},
+ &Gfx::opMoveShowText},
+ {"B", 0, {tchkNone},
+ &Gfx::opFillStroke},
+ {"B*", 0, {tchkNone},
+ &Gfx::opEOFillStroke},
+ {"BDC", 2, {tchkName, tchkProps},
+ &Gfx::opBeginMarkedContent},
+ {"BI", 0, {tchkNone},
+ &Gfx::opBeginImage},
+ {"BMC", 1, {tchkName},
+ &Gfx::opBeginMarkedContent},
+ {"BT", 0, {tchkNone},
+ &Gfx::opBeginText},
+ {"BX", 0, {tchkNone},
+ &Gfx::opBeginIgnoreUndef},
+ {"CS", 1, {tchkName},
+ &Gfx::opSetStrokeColorSpace},
+ {"DP", 2, {tchkName, tchkProps},
+ &Gfx::opMarkPoint},
+ {"Do", 1, {tchkName},
+ &Gfx::opXObject},
+ {"EI", 0, {tchkNone},
+ &Gfx::opEndImage},
+ {"EMC", 0, {tchkNone},
+ &Gfx::opEndMarkedContent},
+ {"ET", 0, {tchkNone},
+ &Gfx::opEndText},
+ {"EX", 0, {tchkNone},
+ &Gfx::opEndIgnoreUndef},
+ {"F", 0, {tchkNone},
+ &Gfx::opFill},
+ {"G", 1, {tchkNum},
+ &Gfx::opSetStrokeGray},
+ {"ID", 0, {tchkNone},
+ &Gfx::opImageData},
+ {"J", 1, {tchkInt},
+ &Gfx::opSetLineCap},
+ {"K", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetStrokeCMYKColor},
+ {"M", 1, {tchkNum},
+ &Gfx::opSetMiterLimit},
+ {"MP", 1, {tchkName},
+ &Gfx::opMarkPoint},
+ {"Q", 0, {tchkNone},
+ &Gfx::opRestore},
+ {"RG", 3, {tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetStrokeRGBColor},
+ {"S", 0, {tchkNone},
+ &Gfx::opStroke},
+ {"SC", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetStrokeColor},
+ {"SCN", -5, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN},
+ &Gfx::opSetStrokeColorN},
+ {"T*", 0, {tchkNone},
+ &Gfx::opTextNextLine},
+ {"TD", 2, {tchkNum, tchkNum},
+ &Gfx::opTextMoveSet},
+ {"TJ", 1, {tchkArray},
+ &Gfx::opShowSpaceText},
+ {"TL", 1, {tchkNum},
+ &Gfx::opSetTextLeading},
+ {"Tc", 1, {tchkNum},
+ &Gfx::opSetCharSpacing},
+ {"Td", 2, {tchkNum, tchkNum},
+ &Gfx::opTextMove},
+ {"Tf", 2, {tchkName, tchkNum},
+ &Gfx::opSetFont},
+ {"Tj", 1, {tchkString},
+ &Gfx::opShowText},
+ {"Tm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &Gfx::opSetTextMatrix},
+ {"Tr", 1, {tchkInt},
+ &Gfx::opSetTextRender},
+ {"Ts", 1, {tchkNum},
+ &Gfx::opSetTextRise},
+ {"Tw", 1, {tchkNum},
+ &Gfx::opSetWordSpacing},
+ {"Tz", 1, {tchkNum},
+ &Gfx::opSetHorizScaling},
+ {"W", 0, {tchkNone},
+ &Gfx::opClip},
+ {"W*", 0, {tchkNone},
+ &Gfx::opEOClip},
+ {"b", 0, {tchkNone},
+ &Gfx::opCloseFillStroke},
+ {"b*", 0, {tchkNone},
+ &Gfx::opCloseEOFillStroke},
+ {"c", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &Gfx::opCurveTo},
+ {"cm", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &Gfx::opConcat},
+ {"cs", 1, {tchkName},
+ &Gfx::opSetFillColorSpace},
+ {"d", 2, {tchkArray, tchkNum},
+ &Gfx::opSetDash},
+ {"d0", 2, {tchkNum, tchkNum},
+ &Gfx::opSetCharWidth},
+ {"d1", 6, {tchkNum, tchkNum, tchkNum, tchkNum,
+ tchkNum, tchkNum},
+ &Gfx::opSetCacheDevice},
+ {"f", 0, {tchkNone},
+ &Gfx::opFill},
+ {"f*", 0, {tchkNone},
+ &Gfx::opEOFill},
+ {"g", 1, {tchkNum},
+ &Gfx::opSetFillGray},
+ {"gs", 1, {tchkName},
+ &Gfx::opSetExtGState},
+ {"h", 0, {tchkNone},
+ &Gfx::opClosePath},
+ {"i", 1, {tchkNum},
+ &Gfx::opSetFlat},
+ {"j", 1, {tchkInt},
+ &Gfx::opSetLineJoin},
+ {"k", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetFillCMYKColor},
+ {"l", 2, {tchkNum, tchkNum},
+ &Gfx::opLineTo},
+ {"m", 2, {tchkNum, tchkNum},
+ &Gfx::opMoveTo},
+ {"n", 0, {tchkNone},
+ &Gfx::opEndPath},
+ {"q", 0, {tchkNone},
+ &Gfx::opSave},
+ {"re", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opRectangle},
+ {"rg", 3, {tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetFillRGBColor},
+ {"ri", 1, {tchkName},
+ &Gfx::opSetRenderingIntent},
+ {"s", 0, {tchkNone},
+ &Gfx::opCloseStroke},
+ {"sc", -4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opSetFillColor},
+ {"scn", -5, {tchkSCN, tchkSCN, tchkSCN, tchkSCN,
+ tchkSCN},
+ &Gfx::opSetFillColorN},
+ {"sh", 1, {tchkName},
+ &Gfx::opShFill},
+ {"v", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opCurveTo1},
+ {"w", 1, {tchkNum},
+ &Gfx::opSetLineWidth},
+ {"y", 4, {tchkNum, tchkNum, tchkNum, tchkNum},
+ &Gfx::opCurveTo2},
+};
+
+#define numOps (sizeof(opTab) / sizeof(Operator))
+
+//------------------------------------------------------------------------
+// GfxResources
+//------------------------------------------------------------------------
+
+GfxResources::GfxResources(XRef *xref, Dict *resDict, GfxResources *nextA) {
+ Object obj1;
+
+ if (resDict) {
+
+ // build font dictionary
+ fonts = NULL;
+ resDict->lookup("Font", &obj1);
+ if (obj1.isDict()) {
+ fonts = new GfxFontDict(xref, obj1.getDict());
+ }
+ obj1.free();
+
+ // get XObject dictionary
+ resDict->lookup("XObject", &xObjDict);
+
+ // get color space dictionary
+ resDict->lookup("ColorSpace", &colorSpaceDict);
+
+ // get pattern dictionary
+ resDict->lookup("Pattern", &patternDict);
+
+ // get shading dictionary
+ resDict->lookup("Shading", &shadingDict);
+
+ // get graphics state parameter dictionary
+ resDict->lookup("ExtGState", &gStateDict);
+
+ } else {
+ fonts = NULL;
+ xObjDict.initNull();
+ colorSpaceDict.initNull();
+ patternDict.initNull();
+ gStateDict.initNull();
+ }
+
+ next = nextA;
+}
+
+GfxResources::~GfxResources() {
+ if (fonts) {
+ delete fonts;
+ }
+ xObjDict.free();
+ colorSpaceDict.free();
+ patternDict.free();
+ shadingDict.free();
+ gStateDict.free();
+}
+
+GfxFont *GfxResources::lookupFont(char *name) {
+ GfxFont *font;
+ GfxResources *resPtr;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->fonts) {
+ if ((font = resPtr->fonts->lookup(name)))
+ return font;
+ }
+ }
+ error(-1, "Unknown font tag '%s'", name);
+ return NULL;
+}
+
+GBool GfxResources::lookupXObject(char *name, Object *obj) {
+ GfxResources *resPtr;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->xObjDict.isDict()) {
+ if (!resPtr->xObjDict.dictLookup(name, obj)->isNull())
+ return gTrue;
+ obj->free();
+ }
+ }
+ error(-1, "XObject '%s' is unknown", name);
+ return gFalse;
+}
+
+GBool GfxResources::lookupXObjectNF(char *name, Object *obj) {
+ GfxResources *resPtr;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->xObjDict.isDict()) {
+ if (!resPtr->xObjDict.dictLookupNF(name, obj)->isNull())
+ return gTrue;
+ obj->free();
+ }
+ }
+ error(-1, "XObject '%s' is unknown", name);
+ return gFalse;
+}
+
+void GfxResources::lookupColorSpace(char *name, Object *obj) {
+ GfxResources *resPtr;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->colorSpaceDict.isDict()) {
+ if (!resPtr->colorSpaceDict.dictLookup(name, obj)->isNull()) {
+ return;
+ }
+ obj->free();
+ }
+ }
+ obj->initNull();
+}
+
+GfxPattern *GfxResources::lookupPattern(char *name) {
+ GfxResources *resPtr;
+ GfxPattern *pattern;
+ Object obj;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->patternDict.isDict()) {
+ if (!resPtr->patternDict.dictLookup(name, &obj)->isNull()) {
+ pattern = GfxPattern::parse(&obj);
+ obj.free();
+ return pattern;
+ }
+ obj.free();
+ }
+ }
+ error(-1, "Unknown pattern '%s'", name);
+ return NULL;
+}
+
+GfxShading *GfxResources::lookupShading(char *name) {
+ GfxResources *resPtr;
+ GfxShading *shading;
+ Object obj;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->shadingDict.isDict()) {
+ if (!resPtr->shadingDict.dictLookup(name, &obj)->isNull()) {
+ shading = GfxShading::parse(&obj);
+ obj.free();
+ return shading;
+ }
+ obj.free();
+ }
+ }
+ error(-1, "Unknown shading '%s'", name);
+ return NULL;
+}
+
+GBool GfxResources::lookupGState(char *name, Object *obj) {
+ GfxResources *resPtr;
+
+ for (resPtr = this; resPtr; resPtr = resPtr->next) {
+ if (resPtr->gStateDict.isDict()) {
+ if (!resPtr->gStateDict.dictLookup(name, obj)->isNull()) {
+ return gTrue;
+ }
+ obj->free();
+ }
+ }
+ error(-1, "ExtGState '%s' is unknown", name);
+ return gFalse;
+}
+
+//------------------------------------------------------------------------
+// Gfx
+//------------------------------------------------------------------------
+
+Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, double dpi,
+ PDFRectangle *box, GBool crop, PDFRectangle *cropBox, int rotate,
+ GBool (*abortCheckCbkA)(void *data),
+ void *abortCheckCbkDataA) {
+ int i;
+
+ xref = xrefA;
+ subPage = gFalse;
+ printCommands = globalParams->getPrintCommands();
+
+ // start the resource stack
+ res = new GfxResources(xref, resDict, NULL);
+
+ // initialize
+ out = outA;
+ state = new GfxState(dpi, box, rotate, out->upsideDown());
+ fontChanged = gFalse;
+ clip = clipNone;
+ ignoreUndef = 0;
+ out->startPage(pageNum, state);
+ out->setDefaultCTM(state->getCTM());
+ out->updateAll(state);
+ for (i = 0; i < 6; ++i) {
+ baseMatrix[i] = state->getCTM()[i];
+ }
+ abortCheckCbk = abortCheckCbkA;
+ abortCheckCbkData = abortCheckCbkDataA;
+
+ // set crop box
+ if (crop) {
+ state->moveTo(cropBox->x1, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y2);
+ state->lineTo(cropBox->x1, cropBox->y2);
+ state->closePath();
+ state->clip();
+ out->clip(state);
+ state->clearPath();
+ }
+}
+
+Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict,
+ PDFRectangle *box, GBool crop, PDFRectangle *cropBox,
+ GBool (*abortCheckCbkA)(void *data),
+ void *abortCheckCbkDataA) {
+ int i;
+
+ xref = xrefA;
+ subPage = gTrue;
+ printCommands = globalParams->getPrintCommands();
+
+ // start the resource stack
+ res = new GfxResources(xref, resDict, NULL);
+
+ // initialize
+ out = outA;
+ state = new GfxState(72, box, 0, gFalse);
+ fontChanged = gFalse;
+ clip = clipNone;
+ ignoreUndef = 0;
+ for (i = 0; i < 6; ++i) {
+ baseMatrix[i] = state->getCTM()[i];
+ }
+ abortCheckCbk = abortCheckCbkA;
+ abortCheckCbkData = abortCheckCbkDataA;
+
+ // set crop box
+ if (crop) {
+ state->moveTo(cropBox->x1, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y1);
+ state->lineTo(cropBox->x2, cropBox->y2);
+ state->lineTo(cropBox->x1, cropBox->y2);
+ state->closePath();
+ state->clip();
+ out->clip(state);
+ state->clearPath();
+ }
+}
+
+Gfx::~Gfx() {
+ while (state->hasSaves()) {
+ state = state->restore();
+ out->restoreState(state);
+ }
+ if (!subPage) {
+ out->endPage();
+ }
+ while (res) {
+ popResources();
+ }
+ if (state) {
+ delete state;
+ }
+}
+
+void Gfx::display(Object *obj, GBool topLevel) {
+ Object obj2;
+ int i;
+
+ if (obj->isArray()) {
+ for (i = 0; i < obj->arrayGetLength(); ++i) {
+ obj->arrayGet(i, &obj2);
+ if (!obj2.isStream()) {
+ error(-1, "Weird page contents");
+ obj2.free();
+ return;
+ }
+ obj2.free();
+ }
+ } else if (!obj->isStream()) {
+ error(-1, "Weird page contents");
+ return;
+ }
+ parser = new Parser(xref, new Lexer(xref, obj));
+ go(topLevel);
+ delete parser;
+ parser = NULL;
+}
+
+void Gfx::go(GBool topLevel) {
+ Object obj;
+ Object args[maxArgs];
+ int numArgs, i;
+ int lastAbortCheck;
+
+ // scan a sequence of objects
+ updateLevel = lastAbortCheck = 0;
+ numArgs = 0;
+ parser->getObj(&obj);
+ while (!obj.isEOF()) {
+
+ // got a command - execute it
+ if (obj.isCmd()) {
+ if (printCommands) {
+ obj.print(stdout);
+ for (i = 0; i < numArgs; ++i) {
+ printf(" ");
+ args[i].print(stdout);
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+ execOp(&obj, args, numArgs);
+ obj.free();
+ for (i = 0; i < numArgs; ++i)
+ args[i].free();
+ numArgs = 0;
+
+ // periodically update display
+ if (++updateLevel >= 20000) {
+ out->dump();
+ updateLevel = 0;
+ }
+
+ // check for an abort
+ if (abortCheckCbk) {
+ if (updateLevel - lastAbortCheck > 10) {
+ if ((*abortCheckCbk)(abortCheckCbkData)) {
+ break;
+ }
+ lastAbortCheck = updateLevel;
+ }
+ }
+
+ // got an argument - save it
+ } else if (numArgs < maxArgs) {
+ args[numArgs++] = obj;
+
+ // too many arguments - something is wrong
+ } else {
+ error(getPos(), "Too many args in content stream");
+ if (printCommands) {
+ printf("throwing away arg: ");
+ obj.print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+ obj.free();
+ }
+
+ // grab the next object
+ parser->getObj(&obj);
+ }
+ obj.free();
+
+ // args at end with no command
+ if (numArgs > 0) {
+ error(getPos(), "Leftover args in content stream");
+ if (printCommands) {
+ printf("%d leftovers:", numArgs);
+ for (i = 0; i < numArgs; ++i) {
+ printf(" ");
+ args[i].print(stdout);
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+ for (i = 0; i < numArgs; ++i)
+ args[i].free();
+ }
+
+ // update display
+ if (topLevel && updateLevel > 0) {
+ out->dump();
+ }
+}
+
+void Gfx::execOp(Object *cmd, Object args[], int numArgs) {
+ Operator *op;
+ const char *name;
+ int i;
+
+ // find operator
+ name = cmd->getCmd();
+ if (!(op = findOp(name))) {
+ if (ignoreUndef == 0)
+ error(getPos(), "Unknown operator '%s'", name);
+ return;
+ }
+
+ // type check args
+ if (op->numArgs >= 0) {
+ if (numArgs != op->numArgs) {
+ error(getPos(), "Wrong number (%d) of args to '%s' operator",
+ numArgs, name);
+ return;
+ }
+ } else {
+ if (numArgs > -op->numArgs) {
+ error(getPos(), "Too many (%d) args to '%s' operator",
+ numArgs, name);
+ return;
+ }
+ }
+ for (i = 0; i < numArgs; ++i) {
+ if (!checkArg(&args[i], op->tchk[i])) {
+ error(getPos(), "Arg #%d to '%s' operator is wrong type (%s)",
+ i, name, args[i].getTypeName());
+ return;
+ }
+ }
+
+ // do it
+ (this->*op->func)(args, numArgs);
+}
+
+Operator *Gfx::findOp(const char *name) {
+ int a, b, m, cmp;
+
+ a = -1;
+ b = numOps;
+ // invariant: opTab[a] < name < opTab[b]
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ cmp = strcmp(opTab[m].name, name);
+ if (cmp < 0)
+ a = m;
+ else if (cmp > 0)
+ b = m;
+ else
+ a = b = m;
+ }
+ if (cmp != 0)
+ return NULL;
+ return &opTab[a];
+}
+
+GBool Gfx::checkArg(Object *arg, TchkType type) {
+ switch (type) {
+ case tchkBool: return arg->isBool();
+ case tchkInt: return arg->isInt();
+ case tchkNum: return arg->isNum();
+ case tchkString: return arg->isString();
+ case tchkName: return arg->isName();
+ case tchkArray: return arg->isArray();
+ case tchkProps: return arg->isDict() || arg->isName();
+ case tchkSCN: return arg->isNum() || arg->isName();
+ case tchkNone: return gFalse;
+ }
+ return gFalse;
+}
+
+int Gfx::getPos() {
+ return parser ? parser->getPos() : -1;
+}
+
+//------------------------------------------------------------------------
+// graphics state operators
+//------------------------------------------------------------------------
+
+void Gfx::opSave(Object /*args*/[], int /*numArgs*/) {
+ out->saveState(state);
+ state = state->save();
+}
+
+void Gfx::opRestore(Object /*args*/[], int /*numArgs*/) {
+ state = state->restore();
+ out->restoreState(state);
+}
+
+void Gfx::opConcat(Object args[], int /*numArgs*/) {
+ state->concatCTM(args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+ out->updateCTM(state, args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+ fontChanged = gTrue;
+}
+
+void Gfx::opSetDash(Object args[], int /*numArgs*/) {
+ Array *a;
+ int length;
+ Object obj;
+ double *dash;
+ int i;
+
+ a = args[0].getArray();
+ length = a->getLength();
+ if (length == 0) {
+ dash = NULL;
+ } else {
+ dash = (double *)gmalloc(length * sizeof(double));
+ for (i = 0; i < length; ++i) {
+ dash[i] = a->get(i, &obj)->getNum();
+ obj.free();
+ }
+ }
+ state->setLineDash(dash, length, args[1].getNum());
+ out->updateLineDash(state);
+}
+
+void Gfx::opSetFlat(Object args[], int /*numArgs*/) {
+ state->setFlatness((int)args[0].getNum());
+ out->updateFlatness(state);
+}
+
+void Gfx::opSetLineJoin(Object args[], int /*numArgs*/) {
+ state->setLineJoin(args[0].getInt());
+ out->updateLineJoin(state);
+}
+
+void Gfx::opSetLineCap(Object args[], int /*numArgs*/) {
+ state->setLineCap(args[0].getInt());
+ out->updateLineCap(state);
+}
+
+void Gfx::opSetMiterLimit(Object args[], int /*numArgs*/) {
+ state->setMiterLimit(args[0].getNum());
+ out->updateMiterLimit(state);
+}
+
+void Gfx::opSetLineWidth(Object args[], int /*numArgs*/) {
+ state->setLineWidth(args[0].getNum());
+ out->updateLineWidth(state);
+}
+
+void Gfx::opSetExtGState(Object args[], int /*numArgs*/) {
+ Object obj1, obj2;
+
+ if (!res->lookupGState(args[0].getName(), &obj1)) {
+ return;
+ }
+ if (!obj1.isDict()) {
+ error(getPos(), "ExtGState '%s' is wrong type", args[0].getName());
+ obj1.free();
+ return;
+ }
+ if (obj1.dictLookup("ca", &obj2)->isNum()) {
+ state->setFillOpacity(obj2.getNum());
+ out->updateFillOpacity(state);
+ }
+ obj2.free();
+ if (obj1.dictLookup("CA", &obj2)->isNum()) {
+ state->setStrokeOpacity(obj2.getNum());
+ out->updateStrokeOpacity(state);
+ }
+ obj2.free();
+ obj1.free();
+}
+
+void Gfx::opSetRenderingIntent(Object /*args*/[], int /*numArgs*/) {
+}
+
+//------------------------------------------------------------------------
+// color operators
+//------------------------------------------------------------------------
+
+void Gfx::opSetFillGray(Object args[], int /*numArgs*/) {
+ GfxColor color;
+
+ state->setFillPattern(NULL);
+ state->setFillColorSpace(new GfxDeviceGrayColorSpace());
+ color.c[0] = args[0].getNum();
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+}
+
+void Gfx::opSetStrokeGray(Object args[], int /*numArgs*/) {
+ GfxColor color;
+
+ state->setStrokePattern(NULL);
+ state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
+ color.c[0] = args[0].getNum();
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+}
+
+void Gfx::opSetFillCMYKColor(Object args[], int /*numArgs*/) {
+ GfxColor color;
+ int i;
+
+ state->setFillPattern(NULL);
+ state->setFillColorSpace(new GfxDeviceCMYKColorSpace());
+ for (i = 0; i < 4; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+}
+
+void Gfx::opSetStrokeCMYKColor(Object args[], int /*numArgs*/) {
+ GfxColor color;
+ int i;
+
+ state->setStrokePattern(NULL);
+ state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace());
+ for (i = 0; i < 4; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+}
+
+void Gfx::opSetFillRGBColor(Object args[], int /*numArgs*/) {
+ GfxColor color;
+ int i;
+
+ state->setFillPattern(NULL);
+ state->setFillColorSpace(new GfxDeviceRGBColorSpace());
+ for (i = 0; i < 3; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+}
+
+void Gfx::opSetStrokeRGBColor(Object args[], int /*numArgs*/) {
+ GfxColor color;
+ int i;
+
+ state->setStrokePattern(NULL);
+ state->setStrokeColorSpace(new GfxDeviceRGBColorSpace());
+ for (i = 0; i < 3; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+}
+
+void Gfx::opSetFillColorSpace(Object args[], int /*numArgs*/) {
+ Object obj;
+ GfxColorSpace *colorSpace;
+ GfxColor color;
+ int i;
+
+ state->setFillPattern(NULL);
+ res->lookupColorSpace(args[0].getName(), &obj);
+ if (obj.isNull()) {
+ colorSpace = GfxColorSpace::parse(&args[0]);
+ } else {
+ colorSpace = GfxColorSpace::parse(&obj);
+ }
+ obj.free();
+ if (colorSpace) {
+ state->setFillColorSpace(colorSpace);
+ } else {
+ error(getPos(), "Bad color space (fill)");
+ }
+ for (i = 0; i < gfxColorMaxComps; ++i) {
+ color.c[i] = 0;
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+}
+
+void Gfx::opSetStrokeColorSpace(Object args[], int /*numArgs*/) {
+ Object obj;
+ GfxColorSpace *colorSpace;
+ GfxColor color;
+ int i;
+
+ state->setStrokePattern(NULL);
+ res->lookupColorSpace(args[0].getName(), &obj);
+ if (obj.isNull()) {
+ colorSpace = GfxColorSpace::parse(&args[0]);
+ } else {
+ colorSpace = GfxColorSpace::parse(&obj);
+ }
+ obj.free();
+ if (colorSpace) {
+ state->setStrokeColorSpace(colorSpace);
+ } else {
+ error(getPos(), "Bad color space (stroke)");
+ }
+ for (i = 0; i < gfxColorMaxComps; ++i) {
+ color.c[i] = 0;
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+}
+
+void Gfx::opSetFillColor(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ state->setFillPattern(NULL);
+ for (i = 0; i < numArgs; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+}
+
+void Gfx::opSetStrokeColor(Object args[], int numArgs) {
+ GfxColor color;
+ int i;
+
+ state->setStrokePattern(NULL);
+ for (i = 0; i < numArgs; ++i) {
+ color.c[i] = args[i].getNum();
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+}
+
+void Gfx::opSetFillColorN(Object args[], int numArgs) {
+ GfxColor color;
+ GfxPattern *pattern;
+ int i;
+
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ if (numArgs > 1) {
+ for (i = 0; i < numArgs && i < 4; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = args[i].getNum();
+ }
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+ }
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
+ state->setFillPattern(pattern);
+ }
+
+ } else {
+ state->setFillPattern(NULL);
+ for (i = 0; i < numArgs && i < 4; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = args[i].getNum();
+ }
+ }
+ state->setFillColor(&color);
+ out->updateFillColor(state);
+ }
+}
+
+void Gfx::opSetStrokeColorN(Object args[], int numArgs) {
+ GfxColor color;
+ GfxPattern *pattern;
+ int i;
+
+ if (state->getStrokeColorSpace()->getMode() == csPattern) {
+ if (numArgs > 1) {
+ for (i = 0; i < numArgs && i < 4; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = args[i].getNum();
+ }
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+ }
+ if (args[numArgs-1].isName() &&
+ (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
+ state->setStrokePattern(pattern);
+ }
+
+ } else {
+ state->setStrokePattern(NULL);
+ for (i = 0; i < numArgs && i < 4; ++i) {
+ if (args[i].isNum()) {
+ color.c[i] = args[i].getNum();
+ }
+ }
+ state->setStrokeColor(&color);
+ out->updateStrokeColor(state);
+ }
+}
+
+//------------------------------------------------------------------------
+// path segment operators
+//------------------------------------------------------------------------
+
+void Gfx::opMoveTo(Object args[], int /*numArgs*/) {
+ state->moveTo(args[0].getNum(), args[1].getNum());
+}
+
+void Gfx::opLineTo(Object args[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ error(getPos(), "No current point in lineto");
+ return;
+ }
+ state->lineTo(args[0].getNum(), args[1].getNum());
+}
+
+void Gfx::opCurveTo(Object args[], int /*numArgs*/) {
+ double x1, y1, x2, y2, x3, y3;
+
+ if (!state->isCurPt()) {
+ error(getPos(), "No current point in curveto");
+ return;
+ }
+ x1 = args[0].getNum();
+ y1 = args[1].getNum();
+ x2 = args[2].getNum();
+ y2 = args[3].getNum();
+ x3 = args[4].getNum();
+ y3 = args[5].getNum();
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+void Gfx::opCurveTo1(Object args[], int /*numArgs*/) {
+ double x1, y1, x2, y2, x3, y3;
+
+ if (!state->isCurPt()) {
+ error(getPos(), "No current point in curveto1");
+ return;
+ }
+ x1 = state->getCurX();
+ y1 = state->getCurY();
+ x2 = args[0].getNum();
+ y2 = args[1].getNum();
+ x3 = args[2].getNum();
+ y3 = args[3].getNum();
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+void Gfx::opCurveTo2(Object args[], int /*numArgs*/) {
+ double x1, y1, x2, y2, x3, y3;
+
+ if (!state->isCurPt()) {
+ error(getPos(), "No current point in curveto2");
+ return;
+ }
+ x1 = args[0].getNum();
+ y1 = args[1].getNum();
+ x2 = args[2].getNum();
+ y2 = args[3].getNum();
+ x3 = x2;
+ y3 = y2;
+ state->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+void Gfx::opRectangle(Object args[], int /*numArgs*/) {
+ double x, y, w, h;
+
+ x = args[0].getNum();
+ y = args[1].getNum();
+ w = args[2].getNum();
+ h = args[3].getNum();
+ state->moveTo(x, y);
+ state->lineTo(x + w, y);
+ state->lineTo(x + w, y + h);
+ state->lineTo(x, y + h);
+ state->closePath();
+}
+
+void Gfx::opClosePath(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ error(getPos(), "No current point in closepath");
+ return;
+ }
+ state->closePath();
+}
+
+//------------------------------------------------------------------------
+// path painting operators
+//------------------------------------------------------------------------
+
+void Gfx::opEndPath(Object /*args*/[], int /*numArgs*/) {
+ doEndPath();
+}
+
+void Gfx::opStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in stroke");
+ return;
+ }
+ if (state->isPath())
+ out->stroke(state);
+ doEndPath();
+}
+
+void Gfx::opCloseStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in closepath/stroke");
+ return;
+ }
+ if (state->isPath()) {
+ state->closePath();
+ out->stroke(state);
+ }
+ doEndPath();
+}
+
+void Gfx::opFill(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in fill");
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gFalse);
+ } else {
+ out->fill(state);
+ }
+ }
+ doEndPath();
+}
+
+void Gfx::opEOFill(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in eofill");
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gTrue);
+ } else {
+ out->eoFill(state);
+ }
+ }
+ doEndPath();
+}
+
+void Gfx::opFillStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in fill/stroke");
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gFalse);
+ } else {
+ out->fill(state);
+ }
+ out->stroke(state);
+ }
+ doEndPath();
+}
+
+void Gfx::opCloseFillStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in closepath/fill/stroke");
+ return;
+ }
+ if (state->isPath()) {
+ state->closePath();
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gFalse);
+ } else {
+ out->fill(state);
+ }
+ out->stroke(state);
+ }
+ doEndPath();
+}
+
+void Gfx::opEOFillStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in eofill/stroke");
+ return;
+ }
+ if (state->isPath()) {
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gTrue);
+ } else {
+ out->eoFill(state);
+ }
+ out->stroke(state);
+ }
+ doEndPath();
+}
+
+void Gfx::opCloseEOFillStroke(Object /*args*/[], int /*numArgs*/) {
+ if (!state->isCurPt()) {
+ //error(getPos(), "No path in closepath/eofill/stroke");
+ return;
+ }
+ if (state->isPath()) {
+ state->closePath();
+ if (state->getFillColorSpace()->getMode() == csPattern) {
+ doPatternFill(gTrue);
+ } else {
+ out->eoFill(state);
+ }
+ out->stroke(state);
+ }
+ doEndPath();
+}
+
+void Gfx::doPatternFill(GBool eoFill) {
+ GfxPatternColorSpace *patCS;
+ GfxPattern *pattern;
+ GfxTilingPattern *tPat;
+ const GfxColorSpace *cs;
+ double xMin, yMin, xMax, yMax, x, y, x1, y1;
+ double cxMin, cyMin, cxMax, cyMax;
+ int xi0, yi0, xi1, yi1, xi, yi;
+ const double *ctm;
+ double *btm, *ptm;
+ double m[6], ictm[6], m1[6], imb[6];
+ double det;
+ double xstep, ystep;
+ int i;
+
+ // this is a bit of a kludge -- patterns can be really slow, so we
+ // skip them if we're only doing text extraction, since they almost
+ // certainly don't contain any text
+ if (!out->needNonText()) {
+ return;
+ }
+
+ // get color space
+ patCS = (GfxPatternColorSpace *)state->getFillColorSpace();
+
+ // get pattern
+ if (!(pattern = state->getFillPattern())) {
+ return;
+ }
+ if (pattern->getType() != 1) {
+ return;
+ }
+ tPat = (GfxTilingPattern *)pattern;
+
+ // construct a (pattern space) -> (current space) transform matrix
+ ctm = state->getCTM();
+ btm = baseMatrix;
+ ptm = tPat->getMatrix();
+ // iCTM = invert CTM
+ det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
+ ictm[0] = ctm[3] * det;
+ ictm[1] = -ctm[1] * det;
+ ictm[2] = -ctm[2] * det;
+ ictm[3] = ctm[0] * det;
+ ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
+ ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
+ // m1 = PTM * BTM = PTM * base transform matrix
+ m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2];
+ m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3];
+ m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2];
+ m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3];
+ m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4];
+ m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5];
+ // m = m1 * iCTM = (PTM * BTM) * (iCTM)
+ m[0] = m1[0] * ictm[0] + m1[1] * ictm[2];
+ m[1] = m1[0] * ictm[1] + m1[1] * ictm[3];
+ m[2] = m1[2] * ictm[0] + m1[3] * ictm[2];
+ m[3] = m1[2] * ictm[1] + m1[3] * ictm[3];
+ m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4];
+ m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5];
+
+ // construct a (base space) -> (pattern space) transform matrix
+ det = 1 / (m1[0] * m1[3] - m1[1] * m1[2]);
+ imb[0] = m1[3] * det;
+ imb[1] = -m1[1] * det;
+ imb[2] = -m1[2] * det;
+ imb[3] = m1[0] * det;
+ imb[4] = (m1[2] * m1[5] - m1[3] * m1[4]) * det;
+ imb[5] = (m1[1] * m1[4] - m1[0] * m1[5]) * det;
+
+ // save current graphics state
+ out->saveState(state);
+ state = state->save();
+
+ // set underlying color space (for uncolored tiling patterns)
+ if (tPat->getPaintType() == 2 && (cs = patCS->getUnder())) {
+ state->setFillColorSpace(cs->copy());
+ } else {
+ state->setFillColorSpace(new GfxDeviceGrayColorSpace());
+ }
+ state->setFillPattern(NULL);
+ out->updateFillColor(state);
+
+ // clip to current path
+ state->clip();
+ if (eoFill) {
+ out->eoClip(state);
+ } else {
+ out->clip(state);
+ }
+ state->clearPath();
+
+ // transform clip region bbox to pattern space
+ state->getClipBBox(&cxMin, &cyMin, &cxMax, &cyMax);
+ xMin = xMax = cxMin * imb[0] + cyMin * imb[2] + imb[4];
+ yMin = yMax = cxMin * imb[1] + cyMin * imb[3] + imb[5];
+ x1 = cxMin * imb[0] + cyMax * imb[2] + imb[4];
+ y1 = cxMin * imb[1] + cyMax * imb[3] + imb[5];
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+ x1 = cxMax * imb[0] + cyMin * imb[2] + imb[4];
+ y1 = cxMax * imb[1] + cyMin * imb[3] + imb[5];
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+ x1 = cxMax * imb[0] + cyMax * imb[2] + imb[4];
+ y1 = cxMax * imb[1] + cyMax * imb[3] + imb[5];
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+
+ // draw the pattern
+ //~ this should treat negative steps differently -- start at right/top
+ //~ edge instead of left/bottom (?)
+ xstep = fabs(tPat->getXStep());
+ ystep = fabs(tPat->getYStep());
+ xi0 = (int)floor(xMin / xstep);
+ xi1 = (int)ceil(xMax / xstep);
+ yi0 = (int)floor(yMin / ystep);
+ yi1 = (int)ceil(yMax / ystep);
+ for (i = 0; i < 4; ++i) {
+ m1[i] = m[i];
+ }
+ for (yi = yi0; yi < yi1; ++yi) {
+ for (xi = xi0; xi < xi1; ++xi) {
+ x = xi * xstep;
+ y = yi * ystep;
+ m1[4] = x * m[0] + y * m[2] + m[4];
+ m1[5] = x * m[1] + y * m[3] + m[5];
+ doForm1(tPat->getContentStream(), tPat->getResDict(),
+ m1, tPat->getBBox());
+ }
+ }
+
+ // restore graphics state
+ state = state->restore();
+ out->restoreState(state);
+}
+
+void Gfx::opShFill(Object args[], int /*numArgs*/) {
+ GfxShading *shading;
+ double xMin, yMin, xMax, yMax;
+
+ if (!(shading = res->lookupShading(args[0].getName()))) {
+ return;
+ }
+
+ // save current graphics state
+ out->saveState(state);
+ state = state->save();
+
+ // clip to bbox
+ if (shading->getHasBBox()) {
+ shading->getBBox(&xMin, &yMin, &xMax, &yMax);
+ state->moveTo(xMin, yMin);
+ state->lineTo(xMax, yMin);
+ state->lineTo(xMax, yMax);
+ state->lineTo(xMin, yMax);
+ state->closePath();
+ state->clip();
+ out->clip(state);
+ state->clearPath();
+ }
+
+ // set the color space
+ state->setFillColorSpace(shading->getColorSpace()->copy());
+
+ // do shading type-specific operations
+ switch (shading->getType()) {
+ case 2:
+ doAxialShFill((GfxAxialShading *)shading);
+ break;
+ case 3:
+ doRadialShFill((GfxRadialShading *)shading);
+ break;
+ }
+
+ // restore graphics state
+ state = state->restore();
+ out->restoreState(state);
+
+ delete shading;
+}
+
+void Gfx::doAxialShFill(GfxAxialShading *shading) {
+ double xMin, yMin, xMax, yMax;
+ double x0, y0, x1, y1;
+ double dx, dy, mul;
+ double tMin, tMax, t, tx, ty;
+ double s[4], sMin, sMax, tmp;
+ double ux0, uy0, ux1, uy1, vx0, vy0, vx1, vy1;
+ double t0, t1, tt;
+ double ta[axialMaxSplits + 1];
+ int next[axialMaxSplits + 1];
+ GfxColor color0, color1;
+ int nComps;
+ int i, j, k, kk;
+
+ // get the clip region bbox
+ state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
+
+ // compute min and max t values, based on the four corners of the
+ // clip region bbox
+ shading->getCoords(&x0, &y0, &x1, &y1);
+ dx = x1 - x0;
+ dy = y1 - y0;
+ mul = 1 / (dx * dx + dy * dy);
+ tMin = tMax = ((xMin - x0) * dx + (yMin - y0) * dy) * mul;
+ t = ((xMin - x0) * dx + (yMax - y0) * dy) * mul;
+ if (t < tMin) {
+ tMin = t;
+ } else if (t > tMax) {
+ tMax = t;
+ }
+ t = ((xMax - x0) * dx + (yMin - y0) * dy) * mul;
+ if (t < tMin) {
+ tMin = t;
+ } else if (t > tMax) {
+ tMax = t;
+ }
+ t = ((xMax - x0) * dx + (yMax - y0) * dy) * mul;
+ if (t < tMin) {
+ tMin = t;
+ } else if (t > tMax) {
+ tMax = t;
+ }
+ if (tMin < 0 && !shading->getExtend0()) {
+ tMin = 0;
+ }
+ if (tMax > 1 && !shading->getExtend1()) {
+ tMax = 1;
+ }
+
+ // get the function domain
+ t0 = shading->getDomain0();
+ t1 = shading->getDomain1();
+
+ // Traverse the t axis and do the shading.
+ //
+ // For each point (tx, ty) on the t axis, consider a line through
+ // that point perpendicular to the t axis:
+ //
+ // x(s) = tx + s * -dy --> s = (x - tx) / -dy
+ // y(s) = ty + s * dx --> s = (y - ty) / dx
+ //
+ // Then look at the intersection of this line with the bounding box
+ // (xMin, yMin, xMax, yMax). In the general case, there are four
+ // intersection points:
+ //
+ // s0 = (xMin - tx) / -dy
+ // s1 = (xMax - tx) / -dy
+ // s2 = (yMin - ty) / dx
+ // s3 = (yMax - ty) / dx
+ //
+ // and we want the middle two s values.
+ //
+ // In the case where dx = 0, take s0 and s1; in the case where dy =
+ // 0, take s2 and s3.
+ //
+ // Each filled polygon is bounded by two of these line segments
+ // perpdendicular to the t axis.
+ //
+ // The t axis is bisected into smaller regions until the color
+ // difference across a region is small enough, and then the region
+ // is painted with a single color.
+
+ // set up
+ nComps = shading->getColorSpace()->getNComps();
+ ta[0] = tMin;
+ ta[axialMaxSplits] = tMax;
+ next[0] = axialMaxSplits;
+
+ // compute the color at t = tMin
+ if (tMin < 0) {
+ tt = t0;
+ } else if (tMin > 1) {
+ tt = t1;
+ } else {
+ tt = t0 + (t1 - t0) * tMin;
+ }
+ shading->getColor(tt, &color0);
+
+ // compute the coordinates of the point on the t axis at t = tMin;
+ // then compute the intersection of the perpendicular line with the
+ // bounding box
+ tx = x0 + tMin * dx;
+ ty = y0 + tMin * dy;
+ if (dx == 0 && dy == 0) {
+ sMin = sMax = 0;
+ } if (dx == 0) {
+ sMin = (xMin - tx) / -dy;
+ sMax = (xMax - tx) / -dy;
+ if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
+ } else if (dy == 0) {
+ sMin = (yMin - ty) / dx;
+ sMax = (yMax - ty) / dx;
+ if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
+ } else {
+ s[0] = (yMin - ty) / dx;
+ s[1] = (yMax - ty) / dx;
+ s[2] = (xMin - tx) / -dy;
+ s[3] = (xMax - tx) / -dy;
+ for (j = 0; j < 3; ++j) {
+ kk = j;
+ for (k = j + 1; k < 4; ++k) {
+ if (s[k] < s[kk]) {
+ kk = k;
+ }
+ }
+ tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
+ }
+ sMin = s[1];
+ sMax = s[2];
+ }
+ ux0 = tx - sMin * dy;
+ uy0 = ty + sMin * dx;
+ vx0 = tx - sMax * dy;
+ vy0 = ty + sMax * dx;
+
+ i = 0;
+ while (i < axialMaxSplits) {
+
+ // bisect until color difference is small enough or we hit the
+ // bisection limit
+ j = next[i];
+ while (j > i + 1) {
+ if (ta[j] < 0) {
+ tt = t0;
+ } else if (ta[j] > 1) {
+ tt = t1;
+ } else {
+ tt = t0 + (t1 - t0) * ta[j];
+ }
+ shading->getColor(tt, &color1);
+ for (k = 0; k < nComps; ++k) {
+ if (fabs(color1.c[k] - color0.c[k]) > axialColorDelta) {
+ break;
+ }
+ }
+ if (k == nComps) {
+ break;
+ }
+ k = (i + j) / 2;
+ ta[k] = 0.5 * (ta[i] + ta[j]);
+ next[i] = k;
+ next[k] = j;
+ j = k;
+ }
+
+ // use the average of the colors of the two sides of the region
+ for (k = 0; k < nComps; ++k) {
+ color0.c[k] = 0.5 * (color0.c[k] + color1.c[k]);
+ }
+
+ // compute the coordinates of the point on the t axis; then
+ // compute the intersection of the perpendicular line with the
+ // bounding box
+ tx = x0 + ta[j] * dx;
+ ty = y0 + ta[j] * dy;
+ if (dx == 0 && dy == 0) {
+ sMin = sMax = 0;
+ } if (dx == 0) {
+ sMin = (xMin - tx) / -dy;
+ sMax = (xMax - tx) / -dy;
+ if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
+ } else if (dy == 0) {
+ sMin = (yMin - ty) / dx;
+ sMax = (yMax - ty) / dx;
+ if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
+ } else {
+ s[0] = (yMin - ty) / dx;
+ s[1] = (yMax - ty) / dx;
+ s[2] = (xMin - tx) / -dy;
+ s[3] = (xMax - tx) / -dy;
+ for (j = 0; j < 3; ++j) {
+ kk = j;
+ for (k = j + 1; k < 4; ++k) {
+ if (s[k] < s[kk]) {
+ kk = k;
+ }
+ }
+ tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
+ }
+ sMin = s[1];
+ sMax = s[2];
+ }
+ ux1 = tx - sMin * dy;
+ uy1 = ty + sMin * dx;
+ vx1 = tx - sMax * dy;
+ vy1 = ty + sMax * dx;
+
+ // set the color
+ state->setFillColor(&color0);
+ out->updateFillColor(state);
+
+ // fill the region
+ state->moveTo(ux0, uy0);
+ state->lineTo(vx0, vy0);
+ state->lineTo(vx1, vy1);
+ state->lineTo(ux1, uy1);
+ state->closePath();
+ out->fill(state);
+ state->clearPath();
+
+ // set up for next region
+ ux0 = ux1;
+ uy0 = uy1;
+ vx0 = vx1;
+ vy0 = vy1;
+ color0 = color1;
+ i = next[i];
+ }
+}
+
+void Gfx::doRadialShFill(GfxRadialShading *shading) {
+ double sMin, sMax, xMin, yMin, xMax, yMax;
+ double x0, y0, r0, x1, y1, r1, t0, t1;
+ int nComps;
+ GfxColor colorA, colorB;
+ double xa, ya, xb, yb, ra, rb;
+ double ta, tb, sa, sb;
+ int ia, ib, k, n;
+ const double *ctm;
+ double angle, t;
+
+ // get the shading info
+ shading->getCoords(&x0, &y0, &r0, &x1, &y1, &r1);
+ t0 = shading->getDomain0();
+ t1 = shading->getDomain1();
+ nComps = shading->getColorSpace()->getNComps();
+
+ // compute the (possibly extended) s range
+ sMin = 0;
+ sMax = 1;
+ if (shading->getExtend0()) {
+ if (r0 < r1) {
+ // extend the smaller end
+ sMin = -r0 / (r1 - r0);
+ } else {
+ // extend the larger end
+ //~ this computes the diagonal of the bounding box -- we should
+ //~ really compute the intersection of the moving/expanding
+ //~ circles with each of the four corners and look for the max
+ //~ radius
+ state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
+ sMin = (sqrt((xMax - xMin) * (xMax - xMin) +
+ (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
+ if (sMin > 0) {
+ sMin = 0;
+ } else if (sMin < -20) {
+ // sanity check
+ sMin = -20;
+ }
+ }
+ }
+ if (shading->getExtend1()) {
+ if (r1 < r0) {
+ // extend the smaller end
+ sMax = -r0 / (r1 - r0);
+ } else if (r1 > r0) {
+ // extend the larger end
+ state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
+ sMax = (sqrt((xMax - xMin) * (xMax - xMin) +
+ (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
+ if (sMax < 1) {
+ sMin = 1;
+ } else if (sMax > 20) {
+ // sanity check
+ sMax = 20;
+ }
+ }
+ }
+
+ // compute the number of steps into which circles must be divided to
+ // achieve a curve flatness of 0.1 pixel in device space for the
+ // largest circle (note that "device space" is 72 dpi when generating
+ // PostScript, hence the relatively small 0.1 pixel accuracy)
+ ctm = state->getCTM();
+ t = fabs(ctm[0]);
+ if (fabs(ctm[1]) > t) {
+ t = fabs(ctm[1]);
+ }
+ if (fabs(ctm[2]) > t) {
+ t = fabs(ctm[2]);
+ }
+ if (fabs(ctm[3]) > t) {
+ t = fabs(ctm[3]);
+ }
+ if (r0 > r1) {
+ t *= r0;
+ } else {
+ t *= r1;
+ }
+ if (t < 1) {
+ n = 3;
+ } else {
+ n = (int)(M_PI / acos(1 - 0.1 / t));
+ if (n < 3) {
+ n = 3;
+ } else if (n > 200) {
+ n = 200;
+ }
+ }
+
+ // Traverse the t axis and do the shading.
+ //
+ // This generates and fills a series of rings. Each ring is defined
+ // by two circles:
+ // sa, ta, xa, ya, ra, colorA
+ // sb, tb, xb, yb, rb, colorB
+ //
+ // The s/t axis is divided into radialMaxSplits parts; these parts
+ // are combined as much as possible while respecting the
+ // radialColorDelta parameter.
+
+ // setup for the start circle
+ ia = 0;
+ sa = sMin;
+ ta = t0 + sa * (t1 - t0);
+ xa = x0 + sa * (x1 - x0);
+ ya = y0 + sa * (y1 - y0);
+ ra = r0 + sa * (r1 - r0);
+ if (ta < t0) {
+ shading->getColor(t0, &colorA);
+ } else if (ta > t1) {
+ shading->getColor(t1, &colorA);
+ } else {
+ shading->getColor(ta, &colorA);
+ }
+
+ while (ia < radialMaxSplits) {
+
+ // go as far along the t axis (toward t1) as we can, such that the
+ // color difference is within the tolerance (radialColorDelta) --
+ // this uses bisection (between the current value, t, and t1),
+ // limited to radialMaxSplits points along the t axis
+ ib = radialMaxSplits;
+ sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
+ tb = t0 + sb * (t1 - t0);
+ if (tb < t0) {
+ shading->getColor(t0, &colorB);
+ } else if (tb > t1) {
+ shading->getColor(t1, &colorB);
+ } else {
+ shading->getColor(tb, &colorB);
+ }
+ while (ib - ia > 1) {
+ for (k = 0; k < nComps; ++k) {
+ if (fabs(colorB.c[k] - colorA.c[k]) > radialColorDelta) {
+ break;
+ }
+ }
+ if (k == nComps) {
+ break;
+ }
+ ib = (ia + ib) / 2;
+ sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
+ tb = t0 + sb * (t1 - t0);
+ if (tb < t0) {
+ shading->getColor(t0, &colorB);
+ } else if (tb > t1) {
+ shading->getColor(t1, &colorB);
+ } else {
+ shading->getColor(tb, &colorB);
+ }
+ }
+
+ // compute center and radius of the circle
+ xb = x0 + sb * (x1 - x0);
+ yb = y0 + sb * (y1 - y0);
+ rb = r0 + sb * (r1 - r0);
+
+ // use the average of the colors at the two circles
+ for (k = 0; k < nComps; ++k) {
+ colorA.c[k] = 0.5 * (colorA.c[k] + colorB.c[k]);
+ }
+ state->setFillColor(&colorA);
+ out->updateFillColor(state);
+
+ // construct path for first circle
+ state->moveTo(xa + ra, ya);
+ for (k = 1; k < n; ++k) {
+ angle = ((double)k / (double)n) * 2 * M_PI;
+ state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
+ }
+ state->closePath();
+
+ // construct and append path for second circle
+ state->moveTo(xb + rb, yb);
+ for (k = 1; k < n; ++k) {
+ angle = ((double)k / (double)n) * 2 * M_PI;
+ state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
+ }
+ state->closePath();
+
+ // fill the ring
+ out->eoFill(state);
+ state->clearPath();
+
+ // step to the next value of t
+ ia = ib;
+ sa = sb;
+ ta = tb;
+ xa = xb;
+ ya = yb;
+ ra = rb;
+ colorA = colorB;
+ }
+}
+
+void Gfx::doEndPath() {
+ if (state->isPath() && clip != clipNone) {
+ state->clip();
+ if (clip == clipNormal) {
+ out->clip(state);
+ } else {
+ out->eoClip(state);
+ }
+ }
+ clip = clipNone;
+ state->clearPath();
+}
+
+//------------------------------------------------------------------------
+// path clipping operators
+//------------------------------------------------------------------------
+
+void Gfx::opClip(Object /*args*/[], int /*numArgs*/) {
+ clip = clipNormal;
+}
+
+void Gfx::opEOClip(Object /*args*/[], int /*numArgs*/) {
+ clip = clipEO;
+}
+
+//------------------------------------------------------------------------
+// text object operators
+//------------------------------------------------------------------------
+
+void Gfx::opBeginText(Object /*args*/[], int /*numArgs*/) {
+ state->setTextMat(1, 0, 0, 1, 0, 0);
+ state->textMoveTo(0, 0);
+ out->updateTextMat(state);
+ out->updateTextPos(state);
+ fontChanged = gTrue;
+}
+
+void Gfx::opEndText(Object /*args*/[], int /*numArgs*/) {
+}
+
+//------------------------------------------------------------------------
+// text state operators
+//------------------------------------------------------------------------
+
+void Gfx::opSetCharSpacing(Object args[], int /*numArgs*/) {
+ state->setCharSpace(args[0].getNum());
+ out->updateCharSpace(state);
+}
+
+void Gfx::opSetFont(Object args[], int /*numArgs*/) {
+ GfxFont *font;
+
+ if (!(font = res->lookupFont(args[0].getName()))) {
+ return;
+ }
+ if (printCommands) {
+ printf(" font: tag=%s name='%s' %g\n",
+ font->getTag()->getCString(),
+ font->getName() ? font->getName()->getCString() : "???",
+ args[1].getNum());
+ fflush(stdout);
+ }
+ state->setFont(font, args[1].getNum());
+ fontChanged = gTrue;
+}
+
+void Gfx::opSetTextLeading(Object args[], int /*numArgs*/) {
+ state->setLeading(args[0].getNum());
+}
+
+void Gfx::opSetTextRender(Object args[], int /*numArgs*/) {
+ state->setRender(args[0].getInt());
+ out->updateRender(state);
+}
+
+void Gfx::opSetTextRise(Object args[], int /*numArgs*/) {
+ state->setRise(args[0].getNum());
+ out->updateRise(state);
+}
+
+void Gfx::opSetWordSpacing(Object args[], int /*numArgs*/) {
+ state->setWordSpace(args[0].getNum());
+ out->updateWordSpace(state);
+}
+
+void Gfx::opSetHorizScaling(Object args[], int /*numArgs*/) {
+ state->setHorizScaling(args[0].getNum());
+ out->updateHorizScaling(state);
+ fontChanged = gTrue;
+}
+
+//------------------------------------------------------------------------
+// text positioning operators
+//------------------------------------------------------------------------
+
+void Gfx::opTextMove(Object args[], int /*numArgs*/) {
+ double tx, ty;
+
+ tx = state->getLineX() + args[0].getNum();
+ ty = state->getLineY() + args[1].getNum();
+ state->textMoveTo(tx, ty);
+ out->updateTextPos(state);
+}
+
+void Gfx::opTextMoveSet(Object args[], int /*numArgs*/) {
+ double tx, ty;
+
+ tx = state->getLineX() + args[0].getNum();
+ ty = args[1].getNum();
+ state->setLeading(-ty);
+ ty += state->getLineY();
+ state->textMoveTo(tx, ty);
+ out->updateTextPos(state);
+}
+
+void Gfx::opSetTextMatrix(Object args[], int /*numArgs*/) {
+ state->setTextMat(args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+ state->textMoveTo(0, 0);
+ out->updateTextMat(state);
+ out->updateTextPos(state);
+ fontChanged = gTrue;
+}
+
+void Gfx::opTextNextLine(Object /*args*/[], int /*numArgs*/) {
+ double tx, ty;
+
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ out->updateTextPos(state);
+}
+
+//------------------------------------------------------------------------
+// text string operators
+//------------------------------------------------------------------------
+
+void Gfx::opShowText(Object args[], int /*numArgs*/) {
+ if (!state->getFont()) {
+ error(getPos(), "No font in show");
+ return;
+ }
+ doShowText(args[0].getString());
+}
+
+void Gfx::opMoveShowText(Object args[], int /*numArgs*/) {
+ double tx, ty;
+
+ if (!state->getFont()) {
+ error(getPos(), "No font in move/show");
+ return;
+ }
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ out->updateTextPos(state);
+ doShowText(args[0].getString());
+}
+
+void Gfx::opMoveSetShowText(Object args[], int /*numArgs*/) {
+ double tx, ty;
+
+ if (!state->getFont()) {
+ error(getPos(), "No font in move/set/show");
+ return;
+ }
+ state->setWordSpace(args[0].getNum());
+ state->setCharSpace(args[1].getNum());
+ tx = state->getLineX();
+ ty = state->getLineY() - state->getLeading();
+ state->textMoveTo(tx, ty);
+ out->updateWordSpace(state);
+ out->updateCharSpace(state);
+ out->updateTextPos(state);
+ doShowText(args[2].getString());
+}
+
+void Gfx::opShowSpaceText(Object args[], int /*numArgs*/) {
+ Array *a;
+ Object obj;
+ int wMode;
+ int i;
+
+ if (!state->getFont()) {
+ error(getPos(), "No font in show/space");
+ return;
+ }
+ wMode = state->getFont()->getWMode();
+ a = args[0].getArray();
+ for (i = 0; i < a->getLength(); ++i) {
+ a->get(i, &obj);
+ if (obj.isNum()) {
+ if (wMode) {
+ state->textShift(0, -obj.getNum() * 0.001 * state->getFontSize());
+ } else {
+ state->textShift(-obj.getNum() * 0.001 * state->getFontSize(), 0);
+ }
+ out->updateTextShift(state, obj.getNum());
+ } else if (obj.isString()) {
+ doShowText(obj.getString());
+ } else {
+ error(getPos(), "Element of show/space array must be number or string");
+ }
+ obj.free();
+ }
+}
+
+void Gfx::doShowText(GString *s) {
+ GfxFont *font;
+ int wMode;
+ double riseX, riseY;
+ CharCode code;
+ Unicode u[8];
+ double x, y, dx, dy, dx2, dy2, curX, curY, tdx, tdy;
+ double originX, originY, tOriginX, tOriginY;
+ double oldCTM[6], newCTM[6];
+ const double *mat;
+ Object charProc;
+ Dict *resDict;
+ Parser *oldParser;
+ char *p;
+ int len, n, uLen, nChars, nSpaces, i;
+
+ if (fontChanged) {
+ out->updateFont(state);
+ fontChanged = gFalse;
+ }
+ font = state->getFont();
+ wMode = font->getWMode();
+
+ if (out->useDrawChar()) {
+ out->beginString(state, s);
+ }
+
+ // handle a Type 3 char
+ if (font->getType() == fontType3 && out->interpretType3Chars()) {
+ mat = state->getCTM();
+ for (i = 0; i < 6; ++i) {
+ oldCTM[i] = mat[i];
+ }
+ mat = state->getTextMat();
+ newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2];
+ newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3];
+ newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2];
+ newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3];
+ mat = font->getFontMatrix();
+ newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2];
+ newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3];
+ newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2];
+ newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3];
+ newCTM[0] *= state->getFontSize();
+ newCTM[3] *= state->getFontSize();
+ newCTM[0] *= state->getHorizScaling();
+ newCTM[2] *= state->getHorizScaling();
+ state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
+ curX = state->getCurX();
+ curY = state->getCurY();
+ oldParser = parser;
+ p = s->getCString();
+ len = s->getLength();
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
+ &dx, &dy, &originX, &originY);
+ dx = dx * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dx += state->getWordSpace();
+ }
+ dx *= state->getHorizScaling();
+ dy *= state->getFontSize();
+ state->textTransformDelta(dx, dy, &tdx, &tdy);
+ state->transform(curX + riseX, curY + riseY, &x, &y);
+ out->saveState(state);
+ state = state->save();
+ state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y);
+ //~ out->updateCTM(???)
+ if (!out->beginType3Char(state, code, u, uLen)) {
+ ((Gfx8BitFont *)font)->getCharProc(code, &charProc);
+ if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
+ pushResources(resDict);
+ }
+ if (charProc.isStream()) {
+ display(&charProc, gFalse);
+ } else {
+ error(getPos(), "Missing or bad Type3 CharProc entry");
+ }
+ out->endType3Char(state);
+ if (resDict) {
+ popResources();
+ }
+ charProc.free();
+ }
+ state = state->restore();
+ out->restoreState(state);
+ // GfxState::restore() does *not* restore the current position,
+ // so we track it here with (curX, curY)
+ curX += tdx;
+ curY += tdy;
+ state->moveTo(curX, curY);
+ p += n;
+ len -= n;
+ }
+ parser = oldParser;
+
+ } else if (out->useDrawChar()) {
+ state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
+ p = s->getCString();
+ len = s->getLength();
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
+ &dx, &dy, &originX, &originY);
+ if (wMode) {
+ dx *= state->getFontSize();
+ dy = dy * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dy += state->getWordSpace();
+ }
+ } else {
+ dx = dx * state->getFontSize() + state->getCharSpace();
+ if (n == 1 && *p == ' ') {
+ dx += state->getWordSpace();
+ }
+ dx *= state->getHorizScaling();
+ dy *= state->getFontSize();
+ }
+ state->textTransformDelta(dx, dy, &tdx, &tdy);
+ originX *= state->getFontSize();
+ originY *= state->getFontSize();
+ state->textTransformDelta(originX, originY, &tOriginX, &tOriginY);
+ out->drawChar(state, state->getCurX() + riseX, state->getCurY() + riseY,
+ tdx, tdy, tOriginX, tOriginY, code, u, uLen);
+ state->shift(tdx, tdy);
+ p += n;
+ len -= n;
+ }
+
+ } else {
+ dx = dy = 0;
+ p = s->getCString();
+ len = s->getLength();
+ nChars = nSpaces = 0;
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
+ &dx2, &dy2, &originX, &originY);
+ dx += dx2;
+ dy += dy2;
+ if (n == 1 && *p == ' ') {
+ ++nSpaces;
+ }
+ ++nChars;
+ p += n;
+ len -= n;
+ }
+ if (wMode) {
+ dx *= state->getFontSize();
+ dy = dy * state->getFontSize()
+ + nChars * state->getCharSpace()
+ + nSpaces * state->getWordSpace();
+ } else {
+ dx = dx * state->getFontSize()
+ + nChars * state->getCharSpace()
+ + nSpaces * state->getWordSpace();
+ dx *= state->getHorizScaling();
+ dy *= state->getFontSize();
+ }
+ state->textTransformDelta(dx, dy, &tdx, &tdy);
+ out->drawString(state, s);
+ state->shift(tdx, tdy);
+ }
+
+ if (out->useDrawChar()) {
+ out->endString(state);
+ }
+
+ updateLevel += 10 * s->getLength();
+}
+
+//------------------------------------------------------------------------
+// XObject operators
+//------------------------------------------------------------------------
+
+void Gfx::opXObject(Object args[], int /*numArgs*/) {
+ Object obj1, obj2, obj3, refObj;
+#ifdef OPI_SUPPORT
+ Object opiDict;
+#endif
+
+ if (!res->lookupXObject(args[0].getName(), &obj1)) {
+ return;
+ }
+ if (!obj1.isStream()) {
+ error(getPos(), "XObject '%s' is wrong type", args[0].getName());
+ obj1.free();
+ return;
+ }
+#ifdef OPI_SUPPORT
+ obj1.streamGetDict()->lookup("OPI", &opiDict);
+ if (opiDict.isDict()) {
+ out->opiBegin(state, opiDict.getDict());
+ }
+#endif
+ obj1.streamGetDict()->lookup("Subtype", &obj2);
+ if (obj2.isName("Image")) {
+ res->lookupXObjectNF(args[0].getName(), &refObj);
+ doImage(&refObj, obj1.getStream(), gFalse);
+ refObj.free();
+ } else if (obj2.isName("Form")) {
+ doForm(&obj1);
+ } else if (obj2.isName("PS")) {
+ obj1.streamGetDict()->lookup("Level1", &obj3);
+ out->psXObject(obj1.getStream(),
+ obj3.isStream() ? obj3.getStream() : (Stream *)NULL);
+ } else if (obj2.isName()) {
+ error(getPos(), "Unknown XObject subtype '%s'", obj2.getName());
+ } else {
+ error(getPos(), "XObject subtype is missing or wrong type");
+ }
+ obj2.free();
+#ifdef OPI_SUPPORT
+ if (opiDict.isDict()) {
+ out->opiEnd(state, opiDict.getDict());
+ }
+ opiDict.free();
+#endif
+ obj1.free();
+}
+
+void Gfx::doImage(Object *ref, Stream *str, GBool inlineImg) {
+ Dict *dict;
+ int width, height;
+ int bits;
+ GBool mask;
+ GBool invert;
+ GfxColorSpace *colorSpace;
+ GfxImageColorMap *colorMap;
+ Object maskObj;
+ GBool haveMask;
+ int maskColors[2*gfxColorMaxComps];
+ Object obj1, obj2;
+ int i;
+
+ // get stream dict
+ dict = str->getDict();
+
+ // get size
+ dict->lookup("Width", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("W", &obj1);
+ }
+ if (!obj1.isInt())
+ goto err2;
+ width = obj1.getInt();
+ obj1.free();
+ dict->lookup("Height", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("H", &obj1);
+ }
+ if (!obj1.isInt())
+ goto err2;
+ height = obj1.getInt();
+ obj1.free();
+
+ // image or mask?
+ dict->lookup("ImageMask", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("IM", &obj1);
+ }
+ mask = gFalse;
+ if (obj1.isBool())
+ mask = obj1.getBool();
+ else if (!obj1.isNull())
+ goto err2;
+ obj1.free();
+
+ // bit depth
+ dict->lookup("BitsPerComponent", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("BPC", &obj1);
+ }
+ if (!obj1.isInt())
+ goto err2;
+ bits = obj1.getInt();
+ obj1.free();
+
+ // display a mask
+ if (mask) {
+
+ // check for inverted mask
+ if (bits != 1)
+ goto err1;
+ invert = gFalse;
+ dict->lookup("Decode", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("D", &obj1);
+ }
+ if (obj1.isArray()) {
+ obj1.arrayGet(0, &obj2);
+ if (obj2.isInt() && obj2.getInt() == 1)
+ invert = gTrue;
+ obj2.free();
+ } else if (!obj1.isNull()) {
+ goto err2;
+ }
+ obj1.free();
+
+ // draw it
+ out->drawImageMask(state, ref, str, width, height, invert, inlineImg);
+
+ } else {
+
+ // get color space and color map
+ dict->lookup("ColorSpace", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("CS", &obj1);
+ }
+ if (obj1.isName()) {
+ res->lookupColorSpace(obj1.getName(), &obj2);
+ if (!obj2.isNull()) {
+ obj1.free();
+ obj1 = obj2;
+ } else {
+ obj2.free();
+ }
+ }
+ colorSpace = GfxColorSpace::parse(&obj1);
+ obj1.free();
+ if (!colorSpace) {
+ goto err1;
+ }
+ dict->lookup("Decode", &obj1);
+ if (obj1.isNull()) {
+ obj1.free();
+ dict->lookup("D", &obj1);
+ }
+ colorMap = new GfxImageColorMap(bits, &obj1, colorSpace);
+ obj1.free();
+ if (!colorMap->isOk()) {
+ delete colorMap;
+ goto err1;
+ }
+
+ // get the mask
+ haveMask = gFalse;
+ dict->lookup("Mask", &maskObj);
+ if (maskObj.isArray()) {
+ for (i = 0;
+ i < maskObj.arrayGetLength() && i < 2*gfxColorMaxComps;
+ ++i) {
+ maskObj.arrayGet(i, &obj1);
+ maskColors[i] = obj1.getInt();
+ obj1.free();
+ }
+ haveMask = gTrue;
+ }
+
+ // draw it
+ out->drawImage(state, ref, str, width, height, colorMap,
+ haveMask ? maskColors : (int *)NULL, inlineImg);
+ delete colorMap;
+
+ maskObj.free();
+ }
+
+ if ((i = width * height) > 1000) {
+ i = 1000;
+ }
+ updateLevel += i;
+
+ return;
+
+ err2:
+ obj1.free();
+ err1:
+ error(getPos(), "Bad image parameters");
+}
+
+void Gfx::doForm(Object *str) {
+ Dict *dict;
+ Object matrixObj, bboxObj;
+ double m[6], bbox[6];
+ Object resObj;
+ Dict *resDict;
+ Object obj1;
+ int i;
+
+ // get stream dict
+ dict = str->streamGetDict();
+
+ // check form type
+ dict->lookup("FormType", &obj1);
+ if (!(obj1.isInt() && obj1.getInt() == 1)) {
+ error(getPos(), "Unknown form type");
+ }
+ obj1.free();
+
+ // get bounding box
+ dict->lookup("BBox", &bboxObj);
+ if (!bboxObj.isArray()) {
+ matrixObj.free();
+ bboxObj.free();
+ error(getPos(), "Bad form bounding box");
+ return;
+ }
+ for (i = 0; i < 4; ++i) {
+ bboxObj.arrayGet(i, &obj1);
+ bbox[i] = obj1.getNum();
+ obj1.free();
+ }
+ bboxObj.free();
+
+ // get matrix
+ dict->lookup("Matrix", &matrixObj);
+ if (matrixObj.isArray()) {
+ for (i = 0; i < 6; ++i) {
+ matrixObj.arrayGet(i, &obj1);
+ m[i] = obj1.getNum();
+ obj1.free();
+ }
+ } else {
+ m[0] = 1; m[1] = 0;
+ m[2] = 0; m[3] = 1;
+ m[4] = 0; m[5] = 0;
+ }
+ matrixObj.free();
+
+ // get resources
+ dict->lookup("Resources", &resObj);
+ resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
+
+ // draw it
+ doForm1(str, resDict, m, bbox);
+
+ resObj.free();
+}
+
+void Gfx::doAnnot(Object *str, double xMin, double yMin,
+ double xMax, double yMax) {
+ Dict *dict, *resDict;
+ Object matrixObj, bboxObj, resObj;
+ Object obj1;
+ double m[6], bbox[6], ictm[6];
+ const double *ctm;
+ double formX0, formY0, formX1, formY1;
+ double annotX0, annotY0, annotX1, annotY1;
+ double det, x, y, sx, sy;
+ int i;
+
+ // get stream dict
+ dict = str->streamGetDict();
+
+ // get the form bounding box
+ dict->lookup("BBox", &bboxObj);
+ if (!bboxObj.isArray()) {
+ bboxObj.free();
+ error(getPos(), "Bad form bounding box");
+ return;
+ }
+ for (i = 0; i < 4; ++i) {
+ bboxObj.arrayGet(i, &obj1);
+ bbox[i] = obj1.getNum();
+ obj1.free();
+ }
+ bboxObj.free();
+
+ // get the form matrix
+ dict->lookup("Matrix", &matrixObj);
+ if (matrixObj.isArray()) {
+ for (i = 0; i < 6; ++i) {
+ matrixObj.arrayGet(i, &obj1);
+ m[i] = obj1.getNum();
+ obj1.free();
+ }
+ } else {
+ m[0] = 1; m[1] = 0;
+ m[2] = 0; m[3] = 1;
+ m[4] = 0; m[5] = 0;
+ }
+ matrixObj.free();
+
+ // transform the form bbox from form space to user space
+ formX0 = bbox[0] * m[0] + bbox[1] * m[2] + m[4];
+ formY0 = bbox[0] * m[1] + bbox[1] * m[3] + m[5];
+ formX1 = bbox[2] * m[0] + bbox[3] * m[2] + m[4];
+ formY1 = bbox[2] * m[1] + bbox[3] * m[3] + m[5];
+
+ // transform the annotation bbox from default user space to user
+ // space: (bbox * baseMatrix) * iCTM
+ ctm = state->getCTM();
+ det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
+ ictm[0] = ctm[3] * det;
+ ictm[1] = -ctm[1] * det;
+ ictm[2] = -ctm[2] * det;
+ ictm[3] = ctm[0] * det;
+ ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
+ ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
+ x = baseMatrix[0] * xMin + baseMatrix[2] * yMin + baseMatrix[4];
+ y = baseMatrix[1] * xMin + baseMatrix[3] * yMin + baseMatrix[5];
+ annotX0 = ictm[0] * x + ictm[2] * y + ictm[4];
+ annotY0 = ictm[1] * x + ictm[3] * y + ictm[5];
+ x = baseMatrix[0] * xMax + baseMatrix[2] * yMax + baseMatrix[4];
+ y = baseMatrix[1] * xMax + baseMatrix[3] * yMax + baseMatrix[5];
+ annotX1 = ictm[0] * x + ictm[2] * y + ictm[4];
+ annotY1 = ictm[1] * x + ictm[3] * y + ictm[5];
+
+ // swap min/max coords
+ if (formX0 > formX1) {
+ x = formX0; formX0 = formX1; formX1 = x;
+ }
+ if (formY0 > formY1) {
+ y = formY0; formY0 = formY1; formY1 = y;
+ }
+ if (annotX0 > annotX1) {
+ x = annotX0; annotX0 = annotX1; annotX1 = x;
+ }
+ if (annotY0 > annotY1) {
+ y = annotY0; annotY0 = annotY1; annotY1 = y;
+ }
+
+ // scale the form to fit the annotation bbox
+ if (formX1 == formX0) {
+ // this shouldn't happen
+ sx = 1;
+ } else {
+ sx = (annotX1 - annotX0) / (formX1 - formX0);
+ }
+ if (formY1 == formY0) {
+ // this shouldn't happen
+ sy = 1;
+ } else {
+ sy = (annotY1 - annotY0) / (formY1 - formY0);
+ }
+ m[0] *= sx;
+ m[2] *= sx;
+ m[4] = (m[4] - formX0) * sx + annotX0;
+ m[1] *= sy;
+ m[3] *= sy;
+ m[5] = (m[5] - formY0) * sy + annotY0;
+
+ // get resources
+ dict->lookup("Resources", &resObj);
+ resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
+
+ // draw it
+ doForm1(str, resDict, m, bbox);
+
+ resObj.free();
+ bboxObj.free();
+}
+
+void Gfx::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox) {
+ Parser *oldParser;
+ double oldBaseMatrix[6];
+ int i;
+
+ // push new resources on stack
+ pushResources(resDict);
+
+ // save current graphics state
+ out->saveState(state);
+ state = state->save();
+
+ // save current parser
+ oldParser = parser;
+
+ // set form transformation matrix
+ state->concatCTM(matrix[0], matrix[1], matrix[2],
+ matrix[3], matrix[4], matrix[5]);
+ out->updateCTM(state, matrix[0], matrix[1], matrix[2],
+ matrix[3], matrix[4], matrix[5]);
+
+ // set new base matrix
+ for (i = 0; i < 6; ++i) {
+ oldBaseMatrix[i] = baseMatrix[i];
+ baseMatrix[i] = state->getCTM()[i];
+ }
+
+ // set form bounding box
+ state->moveTo(bbox[0], bbox[1]);
+ state->lineTo(bbox[2], bbox[1]);
+ state->lineTo(bbox[2], bbox[3]);
+ state->lineTo(bbox[0], bbox[3]);
+ state->closePath();
+ state->clip();
+ out->clip(state);
+ state->clearPath();
+
+ // draw the form
+ display(str, gFalse);
+
+ // restore base matrix
+ for (i = 0; i < 6; ++i) {
+ baseMatrix[i] = oldBaseMatrix[i];
+ }
+
+ // restore parser
+ parser = oldParser;
+
+ // restore graphics state
+ state = state->restore();
+ out->restoreState(state);
+
+ // pop resource stack
+ popResources();
+
+ return;
+}
+
+void Gfx::pushResources(Dict *resDict) {
+ res = new GfxResources(xref, resDict, res);
+}
+
+void Gfx::popResources() {
+ GfxResources *resPtr;
+
+ resPtr = res->getNext();
+ delete res;
+ res = resPtr;
+}
+
+//------------------------------------------------------------------------
+// in-line image operators
+//------------------------------------------------------------------------
+
+void Gfx::opBeginImage(Object /*args*/[], int /*numArgs*/) {
+ Stream *str;
+ int c1, c2;
+
+ // build dict/stream
+ str = buildImageStream();
+
+ // display the image
+ if (str) {
+ doImage(NULL, str, gTrue);
+
+ // skip 'EI' tag
+ c1 = str->getBaseStream()->getChar();
+ c2 = str->getBaseStream()->getChar();
+ while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) {
+ c1 = c2;
+ c2 = str->getBaseStream()->getChar();
+ }
+ delete str;
+ }
+}
+
+Stream *Gfx::buildImageStream() {
+ Object dict;
+ Object obj;
+ char *key;
+ Stream *str;
+
+ // build dictionary
+ dict.initDict(xref);
+ parser->getObj(&obj);
+ while (!obj.isCmd("ID") && !obj.isEOF()) {
+ if (!obj.isName()) {
+ error(getPos(), "Inline image dictionary key must be a name object");
+ obj.free();
+ } else {
+ key = copyString(obj.getName());
+ obj.free();
+ parser->getObj(&obj);
+ if (obj.isEOF() || obj.isError()) {
+ gfree(key);
+ break;
+ }
+ dict.dictAdd(key, &obj);
+ }
+ parser->getObj(&obj);
+ }
+ if (obj.isEOF()) {
+ error(getPos(), "End of file in inline image");
+ obj.free();
+ dict.free();
+ return NULL;
+ }
+ obj.free();
+
+ // make stream
+ str = new EmbedStream(parser->getStream(), &dict);
+ str = str->addFilters(&dict);
+
+ return str;
+}
+
+void Gfx::opImageData(Object /*args*/[], int /*numArgs*/) {
+ error(getPos(), "Internal: got 'ID' operator");
+}
+
+void Gfx::opEndImage(Object /*args*/[], int /*numArgs*/) {
+ error(getPos(), "Internal: got 'EI' operator");
+}
+
+//------------------------------------------------------------------------
+// type 3 font operators
+//------------------------------------------------------------------------
+
+void Gfx::opSetCharWidth(Object args[], int /*numArgs*/) {
+ out->type3D0(state, args[0].getNum(), args[1].getNum());
+}
+
+void Gfx::opSetCacheDevice(Object args[], int /*numArgs*/) {
+ out->type3D1(state, args[0].getNum(), args[1].getNum(),
+ args[2].getNum(), args[3].getNum(),
+ args[4].getNum(), args[5].getNum());
+}
+
+//------------------------------------------------------------------------
+// compatibility operators
+//------------------------------------------------------------------------
+
+void Gfx::opBeginIgnoreUndef(Object /*args*/[], int /*numArgs*/) {
+ ++ignoreUndef;
+}
+
+void Gfx::opEndIgnoreUndef(Object /*args*/[], int /*numArgs*/) {
+ if (ignoreUndef > 0)
+ --ignoreUndef;
+}
+
+//------------------------------------------------------------------------
+// marked content operators
+//------------------------------------------------------------------------
+
+void Gfx::opBeginMarkedContent(Object args[], int numArgs) {
+ if (printCommands) {
+ printf(" marked content: %s ", args[0].getName());
+ if (numArgs == 2)
+ args[2].print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+}
+
+void Gfx::opEndMarkedContent(Object /*args*/[], int /*numArgs*/) {
+}
+
+void Gfx::opMarkPoint(Object args[], int numArgs) {
+ if (printCommands) {
+ printf(" mark point: %s ", args[0].getName());
+ if (numArgs == 2)
+ args[2].print(stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/GfxFont.cc b/filters/kword/pdf/xpdf/xpdf/GfxFont.cc
deleted file mode 100644
index 1ed211743..000000000
--- a/filters/kword/pdf/xpdf/xpdf/GfxFont.cc
+++ /dev/null
@@ -1,1301 +0,0 @@
-//========================================================================
-//
-// GfxFont.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "Error.h"
-#include "Object.h"
-#include "Dict.h"
-#include "GlobalParams.h"
-#include "CMap.h"
-#include "CharCodeToUnicode.h"
-#include "FontEncodingTables.h"
-#include "BuiltinFontTables.h"
-#include "FontFile.h"
-#include "GfxFont.h"
-
-//------------------------------------------------------------------------
-
-struct StdFontMapEntry {
- const char *altName;
- const char *properName;
-};
-
-static StdFontMapEntry stdFontMap[] = {
- { "Arial", "Helvetica" },
- { "Arial,Bold", "Helvetica-Bold" },
- { "Arial,BoldItalic", "Helvetica-BoldOblique" },
- { "Arial,Italic", "Helvetica-Oblique" },
- { "Arial-Bold", "Helvetica-Bold" },
- { "Arial-BoldItalic", "Helvetica-BoldOblique" },
- { "Arial-BoldItalicMT", "Helvetica-BoldOblique" },
- { "Arial-BoldMT", "Helvetica-Bold" },
- { "Arial-Italic", "Helvetica-Oblique" },
- { "Arial-ItalicMT", "Helvetica-Oblique" },
- { "ArialMT", "Helvetica" },
- { "Courier,Bold", "Courier-Bold" },
- { "Courier,Italic", "Courier-Oblique" },
- { "Courier,BoldItalic", "Courier-BoldOblique" },
- { "CourierNew", "Courier" },
- { "CourierNew,Bold", "Courier-Bold" },
- { "CourierNew,BoldItalic", "Courier-BoldOblique" },
- { "CourierNew,Italic", "Courier-Oblique" },
- { "CourierNew-Bold", "Courier-Bold" },
- { "CourierNew-BoldItalic", "Courier-BoldOblique" },
- { "CourierNew-Italic", "Courier-Oblique" },
- { "CourierNewPS-BoldItalicMT", "Courier-BoldOblique" },
- { "CourierNewPS-BoldMT", "Courier-Bold" },
- { "CourierNewPS-ItalicMT", "Courier-Oblique" },
- { "CourierNewPSMT", "Courier" },
- { "Helvetica,Bold", "Helvetica-Bold" },
- { "Helvetica,BoldItalic", "Helvetica-BoldOblique" },
- { "Helvetica,Italic", "Helvetica-Oblique" },
- { "Helvetica-BoldItalic", "Helvetica-BoldOblique" },
- { "Helvetica-Italic", "Helvetica-Oblique" },
- { "TimesNewRoman", "Times-Roman" },
- { "TimesNewRoman,Bold", "Times-Bold" },
- { "TimesNewRoman,BoldItalic", "Times-BoldItalic" },
- { "TimesNewRoman,Italic", "Times-Italic" },
- { "TimesNewRoman-Bold", "Times-Bold" },
- { "TimesNewRoman-BoldItalic", "Times-BoldItalic" },
- { "TimesNewRoman-Italic", "Times-Italic" },
- { "TimesNewRomanPS", "Times-Roman" },
- { "TimesNewRomanPS-Bold", "Times-Bold" },
- { "TimesNewRomanPS-BoldItalic", "Times-BoldItalic" },
- { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
- { "TimesNewRomanPS-BoldMT", "Times-Bold" },
- { "TimesNewRomanPS-Italic", "Times-Italic" },
- { "TimesNewRomanPS-ItalicMT", "Times-Italic" },
- { "TimesNewRomanPSMT", "Times-Roman" }
-};
-
-//------------------------------------------------------------------------
-// GfxFont
-//------------------------------------------------------------------------
-
-GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
- GString *nameA;
- GfxFont *font;
- Object obj1;
-
- // get base font name
- nameA = NULL;
- fontDict->lookup("BaseFont", &obj1);
- if (obj1.isName()) {
- nameA = new GString(obj1.getName());
- }
- obj1.free();
-
- // get font type
- font = NULL;
- fontDict->lookup("Subtype", &obj1);
- if (obj1.isName("Type1") || obj1.isName("MMType1")) {
- font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1, fontDict);
- } else if (obj1.isName("Type1C")) {
- font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1C, fontDict);
- } else if (obj1.isName("Type3")) {
- font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType3, fontDict);
- } else if (obj1.isName("TrueType")) {
- font = new Gfx8BitFont(xref, tagA, idA, nameA, fontTrueType, fontDict);
- } else if (obj1.isName("Type0")) {
- font = new GfxCIDFont(xref, tagA, idA, nameA, fontDict);
- } else {
- error(-1, "Unknown font type: '%s'",
- obj1.isName() ? obj1.getName() : "???");
- font = new Gfx8BitFont(xref, tagA, idA, nameA, fontUnknownType, fontDict);
- }
- obj1.free();
-
- return font;
-}
-
-GfxFont::GfxFont(const char *tagA, Ref idA, GString *nameA) {
- ok = gFalse;
- tag = new GString(tagA);
- id = idA;
- name = nameA;
- embFontName = NULL;
- extFontFile = NULL;
-}
-
-GfxFont::~GfxFont() {
- delete tag;
- if (name) {
- delete name;
- }
- if (embFontName) {
- delete embFontName;
- }
- if (extFontFile) {
- delete extFontFile;
- }
-}
-
-void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
- Object obj1, obj2, obj3, obj4;
- double t;
- int i;
-
- // assume Times-Roman by default (for substitution purposes)
- flags = fontSerif;
-
- embFontID.num = -1;
- embFontID.gen = -1;
- missingWidth = 0;
-
- if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
-
- // get flags
- if (obj1.dictLookup("Flags", &obj2)->isInt()) {
- flags = obj2.getInt();
- }
- obj2.free();
-
- // get name
- obj1.dictLookup("FontName", &obj2);
- if (obj2.isName()) {
- embFontName = new GString(obj2.getName());
- }
- obj2.free();
-
- // look for embedded font file
- if (obj1.dictLookupNF("FontFile", &obj2)->isRef()) {
- if (type == fontType1) {
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- }
- obj2.free();
- if (embFontID.num == -1 &&
- obj1.dictLookupNF("FontFile2", &obj2)->isRef()) {
- if (type == fontTrueType || type == fontCIDType2) {
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- }
- obj2.free();
- if (embFontID.num == -1 &&
- obj1.dictLookupNF("FontFile3", &obj2)->isRef()) {
- if (obj2.fetch(xref, &obj3)->isStream()) {
- obj3.streamGetDict()->lookup("Subtype", &obj4);
- if (obj4.isName("Type1")) {
- if (type == fontType1) {
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- } else if (obj4.isName("Type1C")) {
- if (type == fontType1) {
- type = fontType1C;
- embFontID = obj2.getRef();
- } else if (type == fontType1C) {
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- } else if (obj4.isName("TrueType")) {
- if (type == fontTrueType) {
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- } else if (obj4.isName("CIDFontType0C")) {
- if (type == fontCIDType0) {
- type = fontCIDType0C;
- embFontID = obj2.getRef();
- } else {
- error(-1, "Mismatch between font type and embedded font file");
- }
- } else {
- error(-1, "Unknown embedded font type '%s'",
- obj4.isName() ? obj4.getName() : "???");
- }
- obj4.free();
- }
- obj3.free();
- }
- obj2.free();
-
- // look for MissingWidth
- obj1.dictLookup("MissingWidth", &obj2);
- if (obj2.isNum()) {
- missingWidth = obj2.getNum();
- }
- obj2.free();
-
- // get Ascent and Descent
- obj1.dictLookup("Ascent", &obj2);
- if (obj2.isNum()) {
- t = 0.001 * obj2.getNum();
- // some broken font descriptors set ascent and descent to 0
- if (t != 0) {
- ascent = t;
- }
- }
- obj2.free();
- obj1.dictLookup("Descent", &obj2);
- if (obj2.isNum()) {
- t = 0.001 * obj2.getNum();
- // some broken font descriptors set ascent and descent to 0
- if (t != 0) {
- descent = t;
- }
- }
- obj2.free();
-
- // font FontBBox
- if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
- for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
- if (obj2.arrayGet(i, &obj3)->isNum()) {
- fontBBox[i] = 0.001 * obj3.getNum();
- }
- obj3.free();
- }
- }
- obj2.free();
-
- }
- obj1.free();
-}
-
-CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits) {
- CharCodeToUnicode *ctu;
- GString *buf;
- Object obj1;
- int c;
-
- if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
- obj1.free();
- return NULL;
- }
- buf = new GString();
- obj1.streamReset();
- while ((c = obj1.streamGetChar()) != EOF) {
- buf->append(c);
- }
- obj1.streamClose();
- obj1.free();
- ctu = CharCodeToUnicode::parseCMap(buf, nBits);
- delete buf;
- return ctu;
-}
-
-void GfxFont::findExtFontFile() {
- if (name) {
- if (type == fontType1) {
- extFontFile = globalParams->findFontFile(name, ".pfa", ".pfb");
- } else if (type == fontTrueType) {
- extFontFile = globalParams->findFontFile(name, ".ttf", NULL);
- }
- }
-}
-
-char *GfxFont::readExtFontFile(int *len) {
- FILE *f;
- char *buf;
-
- if (!(f = fopen(extFontFile->getCString(), "rb"))) {
- error(-1, "External font file '%s' vanished", extFontFile->getCString());
- return NULL;
- }
- fseek(f, 0, SEEK_END);
- *len = (int)ftell(f);
- fseek(f, 0, SEEK_SET);
- buf = (char *)gmalloc(*len);
- if ((int)fread(buf, 1, *len, f) != *len) {
- error(-1, "Error reading external font file '%s'", extFontFile);
- }
- fclose(f);
- return buf;
-}
-
-char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
- char *buf;
- Object obj1, obj2;
- Stream *str;
- int c;
- int size, i;
-
- obj1.initRef(embFontID.num, embFontID.gen);
- obj1.fetch(xref, &obj2);
- if (!obj2.isStream()) {
- error(-1, "Embedded font file is not a stream");
- obj2.free();
- obj1.free();
- embFontID.num = -1;
- return NULL;
- }
- str = obj2.getStream();
-
- buf = NULL;
- i = size = 0;
- str->reset();
- while ((c = str->getChar()) != EOF) {
- if (i == size) {
- size += 4096;
- buf = (char *)grealloc(buf, size);
- }
- buf[i++] = c;
- }
- *len = i;
- str->close();
-
- obj2.free();
- obj1.free();
-
- return buf;
-}
-
-//------------------------------------------------------------------------
-// Gfx8BitFont
-//------------------------------------------------------------------------
-
-Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
- GfxFontType typeA, Dict *fontDict):
- GfxFont(tagA, idA, nameA)
-{
- BuiltinFont *builtinFont;
- char **baseEnc;
- GBool baseEncFromFontFile;
- char *buf;
- int len;
- FontFile *fontFile;
- int code, code2;
- char *charName;
- GBool missing, hex;
- Unicode toUnicode[256];
- double mul;
- int firstChar, lastChar;
- Gushort w;
- Object obj1, obj2, obj3;
- int n, i, a, b, m;
-
- type = typeA;
- ctu = NULL;
-
- // Acrobat 4.0 and earlier substituted Base14-compatible fonts
- // without providing Widths and a FontDescriptor, so we munge the
- // names into the proper Base14 names. (This table is from
- // implementation note 44 in the PDF 1.4 spec.)
- if (name) {
- a = 0;
- b = sizeof(stdFontMap) / sizeof(StdFontMapEntry);
- // invariant: stdFontMap[a].altName <= name < stdFontMap[b].altName
- while (b - a > 1) {
- m = (a + b) / 2;
- if (name->cmp(stdFontMap[m].altName) >= 0) {
- a = m;
- } else {
- b = m;
- }
- }
- if (!name->cmp(stdFontMap[a].altName)) {
- delete name;
- name = new GString(stdFontMap[a].properName);
- }
- }
-
- // is it a built-in font?
- builtinFont = NULL;
- if (name) {
- for (i = 0; i < nBuiltinFonts; ++i) {
- if (!name->cmp(builtinFonts[i].name)) {
- builtinFont = &builtinFonts[i];
- break;
- }
- }
- }
-
- // default ascent/descent values
- if (builtinFont) {
- ascent = 0.001 * builtinFont->ascent;
- descent = 0.001 * builtinFont->descent;
- fontBBox[0] = 0.001 * builtinFont->bbox[0];
- fontBBox[1] = 0.001 * builtinFont->bbox[1];
- fontBBox[2] = 0.001 * builtinFont->bbox[2];
- fontBBox[3] = 0.001 * builtinFont->bbox[3];
- } else {
- ascent = 0.95;
- descent = -0.35;
- fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
- }
-
- // get info from font descriptor
- readFontDescriptor(xref, fontDict);
-
- // look for an external font file
- findExtFontFile();
-
- // get font matrix
- fontMat[0] = fontMat[3] = 1;
- fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
- if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
- for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
- if (obj1.arrayGet(i, &obj2)->isNum()) {
- fontMat[i] = obj2.getNum();
- }
- obj2.free();
- }
- }
- obj1.free();
-
- // get Type 3 bounding box, font definition, and resources
- if (type == fontType3) {
- if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
- for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
- if (obj1.arrayGet(i, &obj2)->isNum()) {
- fontBBox[i] = obj2.getNum();
- }
- obj2.free();
- }
- }
- obj1.free();
- if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
- error(-1, "Missing or invalid CharProcs dictionary in Type 3 font");
- charProcs.free();
- }
- if (!fontDict->lookup("Resources", &resources)->isDict()) {
- resources.free();
- }
- }
-
- //----- build the font encoding -----
-
- // Encodings start with a base encoding, which can come from
- // (in order of priority):
- // 1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
- // - MacRoman / MacExpert / WinAnsi / Standard
- // 2. embedded or external font file
- // 3. default:
- // - builtin --> builtin encoding
- // - TrueType --> MacRomanEncoding
- // - others --> StandardEncoding
- // and then add a list of differences (if any) from
- // FontDict.Encoding.Differences.
-
- // check FontDict for base encoding
- hasEncoding = gFalse;
- baseEnc = NULL;
- baseEncFromFontFile = gFalse;
- fontDict->lookup("Encoding", &obj1);
- if (obj1.isDict()) {
- obj1.dictLookup("BaseEncoding", &obj2);
- if (obj2.isName("MacRomanEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)macRomanEncoding;
- } else if (obj2.isName("MacExpertEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)macExpertEncoding;
- } else if (obj2.isName("WinAnsiEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)winAnsiEncoding;
- } else if (obj2.isName("StandardEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)standardEncoding;
- }
- obj2.free();
- } else if (obj1.isName("MacRomanEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)macRomanEncoding;
- } else if (obj1.isName("MacExpertEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)macExpertEncoding;
- } else if (obj1.isName("WinAnsiEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)winAnsiEncoding;
- } else if (obj1.isName("StandardEncoding")) {
- hasEncoding = gTrue;
- baseEnc = (char **)standardEncoding;
- }
-
- // check embedded or external font file for base encoding
- // (only for Type 1 fonts - trying to get an encoding out of a
- // TrueType font is a losing proposition)
- fontFile = NULL;
- buf = NULL;
- if ((type == fontType1 || type == fontType1C) &&
- (extFontFile || embFontID.num >= 0)) {
- if (extFontFile) {
- buf = readExtFontFile(&len);
- } else {
- buf = readEmbFontFile(xref, &len);
- }
- if (buf) {
- if (type == fontType1C && !strncmp(buf, "%!", 2)) {
- // various tools (including Adobe's) occasionally embed Type 1
- // fonts but label them Type 1C
- type = fontType1;
- }
- if (type == fontType1) {
- fontFile = new Type1FontFile(buf, len);
- } else {
- fontFile = new Type1CFontFile(buf, len);
- }
- if (fontFile->getName()) {
- if (embFontName) {
- delete embFontName;
- }
- embFontName = new GString(fontFile->getName());
- }
- if (!baseEnc) {
- baseEnc = fontFile->getEncoding();
- baseEncFromFontFile = gTrue;
- }
- gfree(buf);
- }
- }
-
- // get default base encoding
- if (!baseEnc) {
- if (builtinFont) {
- baseEnc = (char **)builtinFont->defaultBaseEnc;
- hasEncoding = gTrue;
- } else if (type == fontTrueType) {
- baseEnc = (char **)winAnsiEncoding;
- } else {
- baseEnc = (char **)standardEncoding;
- }
- }
-
- // copy the base encoding
- for (i = 0; i < 256; ++i) {
- enc[i] = baseEnc[i];
- if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
- enc[i] = copyString(baseEnc[i]);
- }
- }
-
- // merge differences into encoding
- if (obj1.isDict()) {
- obj1.dictLookup("Differences", &obj2);
- if (obj2.isArray()) {
- hasEncoding = gTrue;
- code = 0;
- for (i = 0; i < obj2.arrayGetLength(); ++i) {
- obj2.arrayGet(i, &obj3);
- if (obj3.isInt()) {
- code = obj3.getInt();
- } else if (obj3.isName()) {
- if (code < 256) {
- if (encFree[code]) {
- gfree(enc[code]);
- }
- enc[code] = copyString(obj3.getName());
- encFree[code] = gTrue;
- }
- ++code;
- } else {
- error(-1, "Wrong type in font encoding resource differences (%s)",
- obj3.getTypeName());
- }
- obj3.free();
- }
- }
- obj2.free();
- }
- obj1.free();
- if (fontFile) {
- delete fontFile;
- }
-
- //----- build the mapping to Unicode -----
-
- // look for a ToUnicode CMap
- if (!(ctu = readToUnicodeCMap(fontDict, 8))) {
-
- // no ToUnicode CMap, so use the char names
-
- // pass 1: use the name-to-Unicode mapping table
- missing = hex = gFalse;
- for (code = 0; code < 256; ++code) {
- if ((charName = enc[code])) {
- if (!(toUnicode[code] = globalParams->mapNameToUnicode(charName)) &&
- strcmp(charName, ".notdef")) {
- // if it wasn't in the name-to-Unicode table, check for a
- // name that looks like 'Axx' or 'xx', where 'A' is any letter
- // and 'xx' is two hex digits
- if ((strlen(charName) == 3 &&
- isalpha(charName[0]) &&
- isxdigit(charName[1]) && isxdigit(charName[2]) &&
- ((charName[1] >= 'a' && charName[1] <= 'f') ||
- (charName[1] >= 'A' && charName[1] <= 'F') ||
- (charName[2] >= 'a' && charName[2] <= 'f') ||
- (charName[2] >= 'A' && charName[2] <= 'F'))) ||
- (strlen(charName) == 2 &&
- isxdigit(charName[0]) && isxdigit(charName[1]) &&
- ((charName[0] >= 'a' && charName[0] <= 'f') ||
- (charName[0] >= 'A' && charName[0] <= 'F') ||
- (charName[1] >= 'a' && charName[1] <= 'f') ||
- (charName[1] >= 'A' && charName[1] <= 'F')))) {
- hex = gTrue;
- }
- missing = gTrue;
- }
- } else {
- toUnicode[code] = 0;
- }
- }
-
- // pass 2: try to fill in the missing chars, looking for names of
- // the form 'Axx', 'xx', 'Ann', 'ABnn', or 'nn', where 'A' and 'B'
- // are any letters, 'xx' is two hex digits, and 'nn' is 2-4
- // decimal digits
- if (missing && globalParams->getMapNumericCharNames()) {
- for (code = 0; code < 256; ++code) {
- if ((charName = enc[code]) && !toUnicode[code] &&
- strcmp(charName, ".notdef")) {
- n = strlen(charName);
- code2 = -1;
- if (hex && n == 3 && isalpha(charName[0]) &&
- isxdigit(charName[1]) && isxdigit(charName[2])) {
- unsigned int tmp;
- sscanf(charName+1, "%x", &tmp);
- code2 = tmp;
- } else if (hex && n == 2 &&
- isxdigit(charName[0]) && isxdigit(charName[1])) {
- unsigned int tmp;
- sscanf(charName, "%x", &tmp);
- code2 = tmp;
- } else if (!hex && n >= 2 && n <= 4 &&
- isdigit(charName[0]) && isdigit(charName[1])) {
- code2 = atoi(charName);
- } else if (n >= 3 && n <= 5 &&
- isdigit(charName[1]) && isdigit(charName[2])) {
- code2 = atoi(charName+1);
- } else if (n >= 4 && n <= 6 &&
- isdigit(charName[2]) && isdigit(charName[3])) {
- code2 = atoi(charName+2);
- }
- if (code2 >= 0 && code2 <= 0xff) {
- toUnicode[code] = (Unicode)code2;
- }
- }
- }
- }
-
- ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
- }
-
- //----- get the character widths -----
-
- // initialize all widths
- for (code = 0; code < 256; ++code) {
- widths[code] = missingWidth * 0.001;
- }
-
- // use widths from font dict, if present
- fontDict->lookup("FirstChar", &obj1);
- firstChar = obj1.isInt() ? obj1.getInt() : 0;
- obj1.free();
- fontDict->lookup("LastChar", &obj1);
- lastChar = obj1.isInt() ? obj1.getInt() : 255;
- obj1.free();
- mul = (type == fontType3) ? fontMat[0] : 0.001;
- fontDict->lookup("Widths", &obj1);
- if (obj1.isArray()) {
- flags |= fontFixedWidth;
- for (code = firstChar; code <= lastChar; ++code) {
- obj1.arrayGet(code - firstChar, &obj2);
- if (obj2.isNum()) {
- widths[code] = obj2.getNum() * mul;
- if (widths[code] != widths[firstChar]) {
- flags &= ~fontFixedWidth;
- }
- }
- obj2.free();
- }
-
- // use widths from built-in font
- } else if (builtinFont) {
- // this is a kludge for broken PDF files that encode char 32
- // as .notdef
- if (builtinFont->widths->getWidth("space", &w)) {
- widths[32] = 0.001 * w;
- }
- for (code = 0; code < 256; ++code) {
- if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
- widths[code] = 0.001 * w;
- }
- }
-
- // couldn't find widths -- use defaults
- } else {
- // this is technically an error -- the Widths entry is required
- // for all but the Base-14 fonts -- but certain PDF generators
- // apparently don't include widths for Arial and TimesNewRoman
- if (isFixedWidth()) {
- i = 0;
- } else if (isSerif()) {
- i = 8;
- } else {
- i = 4;
- }
- if (isBold()) {
- i += 2;
- }
- if (isItalic()) {
- i += 1;
- }
- builtinFont = builtinFontSubst[i];
- // this is a kludge for broken PDF files that encode char 32
- // as .notdef
- if (builtinFont->widths->getWidth("space", &w)) {
- widths[32] = 0.001 * w;
- }
- for (code = 0; code < 256; ++code) {
- if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
- widths[code] = 0.001 * w;
- }
- }
- }
- obj1.free();
-
- ok = gTrue;
-}
-
-Gfx8BitFont::~Gfx8BitFont() {
- int i;
-
- for (i = 0; i < 256; ++i) {
- if (encFree[i] && enc[i]) {
- gfree(enc[i]);
- }
- }
- ctu->decRefCnt();
- if (charProcs.isDict()) {
- charProcs.free();
- }
- if (resources.isDict()) {
- resources.free();
- }
-}
-
-int Gfx8BitFont::getNextChar(char *s, int /*len*/, CharCode *code,
- Unicode *u, int uSize, int *uLen,
- double *dx, double *dy, double *ox, double *oy) {
- CharCode c;
-
- *code = c = (CharCode)(*s & 0xff);
- *uLen = ctu->mapToUnicode(c, u, uSize);
- *dx = widths[c];
- *dy = *ox = *oy = 0;
- return 1;
-}
-
-CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
- ctu->incRefCnt();
- return ctu;
-}
-
-Dict *Gfx8BitFont::getCharProcs() {
- return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
-}
-
-Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
- if (charProcs.isDict()) {
- charProcs.dictLookup(enc[code], proc);
- } else {
- proc->initNull();
- }
- return proc;
-}
-
-Dict *Gfx8BitFont::getResources() {
- return resources.isDict() ? resources.getDict() : (Dict *)NULL;
-}
-
-//------------------------------------------------------------------------
-// GfxCIDFont
-//------------------------------------------------------------------------
-
-static int cmpWidthExcep(const void *w1, const void *w2) {
- return ((GfxFontCIDWidthExcep *)w1)->first -
- ((GfxFontCIDWidthExcep *)w2)->first;
-}
-
-static int cmpWidthExcepV(const void *w1, const void *w2) {
- return ((GfxFontCIDWidthExcepV *)w1)->first -
- ((GfxFontCIDWidthExcepV *)w2)->first;
-}
-
-GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
- Dict *fontDict):
- GfxFont(tagA, idA, nameA)
-{
- Dict *desFontDict;
- GString *collection, *cMapName;
- Object desFontDictObj;
- Object obj1, obj2, obj3, obj4, obj5, obj6;
- int c1, c2;
- int excepsSize, i, j, k;
-
- ascent = 0.95;
- descent = -0.35;
- fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
- cMap = NULL;
- ctu = NULL;
- widths.defWidth = 1.0;
- widths.defHeight = -1.0;
- widths.defVY = 0.880;
- widths.exceps = NULL;
- widths.nExceps = 0;
- widths.excepsV = NULL;
- widths.nExcepsV = 0;
- cidToGID = NULL;
- cidToGIDLen = 0;
-
- // get the descendant font
- if (!fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
- error(-1, "Missing DescendantFonts entry in Type 0 font");
- obj1.free();
- goto err1;
- }
- if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
- error(-1, "Bad descendant font in Type 0 font");
- goto err3;
- }
- obj1.free();
- desFontDict = desFontDictObj.getDict();
-
- // font type
- if (!desFontDict->lookup("Subtype", &obj1)) {
- error(-1, "Missing Subtype entry in Type 0 descendant font");
- goto err3;
- }
- if (obj1.isName("CIDFontType0")) {
- type = fontCIDType0;
- } else if (obj1.isName("CIDFontType2")) {
- type = fontCIDType2;
- } else {
- error(-1, "Unknown Type 0 descendant font type '%s'",
- obj1.isName() ? obj1.getName() : "???");
- goto err3;
- }
- obj1.free();
-
- // get info from font descriptor
- readFontDescriptor(xref, desFontDict);
-
- // look for an external font file
- findExtFontFile();
-
- //----- encoding info -----
-
- // char collection
- if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
- error(-1, "Missing CIDSystemInfo dictionary in Type 0 descendant font");
- goto err3;
- }
- obj1.dictLookup("Registry", &obj2);
- obj1.dictLookup("Ordering", &obj3);
- if (!obj2.isString() || !obj3.isString()) {
- error(-1, "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
- goto err4;
- }
- collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
- obj3.free();
- obj2.free();
- obj1.free();
-
- // look for a ToUnicode CMap
- if (!(ctu = readToUnicodeCMap(fontDict, 16))) {
-
- // the "Adobe-Identity" and "Adobe-UCS" collections don't have
- // cidToUnicode files
- if (collection->cmp("Adobe-Identity") &&
- collection->cmp("Adobe-UCS")) {
-
- // look for a user-supplied .cidToUnicode file
- if (!(ctu = globalParams->getCIDToUnicode(collection))) {
- error(-1, "Unknown character collection '%s'",
- collection->getCString());
- delete collection;
- goto err2;
- }
- }
- }
-
- // encoding (i.e., CMap)
- //~ need to handle a CMap stream here
- //~ also need to deal with the UseCMap entry in the stream dict
- if (!fontDict->lookup("Encoding", &obj1)->isName()) {
- error(-1, "Missing or invalid Encoding entry in Type 0 font");
- delete collection;
- goto err3;
- }
- cMapName = new GString(obj1.getName());
- obj1.free();
- if (!(cMap = globalParams->getCMap(collection, cMapName))) {
- error(-1, "Unknown CMap '%s' for character collection '%s'",
- cMapName->getCString(), collection->getCString());
- delete collection;
- delete cMapName;
- goto err2;
- }
- delete collection;
- delete cMapName;
-
- // CIDToGIDMap (for embedded TrueType fonts)
- if (type == fontCIDType2) {
- fontDict->lookup("CIDToGIDMap", &obj1);
- if (obj1.isStream()) {
- cidToGIDLen = 0;
- i = 64;
- cidToGID = (Gushort *)gmalloc(i * sizeof(Gushort));
- obj1.streamReset();
- while ((c1 = obj1.streamGetChar()) != EOF &&
- (c2 = obj1.streamGetChar()) != EOF) {
- if (cidToGIDLen == i) {
- i *= 2;
- cidToGID = (Gushort *)grealloc(cidToGID, i * sizeof(Gushort));
- }
- cidToGID[cidToGIDLen++] = (Gushort)((c1 << 8) + c2);
- }
- } else if (!obj1.isName("Identity") && !obj1.isNull()) {
- error(-1, "Invalid CIDToGIDMap entry in CID font");
- }
- obj1.free();
- }
-
- //----- character metrics -----
-
- // default char width
- if (desFontDict->lookup("DW", &obj1)->isInt()) {
- widths.defWidth = obj1.getInt() * 0.001;
- }
- obj1.free();
-
- // char width exceptions
- if (desFontDict->lookup("W", &obj1)->isArray()) {
- excepsSize = 0;
- i = 0;
- while (i + 1 < obj1.arrayGetLength()) {
- obj1.arrayGet(i, &obj2);
- obj1.arrayGet(i + 1, &obj3);
- if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
- if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
- if (widths.nExceps == excepsSize) {
- excepsSize += 16;
- widths.exceps = (GfxFontCIDWidthExcep *)
- grealloc(widths.exceps,
- excepsSize * sizeof(GfxFontCIDWidthExcep));
- }
- widths.exceps[widths.nExceps].first = obj2.getInt();
- widths.exceps[widths.nExceps].last = obj3.getInt();
- widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
- ++widths.nExceps;
- } else {
- error(-1, "Bad widths array in Type 0 font");
- }
- obj4.free();
- i += 3;
- } else if (obj2.isInt() && obj3.isArray()) {
- if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
- excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
- widths.exceps = (GfxFontCIDWidthExcep *)
- grealloc(widths.exceps,
- excepsSize * sizeof(GfxFontCIDWidthExcep));
- }
- j = obj2.getInt();
- for (k = 0; k < obj3.arrayGetLength(); ++k) {
- if (obj3.arrayGet(k, &obj4)->isNum()) {
- widths.exceps[widths.nExceps].first = j;
- widths.exceps[widths.nExceps].last = j;
- widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
- ++j;
- ++widths.nExceps;
- } else {
- error(-1, "Bad widths array in Type 0 font");
- }
- obj4.free();
- }
- i += 2;
- } else {
- error(-1, "Bad widths array in Type 0 font");
- ++i;
- }
- obj3.free();
- obj2.free();
- }
- qsort(widths.exceps, widths.nExceps, sizeof(GfxFontCIDWidthExcep),
- &cmpWidthExcep);
- }
- obj1.free();
-
- // default metrics for vertical font
- if (desFontDict->lookup("DW2", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2) {
- if (obj1.arrayGet(0, &obj2)->isNum()) {
- widths.defVY = obj1.getNum() * 0.001;
- }
- obj2.free();
- if (obj1.arrayGet(1, &obj2)->isNum()) {
- widths.defHeight = obj1.getNum() * 0.001;
- }
- obj2.free();
- }
- obj1.free();
-
- // char metric exceptions for vertical font
- if (desFontDict->lookup("W2", &obj1)->isArray()) {
- excepsSize = 0;
- i = 0;
- while (i + 1 < obj1.arrayGetLength()) {
- obj1.arrayGet(0, &obj2);
- obj2.arrayGet(0, &obj3);
- if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
- if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
- obj1.arrayGet(i + 3, &obj5)->isNum() &&
- obj1.arrayGet(i + 4, &obj6)->isNum()) {
- if (widths.nExcepsV == excepsSize) {
- excepsSize += 16;
- widths.excepsV = (GfxFontCIDWidthExcepV *)
- grealloc(widths.excepsV,
- excepsSize * sizeof(GfxFontCIDWidthExcepV));
- }
- widths.excepsV[widths.nExcepsV].first = obj2.getInt();
- widths.excepsV[widths.nExcepsV].last = obj3.getInt();
- widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
- widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
- widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
- ++widths.nExcepsV;
- } else {
- error(-1, "Bad widths (W2) array in Type 0 font");
- }
- obj6.free();
- obj5.free();
- obj4.free();
- i += 5;
- } else if (obj2.isInt() && obj3.isArray()) {
- if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
- excepsSize =
- (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
- widths.excepsV = (GfxFontCIDWidthExcepV *)
- grealloc(widths.excepsV,
- excepsSize * sizeof(GfxFontCIDWidthExcepV));
- }
- j = obj2.getInt();
- for (k = 0; k < obj3.arrayGetLength(); ++k) {
- if (obj3.arrayGet(k, &obj4)->isNum() &&
- obj3.arrayGet(k, &obj5)->isNum() &&
- obj3.arrayGet(k, &obj6)->isNum()) {
- widths.excepsV[widths.nExceps].first = j;
- widths.excepsV[widths.nExceps].last = j;
- widths.excepsV[widths.nExceps].height = obj4.getNum() * 0.001;
- widths.excepsV[widths.nExceps].vx = obj5.getNum() * 0.001;
- widths.excepsV[widths.nExceps].vy = obj6.getNum() * 0.001;
- ++j;
- ++widths.nExcepsV;
- } else {
- error(-1, "Bad widths (W2) array in Type 0 font");
- }
- obj6.free();
- obj5.free();
- obj4.free();
- }
- i += 2;
- } else {
- error(-1, "Bad widths (W2) array in Type 0 font");
- ++i;
- }
- obj3.free();
- obj2.free();
- }
- qsort(widths.excepsV, widths.nExcepsV, sizeof(GfxFontCIDWidthExcepV),
- &cmpWidthExcepV);
- }
- obj1.free();
-
- desFontDictObj.free();
- ok = gTrue;
- return;
-
- err4:
- obj3.free();
- obj2.free();
- err3:
- obj1.free();
- err2:
- desFontDictObj.free();
- err1:;
-}
-
-GfxCIDFont::~GfxCIDFont() {
- if (cMap) {
- cMap->decRefCnt();
- }
- if (ctu) {
- ctu->decRefCnt();
- }
- gfree(widths.exceps);
- gfree(widths.excepsV);
- if (cidToGID) {
- gfree(cidToGID);
- }
-}
-
-int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
- Unicode *u, int uSize, int *uLen,
- double *dx, double *dy, double *ox, double *oy) {
- CID cid;
- double w, h, vx, vy;
- int n, a, b, m;
-
- if (!cMap) {
- *code = 0;
- *uLen = 0;
- *dx = *dy = 0;
- return 1;
- }
-
- *code = (CharCode)(cid = cMap->getCID(s, len, &n));
- if (ctu) {
- *uLen = ctu->mapToUnicode(cid, u, uSize);
- } else {
- *uLen = 0;
- }
-
- // horizontal
- if (cMap->getWMode() == 0) {
- w = widths.defWidth;
- h = vx = vy = 0;
- if (widths.nExceps > 0 && cid >= widths.exceps[0].first) {
- a = 0;
- b = widths.nExceps;
- // invariant: widths.exceps[a].first <= cid < widths.exceps[b].first
- while (b - a > 1) {
- m = (a + b) / 2;
- if (widths.exceps[m].first <= cid) {
- a = m;
- } else {
- b = m;
- }
- }
- if (cid <= widths.exceps[a].last) {
- w = widths.exceps[a].width;
- }
- }
-
- // vertical
- } else {
- w = 0;
- h = widths.defHeight;
- vx = widths.defWidth / 2;
- vy = widths.defVY;
- if (widths.nExcepsV > 0 && cid >= widths.excepsV[0].first) {
- a = 0;
- b = widths.nExcepsV;
- // invariant: widths.excepsV[a].first <= cid < widths.excepsV[b].first
- while (b - a > 1) {
- m = (a + b) / 2;
- if (widths.excepsV[m].last <= cid) {
- a = m;
- } else {
- b = m;
- }
- }
- if (cid <= widths.excepsV[a].last) {
- h = widths.excepsV[a].height;
- vx = widths.excepsV[a].vx;
- vy = widths.excepsV[a].vy;
- }
- }
- }
-
- *dx = w;
- *dy = h;
- *ox = vx;
- *oy = vy;
-
- return n;
-}
-
-int GfxCIDFont::getWMode() {
- return cMap ? cMap->getWMode() : 0;
-}
-
-CharCodeToUnicode *GfxCIDFont::getToUnicode() {
- ctu->incRefCnt();
- return ctu;
-}
-
-GString *GfxCIDFont::getCollection() {
- return cMap ? cMap->getCollection() : (GString *)NULL;
-}
-
-//------------------------------------------------------------------------
-// GfxFontDict
-//------------------------------------------------------------------------
-
-GfxFontDict::GfxFontDict(XRef *xref, Dict *fontDict) {
- int i;
- Object obj1, obj2;
- Ref r;
-
- numFonts = fontDict->getLength();
- fonts = (GfxFont **)gmalloc(numFonts * sizeof(GfxFont *));
- for (i = 0; i < numFonts; ++i) {
- fontDict->getValNF(i, &obj1);
- obj1.fetch(xref, &obj2);
- if (obj2.isDict()) {
- if (obj1.isRef()) {
- r = obj1.getRef();
- } else {
- // no indirect reference for this font, so invent a unique one
- // (legal generation numbers are five digits, so any 6-digit
- // number would be safe)
- r.num = i;
- r.gen = 999999;
- }
- fonts[i] = GfxFont::makeFont(xref, fontDict->getKey(i),
- r, obj2.getDict());
- if (fonts[i] && !fonts[i]->isOk()) {
- delete fonts[i];
- fonts[i] = NULL;
- }
- } else {
- error(-1, "font resource is not a dictionary");
- fonts[i] = NULL;
- }
- obj1.free();
- obj2.free();
- }
-}
-
-GfxFontDict::~GfxFontDict() {
- int i;
-
- for (i = 0; i < numFonts; ++i) {
- if (fonts[i]) {
- delete fonts[i];
- }
- }
- gfree(fonts);
-}
-
-GfxFont *GfxFontDict::lookup(char *tag) {
- int i;
-
- for (i = 0; i < numFonts; ++i) {
- if (fonts[i] && fonts[i]->matches(tag)) {
- return fonts[i];
- }
- }
- return NULL;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/GfxFont.cpp b/filters/kword/pdf/xpdf/xpdf/GfxFont.cpp
new file mode 100644
index 000000000..53708b492
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/GfxFont.cpp
@@ -0,0 +1,1301 @@
+//========================================================================
+//
+// GfxFont.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "Error.h"
+#include "Object.h"
+#include "Dict.h"
+#include "GlobalParams.h"
+#include "CMap.h"
+#include "CharCodeToUnicode.h"
+#include "FontEncodingTables.h"
+#include "BuiltinFontTables.h"
+#include "FontFile.h"
+#include "GfxFont.h"
+
+//------------------------------------------------------------------------
+
+struct StdFontMapEntry {
+ const char *altName;
+ const char *properName;
+};
+
+static StdFontMapEntry stdFontMap[] = {
+ { "Arial", "Helvetica" },
+ { "Arial,Bold", "Helvetica-Bold" },
+ { "Arial,BoldItalic", "Helvetica-BoldOblique" },
+ { "Arial,Italic", "Helvetica-Oblique" },
+ { "Arial-Bold", "Helvetica-Bold" },
+ { "Arial-BoldItalic", "Helvetica-BoldOblique" },
+ { "Arial-BoldItalicMT", "Helvetica-BoldOblique" },
+ { "Arial-BoldMT", "Helvetica-Bold" },
+ { "Arial-Italic", "Helvetica-Oblique" },
+ { "Arial-ItalicMT", "Helvetica-Oblique" },
+ { "ArialMT", "Helvetica" },
+ { "Courier,Bold", "Courier-Bold" },
+ { "Courier,Italic", "Courier-Oblique" },
+ { "Courier,BoldItalic", "Courier-BoldOblique" },
+ { "CourierNew", "Courier" },
+ { "CourierNew,Bold", "Courier-Bold" },
+ { "CourierNew,BoldItalic", "Courier-BoldOblique" },
+ { "CourierNew,Italic", "Courier-Oblique" },
+ { "CourierNew-Bold", "Courier-Bold" },
+ { "CourierNew-BoldItalic", "Courier-BoldOblique" },
+ { "CourierNew-Italic", "Courier-Oblique" },
+ { "CourierNewPS-BoldItalicMT", "Courier-BoldOblique" },
+ { "CourierNewPS-BoldMT", "Courier-Bold" },
+ { "CourierNewPS-ItalicMT", "Courier-Oblique" },
+ { "CourierNewPSMT", "Courier" },
+ { "Helvetica,Bold", "Helvetica-Bold" },
+ { "Helvetica,BoldItalic", "Helvetica-BoldOblique" },
+ { "Helvetica,Italic", "Helvetica-Oblique" },
+ { "Helvetica-BoldItalic", "Helvetica-BoldOblique" },
+ { "Helvetica-Italic", "Helvetica-Oblique" },
+ { "TimesNewRoman", "Times-Roman" },
+ { "TimesNewRoman,Bold", "Times-Bold" },
+ { "TimesNewRoman,BoldItalic", "Times-BoldItalic" },
+ { "TimesNewRoman,Italic", "Times-Italic" },
+ { "TimesNewRoman-Bold", "Times-Bold" },
+ { "TimesNewRoman-BoldItalic", "Times-BoldItalic" },
+ { "TimesNewRoman-Italic", "Times-Italic" },
+ { "TimesNewRomanPS", "Times-Roman" },
+ { "TimesNewRomanPS-Bold", "Times-Bold" },
+ { "TimesNewRomanPS-BoldItalic", "Times-BoldItalic" },
+ { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
+ { "TimesNewRomanPS-BoldMT", "Times-Bold" },
+ { "TimesNewRomanPS-Italic", "Times-Italic" },
+ { "TimesNewRomanPS-ItalicMT", "Times-Italic" },
+ { "TimesNewRomanPSMT", "Times-Roman" }
+};
+
+//------------------------------------------------------------------------
+// GfxFont
+//------------------------------------------------------------------------
+
+GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
+ GString *nameA;
+ GfxFont *font;
+ Object obj1;
+
+ // get base font name
+ nameA = NULL;
+ fontDict->lookup("BaseFont", &obj1);
+ if (obj1.isName()) {
+ nameA = new GString(obj1.getName());
+ }
+ obj1.free();
+
+ // get font type
+ font = NULL;
+ fontDict->lookup("Subtype", &obj1);
+ if (obj1.isName("Type1") || obj1.isName("MMType1")) {
+ font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1, fontDict);
+ } else if (obj1.isName("Type1C")) {
+ font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1C, fontDict);
+ } else if (obj1.isName("Type3")) {
+ font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType3, fontDict);
+ } else if (obj1.isName("TrueType")) {
+ font = new Gfx8BitFont(xref, tagA, idA, nameA, fontTrueType, fontDict);
+ } else if (obj1.isName("Type0")) {
+ font = new GfxCIDFont(xref, tagA, idA, nameA, fontDict);
+ } else {
+ error(-1, "Unknown font type: '%s'",
+ obj1.isName() ? obj1.getName() : "???");
+ font = new Gfx8BitFont(xref, tagA, idA, nameA, fontUnknownType, fontDict);
+ }
+ obj1.free();
+
+ return font;
+}
+
+GfxFont::GfxFont(const char *tagA, Ref idA, GString *nameA) {
+ ok = gFalse;
+ tag = new GString(tagA);
+ id = idA;
+ name = nameA;
+ embFontName = NULL;
+ extFontFile = NULL;
+}
+
+GfxFont::~GfxFont() {
+ delete tag;
+ if (name) {
+ delete name;
+ }
+ if (embFontName) {
+ delete embFontName;
+ }
+ if (extFontFile) {
+ delete extFontFile;
+ }
+}
+
+void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
+ Object obj1, obj2, obj3, obj4;
+ double t;
+ int i;
+
+ // assume Times-Roman by default (for substitution purposes)
+ flags = fontSerif;
+
+ embFontID.num = -1;
+ embFontID.gen = -1;
+ missingWidth = 0;
+
+ if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
+
+ // get flags
+ if (obj1.dictLookup("Flags", &obj2)->isInt()) {
+ flags = obj2.getInt();
+ }
+ obj2.free();
+
+ // get name
+ obj1.dictLookup("FontName", &obj2);
+ if (obj2.isName()) {
+ embFontName = new GString(obj2.getName());
+ }
+ obj2.free();
+
+ // look for embedded font file
+ if (obj1.dictLookupNF("FontFile", &obj2)->isRef()) {
+ if (type == fontType1) {
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ }
+ obj2.free();
+ if (embFontID.num == -1 &&
+ obj1.dictLookupNF("FontFile2", &obj2)->isRef()) {
+ if (type == fontTrueType || type == fontCIDType2) {
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ }
+ obj2.free();
+ if (embFontID.num == -1 &&
+ obj1.dictLookupNF("FontFile3", &obj2)->isRef()) {
+ if (obj2.fetch(xref, &obj3)->isStream()) {
+ obj3.streamGetDict()->lookup("Subtype", &obj4);
+ if (obj4.isName("Type1")) {
+ if (type == fontType1) {
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ } else if (obj4.isName("Type1C")) {
+ if (type == fontType1) {
+ type = fontType1C;
+ embFontID = obj2.getRef();
+ } else if (type == fontType1C) {
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ } else if (obj4.isName("TrueType")) {
+ if (type == fontTrueType) {
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ } else if (obj4.isName("CIDFontType0C")) {
+ if (type == fontCIDType0) {
+ type = fontCIDType0C;
+ embFontID = obj2.getRef();
+ } else {
+ error(-1, "Mismatch between font type and embedded font file");
+ }
+ } else {
+ error(-1, "Unknown embedded font type '%s'",
+ obj4.isName() ? obj4.getName() : "???");
+ }
+ obj4.free();
+ }
+ obj3.free();
+ }
+ obj2.free();
+
+ // look for MissingWidth
+ obj1.dictLookup("MissingWidth", &obj2);
+ if (obj2.isNum()) {
+ missingWidth = obj2.getNum();
+ }
+ obj2.free();
+
+ // get Ascent and Descent
+ obj1.dictLookup("Ascent", &obj2);
+ if (obj2.isNum()) {
+ t = 0.001 * obj2.getNum();
+ // some broken font descriptors set ascent and descent to 0
+ if (t != 0) {
+ ascent = t;
+ }
+ }
+ obj2.free();
+ obj1.dictLookup("Descent", &obj2);
+ if (obj2.isNum()) {
+ t = 0.001 * obj2.getNum();
+ // some broken font descriptors set ascent and descent to 0
+ if (t != 0) {
+ descent = t;
+ }
+ }
+ obj2.free();
+
+ // font FontBBox
+ if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
+ for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
+ if (obj2.arrayGet(i, &obj3)->isNum()) {
+ fontBBox[i] = 0.001 * obj3.getNum();
+ }
+ obj3.free();
+ }
+ }
+ obj2.free();
+
+ }
+ obj1.free();
+}
+
+CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits) {
+ CharCodeToUnicode *ctu;
+ GString *buf;
+ Object obj1;
+ int c;
+
+ if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
+ obj1.free();
+ return NULL;
+ }
+ buf = new GString();
+ obj1.streamReset();
+ while ((c = obj1.streamGetChar()) != EOF) {
+ buf->append(c);
+ }
+ obj1.streamClose();
+ obj1.free();
+ ctu = CharCodeToUnicode::parseCMap(buf, nBits);
+ delete buf;
+ return ctu;
+}
+
+void GfxFont::findExtFontFile() {
+ if (name) {
+ if (type == fontType1) {
+ extFontFile = globalParams->findFontFile(name, ".pfa", ".pfb");
+ } else if (type == fontTrueType) {
+ extFontFile = globalParams->findFontFile(name, ".ttf", NULL);
+ }
+ }
+}
+
+char *GfxFont::readExtFontFile(int *len) {
+ FILE *f;
+ char *buf;
+
+ if (!(f = fopen(extFontFile->getCString(), "rb"))) {
+ error(-1, "External font file '%s' vanished", extFontFile->getCString());
+ return NULL;
+ }
+ fseek(f, 0, SEEK_END);
+ *len = (int)ftell(f);
+ fseek(f, 0, SEEK_SET);
+ buf = (char *)gmalloc(*len);
+ if ((int)fread(buf, 1, *len, f) != *len) {
+ error(-1, "Error reading external font file '%s'", extFontFile);
+ }
+ fclose(f);
+ return buf;
+}
+
+char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
+ char *buf;
+ Object obj1, obj2;
+ Stream *str;
+ int c;
+ int size, i;
+
+ obj1.initRef(embFontID.num, embFontID.gen);
+ obj1.fetch(xref, &obj2);
+ if (!obj2.isStream()) {
+ error(-1, "Embedded font file is not a stream");
+ obj2.free();
+ obj1.free();
+ embFontID.num = -1;
+ return NULL;
+ }
+ str = obj2.getStream();
+
+ buf = NULL;
+ i = size = 0;
+ str->reset();
+ while ((c = str->getChar()) != EOF) {
+ if (i == size) {
+ size += 4096;
+ buf = (char *)grealloc(buf, size);
+ }
+ buf[i++] = c;
+ }
+ *len = i;
+ str->close();
+
+ obj2.free();
+ obj1.free();
+
+ return buf;
+}
+
+//------------------------------------------------------------------------
+// Gfx8BitFont
+//------------------------------------------------------------------------
+
+Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
+ GfxFontType typeA, Dict *fontDict):
+ GfxFont(tagA, idA, nameA)
+{
+ BuiltinFont *builtinFont;
+ char **baseEnc;
+ GBool baseEncFromFontFile;
+ char *buf;
+ int len;
+ FontFile *fontFile;
+ int code, code2;
+ char *charName;
+ GBool missing, hex;
+ Unicode toUnicode[256];
+ double mul;
+ int firstChar, lastChar;
+ Gushort w;
+ Object obj1, obj2, obj3;
+ int n, i, a, b, m;
+
+ type = typeA;
+ ctu = NULL;
+
+ // Acrobat 4.0 and earlier substituted Base14-compatible fonts
+ // without providing Widths and a FontDescriptor, so we munge the
+ // names into the proper Base14 names. (This table is from
+ // implementation note 44 in the PDF 1.4 spec.)
+ if (name) {
+ a = 0;
+ b = sizeof(stdFontMap) / sizeof(StdFontMapEntry);
+ // invariant: stdFontMap[a].altName <= name < stdFontMap[b].altName
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ if (name->cmp(stdFontMap[m].altName) >= 0) {
+ a = m;
+ } else {
+ b = m;
+ }
+ }
+ if (!name->cmp(stdFontMap[a].altName)) {
+ delete name;
+ name = new GString(stdFontMap[a].properName);
+ }
+ }
+
+ // is it a built-in font?
+ builtinFont = NULL;
+ if (name) {
+ for (i = 0; i < nBuiltinFonts; ++i) {
+ if (!name->cmp(builtinFonts[i].name)) {
+ builtinFont = &builtinFonts[i];
+ break;
+ }
+ }
+ }
+
+ // default ascent/descent values
+ if (builtinFont) {
+ ascent = 0.001 * builtinFont->ascent;
+ descent = 0.001 * builtinFont->descent;
+ fontBBox[0] = 0.001 * builtinFont->bbox[0];
+ fontBBox[1] = 0.001 * builtinFont->bbox[1];
+ fontBBox[2] = 0.001 * builtinFont->bbox[2];
+ fontBBox[3] = 0.001 * builtinFont->bbox[3];
+ } else {
+ ascent = 0.95;
+ descent = -0.35;
+ fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
+ }
+
+ // get info from font descriptor
+ readFontDescriptor(xref, fontDict);
+
+ // look for an external font file
+ findExtFontFile();
+
+ // get font matrix
+ fontMat[0] = fontMat[3] = 1;
+ fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
+ if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
+ for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
+ if (obj1.arrayGet(i, &obj2)->isNum()) {
+ fontMat[i] = obj2.getNum();
+ }
+ obj2.free();
+ }
+ }
+ obj1.free();
+
+ // get Type 3 bounding box, font definition, and resources
+ if (type == fontType3) {
+ if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
+ for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
+ if (obj1.arrayGet(i, &obj2)->isNum()) {
+ fontBBox[i] = obj2.getNum();
+ }
+ obj2.free();
+ }
+ }
+ obj1.free();
+ if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
+ error(-1, "Missing or invalid CharProcs dictionary in Type 3 font");
+ charProcs.free();
+ }
+ if (!fontDict->lookup("Resources", &resources)->isDict()) {
+ resources.free();
+ }
+ }
+
+ //----- build the font encoding -----
+
+ // Encodings start with a base encoding, which can come from
+ // (in order of priority):
+ // 1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
+ // - MacRoman / MacExpert / WinAnsi / Standard
+ // 2. embedded or external font file
+ // 3. default:
+ // - builtin --> builtin encoding
+ // - TrueType --> MacRomanEncoding
+ // - others --> StandardEncoding
+ // and then add a list of differences (if any) from
+ // FontDict.Encoding.Differences.
+
+ // check FontDict for base encoding
+ hasEncoding = gFalse;
+ baseEnc = NULL;
+ baseEncFromFontFile = gFalse;
+ fontDict->lookup("Encoding", &obj1);
+ if (obj1.isDict()) {
+ obj1.dictLookup("BaseEncoding", &obj2);
+ if (obj2.isName("MacRomanEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)macRomanEncoding;
+ } else if (obj2.isName("MacExpertEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)macExpertEncoding;
+ } else if (obj2.isName("WinAnsiEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)winAnsiEncoding;
+ } else if (obj2.isName("StandardEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)standardEncoding;
+ }
+ obj2.free();
+ } else if (obj1.isName("MacRomanEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)macRomanEncoding;
+ } else if (obj1.isName("MacExpertEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)macExpertEncoding;
+ } else if (obj1.isName("WinAnsiEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)winAnsiEncoding;
+ } else if (obj1.isName("StandardEncoding")) {
+ hasEncoding = gTrue;
+ baseEnc = (char **)standardEncoding;
+ }
+
+ // check embedded or external font file for base encoding
+ // (only for Type 1 fonts - trying to get an encoding out of a
+ // TrueType font is a losing proposition)
+ fontFile = NULL;
+ buf = NULL;
+ if ((type == fontType1 || type == fontType1C) &&
+ (extFontFile || embFontID.num >= 0)) {
+ if (extFontFile) {
+ buf = readExtFontFile(&len);
+ } else {
+ buf = readEmbFontFile(xref, &len);
+ }
+ if (buf) {
+ if (type == fontType1C && !strncmp(buf, "%!", 2)) {
+ // various tools (including Adobe's) occasionally embed Type 1
+ // fonts but label them Type 1C
+ type = fontType1;
+ }
+ if (type == fontType1) {
+ fontFile = new Type1FontFile(buf, len);
+ } else {
+ fontFile = new Type1CFontFile(buf, len);
+ }
+ if (fontFile->getName()) {
+ if (embFontName) {
+ delete embFontName;
+ }
+ embFontName = new GString(fontFile->getName());
+ }
+ if (!baseEnc) {
+ baseEnc = fontFile->getEncoding();
+ baseEncFromFontFile = gTrue;
+ }
+ gfree(buf);
+ }
+ }
+
+ // get default base encoding
+ if (!baseEnc) {
+ if (builtinFont) {
+ baseEnc = (char **)builtinFont->defaultBaseEnc;
+ hasEncoding = gTrue;
+ } else if (type == fontTrueType) {
+ baseEnc = (char **)winAnsiEncoding;
+ } else {
+ baseEnc = (char **)standardEncoding;
+ }
+ }
+
+ // copy the base encoding
+ for (i = 0; i < 256; ++i) {
+ enc[i] = baseEnc[i];
+ if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
+ enc[i] = copyString(baseEnc[i]);
+ }
+ }
+
+ // merge differences into encoding
+ if (obj1.isDict()) {
+ obj1.dictLookup("Differences", &obj2);
+ if (obj2.isArray()) {
+ hasEncoding = gTrue;
+ code = 0;
+ for (i = 0; i < obj2.arrayGetLength(); ++i) {
+ obj2.arrayGet(i, &obj3);
+ if (obj3.isInt()) {
+ code = obj3.getInt();
+ } else if (obj3.isName()) {
+ if (code < 256) {
+ if (encFree[code]) {
+ gfree(enc[code]);
+ }
+ enc[code] = copyString(obj3.getName());
+ encFree[code] = gTrue;
+ }
+ ++code;
+ } else {
+ error(-1, "Wrong type in font encoding resource differences (%s)",
+ obj3.getTypeName());
+ }
+ obj3.free();
+ }
+ }
+ obj2.free();
+ }
+ obj1.free();
+ if (fontFile) {
+ delete fontFile;
+ }
+
+ //----- build the mapping to Unicode -----
+
+ // look for a ToUnicode CMap
+ if (!(ctu = readToUnicodeCMap(fontDict, 8))) {
+
+ // no ToUnicode CMap, so use the char names
+
+ // pass 1: use the name-to-Unicode mapping table
+ missing = hex = gFalse;
+ for (code = 0; code < 256; ++code) {
+ if ((charName = enc[code])) {
+ if (!(toUnicode[code] = globalParams->mapNameToUnicode(charName)) &&
+ strcmp(charName, ".notdef")) {
+ // if it wasn't in the name-to-Unicode table, check for a
+ // name that looks like 'Axx' or 'xx', where 'A' is any letter
+ // and 'xx' is two hex digits
+ if ((strlen(charName) == 3 &&
+ isalpha(charName[0]) &&
+ isxdigit(charName[1]) && isxdigit(charName[2]) &&
+ ((charName[1] >= 'a' && charName[1] <= 'f') ||
+ (charName[1] >= 'A' && charName[1] <= 'F') ||
+ (charName[2] >= 'a' && charName[2] <= 'f') ||
+ (charName[2] >= 'A' && charName[2] <= 'F'))) ||
+ (strlen(charName) == 2 &&
+ isxdigit(charName[0]) && isxdigit(charName[1]) &&
+ ((charName[0] >= 'a' && charName[0] <= 'f') ||
+ (charName[0] >= 'A' && charName[0] <= 'F') ||
+ (charName[1] >= 'a' && charName[1] <= 'f') ||
+ (charName[1] >= 'A' && charName[1] <= 'F')))) {
+ hex = gTrue;
+ }
+ missing = gTrue;
+ }
+ } else {
+ toUnicode[code] = 0;
+ }
+ }
+
+ // pass 2: try to fill in the missing chars, looking for names of
+ // the form 'Axx', 'xx', 'Ann', 'ABnn', or 'nn', where 'A' and 'B'
+ // are any letters, 'xx' is two hex digits, and 'nn' is 2-4
+ // decimal digits
+ if (missing && globalParams->getMapNumericCharNames()) {
+ for (code = 0; code < 256; ++code) {
+ if ((charName = enc[code]) && !toUnicode[code] &&
+ strcmp(charName, ".notdef")) {
+ n = strlen(charName);
+ code2 = -1;
+ if (hex && n == 3 && isalpha(charName[0]) &&
+ isxdigit(charName[1]) && isxdigit(charName[2])) {
+ unsigned int tmp;
+ sscanf(charName+1, "%x", &tmp);
+ code2 = tmp;
+ } else if (hex && n == 2 &&
+ isxdigit(charName[0]) && isxdigit(charName[1])) {
+ unsigned int tmp;
+ sscanf(charName, "%x", &tmp);
+ code2 = tmp;
+ } else if (!hex && n >= 2 && n <= 4 &&
+ isdigit(charName[0]) && isdigit(charName[1])) {
+ code2 = atoi(charName);
+ } else if (n >= 3 && n <= 5 &&
+ isdigit(charName[1]) && isdigit(charName[2])) {
+ code2 = atoi(charName+1);
+ } else if (n >= 4 && n <= 6 &&
+ isdigit(charName[2]) && isdigit(charName[3])) {
+ code2 = atoi(charName+2);
+ }
+ if (code2 >= 0 && code2 <= 0xff) {
+ toUnicode[code] = (Unicode)code2;
+ }
+ }
+ }
+ }
+
+ ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
+ }
+
+ //----- get the character widths -----
+
+ // initialize all widths
+ for (code = 0; code < 256; ++code) {
+ widths[code] = missingWidth * 0.001;
+ }
+
+ // use widths from font dict, if present
+ fontDict->lookup("FirstChar", &obj1);
+ firstChar = obj1.isInt() ? obj1.getInt() : 0;
+ obj1.free();
+ fontDict->lookup("LastChar", &obj1);
+ lastChar = obj1.isInt() ? obj1.getInt() : 255;
+ obj1.free();
+ mul = (type == fontType3) ? fontMat[0] : 0.001;
+ fontDict->lookup("Widths", &obj1);
+ if (obj1.isArray()) {
+ flags |= fontFixedWidth;
+ for (code = firstChar; code <= lastChar; ++code) {
+ obj1.arrayGet(code - firstChar, &obj2);
+ if (obj2.isNum()) {
+ widths[code] = obj2.getNum() * mul;
+ if (widths[code] != widths[firstChar]) {
+ flags &= ~fontFixedWidth;
+ }
+ }
+ obj2.free();
+ }
+
+ // use widths from built-in font
+ } else if (builtinFont) {
+ // this is a kludge for broken PDF files that encode char 32
+ // as .notdef
+ if (builtinFont->widths->getWidth("space", &w)) {
+ widths[32] = 0.001 * w;
+ }
+ for (code = 0; code < 256; ++code) {
+ if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
+ widths[code] = 0.001 * w;
+ }
+ }
+
+ // couldn't find widths -- use defaults
+ } else {
+ // this is technically an error -- the Widths entry is required
+ // for all but the Base-14 fonts -- but certain PDF generators
+ // apparently don't include widths for Arial and TimesNewRoman
+ if (isFixedWidth()) {
+ i = 0;
+ } else if (isSerif()) {
+ i = 8;
+ } else {
+ i = 4;
+ }
+ if (isBold()) {
+ i += 2;
+ }
+ if (isItalic()) {
+ i += 1;
+ }
+ builtinFont = builtinFontSubst[i];
+ // this is a kludge for broken PDF files that encode char 32
+ // as .notdef
+ if (builtinFont->widths->getWidth("space", &w)) {
+ widths[32] = 0.001 * w;
+ }
+ for (code = 0; code < 256; ++code) {
+ if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
+ widths[code] = 0.001 * w;
+ }
+ }
+ }
+ obj1.free();
+
+ ok = gTrue;
+}
+
+Gfx8BitFont::~Gfx8BitFont() {
+ int i;
+
+ for (i = 0; i < 256; ++i) {
+ if (encFree[i] && enc[i]) {
+ gfree(enc[i]);
+ }
+ }
+ ctu->decRefCnt();
+ if (charProcs.isDict()) {
+ charProcs.free();
+ }
+ if (resources.isDict()) {
+ resources.free();
+ }
+}
+
+int Gfx8BitFont::getNextChar(char *s, int /*len*/, CharCode *code,
+ Unicode *u, int uSize, int *uLen,
+ double *dx, double *dy, double *ox, double *oy) {
+ CharCode c;
+
+ *code = c = (CharCode)(*s & 0xff);
+ *uLen = ctu->mapToUnicode(c, u, uSize);
+ *dx = widths[c];
+ *dy = *ox = *oy = 0;
+ return 1;
+}
+
+CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
+ ctu->incRefCnt();
+ return ctu;
+}
+
+Dict *Gfx8BitFont::getCharProcs() {
+ return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
+}
+
+Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
+ if (charProcs.isDict()) {
+ charProcs.dictLookup(enc[code], proc);
+ } else {
+ proc->initNull();
+ }
+ return proc;
+}
+
+Dict *Gfx8BitFont::getResources() {
+ return resources.isDict() ? resources.getDict() : (Dict *)NULL;
+}
+
+//------------------------------------------------------------------------
+// GfxCIDFont
+//------------------------------------------------------------------------
+
+static int cmpWidthExcep(const void *w1, const void *w2) {
+ return ((GfxFontCIDWidthExcep *)w1)->first -
+ ((GfxFontCIDWidthExcep *)w2)->first;
+}
+
+static int cmpWidthExcepV(const void *w1, const void *w2) {
+ return ((GfxFontCIDWidthExcepV *)w1)->first -
+ ((GfxFontCIDWidthExcepV *)w2)->first;
+}
+
+GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
+ Dict *fontDict):
+ GfxFont(tagA, idA, nameA)
+{
+ Dict *desFontDict;
+ GString *collection, *cMapName;
+ Object desFontDictObj;
+ Object obj1, obj2, obj3, obj4, obj5, obj6;
+ int c1, c2;
+ int excepsSize, i, j, k;
+
+ ascent = 0.95;
+ descent = -0.35;
+ fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
+ cMap = NULL;
+ ctu = NULL;
+ widths.defWidth = 1.0;
+ widths.defHeight = -1.0;
+ widths.defVY = 0.880;
+ widths.exceps = NULL;
+ widths.nExceps = 0;
+ widths.excepsV = NULL;
+ widths.nExcepsV = 0;
+ cidToGID = NULL;
+ cidToGIDLen = 0;
+
+ // get the descendant font
+ if (!fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
+ error(-1, "Missing DescendantFonts entry in Type 0 font");
+ obj1.free();
+ goto err1;
+ }
+ if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
+ error(-1, "Bad descendant font in Type 0 font");
+ goto err3;
+ }
+ obj1.free();
+ desFontDict = desFontDictObj.getDict();
+
+ // font type
+ if (!desFontDict->lookup("Subtype", &obj1)) {
+ error(-1, "Missing Subtype entry in Type 0 descendant font");
+ goto err3;
+ }
+ if (obj1.isName("CIDFontType0")) {
+ type = fontCIDType0;
+ } else if (obj1.isName("CIDFontType2")) {
+ type = fontCIDType2;
+ } else {
+ error(-1, "Unknown Type 0 descendant font type '%s'",
+ obj1.isName() ? obj1.getName() : "???");
+ goto err3;
+ }
+ obj1.free();
+
+ // get info from font descriptor
+ readFontDescriptor(xref, desFontDict);
+
+ // look for an external font file
+ findExtFontFile();
+
+ //----- encoding info -----
+
+ // char collection
+ if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
+ error(-1, "Missing CIDSystemInfo dictionary in Type 0 descendant font");
+ goto err3;
+ }
+ obj1.dictLookup("Registry", &obj2);
+ obj1.dictLookup("Ordering", &obj3);
+ if (!obj2.isString() || !obj3.isString()) {
+ error(-1, "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
+ goto err4;
+ }
+ collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
+ obj3.free();
+ obj2.free();
+ obj1.free();
+
+ // look for a ToUnicode CMap
+ if (!(ctu = readToUnicodeCMap(fontDict, 16))) {
+
+ // the "Adobe-Identity" and "Adobe-UCS" collections don't have
+ // cidToUnicode files
+ if (collection->cmp("Adobe-Identity") &&
+ collection->cmp("Adobe-UCS")) {
+
+ // look for a user-supplied .cidToUnicode file
+ if (!(ctu = globalParams->getCIDToUnicode(collection))) {
+ error(-1, "Unknown character collection '%s'",
+ collection->getCString());
+ delete collection;
+ goto err2;
+ }
+ }
+ }
+
+ // encoding (i.e., CMap)
+ //~ need to handle a CMap stream here
+ //~ also need to deal with the UseCMap entry in the stream dict
+ if (!fontDict->lookup("Encoding", &obj1)->isName()) {
+ error(-1, "Missing or invalid Encoding entry in Type 0 font");
+ delete collection;
+ goto err3;
+ }
+ cMapName = new GString(obj1.getName());
+ obj1.free();
+ if (!(cMap = globalParams->getCMap(collection, cMapName))) {
+ error(-1, "Unknown CMap '%s' for character collection '%s'",
+ cMapName->getCString(), collection->getCString());
+ delete collection;
+ delete cMapName;
+ goto err2;
+ }
+ delete collection;
+ delete cMapName;
+
+ // CIDToGIDMap (for embedded TrueType fonts)
+ if (type == fontCIDType2) {
+ fontDict->lookup("CIDToGIDMap", &obj1);
+ if (obj1.isStream()) {
+ cidToGIDLen = 0;
+ i = 64;
+ cidToGID = (Gushort *)gmalloc(i * sizeof(Gushort));
+ obj1.streamReset();
+ while ((c1 = obj1.streamGetChar()) != EOF &&
+ (c2 = obj1.streamGetChar()) != EOF) {
+ if (cidToGIDLen == i) {
+ i *= 2;
+ cidToGID = (Gushort *)grealloc(cidToGID, i * sizeof(Gushort));
+ }
+ cidToGID[cidToGIDLen++] = (Gushort)((c1 << 8) + c2);
+ }
+ } else if (!obj1.isName("Identity") && !obj1.isNull()) {
+ error(-1, "Invalid CIDToGIDMap entry in CID font");
+ }
+ obj1.free();
+ }
+
+ //----- character metrics -----
+
+ // default char width
+ if (desFontDict->lookup("DW", &obj1)->isInt()) {
+ widths.defWidth = obj1.getInt() * 0.001;
+ }
+ obj1.free();
+
+ // char width exceptions
+ if (desFontDict->lookup("W", &obj1)->isArray()) {
+ excepsSize = 0;
+ i = 0;
+ while (i + 1 < obj1.arrayGetLength()) {
+ obj1.arrayGet(i, &obj2);
+ obj1.arrayGet(i + 1, &obj3);
+ if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
+ if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
+ if (widths.nExceps == excepsSize) {
+ excepsSize += 16;
+ widths.exceps = (GfxFontCIDWidthExcep *)
+ grealloc(widths.exceps,
+ excepsSize * sizeof(GfxFontCIDWidthExcep));
+ }
+ widths.exceps[widths.nExceps].first = obj2.getInt();
+ widths.exceps[widths.nExceps].last = obj3.getInt();
+ widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
+ ++widths.nExceps;
+ } else {
+ error(-1, "Bad widths array in Type 0 font");
+ }
+ obj4.free();
+ i += 3;
+ } else if (obj2.isInt() && obj3.isArray()) {
+ if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
+ excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
+ widths.exceps = (GfxFontCIDWidthExcep *)
+ grealloc(widths.exceps,
+ excepsSize * sizeof(GfxFontCIDWidthExcep));
+ }
+ j = obj2.getInt();
+ for (k = 0; k < obj3.arrayGetLength(); ++k) {
+ if (obj3.arrayGet(k, &obj4)->isNum()) {
+ widths.exceps[widths.nExceps].first = j;
+ widths.exceps[widths.nExceps].last = j;
+ widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
+ ++j;
+ ++widths.nExceps;
+ } else {
+ error(-1, "Bad widths array in Type 0 font");
+ }
+ obj4.free();
+ }
+ i += 2;
+ } else {
+ error(-1, "Bad widths array in Type 0 font");
+ ++i;
+ }
+ obj3.free();
+ obj2.free();
+ }
+ qsort(widths.exceps, widths.nExceps, sizeof(GfxFontCIDWidthExcep),
+ &cmpWidthExcep);
+ }
+ obj1.free();
+
+ // default metrics for vertical font
+ if (desFontDict->lookup("DW2", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2) {
+ if (obj1.arrayGet(0, &obj2)->isNum()) {
+ widths.defVY = obj1.getNum() * 0.001;
+ }
+ obj2.free();
+ if (obj1.arrayGet(1, &obj2)->isNum()) {
+ widths.defHeight = obj1.getNum() * 0.001;
+ }
+ obj2.free();
+ }
+ obj1.free();
+
+ // char metric exceptions for vertical font
+ if (desFontDict->lookup("W2", &obj1)->isArray()) {
+ excepsSize = 0;
+ i = 0;
+ while (i + 1 < obj1.arrayGetLength()) {
+ obj1.arrayGet(0, &obj2);
+ obj2.arrayGet(0, &obj3);
+ if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
+ if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
+ obj1.arrayGet(i + 3, &obj5)->isNum() &&
+ obj1.arrayGet(i + 4, &obj6)->isNum()) {
+ if (widths.nExcepsV == excepsSize) {
+ excepsSize += 16;
+ widths.excepsV = (GfxFontCIDWidthExcepV *)
+ grealloc(widths.excepsV,
+ excepsSize * sizeof(GfxFontCIDWidthExcepV));
+ }
+ widths.excepsV[widths.nExcepsV].first = obj2.getInt();
+ widths.excepsV[widths.nExcepsV].last = obj3.getInt();
+ widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
+ widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
+ widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
+ ++widths.nExcepsV;
+ } else {
+ error(-1, "Bad widths (W2) array in Type 0 font");
+ }
+ obj6.free();
+ obj5.free();
+ obj4.free();
+ i += 5;
+ } else if (obj2.isInt() && obj3.isArray()) {
+ if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
+ excepsSize =
+ (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
+ widths.excepsV = (GfxFontCIDWidthExcepV *)
+ grealloc(widths.excepsV,
+ excepsSize * sizeof(GfxFontCIDWidthExcepV));
+ }
+ j = obj2.getInt();
+ for (k = 0; k < obj3.arrayGetLength(); ++k) {
+ if (obj3.arrayGet(k, &obj4)->isNum() &&
+ obj3.arrayGet(k, &obj5)->isNum() &&
+ obj3.arrayGet(k, &obj6)->isNum()) {
+ widths.excepsV[widths.nExceps].first = j;
+ widths.excepsV[widths.nExceps].last = j;
+ widths.excepsV[widths.nExceps].height = obj4.getNum() * 0.001;
+ widths.excepsV[widths.nExceps].vx = obj5.getNum() * 0.001;
+ widths.excepsV[widths.nExceps].vy = obj6.getNum() * 0.001;
+ ++j;
+ ++widths.nExcepsV;
+ } else {
+ error(-1, "Bad widths (W2) array in Type 0 font");
+ }
+ obj6.free();
+ obj5.free();
+ obj4.free();
+ }
+ i += 2;
+ } else {
+ error(-1, "Bad widths (W2) array in Type 0 font");
+ ++i;
+ }
+ obj3.free();
+ obj2.free();
+ }
+ qsort(widths.excepsV, widths.nExcepsV, sizeof(GfxFontCIDWidthExcepV),
+ &cmpWidthExcepV);
+ }
+ obj1.free();
+
+ desFontDictObj.free();
+ ok = gTrue;
+ return;
+
+ err4:
+ obj3.free();
+ obj2.free();
+ err3:
+ obj1.free();
+ err2:
+ desFontDictObj.free();
+ err1:;
+}
+
+GfxCIDFont::~GfxCIDFont() {
+ if (cMap) {
+ cMap->decRefCnt();
+ }
+ if (ctu) {
+ ctu->decRefCnt();
+ }
+ gfree(widths.exceps);
+ gfree(widths.excepsV);
+ if (cidToGID) {
+ gfree(cidToGID);
+ }
+}
+
+int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
+ Unicode *u, int uSize, int *uLen,
+ double *dx, double *dy, double *ox, double *oy) {
+ CID cid;
+ double w, h, vx, vy;
+ int n, a, b, m;
+
+ if (!cMap) {
+ *code = 0;
+ *uLen = 0;
+ *dx = *dy = 0;
+ return 1;
+ }
+
+ *code = (CharCode)(cid = cMap->getCID(s, len, &n));
+ if (ctu) {
+ *uLen = ctu->mapToUnicode(cid, u, uSize);
+ } else {
+ *uLen = 0;
+ }
+
+ // horizontal
+ if (cMap->getWMode() == 0) {
+ w = widths.defWidth;
+ h = vx = vy = 0;
+ if (widths.nExceps > 0 && cid >= widths.exceps[0].first) {
+ a = 0;
+ b = widths.nExceps;
+ // invariant: widths.exceps[a].first <= cid < widths.exceps[b].first
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ if (widths.exceps[m].first <= cid) {
+ a = m;
+ } else {
+ b = m;
+ }
+ }
+ if (cid <= widths.exceps[a].last) {
+ w = widths.exceps[a].width;
+ }
+ }
+
+ // vertical
+ } else {
+ w = 0;
+ h = widths.defHeight;
+ vx = widths.defWidth / 2;
+ vy = widths.defVY;
+ if (widths.nExcepsV > 0 && cid >= widths.excepsV[0].first) {
+ a = 0;
+ b = widths.nExcepsV;
+ // invariant: widths.excepsV[a].first <= cid < widths.excepsV[b].first
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ if (widths.excepsV[m].last <= cid) {
+ a = m;
+ } else {
+ b = m;
+ }
+ }
+ if (cid <= widths.excepsV[a].last) {
+ h = widths.excepsV[a].height;
+ vx = widths.excepsV[a].vx;
+ vy = widths.excepsV[a].vy;
+ }
+ }
+ }
+
+ *dx = w;
+ *dy = h;
+ *ox = vx;
+ *oy = vy;
+
+ return n;
+}
+
+int GfxCIDFont::getWMode() {
+ return cMap ? cMap->getWMode() : 0;
+}
+
+CharCodeToUnicode *GfxCIDFont::getToUnicode() {
+ ctu->incRefCnt();
+ return ctu;
+}
+
+GString *GfxCIDFont::getCollection() {
+ return cMap ? cMap->getCollection() : (GString *)NULL;
+}
+
+//------------------------------------------------------------------------
+// GfxFontDict
+//------------------------------------------------------------------------
+
+GfxFontDict::GfxFontDict(XRef *xref, Dict *fontDict) {
+ int i;
+ Object obj1, obj2;
+ Ref r;
+
+ numFonts = fontDict->getLength();
+ fonts = (GfxFont **)gmalloc(numFonts * sizeof(GfxFont *));
+ for (i = 0; i < numFonts; ++i) {
+ fontDict->getValNF(i, &obj1);
+ obj1.fetch(xref, &obj2);
+ if (obj2.isDict()) {
+ if (obj1.isRef()) {
+ r = obj1.getRef();
+ } else {
+ // no indirect reference for this font, so invent a unique one
+ // (legal generation numbers are five digits, so any 6-digit
+ // number would be safe)
+ r.num = i;
+ r.gen = 999999;
+ }
+ fonts[i] = GfxFont::makeFont(xref, fontDict->getKey(i),
+ r, obj2.getDict());
+ if (fonts[i] && !fonts[i]->isOk()) {
+ delete fonts[i];
+ fonts[i] = NULL;
+ }
+ } else {
+ error(-1, "font resource is not a dictionary");
+ fonts[i] = NULL;
+ }
+ obj1.free();
+ obj2.free();
+ }
+}
+
+GfxFontDict::~GfxFontDict() {
+ int i;
+
+ for (i = 0; i < numFonts; ++i) {
+ if (fonts[i]) {
+ delete fonts[i];
+ }
+ }
+ gfree(fonts);
+}
+
+GfxFont *GfxFontDict::lookup(char *tag) {
+ int i;
+
+ for (i = 0; i < numFonts; ++i) {
+ if (fonts[i] && fonts[i]->matches(tag)) {
+ return fonts[i];
+ }
+ }
+ return NULL;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/GfxState.cc b/filters/kword/pdf/xpdf/xpdf/GfxState.cc
deleted file mode 100644
index 5101f773d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/GfxState.cc
+++ /dev/null
@@ -1,2338 +0,0 @@
-//========================================================================
-//
-// GfxState.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include <math.h>
-#include <string.h> // for memcpy()
-#include "gmem.h"
-#include "Error.h"
-#include "Object.h"
-#include "Array.h"
-#include "Page.h"
-#include "GfxState.h"
-
-//------------------------------------------------------------------------
-
-static inline double clip01(double x) {
- return (x < 0) ? 0 : ((x > 1) ? 1 : x);
-}
-
-//------------------------------------------------------------------------
-// GfxColorSpace
-//------------------------------------------------------------------------
-
-GfxColorSpace::GfxColorSpace() {
-}
-
-GfxColorSpace::~GfxColorSpace() {
-}
-
-GfxColorSpace *GfxColorSpace::parse(Object *csObj) {
- GfxColorSpace *cs;
- Object obj1;
-
- cs = NULL;
- if (csObj->isName()) {
- if (csObj->isName("DeviceGray") || csObj->isName("G")) {
- cs = new GfxDeviceGrayColorSpace();
- } else if (csObj->isName("DeviceRGB") || csObj->isName("RGB")) {
- cs = new GfxDeviceRGBColorSpace();
- } else if (csObj->isName("DeviceCMYK") || csObj->isName("CMYK")) {
- cs = new GfxDeviceCMYKColorSpace();
- } else if (csObj->isName("Pattern")) {
- cs = new GfxPatternColorSpace(NULL);
- } else {
- error(-1, "Bad color space '%s'", csObj->getName());
- }
- } else if (csObj->isArray()) {
- csObj->arrayGet(0, &obj1);
- if (obj1.isName("DeviceGray") || obj1.isName("G")) {
- cs = new GfxDeviceGrayColorSpace();
- } else if (obj1.isName("DeviceRGB") || obj1.isName("RGB")) {
- cs = new GfxDeviceRGBColorSpace();
- } else if (obj1.isName("DeviceCMYK") || obj1.isName("CMYK")) {
- cs = new GfxDeviceCMYKColorSpace();
- } else if (obj1.isName("CalGray")) {
- cs = GfxCalGrayColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("CalRGB")) {
- cs = GfxCalRGBColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("Lab")) {
- cs = GfxLabColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("ICCBased")) {
- cs = GfxICCBasedColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("Indexed") || obj1.isName("I")) {
- cs = GfxIndexedColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("Separation")) {
- cs = GfxSeparationColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("DeviceN")) {
- cs = GfxDeviceNColorSpace::parse(csObj->getArray());
- } else if (obj1.isName("Pattern")) {
- cs = GfxPatternColorSpace::parse(csObj->getArray());
- } else {
- error(-1, "Bad color space '%s'", csObj->getName());
- }
- obj1.free();
- } else {
- error(-1, "Bad color space - expected name or array");
- }
- return cs;
-}
-
-void GfxColorSpace::getDefaultRanges(double *decodeLow, double *decodeRange,
- int /*maxImgPixel*/) const {
- int i;
-
- for (i = 0; i < getNComps(); ++i) {
- decodeLow[i] = 0;
- decodeRange[i] = 1;
- }
-}
-
-//------------------------------------------------------------------------
-// GfxDeviceGrayColorSpace
-//------------------------------------------------------------------------
-
-GfxDeviceGrayColorSpace::GfxDeviceGrayColorSpace() {
-}
-
-GfxDeviceGrayColorSpace::~GfxDeviceGrayColorSpace() {
-}
-
-GfxColorSpace *GfxDeviceGrayColorSpace::copy() const {
- return new GfxDeviceGrayColorSpace();
-}
-
-void GfxDeviceGrayColorSpace::getGray(const GfxColor *color, double *gray) const {
- *gray = clip01(color->c[0]);
-}
-
-void GfxDeviceGrayColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- rgb->r = rgb->g = rgb->b = clip01(color->c[0]);
-}
-
-void GfxDeviceGrayColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- cmyk->c = cmyk->m = cmyk->y = 0;
- cmyk->k = clip01(1 - color->c[0]);
-}
-
-//------------------------------------------------------------------------
-// GfxCalGrayColorSpace
-//------------------------------------------------------------------------
-
-GfxCalGrayColorSpace::GfxCalGrayColorSpace() {
- whiteX = whiteY = whiteZ = 1;
- blackX = blackY = blackZ = 0;
- gamma = 1;
-}
-
-GfxCalGrayColorSpace::~GfxCalGrayColorSpace() {
-}
-
-GfxColorSpace *GfxCalGrayColorSpace::copy() const {
- GfxCalGrayColorSpace *cs;
-
- cs = new GfxCalGrayColorSpace();
- cs->whiteX = whiteX;
- cs->whiteY = whiteY;
- cs->whiteZ = whiteZ;
- cs->blackX = blackX;
- cs->blackY = blackY;
- cs->blackZ = blackZ;
- cs->gamma = gamma;
- return cs;
-}
-
-GfxColorSpace *GfxCalGrayColorSpace::parse(Array *arr) {
- GfxCalGrayColorSpace *cs;
- Object obj1, obj2, obj3;
-
- arr->get(1, &obj1);
- if (!obj1.isDict()) {
- error(-1, "Bad CalGray color space");
- obj1.free();
- return NULL;
- }
- cs = new GfxCalGrayColorSpace();
- if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->whiteX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->whiteY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->whiteZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->blackX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->blackY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->blackZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("Gamma", &obj2)->isNum()) {
- cs->gamma = obj2.getNum();
- }
- obj2.free();
- obj1.free();
- return cs;
-}
-
-void GfxCalGrayColorSpace::getGray(const GfxColor *color, double *gray) const {
- *gray = clip01(color->c[0]);
-}
-
-void GfxCalGrayColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- rgb->r = rgb->g = rgb->b = clip01(color->c[0]);
-}
-
-void GfxCalGrayColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- cmyk->c = cmyk->m = cmyk->y = 0;
- cmyk->k = clip01(1 - color->c[0]);
-}
-
-//------------------------------------------------------------------------
-// GfxDeviceRGBColorSpace
-//------------------------------------------------------------------------
-
-GfxDeviceRGBColorSpace::GfxDeviceRGBColorSpace() {
-}
-
-GfxDeviceRGBColorSpace::~GfxDeviceRGBColorSpace() {
-}
-
-GfxColorSpace *GfxDeviceRGBColorSpace::copy() const {
- return new GfxDeviceRGBColorSpace();
-}
-
-void GfxDeviceRGBColorSpace::getGray(const GfxColor *color, double *gray) const {
- *gray = clip01(0.299 * color->c[0] +
- 0.587 * color->c[1] +
- 0.114 * color->c[2]);
-}
-
-void GfxDeviceRGBColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- rgb->r = clip01(color->c[0]);
- rgb->g = clip01(color->c[1]);
- rgb->b = clip01(color->c[2]);
-}
-
-void GfxDeviceRGBColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- double c, m, y, k;
-
- c = clip01(1 - color->c[0]);
- m = clip01(1 - color->c[1]);
- y = clip01(1 - color->c[2]);
- k = c;
- if (m < k) {
- k = m;
- }
- if (y < k) {
- k = y;
- }
- cmyk->c = c - k;
- cmyk->m = m - k;
- cmyk->y = y - k;
- cmyk->k = k;
-}
-
-//------------------------------------------------------------------------
-// GfxCalRGBColorSpace
-//------------------------------------------------------------------------
-
-GfxCalRGBColorSpace::GfxCalRGBColorSpace() {
- whiteX = whiteY = whiteZ = 1;
- blackX = blackY = blackZ = 0;
- gammaR = gammaG = gammaB = 1;
- mat[0] = 1; mat[1] = 0; mat[2] = 0;
- mat[3] = 0; mat[4] = 1; mat[5] = 0;
- mat[6] = 0; mat[7] = 0; mat[8] = 1;
-}
-
-GfxCalRGBColorSpace::~GfxCalRGBColorSpace() {
-}
-
-GfxColorSpace *GfxCalRGBColorSpace::copy() const {
- GfxCalRGBColorSpace *cs;
- int i;
-
- cs = new GfxCalRGBColorSpace();
- cs->whiteX = whiteX;
- cs->whiteY = whiteY;
- cs->whiteZ = whiteZ;
- cs->blackX = blackX;
- cs->blackY = blackY;
- cs->blackZ = blackZ;
- cs->gammaR = gammaR;
- cs->gammaG = gammaG;
- cs->gammaB = gammaB;
- for (i = 0; i < 9; ++i) {
- cs->mat[i] = mat[i];
- }
- return cs;
-}
-
-GfxColorSpace *GfxCalRGBColorSpace::parse(Array *arr) {
- GfxCalRGBColorSpace *cs;
- Object obj1, obj2, obj3;
- int i;
-
- arr->get(1, &obj1);
- if (!obj1.isDict()) {
- error(-1, "Bad CalRGB color space");
- obj1.free();
- return NULL;
- }
- cs = new GfxCalRGBColorSpace();
- if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->whiteX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->whiteY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->whiteZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->blackX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->blackY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->blackZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("Gamma", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->gammaR = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->gammaG = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->gammaB = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("Matrix", &obj2)->isArray() &&
- obj2.arrayGetLength() == 9) {
- for (i = 0; i < 9; ++i) {
- obj2.arrayGet(i, &obj3);
- cs->mat[i] = obj3.getNum();
- obj3.free();
- }
- }
- obj2.free();
- obj1.free();
- return cs;
-}
-
-void GfxCalRGBColorSpace::getGray(const GfxColor *color, double *gray) const {
- *gray = clip01(0.299 * color->c[0] +
- 0.587 * color->c[1] +
- 0.114 * color->c[2]);
-}
-
-void GfxCalRGBColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- rgb->r = clip01(color->c[0]);
- rgb->g = clip01(color->c[1]);
- rgb->b = clip01(color->c[2]);
-}
-
-void GfxCalRGBColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- double c, m, y, k;
-
- c = clip01(1 - color->c[0]);
- m = clip01(1 - color->c[1]);
- y = clip01(1 - color->c[2]);
- k = c;
- if (m < k) {
- k = m;
- }
- if (y < k) {
- k = y;
- }
- cmyk->c = c - k;
- cmyk->m = m - k;
- cmyk->y = y - k;
- cmyk->k = k;
-}
-
-//------------------------------------------------------------------------
-// GfxDeviceCMYKColorSpace
-//------------------------------------------------------------------------
-
-GfxDeviceCMYKColorSpace::GfxDeviceCMYKColorSpace() {
-}
-
-GfxDeviceCMYKColorSpace::~GfxDeviceCMYKColorSpace() {
-}
-
-GfxColorSpace *GfxDeviceCMYKColorSpace::copy() const {
- return new GfxDeviceCMYKColorSpace();
-}
-
-void GfxDeviceCMYKColorSpace::getGray(const GfxColor *color, double *gray) const {
- *gray = clip01(1 - color->c[3]
- - 0.299 * color->c[0]
- - 0.587 * color->c[1]
- - 0.114 * color->c[2]);
-}
-
-void GfxDeviceCMYKColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- double c, m, y, aw, ac, am, ay, ar, ag, ab;
-
- c = clip01(color->c[0] + color->c[3]);
- m = clip01(color->c[1] + color->c[3]);
- y = clip01(color->c[2] + color->c[3]);
- aw = (1-c) * (1-m) * (1-y);
- ac = c * (1-m) * (1-y);
- am = (1-c) * m * (1-y);
- ay = (1-c) * (1-m) * y;
- ar = (1-c) * m * y;
- ag = c * (1-m) * y;
- ab = c * m * (1-y);
- rgb->r = clip01(aw + 0.9137*am + 0.9961*ay + 0.9882*ar);
- rgb->g = clip01(aw + 0.6196*ac + ay + 0.5176*ag);
- rgb->b = clip01(aw + 0.7804*ac + 0.5412*am + 0.0667*ar + 0.2118*ag +
- 0.4863*ab);
-}
-
-void GfxDeviceCMYKColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- cmyk->c = clip01(color->c[0]);
- cmyk->m = clip01(color->c[1]);
- cmyk->y = clip01(color->c[2]);
- cmyk->k = clip01(color->c[3]);
-}
-
-//------------------------------------------------------------------------
-// GfxLabColorSpace
-//------------------------------------------------------------------------
-
-// This is the inverse of MatrixLMN in Example 4.10 from the PostScript
-// Language Reference, Third Edition.
-static double xyzrgb[3][3] = {
- { 3.240449, -1.537136, -0.498531 },
- { -0.969265, 1.876011, 0.041556 },
- { 0.055643, -0.204026, 1.057229 }
-};
-
-GfxLabColorSpace::GfxLabColorSpace() {
- whiteX = whiteY = whiteZ = 1;
- blackX = blackY = blackZ = 0;
- aMin = bMin = -100;
- aMax = bMax = 100;
-}
-
-GfxLabColorSpace::~GfxLabColorSpace() {
-}
-
-GfxColorSpace *GfxLabColorSpace::copy() const {
- GfxLabColorSpace *cs;
-
- cs = new GfxLabColorSpace();
- cs->whiteX = whiteX;
- cs->whiteY = whiteY;
- cs->whiteZ = whiteZ;
- cs->blackX = blackX;
- cs->blackY = blackY;
- cs->blackZ = blackZ;
- cs->aMin = aMin;
- cs->aMax = aMax;
- cs->bMin = bMin;
- cs->bMax = bMax;
- cs->kr = kr;
- cs->kg = kg;
- cs->kb = kb;
- return cs;
-}
-
-GfxColorSpace *GfxLabColorSpace::parse(Array *arr) {
- GfxLabColorSpace *cs;
- Object obj1, obj2, obj3;
-
- arr->get(1, &obj1);
- if (!obj1.isDict()) {
- error(-1, "Bad Lab color space");
- obj1.free();
- return NULL;
- }
- cs = new GfxLabColorSpace();
- if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->whiteX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->whiteY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->whiteZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
- obj2.arrayGetLength() == 3) {
- obj2.arrayGet(0, &obj3);
- cs->blackX = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->blackY = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->blackZ = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- if (obj1.dictLookup("Range", &obj2)->isArray() &&
- obj2.arrayGetLength() == 4) {
- obj2.arrayGet(0, &obj3);
- cs->aMin = obj3.getNum();
- obj3.free();
- obj2.arrayGet(1, &obj3);
- cs->aMax = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2, &obj3);
- cs->bMin = obj3.getNum();
- obj3.free();
- obj2.arrayGet(3, &obj3);
- cs->bMax = obj3.getNum();
- obj3.free();
- }
- obj2.free();
- obj1.free();
-
- cs->kr = 1 / (xyzrgb[0][0] * cs->whiteX +
- xyzrgb[0][1] * cs->whiteY +
- xyzrgb[0][2] * cs->whiteZ);
- cs->kg = 1 / (xyzrgb[1][0] * cs->whiteX +
- xyzrgb[1][1] * cs->whiteY +
- xyzrgb[1][2] * cs->whiteZ);
- cs->kb = 1 / (xyzrgb[2][0] * cs->whiteX +
- xyzrgb[2][1] * cs->whiteY +
- xyzrgb[2][2] * cs->whiteZ);
-
- return cs;
-}
-
-void GfxLabColorSpace::getGray(const GfxColor *color, double *gray) const {
- GfxRGB rgb;
-
- getRGB(color, &rgb);
- *gray = clip01(0.299 * rgb.r +
- 0.587 * rgb.g +
- 0.114 * rgb.b);
-}
-
-void GfxLabColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- double X, Y, Z;
- double t1, t2;
- double r, g, b;
-
- // convert L*a*b* to CIE 1931 XYZ color space
- t1 = (color->c[0] + 16) / 116;
- t2 = t1 + color->c[1] / 500;
- if (t2 >= (6.0 / 29.0)) {
- X = t2 * t2 * t2;
- } else {
- X = (108.0 / 841.0) * (t2 - (4.0 / 29.0));
- }
- X *= whiteX;
- if (t1 >= (6.0 / 29.0)) {
- Y = t1 * t1 * t1;
- } else {
- Y = (108.0 / 841.0) * (t1 - (4.0 / 29.0));
- }
- Y *= whiteY;
- t2 = t1 - color->c[2] / 200;
- if (t2 >= (6.0 / 29.0)) {
- Z = t2 * t2 * t2;
- } else {
- Z = (108.0 / 841.0) * (t2 - (4.0 / 29.0));
- }
- Z *= whiteZ;
-
- // convert XYZ to RGB, including gamut mapping and gamma correction
- r = xyzrgb[0][0] * X + xyzrgb[0][1] * Y + xyzrgb[0][2] * Z;
- g = xyzrgb[1][0] * X + xyzrgb[1][1] * Y + xyzrgb[1][2] * Z;
- b = xyzrgb[2][0] * X + xyzrgb[2][1] * Y + xyzrgb[2][2] * Z;
- rgb->r = pow(clip01(r * kr), 0.5);
- rgb->g = pow(clip01(g * kg), 0.5);
- rgb->b = pow(clip01(b * kb), 0.5);
-}
-
-void GfxLabColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- GfxRGB rgb;
- double c, m, y, k;
-
- getRGB(color, &rgb);
- c = clip01(1 - rgb.r);
- m = clip01(1 - rgb.g);
- y = clip01(1 - rgb.b);
- k = c;
- if (m < k) {
- k = m;
- }
- if (y < k) {
- k = y;
- }
- cmyk->c = c - k;
- cmyk->m = m - k;
- cmyk->y = y - k;
- cmyk->k = k;
-}
-
-void GfxLabColorSpace::getDefaultRanges(double *decodeLow, double *decodeRange,
- int /*maxImgPixel*/) const {
- decodeLow[0] = 0;
- decodeRange[0] = 100;
- decodeLow[1] = aMin;
- decodeRange[1] = aMax - aMin;
- decodeLow[2] = bMin;
- decodeRange[2] = bMax - bMin;
-}
-
-//------------------------------------------------------------------------
-// GfxICCBasedColorSpace
-//------------------------------------------------------------------------
-
-GfxICCBasedColorSpace::GfxICCBasedColorSpace(int nCompsA, GfxColorSpace *altA,
- const Ref *iccProfileStreamA) {
- nComps = nCompsA;
- alt = altA;
- iccProfileStream = *iccProfileStreamA;
- rangeMin[0] = rangeMin[1] = rangeMin[2] = rangeMin[3] = 0;
- rangeMax[0] = rangeMax[1] = rangeMax[2] = rangeMax[3] = 1;
-}
-
-GfxICCBasedColorSpace::~GfxICCBasedColorSpace() {
- delete alt;
-}
-
-GfxColorSpace *GfxICCBasedColorSpace::copy() const {
- GfxICCBasedColorSpace *cs;
- int i;
-
- cs = new GfxICCBasedColorSpace(nComps, alt->copy(), &iccProfileStream);
- for (i = 0; i < 4; ++i) {
- cs->rangeMin[i] = rangeMin[i];
- cs->rangeMax[i] = rangeMax[i];
- }
- return cs;
-}
-
-GfxColorSpace *GfxICCBasedColorSpace::parse(Array *arr) {
- GfxICCBasedColorSpace *cs;
- Ref iccProfileStreamA;
- int nCompsA;
- GfxColorSpace *altA;
- Dict *dict;
- Object obj1, obj2, obj3;
- int i;
-
- arr->getNF(1, &obj1);
- if (obj1.isRef()) {
- iccProfileStreamA = obj1.getRef();
- } else {
- iccProfileStreamA.num = 0;
- iccProfileStreamA.gen = 0;
- }
- obj1.free();
- arr->get(1, &obj1);
- if (!obj1.isStream()) {
- error(-1, "Bad ICCBased color space (stream)");
- obj1.free();
- return NULL;
- }
- dict = obj1.streamGetDict();
- if (!dict->lookup("N", &obj2)->isInt()) {
- error(-1, "Bad ICCBased color space (N)");
- obj2.free();
- obj1.free();
- return NULL;
- }
- nCompsA = obj2.getInt();
- obj2.free();
- if (nCompsA > gfxColorMaxComps) {
- error(-1, "ICCBased color space with too many (%d > %d) components",
- nCompsA, gfxColorMaxComps);
- nCompsA = gfxColorMaxComps;
- }
- if (dict->lookup("Alternate", &obj2)->isNull() ||
- !(altA = GfxColorSpace::parse(&obj2))) {
- switch (nCompsA) {
- case 1:
- altA = new GfxDeviceGrayColorSpace();
- break;
- case 3:
- altA = new GfxDeviceRGBColorSpace();
- break;
- case 4:
- altA = new GfxDeviceCMYKColorSpace();
- break;
- default:
- error(-1, "Bad ICCBased color space - invalid N");
- obj2.free();
- obj1.free();
- return NULL;
- }
- }
- obj2.free();
- cs = new GfxICCBasedColorSpace(nCompsA, altA, &iccProfileStreamA);
- if (dict->lookup("Range", &obj2)->isArray() &&
- obj2.arrayGetLength() == 2 * nCompsA) {
- for (i = 0; i < nCompsA; ++i) {
- obj2.arrayGet(2*i, &obj3);
- cs->rangeMin[i] = obj3.getNum();
- obj3.free();
- obj2.arrayGet(2*i+1, &obj3);
- cs->rangeMax[i] = obj3.getNum();
- obj3.free();
- }
- }
- obj2.free();
- obj1.free();
- return cs;
-}
-
-void GfxICCBasedColorSpace::getGray(const GfxColor *color, double *gray) const {
- alt->getGray(color, gray);
-}
-
-void GfxICCBasedColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- alt->getRGB(color, rgb);
-}
-
-void GfxICCBasedColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- alt->getCMYK(color, cmyk);
-}
-
-void GfxICCBasedColorSpace::getDefaultRanges(double *decodeLow,
- double *decodeRange,
- int /*maxImgPixel*/) const {
- int i;
-
- for (i = 0; i < nComps; ++i) {
- decodeLow[i] = rangeMin[i];
- decodeRange[i] = rangeMax[i] - rangeMin[i];
- }
-}
-
-//------------------------------------------------------------------------
-// GfxIndexedColorSpace
-//------------------------------------------------------------------------
-
-GfxIndexedColorSpace::GfxIndexedColorSpace(GfxColorSpace *baseA,
- int indexHighA) {
- base = baseA;
- indexHigh = indexHighA;
- lookup = (Guchar *)gmalloc((indexHigh + 1) * base->getNComps() *
- sizeof(Guchar));
-}
-
-GfxIndexedColorSpace::~GfxIndexedColorSpace() {
- delete base;
- gfree(lookup);
-}
-
-GfxColorSpace *GfxIndexedColorSpace::copy() const {
- GfxIndexedColorSpace *cs;
-
- cs = new GfxIndexedColorSpace(base->copy(), indexHigh);
- memcpy(cs->lookup, lookup,
- (indexHigh + 1) * base->getNComps() * sizeof(Guchar));
- return cs;
-}
-
-GfxColorSpace *GfxIndexedColorSpace::parse(Array *arr) {
- GfxIndexedColorSpace *cs;
- GfxColorSpace *baseA;
- int indexHighA;
- Object obj1;
- int x;
- char *s;
- int n, i, j;
-
- if (arr->getLength() != 4) {
- error(-1, "Bad Indexed color space");
- goto err1;
- }
- arr->get(1, &obj1);
- if (!(baseA = GfxColorSpace::parse(&obj1))) {
- error(-1, "Bad Indexed color space (base color space)");
- goto err2;
- }
- obj1.free();
- if (!arr->get(2, &obj1)->isInt()) {
- error(-1, "Bad Indexed color space (hival)");
- goto err2;
- }
- indexHighA = obj1.getInt();
- obj1.free();
- cs = new GfxIndexedColorSpace(baseA, indexHighA);
- arr->get(3, &obj1);
- n = baseA->getNComps();
- if (obj1.isStream()) {
- obj1.streamReset();
- for (i = 0; i <= indexHighA; ++i) {
- for (j = 0; j < n; ++j) {
- if ((x = obj1.streamGetChar()) == EOF) {
- error(-1, "Bad Indexed color space (lookup table stream too short)");
- goto err3;
- }
- cs->lookup[i*n + j] = (Guchar)x;
- }
- }
- obj1.streamClose();
- } else if (obj1.isString()) {
- if (obj1.getString()->getLength() < (indexHighA + 1) * n) {
- error(-1, "Bad Indexed color space (lookup table string too short)");
- goto err3;
- }
- s = obj1.getString()->getCString();
- for (i = 0; i <= indexHighA; ++i) {
- for (j = 0; j < n; ++j) {
- cs->lookup[i*n + j] = (Guchar)*s++;
- }
- }
- } else {
- error(-1, "Bad Indexed color space (lookup table)");
- goto err3;
- }
- obj1.free();
- return cs;
-
- err3:
- delete cs;
- err2:
- obj1.free();
- err1:
- return NULL;
-}
-
-void GfxIndexedColorSpace::getGray(const GfxColor *color, double *gray) const {
- Guchar *p;
- GfxColor color2;
- double low[gfxColorMaxComps], range[gfxColorMaxComps];
- int n, i;
-
- n = base->getNComps();
- base->getDefaultRanges(low, range, indexHigh);
- p = &lookup[(int)(color->c[0] + 0.5) * n];
- for (i = 0; i < n; ++i) {
- color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
- }
- base->getGray(&color2, gray);
-}
-
-void GfxIndexedColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- Guchar *p;
- GfxColor color2;
- double low[gfxColorMaxComps], range[gfxColorMaxComps];
- int n, i;
-
- n = base->getNComps();
- base->getDefaultRanges(low, range, indexHigh);
- p = &lookup[(int)(color->c[0] + 0.5) * n];
- for (i = 0; i < n; ++i) {
- color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
- }
- base->getRGB(&color2, rgb);
-}
-
-void GfxIndexedColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- Guchar *p;
- GfxColor color2;
- double low[gfxColorMaxComps], range[gfxColorMaxComps];
- int n, i;
-
- n = base->getNComps();
- base->getDefaultRanges(low, range, indexHigh);
- p = &lookup[(int)(color->c[0] + 0.5) * n];
- for (i = 0; i < n; ++i) {
- color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
- }
- base->getCMYK(&color2, cmyk);
-}
-
-void GfxIndexedColorSpace::getDefaultRanges(double *decodeLow,
- double *decodeRange,
- int maxImgPixel) const {
- decodeLow[0] = 0;
- decodeRange[0] = maxImgPixel;
-}
-
-//------------------------------------------------------------------------
-// GfxSeparationColorSpace
-//------------------------------------------------------------------------
-
-GfxSeparationColorSpace::GfxSeparationColorSpace(GString *nameA,
- GfxColorSpace *altA,
- Function *funcA) {
- name = nameA;
- alt = altA;
- func = funcA;
-}
-
-GfxSeparationColorSpace::~GfxSeparationColorSpace() {
- delete name;
- delete alt;
- delete func;
-}
-
-GfxColorSpace *GfxSeparationColorSpace::copy() const {
- return new GfxSeparationColorSpace(name->copy(), alt->copy(), func->copy());
-}
-
-//~ handle the 'All' and 'None' colorants
-GfxColorSpace *GfxSeparationColorSpace::parse(Array *arr) {
- GfxSeparationColorSpace *cs;
- GString *nameA;
- GfxColorSpace *altA;
- Function *funcA;
- Object obj1;
-
- if (arr->getLength() != 4) {
- error(-1, "Bad Separation color space");
- goto err1;
- }
- if (!arr->get(1, &obj1)->isName()) {
- error(-1, "Bad Separation color space (name)");
- goto err2;
- }
- nameA = new GString(obj1.getName());
- obj1.free();
- arr->get(2, &obj1);
- if (!(altA = GfxColorSpace::parse(&obj1))) {
- error(-1, "Bad Separation color space (alternate color space)");
- goto err3;
- }
- obj1.free();
- arr->get(3, &obj1);
- if (!(funcA = Function::parse(&obj1))) {
- goto err4;
- }
- obj1.free();
- cs = new GfxSeparationColorSpace(nameA, altA, funcA);
- return cs;
-
- err4:
- delete altA;
- err3:
- delete nameA;
- err2:
- obj1.free();
- err1:
- return NULL;
-}
-
-void GfxSeparationColorSpace::getGray(const GfxColor *color, double *gray) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getGray(&color2, gray);
-}
-
-void GfxSeparationColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getRGB(&color2, rgb);
-}
-
-void GfxSeparationColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getCMYK(&color2, cmyk);
-}
-
-//------------------------------------------------------------------------
-// GfxDeviceNColorSpace
-//------------------------------------------------------------------------
-
-GfxDeviceNColorSpace::GfxDeviceNColorSpace(int nCompsA,
- GfxColorSpace *altA,
- Function *funcA) {
- nComps = nCompsA;
- alt = altA;
- func = funcA;
-}
-
-GfxDeviceNColorSpace::~GfxDeviceNColorSpace() {
- int i;
-
- for (i = 0; i < nComps; ++i) {
- delete names[i];
- }
- delete alt;
- delete func;
-}
-
-GfxColorSpace *GfxDeviceNColorSpace::copy() const {
- GfxDeviceNColorSpace *cs;
- int i;
-
- cs = new GfxDeviceNColorSpace(nComps, alt->copy(), func->copy());
- for (i = 0; i < nComps; ++i) {
- cs->names[i] = names[i]->copy();
- }
- return cs;
-}
-
-//~ handle the 'None' colorant
-GfxColorSpace *GfxDeviceNColorSpace::parse(Array *arr) {
- GfxDeviceNColorSpace *cs;
- int nCompsA;
- GString *namesA[gfxColorMaxComps];
- GfxColorSpace *altA;
- Function *funcA;
- Object obj1, obj2;
- int i;
-
- if (arr->getLength() != 4 && arr->getLength() != 5) {
- error(-1, "Bad DeviceN color space");
- goto err1;
- }
- if (!arr->get(1, &obj1)->isArray()) {
- error(-1, "Bad DeviceN color space (names)");
- goto err2;
- }
- nCompsA = obj1.arrayGetLength();
- if (nCompsA > gfxColorMaxComps) {
- error(-1, "DeviceN color space with too many (%d > %d) components",
- nCompsA, gfxColorMaxComps);
- nCompsA = gfxColorMaxComps;
- }
- for (i = 0; i < nCompsA; ++i) {
- if (!obj1.arrayGet(i, &obj2)->isName()) {
- error(-1, "Bad DeviceN color space (names)");
- obj2.free();
- goto err2;
- }
- namesA[i] = new GString(obj2.getName());
- obj2.free();
- }
- obj1.free();
- arr->get(2, &obj1);
- if (!(altA = GfxColorSpace::parse(&obj1))) {
- error(-1, "Bad DeviceN color space (alternate color space)");
- goto err3;
- }
- obj1.free();
- arr->get(3, &obj1);
- if (!(funcA = Function::parse(&obj1))) {
- goto err4;
- }
- obj1.free();
- cs = new GfxDeviceNColorSpace(nCompsA, altA, funcA);
- for (i = 0; i < nCompsA; ++i) {
- cs->names[i] = namesA[i];
- }
- return cs;
-
- err4:
- delete altA;
- err3:
- for (i = 0; i < nCompsA; ++i) {
- delete namesA[i];
- }
- err2:
- obj1.free();
- err1:
- return NULL;
-}
-
-void GfxDeviceNColorSpace::getGray(const GfxColor *color, double *gray) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getGray(&color2, gray);
-}
-
-void GfxDeviceNColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getRGB(&color2, rgb);
-}
-
-void GfxDeviceNColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
- GfxColor color2;
-
- func->transform(color->c, color2.c);
- alt->getCMYK(&color2, cmyk);
-}
-
-//------------------------------------------------------------------------
-// GfxPatternColorSpace
-//------------------------------------------------------------------------
-
-GfxPatternColorSpace::GfxPatternColorSpace(GfxColorSpace *underA) {
- under = underA;
-}
-
-GfxPatternColorSpace::~GfxPatternColorSpace() {
- if (under) {
- delete under;
- }
-}
-
-GfxColorSpace *GfxPatternColorSpace::copy() const {
- return new GfxPatternColorSpace(under ? under->copy() :
- (GfxColorSpace *)NULL);
-}
-
-GfxColorSpace *GfxPatternColorSpace::parse(Array *arr) {
- GfxPatternColorSpace *cs;
- GfxColorSpace *underA;
- Object obj1;
-
- if (arr->getLength() != 1 && arr->getLength() != 2) {
- error(-1, "Bad Pattern color space");
- return NULL;
- }
- underA = NULL;
- if (arr->getLength() == 2) {
- arr->get(1, &obj1);
- if (!(underA = GfxColorSpace::parse(&obj1))) {
- error(-1, "Bad Pattern color space (underlying color space)");
- obj1.free();
- return NULL;
- }
- obj1.free();
- }
- cs = new GfxPatternColorSpace(underA);
- return cs;
-}
-
-void GfxPatternColorSpace::getGray(const GfxColor */*color*/, double *gray) const {
- *gray = 0;
-}
-
-void GfxPatternColorSpace::getRGB(const GfxColor */*color*/, GfxRGB *rgb) const {
- rgb->r = rgb->g = rgb->b = 0;
-}
-
-void GfxPatternColorSpace::getCMYK(const GfxColor */*color*/, GfxCMYK *cmyk) const {
- cmyk->c = cmyk->m = cmyk->y = 0;
- cmyk->k = 1;
-}
-
-//------------------------------------------------------------------------
-// Pattern
-//------------------------------------------------------------------------
-
-GfxPattern::GfxPattern(int typeA) {
- type = typeA;
-}
-
-GfxPattern::~GfxPattern() {
-}
-
-GfxPattern *GfxPattern::parse(Object *obj) {
- GfxPattern *pattern;
- Dict *dict;
- Object obj1;
-
- pattern = NULL;
- if (obj->isStream()) {
- dict = obj->streamGetDict();
- dict->lookup("PatternType", &obj1);
- if (obj1.isInt() && obj1.getInt() == 1) {
- pattern = new GfxTilingPattern(dict, obj);
- }
- obj1.free();
- }
- return pattern;
-}
-
-//------------------------------------------------------------------------
-// GfxTilingPattern
-//------------------------------------------------------------------------
-
-GfxTilingPattern::GfxTilingPattern(Dict *streamDict, Object *stream):
- GfxPattern(1)
-{
- Object obj1, obj2;
- int i;
-
- if (streamDict->lookup("PaintType", &obj1)->isInt()) {
- paintType = obj1.getInt();
- } else {
- paintType = 1;
- error(-1, "Invalid or missing PaintType in pattern");
- }
- obj1.free();
- if (streamDict->lookup("TilingType", &obj1)->isInt()) {
- tilingType = obj1.getInt();
- } else {
- tilingType = 1;
- error(-1, "Invalid or missing TilingType in pattern");
- }
- obj1.free();
- bbox[0] = bbox[1] = 0;
- bbox[2] = bbox[3] = 1;
- if (streamDict->lookup("BBox", &obj1)->isArray() &&
- obj1.arrayGetLength() == 4) {
- for (i = 0; i < 4; ++i) {
- if (obj1.arrayGet(i, &obj2)->isNum()) {
- bbox[i] = obj2.getNum();
- }
- obj2.free();
- }
- } else {
- error(-1, "Invalid or missing BBox in pattern");
- }
- obj1.free();
- if (streamDict->lookup("XStep", &obj1)->isNum()) {
- xStep = obj1.getNum();
- } else {
- xStep = 1;
- error(-1, "Invalid or missing XStep in pattern");
- }
- obj1.free();
- if (streamDict->lookup("YStep", &obj1)->isNum()) {
- yStep = obj1.getNum();
- } else {
- yStep = 1;
- error(-1, "Invalid or missing YStep in pattern");
- }
- obj1.free();
- if (!streamDict->lookup("Resources", &resDict)->isDict()) {
- resDict.free();
- resDict.initNull();
- error(-1, "Invalid or missing Resources in pattern");
- }
- matrix[0] = 1; matrix[1] = 0;
- matrix[2] = 0; matrix[3] = 1;
- matrix[4] = 0; matrix[5] = 0;
- if (streamDict->lookup("Matrix", &obj1)->isArray() &&
- obj1.arrayGetLength() == 6) {
- for (i = 0; i < 6; ++i) {
- if (obj1.arrayGet(i, &obj2)->isNum()) {
- matrix[i] = obj2.getNum();
- }
- obj2.free();
- }
- }
- obj1.free();
- stream->copy(&contentStream);
-}
-
-GfxTilingPattern::~GfxTilingPattern() {
- resDict.free();
- contentStream.free();
-}
-
-GfxPattern *GfxTilingPattern::copy() {
- return new GfxTilingPattern(this);
-}
-
-GfxTilingPattern::GfxTilingPattern(GfxTilingPattern *pat):
- GfxPattern(1)
-{
- memcpy(this, pat, sizeof(GfxTilingPattern));
- pat->resDict.copy(&resDict);
- pat->contentStream.copy(&contentStream);
-}
-
-//------------------------------------------------------------------------
-// GfxShading
-//------------------------------------------------------------------------
-
-GfxShading::GfxShading() {
-}
-
-GfxShading::~GfxShading() {
- delete colorSpace;
-}
-
-GfxShading *GfxShading::parse(Object *obj) {
- GfxShading *shading;
- int typeA;
- GfxColorSpace *colorSpaceA;
- GfxColor backgroundA;
- GBool hasBackgroundA;
- double xMinA, yMinA, xMaxA, yMaxA;
- GBool hasBBoxA;
- Object obj1, obj2;
- int i;
-
- shading = NULL;
- if (obj->isDict()) {
-
- if (!obj->dictLookup("ShadingType", &obj1)->isInt()) {
- error(-1, "Invalid ShadingType in shading dictionary");
- obj1.free();
- goto err1;
- }
- typeA = obj1.getInt();
- obj1.free();
-
- obj->dictLookup("ColorSpace", &obj1);
- if (!(colorSpaceA = GfxColorSpace::parse(&obj1))) {
- error(-1, "Bad color space in shading dictionary");
- obj1.free();
- goto err1;
- }
- obj1.free();
-
- for (i = 0; i < gfxColorMaxComps; ++i) {
- backgroundA.c[i] = 0;
- }
- hasBackgroundA = gFalse;
- if (obj->dictLookup("Background", &obj1)->isArray()) {
- if (obj1.arrayGetLength() == colorSpaceA->getNComps()) {
- hasBackgroundA = gTrue;
- for (i = 0; i < colorSpaceA->getNComps(); ++i) {
- backgroundA.c[i] = obj1.arrayGet(i, &obj2)->getNum();
- obj2.free();
- }
- } else {
- error(-1, "Bad Background in shading dictionary");
- }
- }
- obj1.free();
-
- xMinA = yMinA = xMaxA = yMaxA = 0;
- hasBBoxA = gFalse;
- if (obj->dictLookup("BBox", &obj1)->isArray()) {
- if (obj1.arrayGetLength() == 4) {
- hasBBoxA = gTrue;
- xMinA = obj1.arrayGet(0, &obj2)->getNum();
- obj2.free();
- yMinA = obj1.arrayGet(1, &obj2)->getNum();
- obj2.free();
- xMaxA = obj1.arrayGet(2, &obj2)->getNum();
- obj2.free();
- yMaxA = obj1.arrayGet(3, &obj2)->getNum();
- obj2.free();
- } else {
- error(-1, "Bad BBox in shading dictionary");
- }
- }
- obj1.free();
-
- switch (typeA) {
- case 2:
- shading = GfxAxialShading::parse(obj->getDict());
- break;
- case 3:
- shading = GfxRadialShading::parse(obj->getDict());
- break;
- default:
- error(-1, "Unimplemented shading type %d", typeA);
- goto err1;
- }
-
- if (shading) {
- shading->type = typeA;
- shading->colorSpace = colorSpaceA;
- shading->background = backgroundA;
- shading->hasBackground = hasBackgroundA;
- shading->xMin = xMinA;
- shading->yMin = yMinA;
- shading->xMax = xMaxA;
- shading->yMax = yMaxA;
- shading->hasBBox = hasBBoxA;
- } else {
- delete colorSpaceA;
- }
- }
-
- return shading;
-
- err1:
- return NULL;
-}
-
-//------------------------------------------------------------------------
-// GfxAxialShading
-//------------------------------------------------------------------------
-
-GfxAxialShading::GfxAxialShading(double x0A, double y0A,
- double x1A, double y1A,
- double t0A, double t1A,
- Function **funcsA, int nFuncsA,
- GBool extend0A, GBool extend1A) {
- int i;
-
- x0 = x0A;
- y0 = y0A;
- x1 = x1A;
- y1 = y1A;
- t0 = t0A;
- t1 = t1A;
- nFuncs = nFuncsA;
- for (i = 0; i < nFuncs; ++i) {
- funcs[i] = funcsA[i];
- }
- extend0 = extend0A;
- extend1 = extend1A;
-}
-
-GfxAxialShading::~GfxAxialShading() {
- int i;
-
- for (i = 0; i < nFuncs; ++i) {
- delete funcs[i];
- }
-}
-
-GfxAxialShading *GfxAxialShading::parse(Dict *dict) {
- double x0A, y0A, x1A, y1A;
- double t0A, t1A;
- Function *funcsA[gfxColorMaxComps];
- int nFuncsA;
- GBool extend0A, extend1A;
- Object obj1, obj2;
- int i;
-
- x0A = y0A = x1A = y1A = 0;
- if (dict->lookup("Coords", &obj1)->isArray() &&
- obj1.arrayGetLength() == 4) {
- x0A = obj1.arrayGet(0, &obj2)->getNum();
- obj2.free();
- y0A = obj1.arrayGet(1, &obj2)->getNum();
- obj2.free();
- x1A = obj1.arrayGet(2, &obj2)->getNum();
- obj2.free();
- y1A = obj1.arrayGet(3, &obj2)->getNum();
- obj2.free();
- } else {
- error(-1, "Missing or invalid Coords in shading dictionary");
- goto err1;
- }
- obj1.free();
-
- t0A = 0;
- t1A = 1;
- if (dict->lookup("Domain", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2) {
- t0A = obj1.arrayGet(0, &obj2)->getNum();
- obj2.free();
- t1A = obj1.arrayGet(1, &obj2)->getNum();
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("Function", &obj1);
- if (obj1.isArray()) {
- nFuncsA = obj1.arrayGetLength();
- for (i = 0; i < nFuncsA; ++i) {
- obj1.arrayGet(i, &obj2);
- if (!(funcsA[i] = Function::parse(&obj2))) {
- obj1.free();
- obj2.free();
- goto err1;
- }
- obj2.free();
- }
- } else {
- nFuncsA = 1;
- if (!(funcsA[0] = Function::parse(&obj1))) {
- obj1.free();
- goto err1;
- }
- }
- obj1.free();
-
- extend0A = extend1A = gFalse;
- if (dict->lookup("Extend", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2) {
- extend0A = obj1.arrayGet(0, &obj2)->getBool();
- obj2.free();
- extend1A = obj1.arrayGet(1, &obj2)->getBool();
- obj2.free();
- }
- obj1.free();
-
- return new GfxAxialShading(x0A, y0A, x1A, y1A, t0A, t1A,
- funcsA, nFuncsA, extend0A, extend1A);
-
- err1:
- return NULL;
-}
-
-void GfxAxialShading::getColor(double t, GfxColor *color) {
- int i;
-
- for (i = 0; i < nFuncs; ++i) {
- funcs[i]->transform(&t, &color->c[i]);
- }
-}
-
-//------------------------------------------------------------------------
-// GfxRadialShading
-//------------------------------------------------------------------------
-
-GfxRadialShading::GfxRadialShading(double x0A, double y0A, double r0A,
- double x1A, double y1A, double r1A,
- double t0A, double t1A,
- Function **funcsA, int nFuncsA,
- GBool extend0A, GBool extend1A) {
- int i;
-
- x0 = x0A;
- y0 = y0A;
- r0 = r0A;
- x1 = x1A;
- y1 = y1A;
- r1 = r1A;
- t0 = t0A;
- t1 = t1A;
- nFuncs = nFuncsA;
- for (i = 0; i < nFuncs; ++i) {
- funcs[i] = funcsA[i];
- }
- extend0 = extend0A;
- extend1 = extend1A;
-}
-
-GfxRadialShading::~GfxRadialShading() {
- int i;
-
- for (i = 0; i < nFuncs; ++i) {
- delete funcs[i];
- }
-}
-
-GfxRadialShading *GfxRadialShading::parse(Dict *dict) {
- double x0A, y0A, r0A, x1A, y1A, r1A;
- double t0A, t1A;
- Function *funcsA[gfxColorMaxComps];
- int nFuncsA;
- GBool extend0A, extend1A;
- Object obj1, obj2;
- int i;
-
- x0A = y0A = r0A = x1A = y1A = r1A = 0;
- if (dict->lookup("Coords", &obj1)->isArray() &&
- obj1.arrayGetLength() == 6) {
- x0A = obj1.arrayGet(0, &obj2)->getNum();
- obj2.free();
- y0A = obj1.arrayGet(1, &obj2)->getNum();
- obj2.free();
- r0A = obj1.arrayGet(2, &obj2)->getNum();
- obj2.free();
- x1A = obj1.arrayGet(3, &obj2)->getNum();
- obj2.free();
- y1A = obj1.arrayGet(4, &obj2)->getNum();
- obj2.free();
- r1A = obj1.arrayGet(5, &obj2)->getNum();
- obj2.free();
- } else {
- error(-1, "Missing or invalid Coords in shading dictionary");
- goto err1;
- }
- obj1.free();
-
- t0A = 0;
- t1A = 1;
- if (dict->lookup("Domain", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2) {
- t0A = obj1.arrayGet(0, &obj2)->getNum();
- obj2.free();
- t1A = obj1.arrayGet(1, &obj2)->getNum();
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("Function", &obj1);
- if (obj1.isArray()) {
- nFuncsA = obj1.arrayGetLength();
- for (i = 0; i < nFuncsA; ++i) {
- obj1.arrayGet(i, &obj2);
- if (!(funcsA[i] = Function::parse(&obj2))) {
- obj1.free();
- obj2.free();
- goto err1;
- }
- obj2.free();
- }
- } else {
- nFuncsA = 1;
- if (!(funcsA[0] = Function::parse(&obj1))) {
- obj1.free();
- goto err1;
- }
- }
- obj1.free();
-
- extend0A = extend1A = gFalse;
- if (dict->lookup("Extend", &obj1)->isArray() &&
- obj1.arrayGetLength() == 2) {
- extend0A = obj1.arrayGet(0, &obj2)->getBool();
- obj2.free();
- extend1A = obj1.arrayGet(1, &obj2)->getBool();
- obj2.free();
- }
- obj1.free();
-
- return new GfxRadialShading(x0A, y0A, r0A, x1A, y1A, r1A, t0A, t1A,
- funcsA, nFuncsA, extend0A, extend1A);
-
- err1:
- return NULL;
-}
-
-void GfxRadialShading::getColor(double t, GfxColor *color) {
- int i;
-
- for (i = 0; i < nFuncs; ++i) {
- funcs[i]->transform(&t, &color->c[i]);
- }
-}
-
-//------------------------------------------------------------------------
-// GfxImageColorMap
-//------------------------------------------------------------------------
-
-GfxImageColorMap::GfxImageColorMap(int bitsA, Object *decode,
- GfxColorSpace *colorSpaceA) {
- GfxIndexedColorSpace *indexedCS;
- GfxSeparationColorSpace *sepCS;
- int maxPixel, indexHigh;
- const Guchar *lookup2;
- const Function *sepFunc;
- Object obj;
- double x[gfxColorMaxComps];
- double y[gfxColorMaxComps];
- int i, j, k;
-
- ok = gTrue;
-
- // bits per component and color space
- bits = bitsA;
- maxPixel = (1 << bits) - 1;
- colorSpace = colorSpaceA;
-
- // get decode map
- if (decode->isNull()) {
- nComps = colorSpace->getNComps();
- colorSpace->getDefaultRanges(decodeLow, decodeRange, maxPixel);
- } else if (decode->isArray()) {
- nComps = decode->arrayGetLength() / 2;
- if (nComps != colorSpace->getNComps()) {
- goto err1;
- }
- for (i = 0; i < nComps; ++i) {
- decode->arrayGet(2*i, &obj);
- if (!obj.isNum()) {
- goto err2;
- }
- decodeLow[i] = obj.getNum();
- obj.free();
- decode->arrayGet(2*i+1, &obj);
- if (!obj.isNum()) {
- goto err2;
- }
- decodeRange[i] = obj.getNum() - decodeLow[i];
- obj.free();
- }
- } else {
- goto err1;
- }
-
- // Construct a lookup table -- this stores pre-computed decoded
- // values for each component, i.e., the result of applying the
- // decode mapping to each possible image pixel component value.
- //
- // Optimization: for Indexed and Separation color spaces (which have
- // only one component), we store color values in the lookup table
- // rather than component values.
- colorSpace2 = NULL;
- nComps2 = 0;
- if (colorSpace->getMode() == csIndexed) {
- // Note that indexHigh may not be the same as maxPixel --
- // Distiller will remove unused palette entries, resulting in
- // indexHigh < maxPixel.
- indexedCS = (GfxIndexedColorSpace *)colorSpace;
- colorSpace2 = indexedCS->getBase();
- indexHigh = indexedCS->getIndexHigh();
- nComps2 = colorSpace2->getNComps();
- lookup = (double *)gmalloc((indexHigh + 1) * nComps2 * sizeof(double));
- lookup2 = indexedCS->getLookup();
- colorSpace2->getDefaultRanges(x, y, indexHigh);
- for (i = 0; i <= indexHigh; ++i) {
- j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5);
- for (k = 0; k < nComps2; ++k) {
- lookup[j*nComps2 + k] = x[k] + (lookup2[i*nComps2 + k] / 255.0) * y[k];
- }
- }
- } else if (colorSpace->getMode() == csSeparation) {
- sepCS = (GfxSeparationColorSpace *)colorSpace;
- colorSpace2 = sepCS->getAlt();
- nComps2 = colorSpace2->getNComps();
- lookup = (double *)gmalloc((maxPixel + 1) * nComps2 * sizeof(double));
- sepFunc = sepCS->getFunc();
- for (i = 0; i <= maxPixel; ++i) {
- x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel;
- sepFunc->transform(x, y);
- for (k = 0; k < nComps2; ++k) {
- lookup[i*nComps2 + k] = y[k];
- }
- }
- } else {
- lookup = (double *)gmalloc((maxPixel + 1) * nComps * sizeof(double));
- for (i = 0; i <= maxPixel; ++i) {
- for (k = 0; k < nComps; ++k) {
- lookup[i*nComps + k] = decodeLow[k] +
- (i * decodeRange[k]) / maxPixel;
- }
- }
- }
-
- return;
-
- err2:
- obj.free();
- err1:
- ok = gFalse;
-}
-
-GfxImageColorMap::~GfxImageColorMap() {
- delete colorSpace;
- gfree(lookup);
-}
-
-void GfxImageColorMap::getGray(Guchar *x, double *gray) {
- GfxColor color;
- double *p;
- int i;
-
- if (colorSpace2) {
- p = &lookup[x[0] * nComps2];
- for (i = 0; i < nComps2; ++i) {
- color.c[i] = *p++;
- }
- colorSpace2->getGray(&color, gray);
- } else {
- for (i = 0; i < nComps; ++i) {
- color.c[i] = lookup[x[i] * nComps + i];
- }
- colorSpace->getGray(&color, gray);
- }
-}
-
-void GfxImageColorMap::getRGB(Guchar *x, GfxRGB *rgb) {
- GfxColor color;
- double *p;
- int i;
-
- if (colorSpace2) {
- p = &lookup[x[0] * nComps2];
- for (i = 0; i < nComps2; ++i) {
- color.c[i] = *p++;
- }
- colorSpace2->getRGB(&color, rgb);
- } else {
- for (i = 0; i < nComps; ++i) {
- color.c[i] = lookup[x[i] * nComps + i];
- }
- colorSpace->getRGB(&color, rgb);
- }
-}
-
-void GfxImageColorMap::getCMYK(Guchar *x, GfxCMYK *cmyk) {
- GfxColor color;
- double *p;
- int i;
-
- if (colorSpace2) {
- p = &lookup[x[0] * nComps2];
- for (i = 0; i < nComps2; ++i) {
- color.c[i] = *p++;
- }
- colorSpace2->getCMYK(&color, cmyk);
- } else {
- for (i = 0; i < nComps; ++i) {
- color.c[i] = lookup[x[i] * nComps + i];
- }
- colorSpace->getCMYK(&color, cmyk);
- }
-}
-
-//------------------------------------------------------------------------
-// GfxSubpath and GfxPath
-//------------------------------------------------------------------------
-
-GfxSubpath::GfxSubpath(double x1, double y1) {
- size = 16;
- x = (double *)gmalloc(size * sizeof(double));
- y = (double *)gmalloc(size * sizeof(double));
- curve = (GBool *)gmalloc(size * sizeof(GBool));
- n = 1;
- x[0] = x1;
- y[0] = y1;
- curve[0] = gFalse;
- closed = gFalse;
-}
-
-GfxSubpath::~GfxSubpath() {
- gfree(x);
- gfree(y);
- gfree(curve);
-}
-
-// Used for copy().
-GfxSubpath::GfxSubpath(GfxSubpath *subpath) {
- size = subpath->size;
- n = subpath->n;
- x = (double *)gmalloc(size * sizeof(double));
- y = (double *)gmalloc(size * sizeof(double));
- curve = (GBool *)gmalloc(size * sizeof(GBool));
- memcpy(x, subpath->x, n * sizeof(double));
- memcpy(y, subpath->y, n * sizeof(double));
- memcpy(curve, subpath->curve, n * sizeof(GBool));
- closed = subpath->closed;
-}
-
-void GfxSubpath::lineTo(double x1, double y1) {
- if (n >= size) {
- size += 16;
- x = (double *)grealloc(x, size * sizeof(double));
- y = (double *)grealloc(y, size * sizeof(double));
- curve = (GBool *)grealloc(curve, size * sizeof(GBool));
- }
- x[n] = x1;
- y[n] = y1;
- curve[n] = gFalse;
- ++n;
-}
-
-void GfxSubpath::curveTo(double x1, double y1, double x2, double y2,
- double x3, double y3) {
- if (n+3 > size) {
- size += 16;
- x = (double *)grealloc(x, size * sizeof(double));
- y = (double *)grealloc(y, size * sizeof(double));
- curve = (GBool *)grealloc(curve, size * sizeof(GBool));
- }
- x[n] = x1;
- y[n] = y1;
- x[n+1] = x2;
- y[n+1] = y2;
- x[n+2] = x3;
- y[n+2] = y3;
- curve[n] = curve[n+1] = gTrue;
- curve[n+2] = gFalse;
- n += 3;
-}
-
-void GfxSubpath::close() {
- if (x[n-1] != x[0] || y[n-1] != y[0]) {
- lineTo(x[0], y[0]);
- }
- closed = gTrue;
-}
-
-GfxPath::GfxPath() {
- justMoved = gFalse;
- size = 16;
- n = 0;
- firstX = firstY = 0;
- subpaths = (GfxSubpath **)gmalloc(size * sizeof(GfxSubpath *));
-}
-
-GfxPath::~GfxPath() {
- int i;
-
- for (i = 0; i < n; ++i)
- delete subpaths[i];
- gfree(subpaths);
-}
-
-// Used for copy().
-GfxPath::GfxPath(GBool justMoved1, double firstX1, double firstY1,
- GfxSubpath **subpaths1, int n1, int size1) {
- int i;
-
- justMoved = justMoved1;
- firstX = firstX1;
- firstY = firstY1;
- size = size1;
- n = n1;
- subpaths = (GfxSubpath **)gmalloc(size * sizeof(GfxSubpath *));
- for (i = 0; i < n; ++i)
- subpaths[i] = subpaths1[i]->copy();
-}
-
-void GfxPath::moveTo(double x, double y) {
- justMoved = gTrue;
- firstX = x;
- firstY = y;
-}
-
-void GfxPath::lineTo(double x, double y) {
- if (justMoved) {
- if (n >= size) {
- size += 16;
- subpaths = (GfxSubpath **)
- grealloc(subpaths, size * sizeof(GfxSubpath *));
- }
- subpaths[n] = new GfxSubpath(firstX, firstY);
- ++n;
- justMoved = gFalse;
- }
- subpaths[n-1]->lineTo(x, y);
-}
-
-void GfxPath::curveTo(double x1, double y1, double x2, double y2,
- double x3, double y3) {
- if (justMoved) {
- if (n >= size) {
- size += 16;
- subpaths = (GfxSubpath **)
- grealloc(subpaths, size * sizeof(GfxSubpath *));
- }
- subpaths[n] = new GfxSubpath(firstX, firstY);
- ++n;
- justMoved = gFalse;
- }
- subpaths[n-1]->curveTo(x1, y1, x2, y2, x3, y3);
-}
-
-void GfxPath::close() {
- // this is necessary to handle the pathological case of
- // moveto/closepath/clip, which defines an empty clipping region
- if (justMoved) {
- if (n >= size) {
- size += 16;
- subpaths = (GfxSubpath **)
- grealloc(subpaths, size * sizeof(GfxSubpath *));
- }
- subpaths[n] = new GfxSubpath(firstX, firstY);
- ++n;
- justMoved = gFalse;
- }
- subpaths[n-1]->close();
-}
-
-//------------------------------------------------------------------------
-// GfxState
-//------------------------------------------------------------------------
-
-GfxState::GfxState(double dpi, PDFRectangle *pageBox, int rotate,
- GBool upsideDown) {
- double k;
-
- px1 = pageBox->x1;
- py1 = pageBox->y1;
- px2 = pageBox->x2;
- py2 = pageBox->y2;
- k = dpi / 72.0;
- if (rotate == 90) {
- ctm[0] = 0;
- ctm[1] = upsideDown ? k : -k;
- ctm[2] = k;
- ctm[3] = 0;
- ctm[4] = -k * py1;
- ctm[5] = k * (upsideDown ? -px1 : px2);
- pageWidth = k * (py2 - py1);
- pageHeight = k * (px2 - px1);
- } else if (rotate == 180) {
- ctm[0] = -k;
- ctm[1] = 0;
- ctm[2] = 0;
- ctm[3] = upsideDown ? k : -k;
- ctm[4] = k * px2;
- ctm[5] = k * (upsideDown ? -py1 : py2);
- pageWidth = k * (px2 - px1);
- pageHeight = k * (py2 - py1);
- } else if (rotate == 270) {
- ctm[0] = 0;
- ctm[1] = upsideDown ? -k : k;
- ctm[2] = -k;
- ctm[3] = 0;
- ctm[4] = k * py2;
- ctm[5] = k * (upsideDown ? px2 : -px1);
- pageWidth = k * (py2 - py1);
- pageHeight = k * (px2 - px1);
- } else {
- ctm[0] = k;
- ctm[1] = 0;
- ctm[2] = 0;
- ctm[3] = upsideDown ? -k : k;
- ctm[4] = -k * px1;
- ctm[5] = k * (upsideDown ? py2 : -py1);
- pageWidth = k * (px2 - px1);
- pageHeight = k * (py2 - py1);
- }
-
- fillColorSpace = new GfxDeviceGrayColorSpace();
- strokeColorSpace = new GfxDeviceGrayColorSpace();
- fillColor.c[0] = 0;
- strokeColor.c[0] = 0;
- fillPattern = NULL;
- strokePattern = NULL;
- fillOpacity = 1;
- strokeOpacity = 1;
-
- lineWidth = 1;
- lineDash = NULL;
- lineDashLength = 0;
- lineDashStart = 0;
- flatness = 0;
- lineJoin = 0;
- lineCap = 0;
- miterLimit = 10;
-
- font = NULL;
- fontSize = 0;
- textMat[0] = 1; textMat[1] = 0;
- textMat[2] = 0; textMat[3] = 1;
- textMat[4] = 0; textMat[5] = 0;
- charSpace = 0;
- wordSpace = 0;
- horizScaling = 1;
- leading = 0;
- rise = 0;
- render = 0;
-
- path = new GfxPath();
- curX = curY = 0;
- lineX = lineY = 0;
-
- clipXMin = 0;
- clipYMin = 0;
- clipXMax = pageWidth;
- clipYMax = pageHeight;
-
- saved = NULL;
-}
-
-GfxState::~GfxState() {
- if (fillColorSpace) {
- delete fillColorSpace;
- }
- if (strokeColorSpace) {
- delete strokeColorSpace;
- }
- if (fillPattern) {
- delete fillPattern;
- }
- if (strokePattern) {
- delete strokePattern;
- }
- gfree(lineDash);
- if (path) {
- // this gets set to NULL by restore()
- delete path;
- }
- if (saved) {
- delete saved;
- }
-}
-
-// Used for copy();
-GfxState::GfxState(const GfxState *state) {
- memcpy(this, state, sizeof(GfxState));
- if (fillColorSpace) {
- fillColorSpace = state->fillColorSpace->copy();
- }
- if (strokeColorSpace) {
- strokeColorSpace = state->strokeColorSpace->copy();
- }
- if (fillPattern) {
- fillPattern = state->fillPattern->copy();
- }
- if (strokePattern) {
- strokePattern = state->strokePattern->copy();
- }
- if (lineDashLength > 0) {
- lineDash = (double *)gmalloc(lineDashLength * sizeof(double));
- memcpy(lineDash, state->lineDash, lineDashLength * sizeof(double));
- }
- saved = NULL;
-}
-
-void GfxState::getUserClipBBox(double *xMin, double *yMin,
- double *xMax, double *yMax) const {
- double ictm[6];
- double xMin1, yMin1, xMax1, yMax1, det, tx, ty;
-
- // invert the CTM
- det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
- ictm[0] = ctm[3] * det;
- ictm[1] = -ctm[1] * det;
- ictm[2] = -ctm[2] * det;
- ictm[3] = ctm[0] * det;
- ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
- ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
-
- // transform all four corners of the clip bbox; find the min and max
- // x and y values
- xMin1 = xMax1 = clipXMin * ictm[0] + clipYMin * ictm[2] + ictm[4];
- yMin1 = yMax1 = clipXMin * ictm[1] + clipYMin * ictm[3] + ictm[5];
- tx = clipXMin * ictm[0] + clipYMax * ictm[2] + ictm[4];
- ty = clipXMin * ictm[1] + clipYMax * ictm[3] + ictm[5];
- if (tx < xMin1) {
- xMin1 = tx;
- } else if (tx > xMax1) {
- xMax1 = tx;
- }
- if (ty < yMin1) {
- yMin1 = ty;
- } else if (ty > yMax1) {
- yMax1 = ty;
- }
- tx = clipXMax * ictm[0] + clipYMin * ictm[2] + ictm[4];
- ty = clipXMax * ictm[1] + clipYMin * ictm[3] + ictm[5];
- if (tx < xMin1) {
- xMin1 = tx;
- } else if (tx > xMax1) {
- xMax1 = tx;
- }
- if (ty < yMin1) {
- yMin1 = ty;
- } else if (ty > yMax1) {
- yMax1 = ty;
- }
- tx = clipXMax * ictm[0] + clipYMax * ictm[2] + ictm[4];
- ty = clipXMax * ictm[1] + clipYMax * ictm[3] + ictm[5];
- if (tx < xMin1) {
- xMin1 = tx;
- } else if (tx > xMax1) {
- xMax1 = tx;
- }
- if (ty < yMin1) {
- yMin1 = ty;
- } else if (ty > yMax1) {
- yMax1 = ty;
- }
-
- *xMin = xMin1;
- *yMin = yMin1;
- *xMax = xMax1;
- *yMax = yMax1;
-}
-
-double GfxState::transformWidth(double w) {
- double x, y;
-
- x = ctm[0] + ctm[2];
- y = ctm[1] + ctm[3];
- return w * sqrt(0.5 * (x * x + y * y));
-}
-
-double GfxState::getTransformedFontSize() {
- double x1, y1, x2, y2;
-
- x1 = textMat[2] * fontSize;
- y1 = textMat[3] * fontSize;
- x2 = ctm[0] * x1 + ctm[2] * y1;
- y2 = ctm[1] * x1 + ctm[3] * y1;
- return sqrt(x2 * x2 + y2 * y2);
-}
-
-void GfxState::getFontTransMat(double *m11, double *m12,
- double *m21, double *m22) {
- *m11 = (textMat[0] * ctm[0] + textMat[1] * ctm[2]) * fontSize;
- *m12 = (textMat[0] * ctm[1] + textMat[1] * ctm[3]) * fontSize;
- *m21 = (textMat[2] * ctm[0] + textMat[3] * ctm[2]) * fontSize;
- *m22 = (textMat[2] * ctm[1] + textMat[3] * ctm[3]) * fontSize;
-}
-
-void GfxState::setCTM(double a, double b, double c,
- double d, double e, double f) {
- int i;
-
- ctm[0] = a;
- ctm[1] = b;
- ctm[2] = c;
- ctm[3] = d;
- ctm[4] = e;
- ctm[5] = f;
-
- // avoid FP exceptions on badly messed up PDF files
- for (i = 0; i < 6; ++i) {
- if (ctm[i] > 1e10) {
- ctm[i] = 1e10;
- } else if (ctm[i] < -1e10) {
- ctm[i] = -1e10;
- }
- }
-}
-
-void GfxState::concatCTM(double a, double b, double c,
- double d, double e, double f) {
- double a1 = ctm[0];
- double b1 = ctm[1];
- double c1 = ctm[2];
- double d1 = ctm[3];
- int i;
-
- ctm[0] = a * a1 + b * c1;
- ctm[1] = a * b1 + b * d1;
- ctm[2] = c * a1 + d * c1;
- ctm[3] = c * b1 + d * d1;
- ctm[4] = e * a1 + f * c1 + ctm[4];
- ctm[5] = e * b1 + f * d1 + ctm[5];
-
- // avoid FP exceptions on badly messed up PDF files
- for (i = 0; i < 6; ++i) {
- if (ctm[i] > 1e10) {
- ctm[i] = 1e10;
- } else if (ctm[i] < -1e10) {
- ctm[i] = -1e10;
- }
- }
-}
-
-void GfxState::setFillColorSpace(GfxColorSpace *colorSpace) {
- if (fillColorSpace) {
- delete fillColorSpace;
- }
- fillColorSpace = colorSpace;
-}
-
-void GfxState::setStrokeColorSpace(GfxColorSpace *colorSpace) {
- if (strokeColorSpace) {
- delete strokeColorSpace;
- }
- strokeColorSpace = colorSpace;
-}
-
-void GfxState::setFillPattern(GfxPattern *pattern) {
- if (fillPattern) {
- delete fillPattern;
- }
- fillPattern = pattern;
-}
-
-void GfxState::setStrokePattern(GfxPattern *pattern) {
- if (strokePattern) {
- delete strokePattern;
- }
- strokePattern = pattern;
-}
-
-void GfxState::setLineDash(double *dash, int length, double start) {
- if (lineDash)
- gfree(lineDash);
- lineDash = dash;
- lineDashLength = length;
- lineDashStart = start;
-}
-
-void GfxState::clearPath() {
- delete path;
- path = new GfxPath();
-}
-
-void GfxState::clip() {
- double xMin, yMin, xMax, yMax, x, y;
- GfxSubpath *subpath;
- int i, j;
-
- xMin = xMax = yMin = yMax = 0; // make gcc happy
- for (i = 0; i < path->getNumSubpaths(); ++i) {
- subpath = path->getSubpath(i);
- for (j = 0; j < subpath->getNumPoints(); ++j) {
- transform(subpath->getX(j), subpath->getY(j), &x, &y);
- if (i == 0 && j == 0) {
- xMin = xMax = x;
- yMin = yMax = y;
- } else {
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- }
- }
- }
- if (xMin > clipXMin) {
- clipXMin = xMin;
- }
- if (yMin > clipYMin) {
- clipYMin = yMin;
- }
- if (xMax < clipXMax) {
- clipXMax = xMax;
- }
- if (yMax < clipYMax) {
- clipYMax = yMax;
- }
-}
-
-void GfxState::textShift(double tx, double ty) {
- double dx, dy;
-
- textTransformDelta(tx, ty, &dx, &dy);
- curX += dx;
- curY += dy;
-}
-
-void GfxState::shift(double dx, double dy) {
- curX += dx;
- curY += dy;
-}
-
-GfxState *GfxState::save() {
- GfxState *newState;
-
- newState = copy();
- newState->saved = this;
- return newState;
-}
-
-GfxState *GfxState::restore() {
- GfxState *oldState;
-
- if (saved) {
- oldState = saved;
-
- // these attributes aren't saved/restored by the q/Q operators
- oldState->path = path;
- oldState->curX = curX;
- oldState->curY = curY;
- oldState->lineX = lineX;
- oldState->lineY = lineY;
-
- path = NULL;
- saved = NULL;
- delete this;
-
- } else {
- oldState = this;
- }
-
- return oldState;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/GfxState.cpp b/filters/kword/pdf/xpdf/xpdf/GfxState.cpp
new file mode 100644
index 000000000..866e692f1
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/GfxState.cpp
@@ -0,0 +1,2338 @@
+//========================================================================
+//
+// GfxState.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include <math.h>
+#include <string.h> // for memcpy()
+#include "gmem.h"
+#include "Error.h"
+#include "Object.h"
+#include "Array.h"
+#include "Page.h"
+#include "GfxState.h"
+
+//------------------------------------------------------------------------
+
+static inline double clip01(double x) {
+ return (x < 0) ? 0 : ((x > 1) ? 1 : x);
+}
+
+//------------------------------------------------------------------------
+// GfxColorSpace
+//------------------------------------------------------------------------
+
+GfxColorSpace::GfxColorSpace() {
+}
+
+GfxColorSpace::~GfxColorSpace() {
+}
+
+GfxColorSpace *GfxColorSpace::parse(Object *csObj) {
+ GfxColorSpace *cs;
+ Object obj1;
+
+ cs = NULL;
+ if (csObj->isName()) {
+ if (csObj->isName("DeviceGray") || csObj->isName("G")) {
+ cs = new GfxDeviceGrayColorSpace();
+ } else if (csObj->isName("DeviceRGB") || csObj->isName("RGB")) {
+ cs = new GfxDeviceRGBColorSpace();
+ } else if (csObj->isName("DeviceCMYK") || csObj->isName("CMYK")) {
+ cs = new GfxDeviceCMYKColorSpace();
+ } else if (csObj->isName("Pattern")) {
+ cs = new GfxPatternColorSpace(NULL);
+ } else {
+ error(-1, "Bad color space '%s'", csObj->getName());
+ }
+ } else if (csObj->isArray()) {
+ csObj->arrayGet(0, &obj1);
+ if (obj1.isName("DeviceGray") || obj1.isName("G")) {
+ cs = new GfxDeviceGrayColorSpace();
+ } else if (obj1.isName("DeviceRGB") || obj1.isName("RGB")) {
+ cs = new GfxDeviceRGBColorSpace();
+ } else if (obj1.isName("DeviceCMYK") || obj1.isName("CMYK")) {
+ cs = new GfxDeviceCMYKColorSpace();
+ } else if (obj1.isName("CalGray")) {
+ cs = GfxCalGrayColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("CalRGB")) {
+ cs = GfxCalRGBColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("Lab")) {
+ cs = GfxLabColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("ICCBased")) {
+ cs = GfxICCBasedColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("Indexed") || obj1.isName("I")) {
+ cs = GfxIndexedColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("Separation")) {
+ cs = GfxSeparationColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("DeviceN")) {
+ cs = GfxDeviceNColorSpace::parse(csObj->getArray());
+ } else if (obj1.isName("Pattern")) {
+ cs = GfxPatternColorSpace::parse(csObj->getArray());
+ } else {
+ error(-1, "Bad color space '%s'", csObj->getName());
+ }
+ obj1.free();
+ } else {
+ error(-1, "Bad color space - expected name or array");
+ }
+ return cs;
+}
+
+void GfxColorSpace::getDefaultRanges(double *decodeLow, double *decodeRange,
+ int /*maxImgPixel*/) const {
+ int i;
+
+ for (i = 0; i < getNComps(); ++i) {
+ decodeLow[i] = 0;
+ decodeRange[i] = 1;
+ }
+}
+
+//------------------------------------------------------------------------
+// GfxDeviceGrayColorSpace
+//------------------------------------------------------------------------
+
+GfxDeviceGrayColorSpace::GfxDeviceGrayColorSpace() {
+}
+
+GfxDeviceGrayColorSpace::~GfxDeviceGrayColorSpace() {
+}
+
+GfxColorSpace *GfxDeviceGrayColorSpace::copy() const {
+ return new GfxDeviceGrayColorSpace();
+}
+
+void GfxDeviceGrayColorSpace::getGray(const GfxColor *color, double *gray) const {
+ *gray = clip01(color->c[0]);
+}
+
+void GfxDeviceGrayColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ rgb->r = rgb->g = rgb->b = clip01(color->c[0]);
+}
+
+void GfxDeviceGrayColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ cmyk->c = cmyk->m = cmyk->y = 0;
+ cmyk->k = clip01(1 - color->c[0]);
+}
+
+//------------------------------------------------------------------------
+// GfxCalGrayColorSpace
+//------------------------------------------------------------------------
+
+GfxCalGrayColorSpace::GfxCalGrayColorSpace() {
+ whiteX = whiteY = whiteZ = 1;
+ blackX = blackY = blackZ = 0;
+ gamma = 1;
+}
+
+GfxCalGrayColorSpace::~GfxCalGrayColorSpace() {
+}
+
+GfxColorSpace *GfxCalGrayColorSpace::copy() const {
+ GfxCalGrayColorSpace *cs;
+
+ cs = new GfxCalGrayColorSpace();
+ cs->whiteX = whiteX;
+ cs->whiteY = whiteY;
+ cs->whiteZ = whiteZ;
+ cs->blackX = blackX;
+ cs->blackY = blackY;
+ cs->blackZ = blackZ;
+ cs->gamma = gamma;
+ return cs;
+}
+
+GfxColorSpace *GfxCalGrayColorSpace::parse(Array *arr) {
+ GfxCalGrayColorSpace *cs;
+ Object obj1, obj2, obj3;
+
+ arr->get(1, &obj1);
+ if (!obj1.isDict()) {
+ error(-1, "Bad CalGray color space");
+ obj1.free();
+ return NULL;
+ }
+ cs = new GfxCalGrayColorSpace();
+ if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->whiteX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->whiteY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->whiteZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->blackX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->blackY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->blackZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("Gamma", &obj2)->isNum()) {
+ cs->gamma = obj2.getNum();
+ }
+ obj2.free();
+ obj1.free();
+ return cs;
+}
+
+void GfxCalGrayColorSpace::getGray(const GfxColor *color, double *gray) const {
+ *gray = clip01(color->c[0]);
+}
+
+void GfxCalGrayColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ rgb->r = rgb->g = rgb->b = clip01(color->c[0]);
+}
+
+void GfxCalGrayColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ cmyk->c = cmyk->m = cmyk->y = 0;
+ cmyk->k = clip01(1 - color->c[0]);
+}
+
+//------------------------------------------------------------------------
+// GfxDeviceRGBColorSpace
+//------------------------------------------------------------------------
+
+GfxDeviceRGBColorSpace::GfxDeviceRGBColorSpace() {
+}
+
+GfxDeviceRGBColorSpace::~GfxDeviceRGBColorSpace() {
+}
+
+GfxColorSpace *GfxDeviceRGBColorSpace::copy() const {
+ return new GfxDeviceRGBColorSpace();
+}
+
+void GfxDeviceRGBColorSpace::getGray(const GfxColor *color, double *gray) const {
+ *gray = clip01(0.299 * color->c[0] +
+ 0.587 * color->c[1] +
+ 0.114 * color->c[2]);
+}
+
+void GfxDeviceRGBColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ rgb->r = clip01(color->c[0]);
+ rgb->g = clip01(color->c[1]);
+ rgb->b = clip01(color->c[2]);
+}
+
+void GfxDeviceRGBColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ double c, m, y, k;
+
+ c = clip01(1 - color->c[0]);
+ m = clip01(1 - color->c[1]);
+ y = clip01(1 - color->c[2]);
+ k = c;
+ if (m < k) {
+ k = m;
+ }
+ if (y < k) {
+ k = y;
+ }
+ cmyk->c = c - k;
+ cmyk->m = m - k;
+ cmyk->y = y - k;
+ cmyk->k = k;
+}
+
+//------------------------------------------------------------------------
+// GfxCalRGBColorSpace
+//------------------------------------------------------------------------
+
+GfxCalRGBColorSpace::GfxCalRGBColorSpace() {
+ whiteX = whiteY = whiteZ = 1;
+ blackX = blackY = blackZ = 0;
+ gammaR = gammaG = gammaB = 1;
+ mat[0] = 1; mat[1] = 0; mat[2] = 0;
+ mat[3] = 0; mat[4] = 1; mat[5] = 0;
+ mat[6] = 0; mat[7] = 0; mat[8] = 1;
+}
+
+GfxCalRGBColorSpace::~GfxCalRGBColorSpace() {
+}
+
+GfxColorSpace *GfxCalRGBColorSpace::copy() const {
+ GfxCalRGBColorSpace *cs;
+ int i;
+
+ cs = new GfxCalRGBColorSpace();
+ cs->whiteX = whiteX;
+ cs->whiteY = whiteY;
+ cs->whiteZ = whiteZ;
+ cs->blackX = blackX;
+ cs->blackY = blackY;
+ cs->blackZ = blackZ;
+ cs->gammaR = gammaR;
+ cs->gammaG = gammaG;
+ cs->gammaB = gammaB;
+ for (i = 0; i < 9; ++i) {
+ cs->mat[i] = mat[i];
+ }
+ return cs;
+}
+
+GfxColorSpace *GfxCalRGBColorSpace::parse(Array *arr) {
+ GfxCalRGBColorSpace *cs;
+ Object obj1, obj2, obj3;
+ int i;
+
+ arr->get(1, &obj1);
+ if (!obj1.isDict()) {
+ error(-1, "Bad CalRGB color space");
+ obj1.free();
+ return NULL;
+ }
+ cs = new GfxCalRGBColorSpace();
+ if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->whiteX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->whiteY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->whiteZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->blackX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->blackY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->blackZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("Gamma", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->gammaR = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->gammaG = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->gammaB = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("Matrix", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 9) {
+ for (i = 0; i < 9; ++i) {
+ obj2.arrayGet(i, &obj3);
+ cs->mat[i] = obj3.getNum();
+ obj3.free();
+ }
+ }
+ obj2.free();
+ obj1.free();
+ return cs;
+}
+
+void GfxCalRGBColorSpace::getGray(const GfxColor *color, double *gray) const {
+ *gray = clip01(0.299 * color->c[0] +
+ 0.587 * color->c[1] +
+ 0.114 * color->c[2]);
+}
+
+void GfxCalRGBColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ rgb->r = clip01(color->c[0]);
+ rgb->g = clip01(color->c[1]);
+ rgb->b = clip01(color->c[2]);
+}
+
+void GfxCalRGBColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ double c, m, y, k;
+
+ c = clip01(1 - color->c[0]);
+ m = clip01(1 - color->c[1]);
+ y = clip01(1 - color->c[2]);
+ k = c;
+ if (m < k) {
+ k = m;
+ }
+ if (y < k) {
+ k = y;
+ }
+ cmyk->c = c - k;
+ cmyk->m = m - k;
+ cmyk->y = y - k;
+ cmyk->k = k;
+}
+
+//------------------------------------------------------------------------
+// GfxDeviceCMYKColorSpace
+//------------------------------------------------------------------------
+
+GfxDeviceCMYKColorSpace::GfxDeviceCMYKColorSpace() {
+}
+
+GfxDeviceCMYKColorSpace::~GfxDeviceCMYKColorSpace() {
+}
+
+GfxColorSpace *GfxDeviceCMYKColorSpace::copy() const {
+ return new GfxDeviceCMYKColorSpace();
+}
+
+void GfxDeviceCMYKColorSpace::getGray(const GfxColor *color, double *gray) const {
+ *gray = clip01(1 - color->c[3]
+ - 0.299 * color->c[0]
+ - 0.587 * color->c[1]
+ - 0.114 * color->c[2]);
+}
+
+void GfxDeviceCMYKColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ double c, m, y, aw, ac, am, ay, ar, ag, ab;
+
+ c = clip01(color->c[0] + color->c[3]);
+ m = clip01(color->c[1] + color->c[3]);
+ y = clip01(color->c[2] + color->c[3]);
+ aw = (1-c) * (1-m) * (1-y);
+ ac = c * (1-m) * (1-y);
+ am = (1-c) * m * (1-y);
+ ay = (1-c) * (1-m) * y;
+ ar = (1-c) * m * y;
+ ag = c * (1-m) * y;
+ ab = c * m * (1-y);
+ rgb->r = clip01(aw + 0.9137*am + 0.9961*ay + 0.9882*ar);
+ rgb->g = clip01(aw + 0.6196*ac + ay + 0.5176*ag);
+ rgb->b = clip01(aw + 0.7804*ac + 0.5412*am + 0.0667*ar + 0.2118*ag +
+ 0.4863*ab);
+}
+
+void GfxDeviceCMYKColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ cmyk->c = clip01(color->c[0]);
+ cmyk->m = clip01(color->c[1]);
+ cmyk->y = clip01(color->c[2]);
+ cmyk->k = clip01(color->c[3]);
+}
+
+//------------------------------------------------------------------------
+// GfxLabColorSpace
+//------------------------------------------------------------------------
+
+// This is the inverse of MatrixLMN in Example 4.10 from the PostScript
+// Language Reference, Third Edition.
+static double xyzrgb[3][3] = {
+ { 3.240449, -1.537136, -0.498531 },
+ { -0.969265, 1.876011, 0.041556 },
+ { 0.055643, -0.204026, 1.057229 }
+};
+
+GfxLabColorSpace::GfxLabColorSpace() {
+ whiteX = whiteY = whiteZ = 1;
+ blackX = blackY = blackZ = 0;
+ aMin = bMin = -100;
+ aMax = bMax = 100;
+}
+
+GfxLabColorSpace::~GfxLabColorSpace() {
+}
+
+GfxColorSpace *GfxLabColorSpace::copy() const {
+ GfxLabColorSpace *cs;
+
+ cs = new GfxLabColorSpace();
+ cs->whiteX = whiteX;
+ cs->whiteY = whiteY;
+ cs->whiteZ = whiteZ;
+ cs->blackX = blackX;
+ cs->blackY = blackY;
+ cs->blackZ = blackZ;
+ cs->aMin = aMin;
+ cs->aMax = aMax;
+ cs->bMin = bMin;
+ cs->bMax = bMax;
+ cs->kr = kr;
+ cs->kg = kg;
+ cs->kb = kb;
+ return cs;
+}
+
+GfxColorSpace *GfxLabColorSpace::parse(Array *arr) {
+ GfxLabColorSpace *cs;
+ Object obj1, obj2, obj3;
+
+ arr->get(1, &obj1);
+ if (!obj1.isDict()) {
+ error(-1, "Bad Lab color space");
+ obj1.free();
+ return NULL;
+ }
+ cs = new GfxLabColorSpace();
+ if (obj1.dictLookup("WhitePoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->whiteX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->whiteY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->whiteZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("BlackPoint", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 3) {
+ obj2.arrayGet(0, &obj3);
+ cs->blackX = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->blackY = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->blackZ = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ if (obj1.dictLookup("Range", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 4) {
+ obj2.arrayGet(0, &obj3);
+ cs->aMin = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(1, &obj3);
+ cs->aMax = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2, &obj3);
+ cs->bMin = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(3, &obj3);
+ cs->bMax = obj3.getNum();
+ obj3.free();
+ }
+ obj2.free();
+ obj1.free();
+
+ cs->kr = 1 / (xyzrgb[0][0] * cs->whiteX +
+ xyzrgb[0][1] * cs->whiteY +
+ xyzrgb[0][2] * cs->whiteZ);
+ cs->kg = 1 / (xyzrgb[1][0] * cs->whiteX +
+ xyzrgb[1][1] * cs->whiteY +
+ xyzrgb[1][2] * cs->whiteZ);
+ cs->kb = 1 / (xyzrgb[2][0] * cs->whiteX +
+ xyzrgb[2][1] * cs->whiteY +
+ xyzrgb[2][2] * cs->whiteZ);
+
+ return cs;
+}
+
+void GfxLabColorSpace::getGray(const GfxColor *color, double *gray) const {
+ GfxRGB rgb;
+
+ getRGB(color, &rgb);
+ *gray = clip01(0.299 * rgb.r +
+ 0.587 * rgb.g +
+ 0.114 * rgb.b);
+}
+
+void GfxLabColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ double X, Y, Z;
+ double t1, t2;
+ double r, g, b;
+
+ // convert L*a*b* to CIE 1931 XYZ color space
+ t1 = (color->c[0] + 16) / 116;
+ t2 = t1 + color->c[1] / 500;
+ if (t2 >= (6.0 / 29.0)) {
+ X = t2 * t2 * t2;
+ } else {
+ X = (108.0 / 841.0) * (t2 - (4.0 / 29.0));
+ }
+ X *= whiteX;
+ if (t1 >= (6.0 / 29.0)) {
+ Y = t1 * t1 * t1;
+ } else {
+ Y = (108.0 / 841.0) * (t1 - (4.0 / 29.0));
+ }
+ Y *= whiteY;
+ t2 = t1 - color->c[2] / 200;
+ if (t2 >= (6.0 / 29.0)) {
+ Z = t2 * t2 * t2;
+ } else {
+ Z = (108.0 / 841.0) * (t2 - (4.0 / 29.0));
+ }
+ Z *= whiteZ;
+
+ // convert XYZ to RGB, including gamut mapping and gamma correction
+ r = xyzrgb[0][0] * X + xyzrgb[0][1] * Y + xyzrgb[0][2] * Z;
+ g = xyzrgb[1][0] * X + xyzrgb[1][1] * Y + xyzrgb[1][2] * Z;
+ b = xyzrgb[2][0] * X + xyzrgb[2][1] * Y + xyzrgb[2][2] * Z;
+ rgb->r = pow(clip01(r * kr), 0.5);
+ rgb->g = pow(clip01(g * kg), 0.5);
+ rgb->b = pow(clip01(b * kb), 0.5);
+}
+
+void GfxLabColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ GfxRGB rgb;
+ double c, m, y, k;
+
+ getRGB(color, &rgb);
+ c = clip01(1 - rgb.r);
+ m = clip01(1 - rgb.g);
+ y = clip01(1 - rgb.b);
+ k = c;
+ if (m < k) {
+ k = m;
+ }
+ if (y < k) {
+ k = y;
+ }
+ cmyk->c = c - k;
+ cmyk->m = m - k;
+ cmyk->y = y - k;
+ cmyk->k = k;
+}
+
+void GfxLabColorSpace::getDefaultRanges(double *decodeLow, double *decodeRange,
+ int /*maxImgPixel*/) const {
+ decodeLow[0] = 0;
+ decodeRange[0] = 100;
+ decodeLow[1] = aMin;
+ decodeRange[1] = aMax - aMin;
+ decodeLow[2] = bMin;
+ decodeRange[2] = bMax - bMin;
+}
+
+//------------------------------------------------------------------------
+// GfxICCBasedColorSpace
+//------------------------------------------------------------------------
+
+GfxICCBasedColorSpace::GfxICCBasedColorSpace(int nCompsA, GfxColorSpace *altA,
+ const Ref *iccProfileStreamA) {
+ nComps = nCompsA;
+ alt = altA;
+ iccProfileStream = *iccProfileStreamA;
+ rangeMin[0] = rangeMin[1] = rangeMin[2] = rangeMin[3] = 0;
+ rangeMax[0] = rangeMax[1] = rangeMax[2] = rangeMax[3] = 1;
+}
+
+GfxICCBasedColorSpace::~GfxICCBasedColorSpace() {
+ delete alt;
+}
+
+GfxColorSpace *GfxICCBasedColorSpace::copy() const {
+ GfxICCBasedColorSpace *cs;
+ int i;
+
+ cs = new GfxICCBasedColorSpace(nComps, alt->copy(), &iccProfileStream);
+ for (i = 0; i < 4; ++i) {
+ cs->rangeMin[i] = rangeMin[i];
+ cs->rangeMax[i] = rangeMax[i];
+ }
+ return cs;
+}
+
+GfxColorSpace *GfxICCBasedColorSpace::parse(Array *arr) {
+ GfxICCBasedColorSpace *cs;
+ Ref iccProfileStreamA;
+ int nCompsA;
+ GfxColorSpace *altA;
+ Dict *dict;
+ Object obj1, obj2, obj3;
+ int i;
+
+ arr->getNF(1, &obj1);
+ if (obj1.isRef()) {
+ iccProfileStreamA = obj1.getRef();
+ } else {
+ iccProfileStreamA.num = 0;
+ iccProfileStreamA.gen = 0;
+ }
+ obj1.free();
+ arr->get(1, &obj1);
+ if (!obj1.isStream()) {
+ error(-1, "Bad ICCBased color space (stream)");
+ obj1.free();
+ return NULL;
+ }
+ dict = obj1.streamGetDict();
+ if (!dict->lookup("N", &obj2)->isInt()) {
+ error(-1, "Bad ICCBased color space (N)");
+ obj2.free();
+ obj1.free();
+ return NULL;
+ }
+ nCompsA = obj2.getInt();
+ obj2.free();
+ if (nCompsA > gfxColorMaxComps) {
+ error(-1, "ICCBased color space with too many (%d > %d) components",
+ nCompsA, gfxColorMaxComps);
+ nCompsA = gfxColorMaxComps;
+ }
+ if (dict->lookup("Alternate", &obj2)->isNull() ||
+ !(altA = GfxColorSpace::parse(&obj2))) {
+ switch (nCompsA) {
+ case 1:
+ altA = new GfxDeviceGrayColorSpace();
+ break;
+ case 3:
+ altA = new GfxDeviceRGBColorSpace();
+ break;
+ case 4:
+ altA = new GfxDeviceCMYKColorSpace();
+ break;
+ default:
+ error(-1, "Bad ICCBased color space - invalid N");
+ obj2.free();
+ obj1.free();
+ return NULL;
+ }
+ }
+ obj2.free();
+ cs = new GfxICCBasedColorSpace(nCompsA, altA, &iccProfileStreamA);
+ if (dict->lookup("Range", &obj2)->isArray() &&
+ obj2.arrayGetLength() == 2 * nCompsA) {
+ for (i = 0; i < nCompsA; ++i) {
+ obj2.arrayGet(2*i, &obj3);
+ cs->rangeMin[i] = obj3.getNum();
+ obj3.free();
+ obj2.arrayGet(2*i+1, &obj3);
+ cs->rangeMax[i] = obj3.getNum();
+ obj3.free();
+ }
+ }
+ obj2.free();
+ obj1.free();
+ return cs;
+}
+
+void GfxICCBasedColorSpace::getGray(const GfxColor *color, double *gray) const {
+ alt->getGray(color, gray);
+}
+
+void GfxICCBasedColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ alt->getRGB(color, rgb);
+}
+
+void GfxICCBasedColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ alt->getCMYK(color, cmyk);
+}
+
+void GfxICCBasedColorSpace::getDefaultRanges(double *decodeLow,
+ double *decodeRange,
+ int /*maxImgPixel*/) const {
+ int i;
+
+ for (i = 0; i < nComps; ++i) {
+ decodeLow[i] = rangeMin[i];
+ decodeRange[i] = rangeMax[i] - rangeMin[i];
+ }
+}
+
+//------------------------------------------------------------------------
+// GfxIndexedColorSpace
+//------------------------------------------------------------------------
+
+GfxIndexedColorSpace::GfxIndexedColorSpace(GfxColorSpace *baseA,
+ int indexHighA) {
+ base = baseA;
+ indexHigh = indexHighA;
+ lookup = (Guchar *)gmalloc((indexHigh + 1) * base->getNComps() *
+ sizeof(Guchar));
+}
+
+GfxIndexedColorSpace::~GfxIndexedColorSpace() {
+ delete base;
+ gfree(lookup);
+}
+
+GfxColorSpace *GfxIndexedColorSpace::copy() const {
+ GfxIndexedColorSpace *cs;
+
+ cs = new GfxIndexedColorSpace(base->copy(), indexHigh);
+ memcpy(cs->lookup, lookup,
+ (indexHigh + 1) * base->getNComps() * sizeof(Guchar));
+ return cs;
+}
+
+GfxColorSpace *GfxIndexedColorSpace::parse(Array *arr) {
+ GfxIndexedColorSpace *cs;
+ GfxColorSpace *baseA;
+ int indexHighA;
+ Object obj1;
+ int x;
+ char *s;
+ int n, i, j;
+
+ if (arr->getLength() != 4) {
+ error(-1, "Bad Indexed color space");
+ goto err1;
+ }
+ arr->get(1, &obj1);
+ if (!(baseA = GfxColorSpace::parse(&obj1))) {
+ error(-1, "Bad Indexed color space (base color space)");
+ goto err2;
+ }
+ obj1.free();
+ if (!arr->get(2, &obj1)->isInt()) {
+ error(-1, "Bad Indexed color space (hival)");
+ goto err2;
+ }
+ indexHighA = obj1.getInt();
+ obj1.free();
+ cs = new GfxIndexedColorSpace(baseA, indexHighA);
+ arr->get(3, &obj1);
+ n = baseA->getNComps();
+ if (obj1.isStream()) {
+ obj1.streamReset();
+ for (i = 0; i <= indexHighA; ++i) {
+ for (j = 0; j < n; ++j) {
+ if ((x = obj1.streamGetChar()) == EOF) {
+ error(-1, "Bad Indexed color space (lookup table stream too short)");
+ goto err3;
+ }
+ cs->lookup[i*n + j] = (Guchar)x;
+ }
+ }
+ obj1.streamClose();
+ } else if (obj1.isString()) {
+ if (obj1.getString()->getLength() < (indexHighA + 1) * n) {
+ error(-1, "Bad Indexed color space (lookup table string too short)");
+ goto err3;
+ }
+ s = obj1.getString()->getCString();
+ for (i = 0; i <= indexHighA; ++i) {
+ for (j = 0; j < n; ++j) {
+ cs->lookup[i*n + j] = (Guchar)*s++;
+ }
+ }
+ } else {
+ error(-1, "Bad Indexed color space (lookup table)");
+ goto err3;
+ }
+ obj1.free();
+ return cs;
+
+ err3:
+ delete cs;
+ err2:
+ obj1.free();
+ err1:
+ return NULL;
+}
+
+void GfxIndexedColorSpace::getGray(const GfxColor *color, double *gray) const {
+ Guchar *p;
+ GfxColor color2;
+ double low[gfxColorMaxComps], range[gfxColorMaxComps];
+ int n, i;
+
+ n = base->getNComps();
+ base->getDefaultRanges(low, range, indexHigh);
+ p = &lookup[(int)(color->c[0] + 0.5) * n];
+ for (i = 0; i < n; ++i) {
+ color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
+ }
+ base->getGray(&color2, gray);
+}
+
+void GfxIndexedColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ Guchar *p;
+ GfxColor color2;
+ double low[gfxColorMaxComps], range[gfxColorMaxComps];
+ int n, i;
+
+ n = base->getNComps();
+ base->getDefaultRanges(low, range, indexHigh);
+ p = &lookup[(int)(color->c[0] + 0.5) * n];
+ for (i = 0; i < n; ++i) {
+ color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
+ }
+ base->getRGB(&color2, rgb);
+}
+
+void GfxIndexedColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ Guchar *p;
+ GfxColor color2;
+ double low[gfxColorMaxComps], range[gfxColorMaxComps];
+ int n, i;
+
+ n = base->getNComps();
+ base->getDefaultRanges(low, range, indexHigh);
+ p = &lookup[(int)(color->c[0] + 0.5) * n];
+ for (i = 0; i < n; ++i) {
+ color2.c[i] = low[i] + (p[i] / 255.0) * range[i];
+ }
+ base->getCMYK(&color2, cmyk);
+}
+
+void GfxIndexedColorSpace::getDefaultRanges(double *decodeLow,
+ double *decodeRange,
+ int maxImgPixel) const {
+ decodeLow[0] = 0;
+ decodeRange[0] = maxImgPixel;
+}
+
+//------------------------------------------------------------------------
+// GfxSeparationColorSpace
+//------------------------------------------------------------------------
+
+GfxSeparationColorSpace::GfxSeparationColorSpace(GString *nameA,
+ GfxColorSpace *altA,
+ Function *funcA) {
+ name = nameA;
+ alt = altA;
+ func = funcA;
+}
+
+GfxSeparationColorSpace::~GfxSeparationColorSpace() {
+ delete name;
+ delete alt;
+ delete func;
+}
+
+GfxColorSpace *GfxSeparationColorSpace::copy() const {
+ return new GfxSeparationColorSpace(name->copy(), alt->copy(), func->copy());
+}
+
+//~ handle the 'All' and 'None' colorants
+GfxColorSpace *GfxSeparationColorSpace::parse(Array *arr) {
+ GfxSeparationColorSpace *cs;
+ GString *nameA;
+ GfxColorSpace *altA;
+ Function *funcA;
+ Object obj1;
+
+ if (arr->getLength() != 4) {
+ error(-1, "Bad Separation color space");
+ goto err1;
+ }
+ if (!arr->get(1, &obj1)->isName()) {
+ error(-1, "Bad Separation color space (name)");
+ goto err2;
+ }
+ nameA = new GString(obj1.getName());
+ obj1.free();
+ arr->get(2, &obj1);
+ if (!(altA = GfxColorSpace::parse(&obj1))) {
+ error(-1, "Bad Separation color space (alternate color space)");
+ goto err3;
+ }
+ obj1.free();
+ arr->get(3, &obj1);
+ if (!(funcA = Function::parse(&obj1))) {
+ goto err4;
+ }
+ obj1.free();
+ cs = new GfxSeparationColorSpace(nameA, altA, funcA);
+ return cs;
+
+ err4:
+ delete altA;
+ err3:
+ delete nameA;
+ err2:
+ obj1.free();
+ err1:
+ return NULL;
+}
+
+void GfxSeparationColorSpace::getGray(const GfxColor *color, double *gray) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getGray(&color2, gray);
+}
+
+void GfxSeparationColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getRGB(&color2, rgb);
+}
+
+void GfxSeparationColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getCMYK(&color2, cmyk);
+}
+
+//------------------------------------------------------------------------
+// GfxDeviceNColorSpace
+//------------------------------------------------------------------------
+
+GfxDeviceNColorSpace::GfxDeviceNColorSpace(int nCompsA,
+ GfxColorSpace *altA,
+ Function *funcA) {
+ nComps = nCompsA;
+ alt = altA;
+ func = funcA;
+}
+
+GfxDeviceNColorSpace::~GfxDeviceNColorSpace() {
+ int i;
+
+ for (i = 0; i < nComps; ++i) {
+ delete names[i];
+ }
+ delete alt;
+ delete func;
+}
+
+GfxColorSpace *GfxDeviceNColorSpace::copy() const {
+ GfxDeviceNColorSpace *cs;
+ int i;
+
+ cs = new GfxDeviceNColorSpace(nComps, alt->copy(), func->copy());
+ for (i = 0; i < nComps; ++i) {
+ cs->names[i] = names[i]->copy();
+ }
+ return cs;
+}
+
+//~ handle the 'None' colorant
+GfxColorSpace *GfxDeviceNColorSpace::parse(Array *arr) {
+ GfxDeviceNColorSpace *cs;
+ int nCompsA;
+ GString *namesA[gfxColorMaxComps];
+ GfxColorSpace *altA;
+ Function *funcA;
+ Object obj1, obj2;
+ int i;
+
+ if (arr->getLength() != 4 && arr->getLength() != 5) {
+ error(-1, "Bad DeviceN color space");
+ goto err1;
+ }
+ if (!arr->get(1, &obj1)->isArray()) {
+ error(-1, "Bad DeviceN color space (names)");
+ goto err2;
+ }
+ nCompsA = obj1.arrayGetLength();
+ if (nCompsA > gfxColorMaxComps) {
+ error(-1, "DeviceN color space with too many (%d > %d) components",
+ nCompsA, gfxColorMaxComps);
+ nCompsA = gfxColorMaxComps;
+ }
+ for (i = 0; i < nCompsA; ++i) {
+ if (!obj1.arrayGet(i, &obj2)->isName()) {
+ error(-1, "Bad DeviceN color space (names)");
+ obj2.free();
+ goto err2;
+ }
+ namesA[i] = new GString(obj2.getName());
+ obj2.free();
+ }
+ obj1.free();
+ arr->get(2, &obj1);
+ if (!(altA = GfxColorSpace::parse(&obj1))) {
+ error(-1, "Bad DeviceN color space (alternate color space)");
+ goto err3;
+ }
+ obj1.free();
+ arr->get(3, &obj1);
+ if (!(funcA = Function::parse(&obj1))) {
+ goto err4;
+ }
+ obj1.free();
+ cs = new GfxDeviceNColorSpace(nCompsA, altA, funcA);
+ for (i = 0; i < nCompsA; ++i) {
+ cs->names[i] = namesA[i];
+ }
+ return cs;
+
+ err4:
+ delete altA;
+ err3:
+ for (i = 0; i < nCompsA; ++i) {
+ delete namesA[i];
+ }
+ err2:
+ obj1.free();
+ err1:
+ return NULL;
+}
+
+void GfxDeviceNColorSpace::getGray(const GfxColor *color, double *gray) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getGray(&color2, gray);
+}
+
+void GfxDeviceNColorSpace::getRGB(const GfxColor *color, GfxRGB *rgb) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getRGB(&color2, rgb);
+}
+
+void GfxDeviceNColorSpace::getCMYK(const GfxColor *color, GfxCMYK *cmyk) const {
+ GfxColor color2;
+
+ func->transform(color->c, color2.c);
+ alt->getCMYK(&color2, cmyk);
+}
+
+//------------------------------------------------------------------------
+// GfxPatternColorSpace
+//------------------------------------------------------------------------
+
+GfxPatternColorSpace::GfxPatternColorSpace(GfxColorSpace *underA) {
+ under = underA;
+}
+
+GfxPatternColorSpace::~GfxPatternColorSpace() {
+ if (under) {
+ delete under;
+ }
+}
+
+GfxColorSpace *GfxPatternColorSpace::copy() const {
+ return new GfxPatternColorSpace(under ? under->copy() :
+ (GfxColorSpace *)NULL);
+}
+
+GfxColorSpace *GfxPatternColorSpace::parse(Array *arr) {
+ GfxPatternColorSpace *cs;
+ GfxColorSpace *underA;
+ Object obj1;
+
+ if (arr->getLength() != 1 && arr->getLength() != 2) {
+ error(-1, "Bad Pattern color space");
+ return NULL;
+ }
+ underA = NULL;
+ if (arr->getLength() == 2) {
+ arr->get(1, &obj1);
+ if (!(underA = GfxColorSpace::parse(&obj1))) {
+ error(-1, "Bad Pattern color space (underlying color space)");
+ obj1.free();
+ return NULL;
+ }
+ obj1.free();
+ }
+ cs = new GfxPatternColorSpace(underA);
+ return cs;
+}
+
+void GfxPatternColorSpace::getGray(const GfxColor */*color*/, double *gray) const {
+ *gray = 0;
+}
+
+void GfxPatternColorSpace::getRGB(const GfxColor */*color*/, GfxRGB *rgb) const {
+ rgb->r = rgb->g = rgb->b = 0;
+}
+
+void GfxPatternColorSpace::getCMYK(const GfxColor */*color*/, GfxCMYK *cmyk) const {
+ cmyk->c = cmyk->m = cmyk->y = 0;
+ cmyk->k = 1;
+}
+
+//------------------------------------------------------------------------
+// Pattern
+//------------------------------------------------------------------------
+
+GfxPattern::GfxPattern(int typeA) {
+ type = typeA;
+}
+
+GfxPattern::~GfxPattern() {
+}
+
+GfxPattern *GfxPattern::parse(Object *obj) {
+ GfxPattern *pattern;
+ Dict *dict;
+ Object obj1;
+
+ pattern = NULL;
+ if (obj->isStream()) {
+ dict = obj->streamGetDict();
+ dict->lookup("PatternType", &obj1);
+ if (obj1.isInt() && obj1.getInt() == 1) {
+ pattern = new GfxTilingPattern(dict, obj);
+ }
+ obj1.free();
+ }
+ return pattern;
+}
+
+//------------------------------------------------------------------------
+// GfxTilingPattern
+//------------------------------------------------------------------------
+
+GfxTilingPattern::GfxTilingPattern(Dict *streamDict, Object *stream):
+ GfxPattern(1)
+{
+ Object obj1, obj2;
+ int i;
+
+ if (streamDict->lookup("PaintType", &obj1)->isInt()) {
+ paintType = obj1.getInt();
+ } else {
+ paintType = 1;
+ error(-1, "Invalid or missing PaintType in pattern");
+ }
+ obj1.free();
+ if (streamDict->lookup("TilingType", &obj1)->isInt()) {
+ tilingType = obj1.getInt();
+ } else {
+ tilingType = 1;
+ error(-1, "Invalid or missing TilingType in pattern");
+ }
+ obj1.free();
+ bbox[0] = bbox[1] = 0;
+ bbox[2] = bbox[3] = 1;
+ if (streamDict->lookup("BBox", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 4) {
+ for (i = 0; i < 4; ++i) {
+ if (obj1.arrayGet(i, &obj2)->isNum()) {
+ bbox[i] = obj2.getNum();
+ }
+ obj2.free();
+ }
+ } else {
+ error(-1, "Invalid or missing BBox in pattern");
+ }
+ obj1.free();
+ if (streamDict->lookup("XStep", &obj1)->isNum()) {
+ xStep = obj1.getNum();
+ } else {
+ xStep = 1;
+ error(-1, "Invalid or missing XStep in pattern");
+ }
+ obj1.free();
+ if (streamDict->lookup("YStep", &obj1)->isNum()) {
+ yStep = obj1.getNum();
+ } else {
+ yStep = 1;
+ error(-1, "Invalid or missing YStep in pattern");
+ }
+ obj1.free();
+ if (!streamDict->lookup("Resources", &resDict)->isDict()) {
+ resDict.free();
+ resDict.initNull();
+ error(-1, "Invalid or missing Resources in pattern");
+ }
+ matrix[0] = 1; matrix[1] = 0;
+ matrix[2] = 0; matrix[3] = 1;
+ matrix[4] = 0; matrix[5] = 0;
+ if (streamDict->lookup("Matrix", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 6) {
+ for (i = 0; i < 6; ++i) {
+ if (obj1.arrayGet(i, &obj2)->isNum()) {
+ matrix[i] = obj2.getNum();
+ }
+ obj2.free();
+ }
+ }
+ obj1.free();
+ stream->copy(&contentStream);
+}
+
+GfxTilingPattern::~GfxTilingPattern() {
+ resDict.free();
+ contentStream.free();
+}
+
+GfxPattern *GfxTilingPattern::copy() {
+ return new GfxTilingPattern(this);
+}
+
+GfxTilingPattern::GfxTilingPattern(GfxTilingPattern *pat):
+ GfxPattern(1)
+{
+ memcpy(this, pat, sizeof(GfxTilingPattern));
+ pat->resDict.copy(&resDict);
+ pat->contentStream.copy(&contentStream);
+}
+
+//------------------------------------------------------------------------
+// GfxShading
+//------------------------------------------------------------------------
+
+GfxShading::GfxShading() {
+}
+
+GfxShading::~GfxShading() {
+ delete colorSpace;
+}
+
+GfxShading *GfxShading::parse(Object *obj) {
+ GfxShading *shading;
+ int typeA;
+ GfxColorSpace *colorSpaceA;
+ GfxColor backgroundA;
+ GBool hasBackgroundA;
+ double xMinA, yMinA, xMaxA, yMaxA;
+ GBool hasBBoxA;
+ Object obj1, obj2;
+ int i;
+
+ shading = NULL;
+ if (obj->isDict()) {
+
+ if (!obj->dictLookup("ShadingType", &obj1)->isInt()) {
+ error(-1, "Invalid ShadingType in shading dictionary");
+ obj1.free();
+ goto err1;
+ }
+ typeA = obj1.getInt();
+ obj1.free();
+
+ obj->dictLookup("ColorSpace", &obj1);
+ if (!(colorSpaceA = GfxColorSpace::parse(&obj1))) {
+ error(-1, "Bad color space in shading dictionary");
+ obj1.free();
+ goto err1;
+ }
+ obj1.free();
+
+ for (i = 0; i < gfxColorMaxComps; ++i) {
+ backgroundA.c[i] = 0;
+ }
+ hasBackgroundA = gFalse;
+ if (obj->dictLookup("Background", &obj1)->isArray()) {
+ if (obj1.arrayGetLength() == colorSpaceA->getNComps()) {
+ hasBackgroundA = gTrue;
+ for (i = 0; i < colorSpaceA->getNComps(); ++i) {
+ backgroundA.c[i] = obj1.arrayGet(i, &obj2)->getNum();
+ obj2.free();
+ }
+ } else {
+ error(-1, "Bad Background in shading dictionary");
+ }
+ }
+ obj1.free();
+
+ xMinA = yMinA = xMaxA = yMaxA = 0;
+ hasBBoxA = gFalse;
+ if (obj->dictLookup("BBox", &obj1)->isArray()) {
+ if (obj1.arrayGetLength() == 4) {
+ hasBBoxA = gTrue;
+ xMinA = obj1.arrayGet(0, &obj2)->getNum();
+ obj2.free();
+ yMinA = obj1.arrayGet(1, &obj2)->getNum();
+ obj2.free();
+ xMaxA = obj1.arrayGet(2, &obj2)->getNum();
+ obj2.free();
+ yMaxA = obj1.arrayGet(3, &obj2)->getNum();
+ obj2.free();
+ } else {
+ error(-1, "Bad BBox in shading dictionary");
+ }
+ }
+ obj1.free();
+
+ switch (typeA) {
+ case 2:
+ shading = GfxAxialShading::parse(obj->getDict());
+ break;
+ case 3:
+ shading = GfxRadialShading::parse(obj->getDict());
+ break;
+ default:
+ error(-1, "Unimplemented shading type %d", typeA);
+ goto err1;
+ }
+
+ if (shading) {
+ shading->type = typeA;
+ shading->colorSpace = colorSpaceA;
+ shading->background = backgroundA;
+ shading->hasBackground = hasBackgroundA;
+ shading->xMin = xMinA;
+ shading->yMin = yMinA;
+ shading->xMax = xMaxA;
+ shading->yMax = yMaxA;
+ shading->hasBBox = hasBBoxA;
+ } else {
+ delete colorSpaceA;
+ }
+ }
+
+ return shading;
+
+ err1:
+ return NULL;
+}
+
+//------------------------------------------------------------------------
+// GfxAxialShading
+//------------------------------------------------------------------------
+
+GfxAxialShading::GfxAxialShading(double x0A, double y0A,
+ double x1A, double y1A,
+ double t0A, double t1A,
+ Function **funcsA, int nFuncsA,
+ GBool extend0A, GBool extend1A) {
+ int i;
+
+ x0 = x0A;
+ y0 = y0A;
+ x1 = x1A;
+ y1 = y1A;
+ t0 = t0A;
+ t1 = t1A;
+ nFuncs = nFuncsA;
+ for (i = 0; i < nFuncs; ++i) {
+ funcs[i] = funcsA[i];
+ }
+ extend0 = extend0A;
+ extend1 = extend1A;
+}
+
+GfxAxialShading::~GfxAxialShading() {
+ int i;
+
+ for (i = 0; i < nFuncs; ++i) {
+ delete funcs[i];
+ }
+}
+
+GfxAxialShading *GfxAxialShading::parse(Dict *dict) {
+ double x0A, y0A, x1A, y1A;
+ double t0A, t1A;
+ Function *funcsA[gfxColorMaxComps];
+ int nFuncsA;
+ GBool extend0A, extend1A;
+ Object obj1, obj2;
+ int i;
+
+ x0A = y0A = x1A = y1A = 0;
+ if (dict->lookup("Coords", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 4) {
+ x0A = obj1.arrayGet(0, &obj2)->getNum();
+ obj2.free();
+ y0A = obj1.arrayGet(1, &obj2)->getNum();
+ obj2.free();
+ x1A = obj1.arrayGet(2, &obj2)->getNum();
+ obj2.free();
+ y1A = obj1.arrayGet(3, &obj2)->getNum();
+ obj2.free();
+ } else {
+ error(-1, "Missing or invalid Coords in shading dictionary");
+ goto err1;
+ }
+ obj1.free();
+
+ t0A = 0;
+ t1A = 1;
+ if (dict->lookup("Domain", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2) {
+ t0A = obj1.arrayGet(0, &obj2)->getNum();
+ obj2.free();
+ t1A = obj1.arrayGet(1, &obj2)->getNum();
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("Function", &obj1);
+ if (obj1.isArray()) {
+ nFuncsA = obj1.arrayGetLength();
+ for (i = 0; i < nFuncsA; ++i) {
+ obj1.arrayGet(i, &obj2);
+ if (!(funcsA[i] = Function::parse(&obj2))) {
+ obj1.free();
+ obj2.free();
+ goto err1;
+ }
+ obj2.free();
+ }
+ } else {
+ nFuncsA = 1;
+ if (!(funcsA[0] = Function::parse(&obj1))) {
+ obj1.free();
+ goto err1;
+ }
+ }
+ obj1.free();
+
+ extend0A = extend1A = gFalse;
+ if (dict->lookup("Extend", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2) {
+ extend0A = obj1.arrayGet(0, &obj2)->getBool();
+ obj2.free();
+ extend1A = obj1.arrayGet(1, &obj2)->getBool();
+ obj2.free();
+ }
+ obj1.free();
+
+ return new GfxAxialShading(x0A, y0A, x1A, y1A, t0A, t1A,
+ funcsA, nFuncsA, extend0A, extend1A);
+
+ err1:
+ return NULL;
+}
+
+void GfxAxialShading::getColor(double t, GfxColor *color) {
+ int i;
+
+ for (i = 0; i < nFuncs; ++i) {
+ funcs[i]->transform(&t, &color->c[i]);
+ }
+}
+
+//------------------------------------------------------------------------
+// GfxRadialShading
+//------------------------------------------------------------------------
+
+GfxRadialShading::GfxRadialShading(double x0A, double y0A, double r0A,
+ double x1A, double y1A, double r1A,
+ double t0A, double t1A,
+ Function **funcsA, int nFuncsA,
+ GBool extend0A, GBool extend1A) {
+ int i;
+
+ x0 = x0A;
+ y0 = y0A;
+ r0 = r0A;
+ x1 = x1A;
+ y1 = y1A;
+ r1 = r1A;
+ t0 = t0A;
+ t1 = t1A;
+ nFuncs = nFuncsA;
+ for (i = 0; i < nFuncs; ++i) {
+ funcs[i] = funcsA[i];
+ }
+ extend0 = extend0A;
+ extend1 = extend1A;
+}
+
+GfxRadialShading::~GfxRadialShading() {
+ int i;
+
+ for (i = 0; i < nFuncs; ++i) {
+ delete funcs[i];
+ }
+}
+
+GfxRadialShading *GfxRadialShading::parse(Dict *dict) {
+ double x0A, y0A, r0A, x1A, y1A, r1A;
+ double t0A, t1A;
+ Function *funcsA[gfxColorMaxComps];
+ int nFuncsA;
+ GBool extend0A, extend1A;
+ Object obj1, obj2;
+ int i;
+
+ x0A = y0A = r0A = x1A = y1A = r1A = 0;
+ if (dict->lookup("Coords", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 6) {
+ x0A = obj1.arrayGet(0, &obj2)->getNum();
+ obj2.free();
+ y0A = obj1.arrayGet(1, &obj2)->getNum();
+ obj2.free();
+ r0A = obj1.arrayGet(2, &obj2)->getNum();
+ obj2.free();
+ x1A = obj1.arrayGet(3, &obj2)->getNum();
+ obj2.free();
+ y1A = obj1.arrayGet(4, &obj2)->getNum();
+ obj2.free();
+ r1A = obj1.arrayGet(5, &obj2)->getNum();
+ obj2.free();
+ } else {
+ error(-1, "Missing or invalid Coords in shading dictionary");
+ goto err1;
+ }
+ obj1.free();
+
+ t0A = 0;
+ t1A = 1;
+ if (dict->lookup("Domain", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2) {
+ t0A = obj1.arrayGet(0, &obj2)->getNum();
+ obj2.free();
+ t1A = obj1.arrayGet(1, &obj2)->getNum();
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("Function", &obj1);
+ if (obj1.isArray()) {
+ nFuncsA = obj1.arrayGetLength();
+ for (i = 0; i < nFuncsA; ++i) {
+ obj1.arrayGet(i, &obj2);
+ if (!(funcsA[i] = Function::parse(&obj2))) {
+ obj1.free();
+ obj2.free();
+ goto err1;
+ }
+ obj2.free();
+ }
+ } else {
+ nFuncsA = 1;
+ if (!(funcsA[0] = Function::parse(&obj1))) {
+ obj1.free();
+ goto err1;
+ }
+ }
+ obj1.free();
+
+ extend0A = extend1A = gFalse;
+ if (dict->lookup("Extend", &obj1)->isArray() &&
+ obj1.arrayGetLength() == 2) {
+ extend0A = obj1.arrayGet(0, &obj2)->getBool();
+ obj2.free();
+ extend1A = obj1.arrayGet(1, &obj2)->getBool();
+ obj2.free();
+ }
+ obj1.free();
+
+ return new GfxRadialShading(x0A, y0A, r0A, x1A, y1A, r1A, t0A, t1A,
+ funcsA, nFuncsA, extend0A, extend1A);
+
+ err1:
+ return NULL;
+}
+
+void GfxRadialShading::getColor(double t, GfxColor *color) {
+ int i;
+
+ for (i = 0; i < nFuncs; ++i) {
+ funcs[i]->transform(&t, &color->c[i]);
+ }
+}
+
+//------------------------------------------------------------------------
+// GfxImageColorMap
+//------------------------------------------------------------------------
+
+GfxImageColorMap::GfxImageColorMap(int bitsA, Object *decode,
+ GfxColorSpace *colorSpaceA) {
+ GfxIndexedColorSpace *indexedCS;
+ GfxSeparationColorSpace *sepCS;
+ int maxPixel, indexHigh;
+ const Guchar *lookup2;
+ const Function *sepFunc;
+ Object obj;
+ double x[gfxColorMaxComps];
+ double y[gfxColorMaxComps];
+ int i, j, k;
+
+ ok = gTrue;
+
+ // bits per component and color space
+ bits = bitsA;
+ maxPixel = (1 << bits) - 1;
+ colorSpace = colorSpaceA;
+
+ // get decode map
+ if (decode->isNull()) {
+ nComps = colorSpace->getNComps();
+ colorSpace->getDefaultRanges(decodeLow, decodeRange, maxPixel);
+ } else if (decode->isArray()) {
+ nComps = decode->arrayGetLength() / 2;
+ if (nComps != colorSpace->getNComps()) {
+ goto err1;
+ }
+ for (i = 0; i < nComps; ++i) {
+ decode->arrayGet(2*i, &obj);
+ if (!obj.isNum()) {
+ goto err2;
+ }
+ decodeLow[i] = obj.getNum();
+ obj.free();
+ decode->arrayGet(2*i+1, &obj);
+ if (!obj.isNum()) {
+ goto err2;
+ }
+ decodeRange[i] = obj.getNum() - decodeLow[i];
+ obj.free();
+ }
+ } else {
+ goto err1;
+ }
+
+ // Construct a lookup table -- this stores pre-computed decoded
+ // values for each component, i.e., the result of applying the
+ // decode mapping to each possible image pixel component value.
+ //
+ // Optimization: for Indexed and Separation color spaces (which have
+ // only one component), we store color values in the lookup table
+ // rather than component values.
+ colorSpace2 = NULL;
+ nComps2 = 0;
+ if (colorSpace->getMode() == csIndexed) {
+ // Note that indexHigh may not be the same as maxPixel --
+ // Distiller will remove unused palette entries, resulting in
+ // indexHigh < maxPixel.
+ indexedCS = (GfxIndexedColorSpace *)colorSpace;
+ colorSpace2 = indexedCS->getBase();
+ indexHigh = indexedCS->getIndexHigh();
+ nComps2 = colorSpace2->getNComps();
+ lookup = (double *)gmalloc((indexHigh + 1) * nComps2 * sizeof(double));
+ lookup2 = indexedCS->getLookup();
+ colorSpace2->getDefaultRanges(x, y, indexHigh);
+ for (i = 0; i <= indexHigh; ++i) {
+ j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5);
+ for (k = 0; k < nComps2; ++k) {
+ lookup[j*nComps2 + k] = x[k] + (lookup2[i*nComps2 + k] / 255.0) * y[k];
+ }
+ }
+ } else if (colorSpace->getMode() == csSeparation) {
+ sepCS = (GfxSeparationColorSpace *)colorSpace;
+ colorSpace2 = sepCS->getAlt();
+ nComps2 = colorSpace2->getNComps();
+ lookup = (double *)gmalloc((maxPixel + 1) * nComps2 * sizeof(double));
+ sepFunc = sepCS->getFunc();
+ for (i = 0; i <= maxPixel; ++i) {
+ x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel;
+ sepFunc->transform(x, y);
+ for (k = 0; k < nComps2; ++k) {
+ lookup[i*nComps2 + k] = y[k];
+ }
+ }
+ } else {
+ lookup = (double *)gmalloc((maxPixel + 1) * nComps * sizeof(double));
+ for (i = 0; i <= maxPixel; ++i) {
+ for (k = 0; k < nComps; ++k) {
+ lookup[i*nComps + k] = decodeLow[k] +
+ (i * decodeRange[k]) / maxPixel;
+ }
+ }
+ }
+
+ return;
+
+ err2:
+ obj.free();
+ err1:
+ ok = gFalse;
+}
+
+GfxImageColorMap::~GfxImageColorMap() {
+ delete colorSpace;
+ gfree(lookup);
+}
+
+void GfxImageColorMap::getGray(Guchar *x, double *gray) {
+ GfxColor color;
+ double *p;
+ int i;
+
+ if (colorSpace2) {
+ p = &lookup[x[0] * nComps2];
+ for (i = 0; i < nComps2; ++i) {
+ color.c[i] = *p++;
+ }
+ colorSpace2->getGray(&color, gray);
+ } else {
+ for (i = 0; i < nComps; ++i) {
+ color.c[i] = lookup[x[i] * nComps + i];
+ }
+ colorSpace->getGray(&color, gray);
+ }
+}
+
+void GfxImageColorMap::getRGB(Guchar *x, GfxRGB *rgb) {
+ GfxColor color;
+ double *p;
+ int i;
+
+ if (colorSpace2) {
+ p = &lookup[x[0] * nComps2];
+ for (i = 0; i < nComps2; ++i) {
+ color.c[i] = *p++;
+ }
+ colorSpace2->getRGB(&color, rgb);
+ } else {
+ for (i = 0; i < nComps; ++i) {
+ color.c[i] = lookup[x[i] * nComps + i];
+ }
+ colorSpace->getRGB(&color, rgb);
+ }
+}
+
+void GfxImageColorMap::getCMYK(Guchar *x, GfxCMYK *cmyk) {
+ GfxColor color;
+ double *p;
+ int i;
+
+ if (colorSpace2) {
+ p = &lookup[x[0] * nComps2];
+ for (i = 0; i < nComps2; ++i) {
+ color.c[i] = *p++;
+ }
+ colorSpace2->getCMYK(&color, cmyk);
+ } else {
+ for (i = 0; i < nComps; ++i) {
+ color.c[i] = lookup[x[i] * nComps + i];
+ }
+ colorSpace->getCMYK(&color, cmyk);
+ }
+}
+
+//------------------------------------------------------------------------
+// GfxSubpath and GfxPath
+//------------------------------------------------------------------------
+
+GfxSubpath::GfxSubpath(double x1, double y1) {
+ size = 16;
+ x = (double *)gmalloc(size * sizeof(double));
+ y = (double *)gmalloc(size * sizeof(double));
+ curve = (GBool *)gmalloc(size * sizeof(GBool));
+ n = 1;
+ x[0] = x1;
+ y[0] = y1;
+ curve[0] = gFalse;
+ closed = gFalse;
+}
+
+GfxSubpath::~GfxSubpath() {
+ gfree(x);
+ gfree(y);
+ gfree(curve);
+}
+
+// Used for copy().
+GfxSubpath::GfxSubpath(GfxSubpath *subpath) {
+ size = subpath->size;
+ n = subpath->n;
+ x = (double *)gmalloc(size * sizeof(double));
+ y = (double *)gmalloc(size * sizeof(double));
+ curve = (GBool *)gmalloc(size * sizeof(GBool));
+ memcpy(x, subpath->x, n * sizeof(double));
+ memcpy(y, subpath->y, n * sizeof(double));
+ memcpy(curve, subpath->curve, n * sizeof(GBool));
+ closed = subpath->closed;
+}
+
+void GfxSubpath::lineTo(double x1, double y1) {
+ if (n >= size) {
+ size += 16;
+ x = (double *)grealloc(x, size * sizeof(double));
+ y = (double *)grealloc(y, size * sizeof(double));
+ curve = (GBool *)grealloc(curve, size * sizeof(GBool));
+ }
+ x[n] = x1;
+ y[n] = y1;
+ curve[n] = gFalse;
+ ++n;
+}
+
+void GfxSubpath::curveTo(double x1, double y1, double x2, double y2,
+ double x3, double y3) {
+ if (n+3 > size) {
+ size += 16;
+ x = (double *)grealloc(x, size * sizeof(double));
+ y = (double *)grealloc(y, size * sizeof(double));
+ curve = (GBool *)grealloc(curve, size * sizeof(GBool));
+ }
+ x[n] = x1;
+ y[n] = y1;
+ x[n+1] = x2;
+ y[n+1] = y2;
+ x[n+2] = x3;
+ y[n+2] = y3;
+ curve[n] = curve[n+1] = gTrue;
+ curve[n+2] = gFalse;
+ n += 3;
+}
+
+void GfxSubpath::close() {
+ if (x[n-1] != x[0] || y[n-1] != y[0]) {
+ lineTo(x[0], y[0]);
+ }
+ closed = gTrue;
+}
+
+GfxPath::GfxPath() {
+ justMoved = gFalse;
+ size = 16;
+ n = 0;
+ firstX = firstY = 0;
+ subpaths = (GfxSubpath **)gmalloc(size * sizeof(GfxSubpath *));
+}
+
+GfxPath::~GfxPath() {
+ int i;
+
+ for (i = 0; i < n; ++i)
+ delete subpaths[i];
+ gfree(subpaths);
+}
+
+// Used for copy().
+GfxPath::GfxPath(GBool justMoved1, double firstX1, double firstY1,
+ GfxSubpath **subpaths1, int n1, int size1) {
+ int i;
+
+ justMoved = justMoved1;
+ firstX = firstX1;
+ firstY = firstY1;
+ size = size1;
+ n = n1;
+ subpaths = (GfxSubpath **)gmalloc(size * sizeof(GfxSubpath *));
+ for (i = 0; i < n; ++i)
+ subpaths[i] = subpaths1[i]->copy();
+}
+
+void GfxPath::moveTo(double x, double y) {
+ justMoved = gTrue;
+ firstX = x;
+ firstY = y;
+}
+
+void GfxPath::lineTo(double x, double y) {
+ if (justMoved) {
+ if (n >= size) {
+ size += 16;
+ subpaths = (GfxSubpath **)
+ grealloc(subpaths, size * sizeof(GfxSubpath *));
+ }
+ subpaths[n] = new GfxSubpath(firstX, firstY);
+ ++n;
+ justMoved = gFalse;
+ }
+ subpaths[n-1]->lineTo(x, y);
+}
+
+void GfxPath::curveTo(double x1, double y1, double x2, double y2,
+ double x3, double y3) {
+ if (justMoved) {
+ if (n >= size) {
+ size += 16;
+ subpaths = (GfxSubpath **)
+ grealloc(subpaths, size * sizeof(GfxSubpath *));
+ }
+ subpaths[n] = new GfxSubpath(firstX, firstY);
+ ++n;
+ justMoved = gFalse;
+ }
+ subpaths[n-1]->curveTo(x1, y1, x2, y2, x3, y3);
+}
+
+void GfxPath::close() {
+ // this is necessary to handle the pathological case of
+ // moveto/closepath/clip, which defines an empty clipping region
+ if (justMoved) {
+ if (n >= size) {
+ size += 16;
+ subpaths = (GfxSubpath **)
+ grealloc(subpaths, size * sizeof(GfxSubpath *));
+ }
+ subpaths[n] = new GfxSubpath(firstX, firstY);
+ ++n;
+ justMoved = gFalse;
+ }
+ subpaths[n-1]->close();
+}
+
+//------------------------------------------------------------------------
+// GfxState
+//------------------------------------------------------------------------
+
+GfxState::GfxState(double dpi, PDFRectangle *pageBox, int rotate,
+ GBool upsideDown) {
+ double k;
+
+ px1 = pageBox->x1;
+ py1 = pageBox->y1;
+ px2 = pageBox->x2;
+ py2 = pageBox->y2;
+ k = dpi / 72.0;
+ if (rotate == 90) {
+ ctm[0] = 0;
+ ctm[1] = upsideDown ? k : -k;
+ ctm[2] = k;
+ ctm[3] = 0;
+ ctm[4] = -k * py1;
+ ctm[5] = k * (upsideDown ? -px1 : px2);
+ pageWidth = k * (py2 - py1);
+ pageHeight = k * (px2 - px1);
+ } else if (rotate == 180) {
+ ctm[0] = -k;
+ ctm[1] = 0;
+ ctm[2] = 0;
+ ctm[3] = upsideDown ? k : -k;
+ ctm[4] = k * px2;
+ ctm[5] = k * (upsideDown ? -py1 : py2);
+ pageWidth = k * (px2 - px1);
+ pageHeight = k * (py2 - py1);
+ } else if (rotate == 270) {
+ ctm[0] = 0;
+ ctm[1] = upsideDown ? -k : k;
+ ctm[2] = -k;
+ ctm[3] = 0;
+ ctm[4] = k * py2;
+ ctm[5] = k * (upsideDown ? px2 : -px1);
+ pageWidth = k * (py2 - py1);
+ pageHeight = k * (px2 - px1);
+ } else {
+ ctm[0] = k;
+ ctm[1] = 0;
+ ctm[2] = 0;
+ ctm[3] = upsideDown ? -k : k;
+ ctm[4] = -k * px1;
+ ctm[5] = k * (upsideDown ? py2 : -py1);
+ pageWidth = k * (px2 - px1);
+ pageHeight = k * (py2 - py1);
+ }
+
+ fillColorSpace = new GfxDeviceGrayColorSpace();
+ strokeColorSpace = new GfxDeviceGrayColorSpace();
+ fillColor.c[0] = 0;
+ strokeColor.c[0] = 0;
+ fillPattern = NULL;
+ strokePattern = NULL;
+ fillOpacity = 1;
+ strokeOpacity = 1;
+
+ lineWidth = 1;
+ lineDash = NULL;
+ lineDashLength = 0;
+ lineDashStart = 0;
+ flatness = 0;
+ lineJoin = 0;
+ lineCap = 0;
+ miterLimit = 10;
+
+ font = NULL;
+ fontSize = 0;
+ textMat[0] = 1; textMat[1] = 0;
+ textMat[2] = 0; textMat[3] = 1;
+ textMat[4] = 0; textMat[5] = 0;
+ charSpace = 0;
+ wordSpace = 0;
+ horizScaling = 1;
+ leading = 0;
+ rise = 0;
+ render = 0;
+
+ path = new GfxPath();
+ curX = curY = 0;
+ lineX = lineY = 0;
+
+ clipXMin = 0;
+ clipYMin = 0;
+ clipXMax = pageWidth;
+ clipYMax = pageHeight;
+
+ saved = NULL;
+}
+
+GfxState::~GfxState() {
+ if (fillColorSpace) {
+ delete fillColorSpace;
+ }
+ if (strokeColorSpace) {
+ delete strokeColorSpace;
+ }
+ if (fillPattern) {
+ delete fillPattern;
+ }
+ if (strokePattern) {
+ delete strokePattern;
+ }
+ gfree(lineDash);
+ if (path) {
+ // this gets set to NULL by restore()
+ delete path;
+ }
+ if (saved) {
+ delete saved;
+ }
+}
+
+// Used for copy();
+GfxState::GfxState(const GfxState *state) {
+ memcpy(this, state, sizeof(GfxState));
+ if (fillColorSpace) {
+ fillColorSpace = state->fillColorSpace->copy();
+ }
+ if (strokeColorSpace) {
+ strokeColorSpace = state->strokeColorSpace->copy();
+ }
+ if (fillPattern) {
+ fillPattern = state->fillPattern->copy();
+ }
+ if (strokePattern) {
+ strokePattern = state->strokePattern->copy();
+ }
+ if (lineDashLength > 0) {
+ lineDash = (double *)gmalloc(lineDashLength * sizeof(double));
+ memcpy(lineDash, state->lineDash, lineDashLength * sizeof(double));
+ }
+ saved = NULL;
+}
+
+void GfxState::getUserClipBBox(double *xMin, double *yMin,
+ double *xMax, double *yMax) const {
+ double ictm[6];
+ double xMin1, yMin1, xMax1, yMax1, det, tx, ty;
+
+ // invert the CTM
+ det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
+ ictm[0] = ctm[3] * det;
+ ictm[1] = -ctm[1] * det;
+ ictm[2] = -ctm[2] * det;
+ ictm[3] = ctm[0] * det;
+ ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
+ ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
+
+ // transform all four corners of the clip bbox; find the min and max
+ // x and y values
+ xMin1 = xMax1 = clipXMin * ictm[0] + clipYMin * ictm[2] + ictm[4];
+ yMin1 = yMax1 = clipXMin * ictm[1] + clipYMin * ictm[3] + ictm[5];
+ tx = clipXMin * ictm[0] + clipYMax * ictm[2] + ictm[4];
+ ty = clipXMin * ictm[1] + clipYMax * ictm[3] + ictm[5];
+ if (tx < xMin1) {
+ xMin1 = tx;
+ } else if (tx > xMax1) {
+ xMax1 = tx;
+ }
+ if (ty < yMin1) {
+ yMin1 = ty;
+ } else if (ty > yMax1) {
+ yMax1 = ty;
+ }
+ tx = clipXMax * ictm[0] + clipYMin * ictm[2] + ictm[4];
+ ty = clipXMax * ictm[1] + clipYMin * ictm[3] + ictm[5];
+ if (tx < xMin1) {
+ xMin1 = tx;
+ } else if (tx > xMax1) {
+ xMax1 = tx;
+ }
+ if (ty < yMin1) {
+ yMin1 = ty;
+ } else if (ty > yMax1) {
+ yMax1 = ty;
+ }
+ tx = clipXMax * ictm[0] + clipYMax * ictm[2] + ictm[4];
+ ty = clipXMax * ictm[1] + clipYMax * ictm[3] + ictm[5];
+ if (tx < xMin1) {
+ xMin1 = tx;
+ } else if (tx > xMax1) {
+ xMax1 = tx;
+ }
+ if (ty < yMin1) {
+ yMin1 = ty;
+ } else if (ty > yMax1) {
+ yMax1 = ty;
+ }
+
+ *xMin = xMin1;
+ *yMin = yMin1;
+ *xMax = xMax1;
+ *yMax = yMax1;
+}
+
+double GfxState::transformWidth(double w) {
+ double x, y;
+
+ x = ctm[0] + ctm[2];
+ y = ctm[1] + ctm[3];
+ return w * sqrt(0.5 * (x * x + y * y));
+}
+
+double GfxState::getTransformedFontSize() {
+ double x1, y1, x2, y2;
+
+ x1 = textMat[2] * fontSize;
+ y1 = textMat[3] * fontSize;
+ x2 = ctm[0] * x1 + ctm[2] * y1;
+ y2 = ctm[1] * x1 + ctm[3] * y1;
+ return sqrt(x2 * x2 + y2 * y2);
+}
+
+void GfxState::getFontTransMat(double *m11, double *m12,
+ double *m21, double *m22) {
+ *m11 = (textMat[0] * ctm[0] + textMat[1] * ctm[2]) * fontSize;
+ *m12 = (textMat[0] * ctm[1] + textMat[1] * ctm[3]) * fontSize;
+ *m21 = (textMat[2] * ctm[0] + textMat[3] * ctm[2]) * fontSize;
+ *m22 = (textMat[2] * ctm[1] + textMat[3] * ctm[3]) * fontSize;
+}
+
+void GfxState::setCTM(double a, double b, double c,
+ double d, double e, double f) {
+ int i;
+
+ ctm[0] = a;
+ ctm[1] = b;
+ ctm[2] = c;
+ ctm[3] = d;
+ ctm[4] = e;
+ ctm[5] = f;
+
+ // avoid FP exceptions on badly messed up PDF files
+ for (i = 0; i < 6; ++i) {
+ if (ctm[i] > 1e10) {
+ ctm[i] = 1e10;
+ } else if (ctm[i] < -1e10) {
+ ctm[i] = -1e10;
+ }
+ }
+}
+
+void GfxState::concatCTM(double a, double b, double c,
+ double d, double e, double f) {
+ double a1 = ctm[0];
+ double b1 = ctm[1];
+ double c1 = ctm[2];
+ double d1 = ctm[3];
+ int i;
+
+ ctm[0] = a * a1 + b * c1;
+ ctm[1] = a * b1 + b * d1;
+ ctm[2] = c * a1 + d * c1;
+ ctm[3] = c * b1 + d * d1;
+ ctm[4] = e * a1 + f * c1 + ctm[4];
+ ctm[5] = e * b1 + f * d1 + ctm[5];
+
+ // avoid FP exceptions on badly messed up PDF files
+ for (i = 0; i < 6; ++i) {
+ if (ctm[i] > 1e10) {
+ ctm[i] = 1e10;
+ } else if (ctm[i] < -1e10) {
+ ctm[i] = -1e10;
+ }
+ }
+}
+
+void GfxState::setFillColorSpace(GfxColorSpace *colorSpace) {
+ if (fillColorSpace) {
+ delete fillColorSpace;
+ }
+ fillColorSpace = colorSpace;
+}
+
+void GfxState::setStrokeColorSpace(GfxColorSpace *colorSpace) {
+ if (strokeColorSpace) {
+ delete strokeColorSpace;
+ }
+ strokeColorSpace = colorSpace;
+}
+
+void GfxState::setFillPattern(GfxPattern *pattern) {
+ if (fillPattern) {
+ delete fillPattern;
+ }
+ fillPattern = pattern;
+}
+
+void GfxState::setStrokePattern(GfxPattern *pattern) {
+ if (strokePattern) {
+ delete strokePattern;
+ }
+ strokePattern = pattern;
+}
+
+void GfxState::setLineDash(double *dash, int length, double start) {
+ if (lineDash)
+ gfree(lineDash);
+ lineDash = dash;
+ lineDashLength = length;
+ lineDashStart = start;
+}
+
+void GfxState::clearPath() {
+ delete path;
+ path = new GfxPath();
+}
+
+void GfxState::clip() {
+ double xMin, yMin, xMax, yMax, x, y;
+ GfxSubpath *subpath;
+ int i, j;
+
+ xMin = xMax = yMin = yMax = 0; // make gcc happy
+ for (i = 0; i < path->getNumSubpaths(); ++i) {
+ subpath = path->getSubpath(i);
+ for (j = 0; j < subpath->getNumPoints(); ++j) {
+ transform(subpath->getX(j), subpath->getY(j), &x, &y);
+ if (i == 0 && j == 0) {
+ xMin = xMax = x;
+ yMin = yMax = y;
+ } else {
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ }
+ }
+ }
+ if (xMin > clipXMin) {
+ clipXMin = xMin;
+ }
+ if (yMin > clipYMin) {
+ clipYMin = yMin;
+ }
+ if (xMax < clipXMax) {
+ clipXMax = xMax;
+ }
+ if (yMax < clipYMax) {
+ clipYMax = yMax;
+ }
+}
+
+void GfxState::textShift(double tx, double ty) {
+ double dx, dy;
+
+ textTransformDelta(tx, ty, &dx, &dy);
+ curX += dx;
+ curY += dy;
+}
+
+void GfxState::shift(double dx, double dy) {
+ curX += dx;
+ curY += dy;
+}
+
+GfxState *GfxState::save() {
+ GfxState *newState;
+
+ newState = copy();
+ newState->saved = this;
+ return newState;
+}
+
+GfxState *GfxState::restore() {
+ GfxState *oldState;
+
+ if (saved) {
+ oldState = saved;
+
+ // these attributes aren't saved/restored by the q/Q operators
+ oldState->path = path;
+ oldState->curX = curX;
+ oldState->curY = curY;
+ oldState->lineX = lineX;
+ oldState->lineY = lineY;
+
+ path = NULL;
+ saved = NULL;
+ delete this;
+
+ } else {
+ oldState = this;
+ }
+
+ return oldState;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/GlobalParams.cc b/filters/kword/pdf/xpdf/xpdf/GlobalParams.cc
deleted file mode 100644
index 8a7b36de8..000000000
--- a/filters/kword/pdf/xpdf/xpdf/GlobalParams.cc
+++ /dev/null
@@ -1,1112 +0,0 @@
-//========================================================================
-//
-// GlobalParams.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <string.h>
-#include <ctype.h>
-#ifdef HAVE_PAPER_H
-#include <paper.h>
-#endif
-#include "gmem.h"
-#include "GString.h"
-#include "GList.h"
-#include "GHash.h"
-#include "gfile.h"
-#include "Error.h"
-#include "NameToCharCode.h"
-#include "CharCodeToUnicode.h"
-#include "UnicodeMap.h"
-#include "CMap.h"
-#include "BuiltinFontTables.h"
-#include "FontEncodingTables.h"
-#include "GlobalParams.h"
-
-#include "NameToUnicodeTable.h"
-#include "UnicodeMapTables.h"
-#include "DisplayFontTable.h"
-#include "UTF8.h"
-
-//------------------------------------------------------------------------
-
-GlobalParams *globalParams = NULL;
-
-//------------------------------------------------------------------------
-// DisplayFontParam
-//------------------------------------------------------------------------
-
-DisplayFontParam::DisplayFontParam(GString *nameA,
- DisplayFontParamKind kindA) {
- name = nameA;
- kind = kindA;
- switch (kind) {
- case displayFontX:
- x.xlfd = NULL;
- x.encoding = NULL;
- break;
- case displayFontT1:
- t1.fileName = NULL;
- break;
- case displayFontTT:
- tt.fileName = NULL;
- break;
- }
-}
-
-DisplayFontParam::DisplayFontParam(const char *nameA, const char *xlfdA,
- const char *encodingA) {
- name = new GString(nameA);
- kind = displayFontX;
- x.xlfd = new GString(xlfdA);
- x.encoding = new GString(encodingA);
-}
-
-DisplayFontParam::~DisplayFontParam() {
- delete name;
- switch (kind) {
- case displayFontX:
- if (x.xlfd) {
- delete x.xlfd;
- }
- if (x.encoding) {
- delete x.encoding;
- }
- break;
- case displayFontT1:
- if (t1.fileName) {
- delete t1.fileName;
- }
- break;
- case displayFontTT:
- if (tt.fileName) {
- delete tt.fileName;
- }
- break;
- }
-}
-
-//------------------------------------------------------------------------
-// PSFontParam
-//------------------------------------------------------------------------
-
-PSFontParam::PSFontParam(GString *pdfFontNameA, int wModeA,
- GString *psFontNameA, GString *encodingA) {
- pdfFontName = pdfFontNameA;
- wMode = wModeA;
- psFontName = psFontNameA;
- encoding = encodingA;
-}
-
-PSFontParam::~PSFontParam() {
- delete pdfFontName;
- delete psFontName;
- if (encoding) {
- delete encoding;
- }
-}
-
-//------------------------------------------------------------------------
-// parsing
-//------------------------------------------------------------------------
-
-GlobalParams::GlobalParams(const char *cfgFileName) {
- UnicodeMap *map;
- DisplayFontParam *dfp;
- GString *fileName;
- FILE *f;
- int i;
-
- initBuiltinFontTables();
-
- // scan the encoding in reverse because we want the lowest-numbered
- // index for each char name ('space' is encoded twice)
- macRomanReverseMap = new NameToCharCode();
- for (i = 255; i >= 0; --i) {
- if (macRomanEncoding[i]) {
- macRomanReverseMap->add(macRomanEncoding[i], (CharCode)i);
- }
- }
-
- nameToUnicode = new NameToCharCode();
- cidToUnicodes = new GHash(gTrue);
- residentUnicodeMaps = new GHash();
- unicodeMaps = new GHash(gTrue);
- cMapDirs = new GHash(gTrue);
- toUnicodeDirs = new GList();
- displayFonts = new GHash();
- displayCIDFonts = new GHash();
- displayNamedCIDFonts = new GHash();
-#ifdef HAVE_PAPER_H
- char *paperName;
- const struct paper *paperType;
- paperinit();
- if ((paperName = systempapername())) {
- paperType = paperinfo(paperName);
- psPaperWidth = (int)paperpswidth(paperType);
- psPaperHeight = (int)paperpsheight(paperType);
- } else {
- error(-1, "No paper information available - using defaults");
- psPaperWidth = defPaperWidth;
- psPaperHeight = defPaperHeight;
- }
- paperdone();
-#else
- psPaperWidth = defPaperWidth;
- psPaperHeight = defPaperHeight;
-#endif
- psDuplex = gFalse;
- psLevel = psLevel2;
- psFile = NULL;
- psFonts = new GHash();
- psNamedFonts16 = new GList();
- psFonts16 = new GList();
- psEmbedType1 = gTrue;
- psEmbedTrueType = gTrue;
- psEmbedCIDPostScript = gTrue;
- psEmbedCIDTrueType = gTrue;
- psOPI = gFalse;
- psASCIIHex = gFalse;
- textEncoding = new GString("Latin1");
-#if defined(WIN32)
- textEOL = eolDOS;
-#elif defined(MACOS)
- textEOL = eolMac;
-#else
- textEOL = eolUnix;
-#endif
- textKeepTinyChars = gFalse;
- fontDirs = new GList();
- initialZoom = new GString("1");
- t1libControl = fontRastAALow;
- freetypeControl = fontRastAALow;
- urlCommand = NULL;
- movieCommand = NULL;
- mapNumericCharNames = gTrue;
- printCommands = gFalse;
- errQuiet = gFalse;
-
- cidToUnicodeCache = new CIDToUnicodeCache();
- unicodeMapCache = new UnicodeMapCache();
- cMapCache = new CMapCache();
-
- // set up the initial nameToUnicode table
- for (i = 0; nameToUnicodeTab[i].name; ++i) {
- nameToUnicode->add(nameToUnicodeTab[i].name, nameToUnicodeTab[i].u);
- }
-
- // set up the residentUnicodeMaps table
- map = new UnicodeMap("Latin1", gFalse,
- latin1UnicodeMapRanges, latin1UnicodeMapLen);
- residentUnicodeMaps->add(map->getEncodingName(), map);
- map = new UnicodeMap("ASCII7", gFalse,
- ascii7UnicodeMapRanges, ascii7UnicodeMapLen);
- residentUnicodeMaps->add(map->getEncodingName(), map);
- map = new UnicodeMap("Symbol", gFalse,
- symbolUnicodeMapRanges, symbolUnicodeMapLen);
- residentUnicodeMaps->add(map->getEncodingName(), map);
- map = new UnicodeMap("ZapfDingbats", gFalse, zapfDingbatsUnicodeMapRanges,
- zapfDingbatsUnicodeMapLen);
- residentUnicodeMaps->add(map->getEncodingName(), map);
- map = new UnicodeMap("UTF-8", gTrue, &mapUTF8);
- residentUnicodeMaps->add(map->getEncodingName(), map);
- map = new UnicodeMap("UCS-2", gTrue, &mapUCS2);
- residentUnicodeMaps->add(map->getEncodingName(), map);
-
- // default displayFonts table
- for (i = 0; displayFontTab[i].name; ++i) {
- dfp = new DisplayFontParam(displayFontTab[i].name,
- displayFontTab[i].xlfd,
- displayFontTab[i].encoding);
- displayFonts->add(dfp->name, dfp);
- }
-
- // look for a user config file, then a system-wide config file
- f = NULL;
- fileName = NULL;
- if (cfgFileName && cfgFileName[0]) {
- fileName = new GString(cfgFileName);
- if (!(f = fopen(fileName->getCString(), "r"))) {
- delete fileName;
- }
- }
- if (!f) {
- fileName = appendToPath(getHomeDir(), xpdfUserConfigFile);
- if (!(f = fopen(fileName->getCString(), "r"))) {
- delete fileName;
- }
- }
- if (!f) {
-#if defined(WIN32) && !defined(__CYGWIN32__)
- char buf[512];
- i = GetModuleFileName(NULL, buf, sizeof(buf));
- if (i <= 0 || i >= sizeof(buf)) {
- // error or path too long for buffer - just use the current dir
- buf[0] = '\0';
- }
- fileName = grabPath(buf);
- appendToPath(fileName, xpdfSysConfigFile);
-#else
- fileName = new GString(xpdfSysConfigFile);
-#endif
- if (!(f = fopen(fileName->getCString(), "r"))) {
- delete fileName;
- }
- }
- if (f) {
- parseFile(fileName, f);
- delete fileName;
- fclose(f);
- }
-}
-
-void GlobalParams::parseFile(GString *fileName, FILE *f) {
- int line;
- GList *tokens;
- GString *cmd, *incFile;
- char *p1, *p2;
- char buf[512];
- FILE *f2;
-
- line = 1;
- while (fgets(buf, sizeof(buf) - 1, f)) {
-
- // break the line into tokens
- tokens = new GList();
- p1 = buf;
- while (*p1) {
- for (; *p1 && isspace(*p1); ++p1) ;
- if (!*p1) {
- break;
- }
- if (*p1 == '"' || *p1 == '\'') {
- for (p2 = p1 + 1; *p2 && *p2 != *p1; ++p2) ;
- ++p1;
- } else {
- for (p2 = p1 + 1; *p2 && !isspace(*p2); ++p2) ;
- }
- tokens->append(new GString(p1, p2 - p1));
- p1 = p2 + 1;
- }
-
- if (tokens->getLength() > 0 &&
- ((GString *)tokens->get(0))->getChar(0) != '#') {
- cmd = (GString *)tokens->get(0);
- if (!cmd->cmp("include")) {
- if (tokens->getLength() == 2) {
- incFile = (GString *)tokens->get(1);
- if ((f2 = fopen(incFile->getCString(), "r"))) {
- parseFile(incFile, f2);
- fclose(f2);
- } else {
- error(-1, "Couldn't find included config file: '%s' (%s:%d)",
- incFile->getCString(), fileName->getCString(), line);
- }
- } else {
- error(-1, "Bad 'include' config file command (%s:%d)",
- fileName->getCString(), line);
- }
- } else if (!cmd->cmp("nameToUnicode")) {
- parseNameToUnicode(tokens, fileName, line);
- } else if (!cmd->cmp("cidToUnicode")) {
- parseCIDToUnicode(tokens, fileName, line);
- } else if (!cmd->cmp("unicodeMap")) {
- parseUnicodeMap(tokens, fileName, line);
- } else if (!cmd->cmp("cMapDir")) {
- parseCMapDir(tokens, fileName, line);
- } else if (!cmd->cmp("toUnicodeDir")) {
- parseToUnicodeDir(tokens, fileName, line);
- } else if (!cmd->cmp("displayFontX")) {
- parseDisplayFont(tokens, displayFonts, displayFontX, fileName, line);
- } else if (!cmd->cmp("displayFontT1")) {
- parseDisplayFont(tokens, displayFonts, displayFontT1, fileName, line);
- } else if (!cmd->cmp("displayFontTT")) {
- parseDisplayFont(tokens, displayFonts, displayFontTT, fileName, line);
- } else if (!cmd->cmp("displayCIDFontX")) {
- parseDisplayFont(tokens, displayCIDFonts,
- displayFontX, fileName, line);
- } else if (!cmd->cmp("displayNamedCIDFontX")) {
- parseDisplayFont(tokens, displayNamedCIDFonts,
- displayFontX, fileName, line);
- } else if (!cmd->cmp("psFile")) {
- parsePSFile(tokens, fileName, line);
- } else if (!cmd->cmp("psFont")) {
- parsePSFont(tokens, fileName, line);
- } else if (!cmd->cmp("psNamedFont16")) {
- parsePSFont16("psNamedFont16", psNamedFonts16,
- tokens, fileName, line);
- } else if (!cmd->cmp("psFont16")) {
- parsePSFont16("psFont16", psFonts16, tokens, fileName, line);
- } else if (!cmd->cmp("psPaperSize")) {
- parsePSPaperSize(tokens, fileName, line);
- } else if (!cmd->cmp("psDuplex")) {
- parseYesNo("psDuplex", &psDuplex, tokens, fileName, line);
- } else if (!cmd->cmp("psLevel")) {
- parsePSLevel(tokens, fileName, line);
- } else if (!cmd->cmp("psEmbedType1Fonts")) {
- parseYesNo("psEmbedType1", &psEmbedType1, tokens, fileName, line);
- } else if (!cmd->cmp("psEmbedTrueTypeFonts")) {
- parseYesNo("psEmbedTrueType", &psEmbedTrueType,
- tokens, fileName, line);
- } else if (!cmd->cmp("psEmbedCIDPostScriptFonts")) {
- parseYesNo("psEmbedCIDPostScript", &psEmbedCIDPostScript,
- tokens, fileName, line);
- } else if (!cmd->cmp("psEmbedCIDTrueTypeFonts")) {
- parseYesNo("psEmbedCIDTrueType", &psEmbedCIDTrueType,
- tokens, fileName, line);
- } else if (!cmd->cmp("psOPI")) {
- parseYesNo("psOPI", &psOPI, tokens, fileName, line);
- } else if (!cmd->cmp("psASCIIHex")) {
- parseYesNo("psASCIIHex", &psASCIIHex, tokens, fileName, line);
- } else if (!cmd->cmp("textEncoding")) {
- parseTextEncoding(tokens, fileName, line);
- } else if (!cmd->cmp("textEOL")) {
- parseTextEOL(tokens, fileName, line);
- } else if (!cmd->cmp("textKeepTinyChars")) {
- parseYesNo("textKeepTinyChars", &textKeepTinyChars,
- tokens, fileName, line);
- } else if (!cmd->cmp("fontDir")) {
- parseFontDir(tokens, fileName, line);
- } else if (!cmd->cmp("initialZoom")) {
- parseInitialZoom(tokens, fileName, line);
- } else if (!cmd->cmp("t1libControl")) {
- parseFontRastControl("t1libControl", &t1libControl,
- tokens, fileName, line);
- } else if (!cmd->cmp("freetypeControl")) {
- parseFontRastControl("freetypeControl", &freetypeControl,
- tokens, fileName, line);
- } else if (!cmd->cmp("urlCommand")) {
- parseCommand("urlCommand", &urlCommand, tokens, fileName, line);
- } else if (!cmd->cmp("movieCommand")) {
- parseCommand("movieCommand", &movieCommand, tokens, fileName, line);
- } else if (!cmd->cmp("mapNumericCharNames")) {
- parseYesNo("mapNumericCharNames", &mapNumericCharNames,
- tokens, fileName, line);
- } else if (!cmd->cmp("printCommands")) {
- parseYesNo("printCommands", &printCommands, tokens, fileName, line);
- } else if (!cmd->cmp("errQuiet")) {
- parseYesNo("errQuiet", &errQuiet, tokens, fileName, line);
- } else if (!cmd->cmp("fontpath") || !cmd->cmp("fontmap")) {
- error(-1, "Unknown config file command");
- error(-1, "-- the config file format has changed since Xpdf 0.9x");
- } else {
- error(-1, "Unknown config file command '%s' (%s:%d)",
- cmd->getCString(), fileName->getCString(), line);
- }
- }
-
- deleteGList(tokens, GString);
- ++line;
- }
-}
-
-void GlobalParams::parseNameToUnicode(GList *tokens, GString *fileName,
- int line) {
- GString *name;
- char *tok1, *tok2;
- FILE *f;
- char buf[256];
- int line2;
- Unicode u;
-
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'nameToUnicode' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- name = (GString *)tokens->get(1);
- if (!(f = fopen(name->getCString(), "r"))) {
- error(-1, "Couldn't open 'nameToUnicode' file '%s'",
- name->getCString());
- return;
- }
- line2 = 1;
- while (fgets(buf, sizeof(buf), f)) {
- tok1 = strtok(buf, " \t\r\n");
- tok2 = strtok(NULL, " \t\r\n");
- if (tok1 && tok2) {
- sscanf(tok1, "%x", &u);
- nameToUnicode->add(tok2, u);
- } else {
- error(-1, "Bad line in 'nameToUnicode' file (%s:%d)", name, line2);
- }
- ++line2;
- }
- fclose(f);
-}
-
-void GlobalParams::parseCIDToUnicode(GList *tokens, GString *fileName,
- int line) {
- GString *collection, *name, *old;
-
- if (tokens->getLength() != 3) {
- error(-1, "Bad 'cidToUnicode' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- collection = (GString *)tokens->get(1);
- name = (GString *)tokens->get(2);
- if ((old = (GString *)cidToUnicodes->remove(collection))) {
- delete old;
- }
- cidToUnicodes->add(collection->copy(), name->copy());
-}
-
-void GlobalParams::parseUnicodeMap(GList *tokens, GString *fileName,
- int line) {
- GString *encodingName, *name, *old;
-
- if (tokens->getLength() != 3) {
- error(-1, "Bad 'unicodeMap' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- encodingName = (GString *)tokens->get(1);
- name = (GString *)tokens->get(2);
- if ((old = (GString *)unicodeMaps->remove(encodingName))) {
- delete old;
- }
- unicodeMaps->add(encodingName->copy(), name->copy());
-}
-
-void GlobalParams::parseCMapDir(GList *tokens, GString *fileName, int line) {
- GString *collection, *dir;
- GList *list;
-
- if (tokens->getLength() != 3) {
- error(-1, "Bad 'cMapDir' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- collection = (GString *)tokens->get(1);
- dir = (GString *)tokens->get(2);
- if (!(list = (GList *)cMapDirs->lookup(collection))) {
- list = new GList();
- cMapDirs->add(collection->copy(), list);
- }
- list->append(dir->copy());
-}
-
-void GlobalParams::parseToUnicodeDir(GList *tokens, GString *fileName,
- int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'toUnicodeDir' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- toUnicodeDirs->append(((GString *)tokens->get(1))->copy());
-}
-
-void GlobalParams::parseDisplayFont(GList *tokens, GHash *fontHash,
- DisplayFontParamKind kind,
- GString *fileName, int line) {
- DisplayFontParam *param, *old;
-
- if (tokens->getLength() < 2) {
- goto err1;
- }
- param = new DisplayFontParam(((GString *)tokens->get(1))->copy(), kind);
-
- switch (kind) {
- case displayFontX:
- if (tokens->getLength() != 4) {
- goto err2;
- }
- param->x.xlfd = ((GString *)tokens->get(2))->copy();
- param->x.encoding = ((GString *)tokens->get(3))->copy();
- break;
- case displayFontT1:
- if (tokens->getLength() != 3) {
- goto err2;
- }
- param->t1.fileName = ((GString *)tokens->get(2))->copy();
- break;
- case displayFontTT:
- if (tokens->getLength() != 3) {
- goto err2;
- }
- param->tt.fileName = ((GString *)tokens->get(2))->copy();
- break;
- }
-
- if ((old = (DisplayFontParam *)fontHash->remove(param->name))) {
- delete old;
- }
- fontHash->add(param->name, param);
- return;
-
- err2:
- delete param;
- err1:
- error(-1, "Bad 'display*Font*' config file command (%s:%d)",
- fileName->getCString(), line);
-}
-
-void GlobalParams::parsePSPaperSize(GList *tokens, GString *fileName,
- int line) {
- GString *tok;
-
- if (tokens->getLength() == 2) {
- tok = (GString *)tokens->get(1);
- if (!setPSPaperSize(tok->getCString())) {
- error(-1, "Bad 'psPaperSize' config file command (%s:%d)",
- fileName->getCString(), line);
- }
- } else if (tokens->getLength() == 3) {
- tok = (GString *)tokens->get(1);
- psPaperWidth = atoi(tok->getCString());
- tok = (GString *)tokens->get(2);
- psPaperHeight = atoi(tok->getCString());
- } else {
- error(-1, "Bad 'psPaperSize' config file command (%s:%d)",
- fileName->getCString(), line);
- }
-}
-
-void GlobalParams::parsePSLevel(GList *tokens, GString *fileName, int line) {
- GString *tok;
-
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'psLevel' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- tok = (GString *)tokens->get(1);
- if (!tok->cmp("level1")) {
- psLevel = psLevel1;
- } else if (!tok->cmp("level1sep")) {
- psLevel = psLevel1Sep;
- } else if (!tok->cmp("level2")) {
- psLevel = psLevel2;
- } else if (!tok->cmp("level2sep")) {
- psLevel = psLevel2Sep;
- } else if (!tok->cmp("level3")) {
- psLevel = psLevel3;
- } else if (!tok->cmp("level3Sep")) {
- psLevel = psLevel3Sep;
- } else {
- error(-1, "Bad 'psLevel' config file command (%s:%d)",
- fileName->getCString(), line);
- }
-}
-
-void GlobalParams::parsePSFile(GList *tokens, GString *fileName, int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'psFile' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- if (psFile) {
- delete psFile;
- }
- psFile = ((GString *)tokens->get(1))->copy();
-}
-
-void GlobalParams::parsePSFont(GList *tokens, GString *fileName, int line) {
- PSFontParam *param;
-
- if (tokens->getLength() != 3) {
- error(-1, "Bad 'psFont' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- param = new PSFontParam(((GString *)tokens->get(1))->copy(), 0,
- ((GString *)tokens->get(2))->copy(), NULL);
- psFonts->add(param->pdfFontName, param);
-}
-
-void GlobalParams::parsePSFont16(const char *cmdName, GList *fontList,
- GList *tokens, GString *fileName, int line) {
- PSFontParam *param;
- int wMode;
- GString *tok;
-
- if (tokens->getLength() != 5) {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- return;
- }
- tok = (GString *)tokens->get(2);
- if (!tok->cmp("H")) {
- wMode = 0;
- } else if (!tok->cmp("V")) {
- wMode = 1;
- } else {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- return;
- }
- param = new PSFontParam(((GString *)tokens->get(1))->copy(),
- wMode,
- ((GString *)tokens->get(3))->copy(),
- ((GString *)tokens->get(4))->copy());
- fontList->append(param);
-}
-
-void GlobalParams::parseTextEncoding(GList *tokens, GString *fileName,
- int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'textEncoding' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- delete textEncoding;
- textEncoding = ((GString *)tokens->get(1))->copy();
-}
-
-void GlobalParams::parseTextEOL(GList *tokens, GString *fileName, int line) {
- GString *tok;
-
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'textEOL' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- tok = (GString *)tokens->get(1);
- if (!tok->cmp("unix")) {
- textEOL = eolUnix;
- } else if (!tok->cmp("dos")) {
- textEOL = eolDOS;
- } else if (!tok->cmp("mac")) {
- textEOL = eolMac;
- } else {
- error(-1, "Bad 'textEOL' config file command (%s:%d)",
- fileName->getCString(), line);
- }
-}
-
-void GlobalParams::parseFontDir(GList *tokens, GString *fileName, int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'fontDir' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- fontDirs->append(((GString *)tokens->get(1))->copy());
-}
-
-void GlobalParams::parseInitialZoom(GList *tokens,
- GString *fileName, int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad 'initialZoom' config file command (%s:%d)",
- fileName->getCString(), line);
- return;
- }
- delete initialZoom;
- initialZoom = ((GString *)tokens->get(1))->copy();
-}
-
-void GlobalParams::parseFontRastControl(const char *cmdName, FontRastControl *val,
- GList *tokens, GString *fileName,
- int line) {
- GString *tok;
-
- if (tokens->getLength() != 2) {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- return;
- }
- tok = (GString *)tokens->get(1);
- if (!setFontRastControl(val, tok->getCString())) {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- }
-}
-
-void GlobalParams::parseCommand(const char *cmdName, GString **val,
- GList *tokens, GString *fileName, int line) {
- if (tokens->getLength() != 2) {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- return;
- }
- if (*val) {
- delete *val;
- }
- *val = ((GString *)tokens->get(1))->copy();
-}
-
-void GlobalParams::parseYesNo(const char *cmdName, GBool *flag,
- GList *tokens, GString *fileName, int line) {
- GString *tok;
-
- if (tokens->getLength() != 2) {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- return;
- }
- tok = (GString *)tokens->get(1);
- if (!tok->cmp("yes")) {
- *flag = gTrue;
- } else if (!tok->cmp("no")) {
- *flag = gFalse;
- } else {
- error(-1, "Bad '%s' config file command (%s:%d)",
- cmdName, fileName->getCString(), line);
- }
-}
-
-GlobalParams::~GlobalParams() {
- GHashIter *iter;
- GString *key;
- GList *list;
-
- freeBuiltinFontTables();
-
- delete macRomanReverseMap;
-
- delete nameToUnicode;
- deleteGHash(cidToUnicodes, GString);
- deleteGHash(residentUnicodeMaps, UnicodeMap);
- deleteGHash(unicodeMaps, GString);
- deleteGList(toUnicodeDirs, GString);
- deleteGHash(displayFonts, DisplayFontParam);
- deleteGHash(displayCIDFonts, DisplayFontParam);
- deleteGHash(displayNamedCIDFonts, DisplayFontParam);
- if (psFile) {
- delete psFile;
- }
- deleteGHash(psFonts, PSFontParam);
- deleteGList(psNamedFonts16, PSFontParam);
- deleteGList(psFonts16, PSFontParam);
- delete textEncoding;
- deleteGList(fontDirs, GString);
- delete initialZoom;
- if (urlCommand) {
- delete urlCommand;
- }
- if (movieCommand) {
- delete movieCommand;
- }
-
- cMapDirs->startIter(&iter);
- while (cMapDirs->getNext(&iter, &key, (void **)&list)) {
- deleteGList(list, GString);
- }
- delete cMapDirs;
-
- delete cidToUnicodeCache;
- delete unicodeMapCache;
- delete cMapCache;
-}
-
-//------------------------------------------------------------------------
-// accessors
-//------------------------------------------------------------------------
-
-CharCode GlobalParams::getMacRomanCharCode(const char *charName) {
- return macRomanReverseMap->lookup(charName);
-}
-
-Unicode GlobalParams::mapNameToUnicode(const char *charName) {
- return nameToUnicode->lookup(charName);
-}
-
-FILE *GlobalParams::getCIDToUnicodeFile(const GString *collection) {
- GString *fileName;
-
- if (!(fileName = (GString *)cidToUnicodes->lookup(collection))) {
- return NULL;
- }
- return fopen(fileName->getCString(), "r");
-}
-
-UnicodeMap *GlobalParams::getResidentUnicodeMap(const GString *encodingName) {
- return (UnicodeMap *)residentUnicodeMaps->lookup(encodingName);
-}
-
-FILE *GlobalParams::getUnicodeMapFile(const GString *encodingName) {
- GString *fileName;
-
- if (!(fileName = (GString *)unicodeMaps->lookup(encodingName))) {
- return NULL;
- }
- return fopen(fileName->getCString(), "r");
-}
-
-FILE *GlobalParams::findCMapFile(const GString *collection, const GString *cMapName) {
- GList *list;
- GString *dir;
- GString *fileName;
- FILE *f;
- int i;
-
- if (!(list = (GList *)cMapDirs->lookup(collection))) {
- return NULL;
- }
- for (i = 0; i < list->getLength(); ++i) {
- dir = (GString *)list->get(i);
- fileName = appendToPath(dir->copy(), cMapName->getCString());
- f = fopen(fileName->getCString(), "r");
- delete fileName;
- if (f) {
- return f;
- }
- }
- return NULL;
-}
-
-FILE *GlobalParams::findToUnicodeFile(const GString *name) {
- GString *dir, *fileName;
- FILE *f;
- int i;
-
- for (i = 0; i < toUnicodeDirs->getLength(); ++i) {
- dir = (GString *)toUnicodeDirs->get(i);
- fileName = appendToPath(dir->copy(), name->getCString());
- f = fopen(fileName->getCString(), "r");
- delete fileName;
- if (f) {
- return f;
- }
- }
- return NULL;
-}
-
-DisplayFontParam *GlobalParams::getDisplayFont(const GString *fontName) {
- return (DisplayFontParam *)displayFonts->lookup(fontName);
-}
-
-DisplayFontParam *GlobalParams::getDisplayCIDFont(const GString *fontName,
- const GString *collection) {
- DisplayFontParam *dfp;
-
- if (!fontName ||
- !(dfp = (DisplayFontParam *)displayNamedCIDFonts->lookup(fontName))) {
- dfp = (DisplayFontParam *)displayCIDFonts->lookup(collection);
- }
- return dfp;
-}
-
-PSFontParam *GlobalParams::getPSFont(GString *fontName) {
- return (PSFontParam *)psFonts->lookup(fontName);
-}
-
-PSFontParam *GlobalParams::getPSFont16(GString *fontName,
- GString *collection, int wMode) {
- PSFontParam *p;
- int i;
-
- p = NULL;
- if (fontName) {
- for (i = 0; i < psNamedFonts16->getLength(); ++i) {
- p = (PSFontParam *)psNamedFonts16->get(i);
- if (!p->pdfFontName->cmp(fontName) &&
- p->wMode == wMode) {
- break;
- }
- p = NULL;
- }
- }
- if (!p && collection) {
- for (i = 0; i < psFonts16->getLength(); ++i) {
- p = (PSFontParam *)psFonts16->get(i);
- if (!p->pdfFontName->cmp(collection) &&
- p->wMode == wMode) {
- break;
- }
- p = NULL;
- }
- }
- return p;
-}
-
-GString *GlobalParams::findFontFile(const GString *fontName,
- const char *ext1, const char *ext2) {
- GString *dir, *fileName;
- FILE *f;
- int i;
-
- for (i = 0; i < fontDirs->getLength(); ++i) {
- dir = (GString *)fontDirs->get(i);
- if (ext1) {
- fileName = appendToPath(dir->copy(), fontName->getCString());
- fileName->append(ext1);
- if ((f = fopen(fileName->getCString(), "r"))) {
- fclose(f);
- return fileName;
- }
- delete fileName;
- }
- if (ext2) {
- fileName = appendToPath(dir->copy(), fontName->getCString());
- fileName->append(ext2);
- if ((f = fopen(fileName->getCString(), "r"))) {
- fclose(f);
- return fileName;
- }
- delete fileName;
- }
- }
- return NULL;
-}
-
-CharCodeToUnicode *GlobalParams::getCIDToUnicode(GString *collection) {
- return cidToUnicodeCache->getCIDToUnicode(collection);
-}
-
-UnicodeMap *GlobalParams::getUnicodeMap(GString *encodingName) {
- UnicodeMap *map;
-
- if ((map = getResidentUnicodeMap(encodingName))) {
- map->incRefCnt();
- return map;
- }
- return unicodeMapCache->getUnicodeMap(encodingName);
-}
-
-CMap *GlobalParams::getCMap(GString *collection, GString *cMapName) {
- return cMapCache->getCMap(collection, cMapName);
-}
-
-UnicodeMap *GlobalParams::getTextEncoding() {
- return getUnicodeMap(textEncoding);
-}
-
-//------------------------------------------------------------------------
-// functions to set parameters
-//------------------------------------------------------------------------
-
-void GlobalParams::addDisplayFont(DisplayFontParam *param) {
- DisplayFontParam *old;
-
- if ((old = (DisplayFontParam *)displayFonts->remove(param->name))) {
- delete old;
- }
- displayFonts->add(param->name, param);
-}
-
-void GlobalParams::setPSFile(char *file) {
- if (psFile) {
- delete psFile;
- }
- psFile = new GString(file);
-}
-
-GBool GlobalParams::setPSPaperSize(char *size) {
- if (!strcmp(size, "letter")) {
- psPaperWidth = 612;
- psPaperHeight = 792;
- } else if (!strcmp(size, "legal")) {
- psPaperWidth = 612;
- psPaperHeight = 1008;
- } else if (!strcmp(size, "A4")) {
- psPaperWidth = 595;
- psPaperHeight = 842;
- } else if (!strcmp(size, "A3")) {
- psPaperWidth = 842;
- psPaperHeight = 1190;
- } else {
- return gFalse;
- }
- return gTrue;
-}
-
-void GlobalParams::setPSPaperWidth(int width) {
- psPaperWidth = width;
-}
-
-void GlobalParams::setPSPaperHeight(int height) {
- psPaperHeight = height;
-}
-
-void GlobalParams::setPSDuplex(GBool duplex) {
- psDuplex = duplex;
-}
-
-void GlobalParams::setPSLevel(PSLevel level) {
- psLevel = level;
-}
-
-void GlobalParams::setPSEmbedType1(GBool embed) {
- psEmbedType1 = embed;
-}
-
-void GlobalParams::setPSEmbedTrueType(GBool embed) {
- psEmbedTrueType = embed;
-}
-
-void GlobalParams::setPSEmbedCIDPostScript(GBool embed) {
- psEmbedCIDPostScript = embed;
-}
-
-void GlobalParams::setPSEmbedCIDTrueType(GBool embed) {
- psEmbedCIDTrueType = embed;
-}
-
-void GlobalParams::setPSOPI(GBool opi) {
- psOPI = opi;
-}
-
-void GlobalParams::setPSASCIIHex(GBool hex) {
- psASCIIHex = hex;
-}
-
-void GlobalParams::setTextEncoding(char *encodingName) {
- delete textEncoding;
- textEncoding = new GString(encodingName);
-}
-
-GBool GlobalParams::setTextEOL(char *s) {
- if (!strcmp(s, "unix")) {
- textEOL = eolUnix;
- } else if (!strcmp(s, "dos")) {
- textEOL = eolDOS;
- } else if (!strcmp(s, "mac")) {
- textEOL = eolMac;
- } else {
- return gFalse;
- }
- return gTrue;
-}
-
-void GlobalParams::setTextKeepTinyChars(GBool keep) {
- textKeepTinyChars = keep;
-}
-
-void GlobalParams::setInitialZoom(char *s) {
- delete initialZoom;
- initialZoom = new GString(s);
-}
-
-GBool GlobalParams::setT1libControl(char *s) {
- return setFontRastControl(&t1libControl, s);
-}
-
-GBool GlobalParams::setFreeTypeControl(char *s) {
- return setFontRastControl(&freetypeControl, s);
-}
-
-GBool GlobalParams::setFontRastControl(FontRastControl *val, const char *s) {
- if (!strcmp(s, "none")) {
- *val = fontRastNone;
- } else if (!strcmp(s, "plain")) {
- *val = fontRastPlain;
- } else if (!strcmp(s, "low")) {
- *val = fontRastAALow;
- } else if (!strcmp(s, "high")) {
- *val = fontRastAAHigh;
- } else {
- return gFalse;
- }
- return gTrue;
-}
-
-void GlobalParams::setMapNumericCharNames(GBool map) {
- mapNumericCharNames = map;
-}
-
-void GlobalParams::setPrintCommands(GBool printCommandsA) {
- printCommands = printCommandsA;
-}
-
-void GlobalParams::setErrQuiet(GBool errQuietA) {
- errQuiet = errQuietA;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/GlobalParams.cpp b/filters/kword/pdf/xpdf/xpdf/GlobalParams.cpp
new file mode 100644
index 000000000..be2569d34
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/GlobalParams.cpp
@@ -0,0 +1,1112 @@
+//========================================================================
+//
+// GlobalParams.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <string.h>
+#include <ctype.h>
+#ifdef HAVE_PAPER_H
+#include <paper.h>
+#endif
+#include "gmem.h"
+#include "GString.h"
+#include "GList.h"
+#include "GHash.h"
+#include "gfile.h"
+#include "Error.h"
+#include "NameToCharCode.h"
+#include "CharCodeToUnicode.h"
+#include "UnicodeMap.h"
+#include "CMap.h"
+#include "BuiltinFontTables.h"
+#include "FontEncodingTables.h"
+#include "GlobalParams.h"
+
+#include "NameToUnicodeTable.h"
+#include "UnicodeMapTables.h"
+#include "DisplayFontTable.h"
+#include "UTF8.h"
+
+//------------------------------------------------------------------------
+
+GlobalParams *globalParams = NULL;
+
+//------------------------------------------------------------------------
+// DisplayFontParam
+//------------------------------------------------------------------------
+
+DisplayFontParam::DisplayFontParam(GString *nameA,
+ DisplayFontParamKind kindA) {
+ name = nameA;
+ kind = kindA;
+ switch (kind) {
+ case displayFontX:
+ x.xlfd = NULL;
+ x.encoding = NULL;
+ break;
+ case displayFontT1:
+ t1.fileName = NULL;
+ break;
+ case displayFontTT:
+ tt.fileName = NULL;
+ break;
+ }
+}
+
+DisplayFontParam::DisplayFontParam(const char *nameA, const char *xlfdA,
+ const char *encodingA) {
+ name = new GString(nameA);
+ kind = displayFontX;
+ x.xlfd = new GString(xlfdA);
+ x.encoding = new GString(encodingA);
+}
+
+DisplayFontParam::~DisplayFontParam() {
+ delete name;
+ switch (kind) {
+ case displayFontX:
+ if (x.xlfd) {
+ delete x.xlfd;
+ }
+ if (x.encoding) {
+ delete x.encoding;
+ }
+ break;
+ case displayFontT1:
+ if (t1.fileName) {
+ delete t1.fileName;
+ }
+ break;
+ case displayFontTT:
+ if (tt.fileName) {
+ delete tt.fileName;
+ }
+ break;
+ }
+}
+
+//------------------------------------------------------------------------
+// PSFontParam
+//------------------------------------------------------------------------
+
+PSFontParam::PSFontParam(GString *pdfFontNameA, int wModeA,
+ GString *psFontNameA, GString *encodingA) {
+ pdfFontName = pdfFontNameA;
+ wMode = wModeA;
+ psFontName = psFontNameA;
+ encoding = encodingA;
+}
+
+PSFontParam::~PSFontParam() {
+ delete pdfFontName;
+ delete psFontName;
+ if (encoding) {
+ delete encoding;
+ }
+}
+
+//------------------------------------------------------------------------
+// parsing
+//------------------------------------------------------------------------
+
+GlobalParams::GlobalParams(const char *cfgFileName) {
+ UnicodeMap *map;
+ DisplayFontParam *dfp;
+ GString *fileName;
+ FILE *f;
+ int i;
+
+ initBuiltinFontTables();
+
+ // scan the encoding in reverse because we want the lowest-numbered
+ // index for each char name ('space' is encoded twice)
+ macRomanReverseMap = new NameToCharCode();
+ for (i = 255; i >= 0; --i) {
+ if (macRomanEncoding[i]) {
+ macRomanReverseMap->add(macRomanEncoding[i], (CharCode)i);
+ }
+ }
+
+ nameToUnicode = new NameToCharCode();
+ cidToUnicodes = new GHash(gTrue);
+ residentUnicodeMaps = new GHash();
+ unicodeMaps = new GHash(gTrue);
+ cMapDirs = new GHash(gTrue);
+ toUnicodeDirs = new GList();
+ displayFonts = new GHash();
+ displayCIDFonts = new GHash();
+ displayNamedCIDFonts = new GHash();
+#ifdef HAVE_PAPER_H
+ char *paperName;
+ const struct paper *paperType;
+ paperinit();
+ if ((paperName = systempapername())) {
+ paperType = paperinfo(paperName);
+ psPaperWidth = (int)paperpswidth(paperType);
+ psPaperHeight = (int)paperpsheight(paperType);
+ } else {
+ error(-1, "No paper information available - using defaults");
+ psPaperWidth = defPaperWidth;
+ psPaperHeight = defPaperHeight;
+ }
+ paperdone();
+#else
+ psPaperWidth = defPaperWidth;
+ psPaperHeight = defPaperHeight;
+#endif
+ psDuplex = gFalse;
+ psLevel = psLevel2;
+ psFile = NULL;
+ psFonts = new GHash();
+ psNamedFonts16 = new GList();
+ psFonts16 = new GList();
+ psEmbedType1 = gTrue;
+ psEmbedTrueType = gTrue;
+ psEmbedCIDPostScript = gTrue;
+ psEmbedCIDTrueType = gTrue;
+ psOPI = gFalse;
+ psASCIIHex = gFalse;
+ textEncoding = new GString("Latin1");
+#if defined(WIN32)
+ textEOL = eolDOS;
+#elif defined(MACOS)
+ textEOL = eolMac;
+#else
+ textEOL = eolUnix;
+#endif
+ textKeepTinyChars = gFalse;
+ fontDirs = new GList();
+ initialZoom = new GString("1");
+ t1libControl = fontRastAALow;
+ freetypeControl = fontRastAALow;
+ urlCommand = NULL;
+ movieCommand = NULL;
+ mapNumericCharNames = gTrue;
+ printCommands = gFalse;
+ errQuiet = gFalse;
+
+ cidToUnicodeCache = new CIDToUnicodeCache();
+ unicodeMapCache = new UnicodeMapCache();
+ cMapCache = new CMapCache();
+
+ // set up the initial nameToUnicode table
+ for (i = 0; nameToUnicodeTab[i].name; ++i) {
+ nameToUnicode->add(nameToUnicodeTab[i].name, nameToUnicodeTab[i].u);
+ }
+
+ // set up the residentUnicodeMaps table
+ map = new UnicodeMap("Latin1", gFalse,
+ latin1UnicodeMapRanges, latin1UnicodeMapLen);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+ map = new UnicodeMap("ASCII7", gFalse,
+ ascii7UnicodeMapRanges, ascii7UnicodeMapLen);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+ map = new UnicodeMap("Symbol", gFalse,
+ symbolUnicodeMapRanges, symbolUnicodeMapLen);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+ map = new UnicodeMap("ZapfDingbats", gFalse, zapfDingbatsUnicodeMapRanges,
+ zapfDingbatsUnicodeMapLen);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+ map = new UnicodeMap("UTF-8", gTrue, &mapUTF8);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+ map = new UnicodeMap("UCS-2", gTrue, &mapUCS2);
+ residentUnicodeMaps->add(map->getEncodingName(), map);
+
+ // default displayFonts table
+ for (i = 0; displayFontTab[i].name; ++i) {
+ dfp = new DisplayFontParam(displayFontTab[i].name,
+ displayFontTab[i].xlfd,
+ displayFontTab[i].encoding);
+ displayFonts->add(dfp->name, dfp);
+ }
+
+ // look for a user config file, then a system-wide config file
+ f = NULL;
+ fileName = NULL;
+ if (cfgFileName && cfgFileName[0]) {
+ fileName = new GString(cfgFileName);
+ if (!(f = fopen(fileName->getCString(), "r"))) {
+ delete fileName;
+ }
+ }
+ if (!f) {
+ fileName = appendToPath(getHomeDir(), xpdfUserConfigFile);
+ if (!(f = fopen(fileName->getCString(), "r"))) {
+ delete fileName;
+ }
+ }
+ if (!f) {
+#if defined(WIN32) && !defined(__CYGWIN32__)
+ char buf[512];
+ i = GetModuleFileName(NULL, buf, sizeof(buf));
+ if (i <= 0 || i >= sizeof(buf)) {
+ // error or path too long for buffer - just use the current dir
+ buf[0] = '\0';
+ }
+ fileName = grabPath(buf);
+ appendToPath(fileName, xpdfSysConfigFile);
+#else
+ fileName = new GString(xpdfSysConfigFile);
+#endif
+ if (!(f = fopen(fileName->getCString(), "r"))) {
+ delete fileName;
+ }
+ }
+ if (f) {
+ parseFile(fileName, f);
+ delete fileName;
+ fclose(f);
+ }
+}
+
+void GlobalParams::parseFile(GString *fileName, FILE *f) {
+ int line;
+ GList *tokens;
+ GString *cmd, *incFile;
+ char *p1, *p2;
+ char buf[512];
+ FILE *f2;
+
+ line = 1;
+ while (fgets(buf, sizeof(buf) - 1, f)) {
+
+ // break the line into tokens
+ tokens = new GList();
+ p1 = buf;
+ while (*p1) {
+ for (; *p1 && isspace(*p1); ++p1) ;
+ if (!*p1) {
+ break;
+ }
+ if (*p1 == '"' || *p1 == '\'') {
+ for (p2 = p1 + 1; *p2 && *p2 != *p1; ++p2) ;
+ ++p1;
+ } else {
+ for (p2 = p1 + 1; *p2 && !isspace(*p2); ++p2) ;
+ }
+ tokens->append(new GString(p1, p2 - p1));
+ p1 = p2 + 1;
+ }
+
+ if (tokens->getLength() > 0 &&
+ ((GString *)tokens->get(0))->getChar(0) != '#') {
+ cmd = (GString *)tokens->get(0);
+ if (!cmd->cmp("include")) {
+ if (tokens->getLength() == 2) {
+ incFile = (GString *)tokens->get(1);
+ if ((f2 = fopen(incFile->getCString(), "r"))) {
+ parseFile(incFile, f2);
+ fclose(f2);
+ } else {
+ error(-1, "Couldn't find included config file: '%s' (%s:%d)",
+ incFile->getCString(), fileName->getCString(), line);
+ }
+ } else {
+ error(-1, "Bad 'include' config file command (%s:%d)",
+ fileName->getCString(), line);
+ }
+ } else if (!cmd->cmp("nameToUnicode")) {
+ parseNameToUnicode(tokens, fileName, line);
+ } else if (!cmd->cmp("cidToUnicode")) {
+ parseCIDToUnicode(tokens, fileName, line);
+ } else if (!cmd->cmp("unicodeMap")) {
+ parseUnicodeMap(tokens, fileName, line);
+ } else if (!cmd->cmp("cMapDir")) {
+ parseCMapDir(tokens, fileName, line);
+ } else if (!cmd->cmp("toUnicodeDir")) {
+ parseToUnicodeDir(tokens, fileName, line);
+ } else if (!cmd->cmp("displayFontX")) {
+ parseDisplayFont(tokens, displayFonts, displayFontX, fileName, line);
+ } else if (!cmd->cmp("displayFontT1")) {
+ parseDisplayFont(tokens, displayFonts, displayFontT1, fileName, line);
+ } else if (!cmd->cmp("displayFontTT")) {
+ parseDisplayFont(tokens, displayFonts, displayFontTT, fileName, line);
+ } else if (!cmd->cmp("displayCIDFontX")) {
+ parseDisplayFont(tokens, displayCIDFonts,
+ displayFontX, fileName, line);
+ } else if (!cmd->cmp("displayNamedCIDFontX")) {
+ parseDisplayFont(tokens, displayNamedCIDFonts,
+ displayFontX, fileName, line);
+ } else if (!cmd->cmp("psFile")) {
+ parsePSFile(tokens, fileName, line);
+ } else if (!cmd->cmp("psFont")) {
+ parsePSFont(tokens, fileName, line);
+ } else if (!cmd->cmp("psNamedFont16")) {
+ parsePSFont16("psNamedFont16", psNamedFonts16,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("psFont16")) {
+ parsePSFont16("psFont16", psFonts16, tokens, fileName, line);
+ } else if (!cmd->cmp("psPaperSize")) {
+ parsePSPaperSize(tokens, fileName, line);
+ } else if (!cmd->cmp("psDuplex")) {
+ parseYesNo("psDuplex", &psDuplex, tokens, fileName, line);
+ } else if (!cmd->cmp("psLevel")) {
+ parsePSLevel(tokens, fileName, line);
+ } else if (!cmd->cmp("psEmbedType1Fonts")) {
+ parseYesNo("psEmbedType1", &psEmbedType1, tokens, fileName, line);
+ } else if (!cmd->cmp("psEmbedTrueTypeFonts")) {
+ parseYesNo("psEmbedTrueType", &psEmbedTrueType,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("psEmbedCIDPostScriptFonts")) {
+ parseYesNo("psEmbedCIDPostScript", &psEmbedCIDPostScript,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("psEmbedCIDTrueTypeFonts")) {
+ parseYesNo("psEmbedCIDTrueType", &psEmbedCIDTrueType,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("psOPI")) {
+ parseYesNo("psOPI", &psOPI, tokens, fileName, line);
+ } else if (!cmd->cmp("psASCIIHex")) {
+ parseYesNo("psASCIIHex", &psASCIIHex, tokens, fileName, line);
+ } else if (!cmd->cmp("textEncoding")) {
+ parseTextEncoding(tokens, fileName, line);
+ } else if (!cmd->cmp("textEOL")) {
+ parseTextEOL(tokens, fileName, line);
+ } else if (!cmd->cmp("textKeepTinyChars")) {
+ parseYesNo("textKeepTinyChars", &textKeepTinyChars,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("fontDir")) {
+ parseFontDir(tokens, fileName, line);
+ } else if (!cmd->cmp("initialZoom")) {
+ parseInitialZoom(tokens, fileName, line);
+ } else if (!cmd->cmp("t1libControl")) {
+ parseFontRastControl("t1libControl", &t1libControl,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("freetypeControl")) {
+ parseFontRastControl("freetypeControl", &freetypeControl,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("urlCommand")) {
+ parseCommand("urlCommand", &urlCommand, tokens, fileName, line);
+ } else if (!cmd->cmp("movieCommand")) {
+ parseCommand("movieCommand", &movieCommand, tokens, fileName, line);
+ } else if (!cmd->cmp("mapNumericCharNames")) {
+ parseYesNo("mapNumericCharNames", &mapNumericCharNames,
+ tokens, fileName, line);
+ } else if (!cmd->cmp("printCommands")) {
+ parseYesNo("printCommands", &printCommands, tokens, fileName, line);
+ } else if (!cmd->cmp("errQuiet")) {
+ parseYesNo("errQuiet", &errQuiet, tokens, fileName, line);
+ } else if (!cmd->cmp("fontpath") || !cmd->cmp("fontmap")) {
+ error(-1, "Unknown config file command");
+ error(-1, "-- the config file format has changed since Xpdf 0.9x");
+ } else {
+ error(-1, "Unknown config file command '%s' (%s:%d)",
+ cmd->getCString(), fileName->getCString(), line);
+ }
+ }
+
+ deleteGList(tokens, GString);
+ ++line;
+ }
+}
+
+void GlobalParams::parseNameToUnicode(GList *tokens, GString *fileName,
+ int line) {
+ GString *name;
+ char *tok1, *tok2;
+ FILE *f;
+ char buf[256];
+ int line2;
+ Unicode u;
+
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'nameToUnicode' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ name = (GString *)tokens->get(1);
+ if (!(f = fopen(name->getCString(), "r"))) {
+ error(-1, "Couldn't open 'nameToUnicode' file '%s'",
+ name->getCString());
+ return;
+ }
+ line2 = 1;
+ while (fgets(buf, sizeof(buf), f)) {
+ tok1 = strtok(buf, " \t\r\n");
+ tok2 = strtok(NULL, " \t\r\n");
+ if (tok1 && tok2) {
+ sscanf(tok1, "%x", &u);
+ nameToUnicode->add(tok2, u);
+ } else {
+ error(-1, "Bad line in 'nameToUnicode' file (%s:%d)", name, line2);
+ }
+ ++line2;
+ }
+ fclose(f);
+}
+
+void GlobalParams::parseCIDToUnicode(GList *tokens, GString *fileName,
+ int line) {
+ GString *collection, *name, *old;
+
+ if (tokens->getLength() != 3) {
+ error(-1, "Bad 'cidToUnicode' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ collection = (GString *)tokens->get(1);
+ name = (GString *)tokens->get(2);
+ if ((old = (GString *)cidToUnicodes->remove(collection))) {
+ delete old;
+ }
+ cidToUnicodes->add(collection->copy(), name->copy());
+}
+
+void GlobalParams::parseUnicodeMap(GList *tokens, GString *fileName,
+ int line) {
+ GString *encodingName, *name, *old;
+
+ if (tokens->getLength() != 3) {
+ error(-1, "Bad 'unicodeMap' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ encodingName = (GString *)tokens->get(1);
+ name = (GString *)tokens->get(2);
+ if ((old = (GString *)unicodeMaps->remove(encodingName))) {
+ delete old;
+ }
+ unicodeMaps->add(encodingName->copy(), name->copy());
+}
+
+void GlobalParams::parseCMapDir(GList *tokens, GString *fileName, int line) {
+ GString *collection, *dir;
+ GList *list;
+
+ if (tokens->getLength() != 3) {
+ error(-1, "Bad 'cMapDir' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ collection = (GString *)tokens->get(1);
+ dir = (GString *)tokens->get(2);
+ if (!(list = (GList *)cMapDirs->lookup(collection))) {
+ list = new GList();
+ cMapDirs->add(collection->copy(), list);
+ }
+ list->append(dir->copy());
+}
+
+void GlobalParams::parseToUnicodeDir(GList *tokens, GString *fileName,
+ int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'toUnicodeDir' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ toUnicodeDirs->append(((GString *)tokens->get(1))->copy());
+}
+
+void GlobalParams::parseDisplayFont(GList *tokens, GHash *fontHash,
+ DisplayFontParamKind kind,
+ GString *fileName, int line) {
+ DisplayFontParam *param, *old;
+
+ if (tokens->getLength() < 2) {
+ goto err1;
+ }
+ param = new DisplayFontParam(((GString *)tokens->get(1))->copy(), kind);
+
+ switch (kind) {
+ case displayFontX:
+ if (tokens->getLength() != 4) {
+ goto err2;
+ }
+ param->x.xlfd = ((GString *)tokens->get(2))->copy();
+ param->x.encoding = ((GString *)tokens->get(3))->copy();
+ break;
+ case displayFontT1:
+ if (tokens->getLength() != 3) {
+ goto err2;
+ }
+ param->t1.fileName = ((GString *)tokens->get(2))->copy();
+ break;
+ case displayFontTT:
+ if (tokens->getLength() != 3) {
+ goto err2;
+ }
+ param->tt.fileName = ((GString *)tokens->get(2))->copy();
+ break;
+ }
+
+ if ((old = (DisplayFontParam *)fontHash->remove(param->name))) {
+ delete old;
+ }
+ fontHash->add(param->name, param);
+ return;
+
+ err2:
+ delete param;
+ err1:
+ error(-1, "Bad 'display*Font*' config file command (%s:%d)",
+ fileName->getCString(), line);
+}
+
+void GlobalParams::parsePSPaperSize(GList *tokens, GString *fileName,
+ int line) {
+ GString *tok;
+
+ if (tokens->getLength() == 2) {
+ tok = (GString *)tokens->get(1);
+ if (!setPSPaperSize(tok->getCString())) {
+ error(-1, "Bad 'psPaperSize' config file command (%s:%d)",
+ fileName->getCString(), line);
+ }
+ } else if (tokens->getLength() == 3) {
+ tok = (GString *)tokens->get(1);
+ psPaperWidth = atoi(tok->getCString());
+ tok = (GString *)tokens->get(2);
+ psPaperHeight = atoi(tok->getCString());
+ } else {
+ error(-1, "Bad 'psPaperSize' config file command (%s:%d)",
+ fileName->getCString(), line);
+ }
+}
+
+void GlobalParams::parsePSLevel(GList *tokens, GString *fileName, int line) {
+ GString *tok;
+
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'psLevel' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ tok = (GString *)tokens->get(1);
+ if (!tok->cmp("level1")) {
+ psLevel = psLevel1;
+ } else if (!tok->cmp("level1sep")) {
+ psLevel = psLevel1Sep;
+ } else if (!tok->cmp("level2")) {
+ psLevel = psLevel2;
+ } else if (!tok->cmp("level2sep")) {
+ psLevel = psLevel2Sep;
+ } else if (!tok->cmp("level3")) {
+ psLevel = psLevel3;
+ } else if (!tok->cmp("level3Sep")) {
+ psLevel = psLevel3Sep;
+ } else {
+ error(-1, "Bad 'psLevel' config file command (%s:%d)",
+ fileName->getCString(), line);
+ }
+}
+
+void GlobalParams::parsePSFile(GList *tokens, GString *fileName, int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'psFile' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ if (psFile) {
+ delete psFile;
+ }
+ psFile = ((GString *)tokens->get(1))->copy();
+}
+
+void GlobalParams::parsePSFont(GList *tokens, GString *fileName, int line) {
+ PSFontParam *param;
+
+ if (tokens->getLength() != 3) {
+ error(-1, "Bad 'psFont' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ param = new PSFontParam(((GString *)tokens->get(1))->copy(), 0,
+ ((GString *)tokens->get(2))->copy(), NULL);
+ psFonts->add(param->pdfFontName, param);
+}
+
+void GlobalParams::parsePSFont16(const char *cmdName, GList *fontList,
+ GList *tokens, GString *fileName, int line) {
+ PSFontParam *param;
+ int wMode;
+ GString *tok;
+
+ if (tokens->getLength() != 5) {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ return;
+ }
+ tok = (GString *)tokens->get(2);
+ if (!tok->cmp("H")) {
+ wMode = 0;
+ } else if (!tok->cmp("V")) {
+ wMode = 1;
+ } else {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ return;
+ }
+ param = new PSFontParam(((GString *)tokens->get(1))->copy(),
+ wMode,
+ ((GString *)tokens->get(3))->copy(),
+ ((GString *)tokens->get(4))->copy());
+ fontList->append(param);
+}
+
+void GlobalParams::parseTextEncoding(GList *tokens, GString *fileName,
+ int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'textEncoding' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ delete textEncoding;
+ textEncoding = ((GString *)tokens->get(1))->copy();
+}
+
+void GlobalParams::parseTextEOL(GList *tokens, GString *fileName, int line) {
+ GString *tok;
+
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'textEOL' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ tok = (GString *)tokens->get(1);
+ if (!tok->cmp("unix")) {
+ textEOL = eolUnix;
+ } else if (!tok->cmp("dos")) {
+ textEOL = eolDOS;
+ } else if (!tok->cmp("mac")) {
+ textEOL = eolMac;
+ } else {
+ error(-1, "Bad 'textEOL' config file command (%s:%d)",
+ fileName->getCString(), line);
+ }
+}
+
+void GlobalParams::parseFontDir(GList *tokens, GString *fileName, int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'fontDir' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ fontDirs->append(((GString *)tokens->get(1))->copy());
+}
+
+void GlobalParams::parseInitialZoom(GList *tokens,
+ GString *fileName, int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad 'initialZoom' config file command (%s:%d)",
+ fileName->getCString(), line);
+ return;
+ }
+ delete initialZoom;
+ initialZoom = ((GString *)tokens->get(1))->copy();
+}
+
+void GlobalParams::parseFontRastControl(const char *cmdName, FontRastControl *val,
+ GList *tokens, GString *fileName,
+ int line) {
+ GString *tok;
+
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ return;
+ }
+ tok = (GString *)tokens->get(1);
+ if (!setFontRastControl(val, tok->getCString())) {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ }
+}
+
+void GlobalParams::parseCommand(const char *cmdName, GString **val,
+ GList *tokens, GString *fileName, int line) {
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ return;
+ }
+ if (*val) {
+ delete *val;
+ }
+ *val = ((GString *)tokens->get(1))->copy();
+}
+
+void GlobalParams::parseYesNo(const char *cmdName, GBool *flag,
+ GList *tokens, GString *fileName, int line) {
+ GString *tok;
+
+ if (tokens->getLength() != 2) {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ return;
+ }
+ tok = (GString *)tokens->get(1);
+ if (!tok->cmp("yes")) {
+ *flag = gTrue;
+ } else if (!tok->cmp("no")) {
+ *flag = gFalse;
+ } else {
+ error(-1, "Bad '%s' config file command (%s:%d)",
+ cmdName, fileName->getCString(), line);
+ }
+}
+
+GlobalParams::~GlobalParams() {
+ GHashIter *iter;
+ GString *key;
+ GList *list;
+
+ freeBuiltinFontTables();
+
+ delete macRomanReverseMap;
+
+ delete nameToUnicode;
+ deleteGHash(cidToUnicodes, GString);
+ deleteGHash(residentUnicodeMaps, UnicodeMap);
+ deleteGHash(unicodeMaps, GString);
+ deleteGList(toUnicodeDirs, GString);
+ deleteGHash(displayFonts, DisplayFontParam);
+ deleteGHash(displayCIDFonts, DisplayFontParam);
+ deleteGHash(displayNamedCIDFonts, DisplayFontParam);
+ if (psFile) {
+ delete psFile;
+ }
+ deleteGHash(psFonts, PSFontParam);
+ deleteGList(psNamedFonts16, PSFontParam);
+ deleteGList(psFonts16, PSFontParam);
+ delete textEncoding;
+ deleteGList(fontDirs, GString);
+ delete initialZoom;
+ if (urlCommand) {
+ delete urlCommand;
+ }
+ if (movieCommand) {
+ delete movieCommand;
+ }
+
+ cMapDirs->startIter(&iter);
+ while (cMapDirs->getNext(&iter, &key, (void **)&list)) {
+ deleteGList(list, GString);
+ }
+ delete cMapDirs;
+
+ delete cidToUnicodeCache;
+ delete unicodeMapCache;
+ delete cMapCache;
+}
+
+//------------------------------------------------------------------------
+// accessors
+//------------------------------------------------------------------------
+
+CharCode GlobalParams::getMacRomanCharCode(const char *charName) {
+ return macRomanReverseMap->lookup(charName);
+}
+
+Unicode GlobalParams::mapNameToUnicode(const char *charName) {
+ return nameToUnicode->lookup(charName);
+}
+
+FILE *GlobalParams::getCIDToUnicodeFile(const GString *collection) {
+ GString *fileName;
+
+ if (!(fileName = (GString *)cidToUnicodes->lookup(collection))) {
+ return NULL;
+ }
+ return fopen(fileName->getCString(), "r");
+}
+
+UnicodeMap *GlobalParams::getResidentUnicodeMap(const GString *encodingName) {
+ return (UnicodeMap *)residentUnicodeMaps->lookup(encodingName);
+}
+
+FILE *GlobalParams::getUnicodeMapFile(const GString *encodingName) {
+ GString *fileName;
+
+ if (!(fileName = (GString *)unicodeMaps->lookup(encodingName))) {
+ return NULL;
+ }
+ return fopen(fileName->getCString(), "r");
+}
+
+FILE *GlobalParams::findCMapFile(const GString *collection, const GString *cMapName) {
+ GList *list;
+ GString *dir;
+ GString *fileName;
+ FILE *f;
+ int i;
+
+ if (!(list = (GList *)cMapDirs->lookup(collection))) {
+ return NULL;
+ }
+ for (i = 0; i < list->getLength(); ++i) {
+ dir = (GString *)list->get(i);
+ fileName = appendToPath(dir->copy(), cMapName->getCString());
+ f = fopen(fileName->getCString(), "r");
+ delete fileName;
+ if (f) {
+ return f;
+ }
+ }
+ return NULL;
+}
+
+FILE *GlobalParams::findToUnicodeFile(const GString *name) {
+ GString *dir, *fileName;
+ FILE *f;
+ int i;
+
+ for (i = 0; i < toUnicodeDirs->getLength(); ++i) {
+ dir = (GString *)toUnicodeDirs->get(i);
+ fileName = appendToPath(dir->copy(), name->getCString());
+ f = fopen(fileName->getCString(), "r");
+ delete fileName;
+ if (f) {
+ return f;
+ }
+ }
+ return NULL;
+}
+
+DisplayFontParam *GlobalParams::getDisplayFont(const GString *fontName) {
+ return (DisplayFontParam *)displayFonts->lookup(fontName);
+}
+
+DisplayFontParam *GlobalParams::getDisplayCIDFont(const GString *fontName,
+ const GString *collection) {
+ DisplayFontParam *dfp;
+
+ if (!fontName ||
+ !(dfp = (DisplayFontParam *)displayNamedCIDFonts->lookup(fontName))) {
+ dfp = (DisplayFontParam *)displayCIDFonts->lookup(collection);
+ }
+ return dfp;
+}
+
+PSFontParam *GlobalParams::getPSFont(GString *fontName) {
+ return (PSFontParam *)psFonts->lookup(fontName);
+}
+
+PSFontParam *GlobalParams::getPSFont16(GString *fontName,
+ GString *collection, int wMode) {
+ PSFontParam *p;
+ int i;
+
+ p = NULL;
+ if (fontName) {
+ for (i = 0; i < psNamedFonts16->getLength(); ++i) {
+ p = (PSFontParam *)psNamedFonts16->get(i);
+ if (!p->pdfFontName->cmp(fontName) &&
+ p->wMode == wMode) {
+ break;
+ }
+ p = NULL;
+ }
+ }
+ if (!p && collection) {
+ for (i = 0; i < psFonts16->getLength(); ++i) {
+ p = (PSFontParam *)psFonts16->get(i);
+ if (!p->pdfFontName->cmp(collection) &&
+ p->wMode == wMode) {
+ break;
+ }
+ p = NULL;
+ }
+ }
+ return p;
+}
+
+GString *GlobalParams::findFontFile(const GString *fontName,
+ const char *ext1, const char *ext2) {
+ GString *dir, *fileName;
+ FILE *f;
+ int i;
+
+ for (i = 0; i < fontDirs->getLength(); ++i) {
+ dir = (GString *)fontDirs->get(i);
+ if (ext1) {
+ fileName = appendToPath(dir->copy(), fontName->getCString());
+ fileName->append(ext1);
+ if ((f = fopen(fileName->getCString(), "r"))) {
+ fclose(f);
+ return fileName;
+ }
+ delete fileName;
+ }
+ if (ext2) {
+ fileName = appendToPath(dir->copy(), fontName->getCString());
+ fileName->append(ext2);
+ if ((f = fopen(fileName->getCString(), "r"))) {
+ fclose(f);
+ return fileName;
+ }
+ delete fileName;
+ }
+ }
+ return NULL;
+}
+
+CharCodeToUnicode *GlobalParams::getCIDToUnicode(GString *collection) {
+ return cidToUnicodeCache->getCIDToUnicode(collection);
+}
+
+UnicodeMap *GlobalParams::getUnicodeMap(GString *encodingName) {
+ UnicodeMap *map;
+
+ if ((map = getResidentUnicodeMap(encodingName))) {
+ map->incRefCnt();
+ return map;
+ }
+ return unicodeMapCache->getUnicodeMap(encodingName);
+}
+
+CMap *GlobalParams::getCMap(GString *collection, GString *cMapName) {
+ return cMapCache->getCMap(collection, cMapName);
+}
+
+UnicodeMap *GlobalParams::getTextEncoding() {
+ return getUnicodeMap(textEncoding);
+}
+
+//------------------------------------------------------------------------
+// functions to set parameters
+//------------------------------------------------------------------------
+
+void GlobalParams::addDisplayFont(DisplayFontParam *param) {
+ DisplayFontParam *old;
+
+ if ((old = (DisplayFontParam *)displayFonts->remove(param->name))) {
+ delete old;
+ }
+ displayFonts->add(param->name, param);
+}
+
+void GlobalParams::setPSFile(char *file) {
+ if (psFile) {
+ delete psFile;
+ }
+ psFile = new GString(file);
+}
+
+GBool GlobalParams::setPSPaperSize(char *size) {
+ if (!strcmp(size, "letter")) {
+ psPaperWidth = 612;
+ psPaperHeight = 792;
+ } else if (!strcmp(size, "legal")) {
+ psPaperWidth = 612;
+ psPaperHeight = 1008;
+ } else if (!strcmp(size, "A4")) {
+ psPaperWidth = 595;
+ psPaperHeight = 842;
+ } else if (!strcmp(size, "A3")) {
+ psPaperWidth = 842;
+ psPaperHeight = 1190;
+ } else {
+ return gFalse;
+ }
+ return gTrue;
+}
+
+void GlobalParams::setPSPaperWidth(int width) {
+ psPaperWidth = width;
+}
+
+void GlobalParams::setPSPaperHeight(int height) {
+ psPaperHeight = height;
+}
+
+void GlobalParams::setPSDuplex(GBool duplex) {
+ psDuplex = duplex;
+}
+
+void GlobalParams::setPSLevel(PSLevel level) {
+ psLevel = level;
+}
+
+void GlobalParams::setPSEmbedType1(GBool embed) {
+ psEmbedType1 = embed;
+}
+
+void GlobalParams::setPSEmbedTrueType(GBool embed) {
+ psEmbedTrueType = embed;
+}
+
+void GlobalParams::setPSEmbedCIDPostScript(GBool embed) {
+ psEmbedCIDPostScript = embed;
+}
+
+void GlobalParams::setPSEmbedCIDTrueType(GBool embed) {
+ psEmbedCIDTrueType = embed;
+}
+
+void GlobalParams::setPSOPI(GBool opi) {
+ psOPI = opi;
+}
+
+void GlobalParams::setPSASCIIHex(GBool hex) {
+ psASCIIHex = hex;
+}
+
+void GlobalParams::setTextEncoding(char *encodingName) {
+ delete textEncoding;
+ textEncoding = new GString(encodingName);
+}
+
+GBool GlobalParams::setTextEOL(char *s) {
+ if (!strcmp(s, "unix")) {
+ textEOL = eolUnix;
+ } else if (!strcmp(s, "dos")) {
+ textEOL = eolDOS;
+ } else if (!strcmp(s, "mac")) {
+ textEOL = eolMac;
+ } else {
+ return gFalse;
+ }
+ return gTrue;
+}
+
+void GlobalParams::setTextKeepTinyChars(GBool keep) {
+ textKeepTinyChars = keep;
+}
+
+void GlobalParams::setInitialZoom(char *s) {
+ delete initialZoom;
+ initialZoom = new GString(s);
+}
+
+GBool GlobalParams::setT1libControl(char *s) {
+ return setFontRastControl(&t1libControl, s);
+}
+
+GBool GlobalParams::setFreeTypeControl(char *s) {
+ return setFontRastControl(&freetypeControl, s);
+}
+
+GBool GlobalParams::setFontRastControl(FontRastControl *val, const char *s) {
+ if (!strcmp(s, "none")) {
+ *val = fontRastNone;
+ } else if (!strcmp(s, "plain")) {
+ *val = fontRastPlain;
+ } else if (!strcmp(s, "low")) {
+ *val = fontRastAALow;
+ } else if (!strcmp(s, "high")) {
+ *val = fontRastAAHigh;
+ } else {
+ return gFalse;
+ }
+ return gTrue;
+}
+
+void GlobalParams::setMapNumericCharNames(GBool map) {
+ mapNumericCharNames = map;
+}
+
+void GlobalParams::setPrintCommands(GBool printCommandsA) {
+ printCommands = printCommandsA;
+}
+
+void GlobalParams::setErrQuiet(GBool errQuietA) {
+ errQuiet = errQuietA;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cc
deleted file mode 100644
index 1a6d87e1f..000000000
--- a/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cc
+++ /dev/null
@@ -1,194 +0,0 @@
-//========================================================================
-//
-// ImageOutputDev.cc
-//
-// Copyright 1998-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "config.h"
-#include "Error.h"
-#include "GfxState.h"
-#include "Object.h"
-#include "Stream.h"
-#include "ImageOutputDev.h"
-
-ImageOutputDev::ImageOutputDev(char *fileRootA, GBool dumpJPEGA) {
- fileRoot = copyString(fileRootA);
- fileName = (char *)gmalloc(strlen(fileRoot) + 20);
- dumpJPEG = dumpJPEGA;
- imgNum = 0;
- ok = gTrue;
-}
-
-ImageOutputDev::~ImageOutputDev() {
- gfree(fileName);
- gfree(fileRoot);
-}
-
-void ImageOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
- int width, int height, GBool invert,
- GBool inlineImg) {
- FILE *f;
- int c;
- int size, i;
-
- // dump JPEG file
- if (dumpJPEG && str->getKind() == strDCT && !inlineImg) {
-
- // open the image file
- sprintf(fileName, "%s-%03d.jpg", fileRoot, imgNum);
- ++imgNum;
- if (!(f = fopen(fileName, "wb"))) {
- error(-1, "Couldn't open image file '%s'", fileName);
- return;
- }
-
- // initialize stream
- str = ((DCTStream *)str)->getRawStream();
- str->reset();
-
- // copy the stream
- while ((c = str->getChar()) != EOF)
- fputc(c, f);
-
- str->close();
- fclose(f);
-
- // dump PBM file
- } else {
-
- // open the image file and write the PBM header
- sprintf(fileName, "%s-%03d.pbm", fileRoot, imgNum);
- ++imgNum;
- if (!(f = fopen(fileName, "wb"))) {
- error(-1, "Couldn't open image file '%s'", fileName);
- return;
- }
- fprintf(f, "P4\n");
- fprintf(f, "%d %d\n", width, height);
-
- // initialize stream
- str->reset();
-
- // copy the stream
- size = height * ((width + 7) / 8);
- for (i = 0; i < size; ++i) {
- fputc(str->getChar(), f);
- }
-
- str->close();
- fclose(f);
- }
-}
-
-void ImageOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
- int width, int height,
- GfxImageColorMap *colorMap,
- int *maskColors, GBool inlineImg) {
- FILE *f;
- ImageStream *imgStr;
- Guchar *p;
- GfxRGB rgb;
- int x, y;
- int c;
- int size, i;
-
- // dump JPEG file
- if (dumpJPEG && str->getKind() == strDCT &&
- colorMap->getNumPixelComps() == 3 &&
- !inlineImg) {
-
- // open the image file
- sprintf(fileName, "%s-%03d.jpg", fileRoot, imgNum);
- ++imgNum;
- if (!(f = fopen(fileName, "wb"))) {
- error(-1, "Couldn't open image file '%s'", fileName);
- return;
- }
-
- // initialize stream
- str = ((DCTStream *)str)->getRawStream();
- str->reset();
-
- // copy the stream
- while ((c = str->getChar()) != EOF)
- fputc(c, f);
-
- str->close();
- fclose(f);
-
- // dump PBM file
- } else if (colorMap->getNumPixelComps() == 1 &&
- colorMap->getBits() == 1) {
-
- // open the image file and write the PBM header
- sprintf(fileName, "%s-%03d.pbm", fileRoot, imgNum);
- ++imgNum;
- if (!(f = fopen(fileName, "wb"))) {
- error(-1, "Couldn't open image file '%s'", fileName);
- return;
- }
- fprintf(f, "P4\n");
- fprintf(f, "%d %d\n", width, height);
-
- // initialize stream
- str->reset();
-
- // copy the stream
- size = height * ((width + 7) / 8);
- for (i = 0; i < size; ++i) {
- fputc(str->getChar() ^ 0xff, f);
- }
-
- str->close();
- fclose(f);
-
- // dump PPM file
- } else {
-
- // open the image file and write the PPM header
- sprintf(fileName, "%s-%03d.ppm", fileRoot, imgNum);
- ++imgNum;
- if (!(f = fopen(fileName, "wb"))) {
- error(-1, "Couldn't open image file '%s'", fileName);
- return;
- }
- fprintf(f, "P6\n");
- fprintf(f, "%d %d\n", width, height);
- fprintf(f, "255\n");
-
- // initialize stream
- imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
- colorMap->getBits());
- imgStr->reset();
-
- // for each line...
- for (y = 0; y < height; ++y) {
-
- // write the line
- p = imgStr->getLine();
- for (x = 0; x < width; ++x) {
- colorMap->getRGB(p, &rgb);
- fputc((int)(rgb.r * 255 + 0.5), f);
- fputc((int)(rgb.g * 255 + 0.5), f);
- fputc((int)(rgb.b * 255 + 0.5), f);
- p += colorMap->getNumPixelComps();
- }
- }
- delete imgStr;
-
- fclose(f);
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cpp
new file mode 100644
index 000000000..9c1628437
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/ImageOutputDev.cpp
@@ -0,0 +1,194 @@
+//========================================================================
+//
+// ImageOutputDev.cpp
+//
+// Copyright 1998-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "config.h"
+#include "Error.h"
+#include "GfxState.h"
+#include "Object.h"
+#include "Stream.h"
+#include "ImageOutputDev.h"
+
+ImageOutputDev::ImageOutputDev(char *fileRootA, GBool dumpJPEGA) {
+ fileRoot = copyString(fileRootA);
+ fileName = (char *)gmalloc(strlen(fileRoot) + 20);
+ dumpJPEG = dumpJPEGA;
+ imgNum = 0;
+ ok = gTrue;
+}
+
+ImageOutputDev::~ImageOutputDev() {
+ gfree(fileName);
+ gfree(fileRoot);
+}
+
+void ImageOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
+ int width, int height, GBool invert,
+ GBool inlineImg) {
+ FILE *f;
+ int c;
+ int size, i;
+
+ // dump JPEG file
+ if (dumpJPEG && str->getKind() == strDCT && !inlineImg) {
+
+ // open the image file
+ sprintf(fileName, "%s-%03d.jpg", fileRoot, imgNum);
+ ++imgNum;
+ if (!(f = fopen(fileName, "wb"))) {
+ error(-1, "Couldn't open image file '%s'", fileName);
+ return;
+ }
+
+ // initialize stream
+ str = ((DCTStream *)str)->getRawStream();
+ str->reset();
+
+ // copy the stream
+ while ((c = str->getChar()) != EOF)
+ fputc(c, f);
+
+ str->close();
+ fclose(f);
+
+ // dump PBM file
+ } else {
+
+ // open the image file and write the PBM header
+ sprintf(fileName, "%s-%03d.pbm", fileRoot, imgNum);
+ ++imgNum;
+ if (!(f = fopen(fileName, "wb"))) {
+ error(-1, "Couldn't open image file '%s'", fileName);
+ return;
+ }
+ fprintf(f, "P4\n");
+ fprintf(f, "%d %d\n", width, height);
+
+ // initialize stream
+ str->reset();
+
+ // copy the stream
+ size = height * ((width + 7) / 8);
+ for (i = 0; i < size; ++i) {
+ fputc(str->getChar(), f);
+ }
+
+ str->close();
+ fclose(f);
+ }
+}
+
+void ImageOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
+ int width, int height,
+ GfxImageColorMap *colorMap,
+ int *maskColors, GBool inlineImg) {
+ FILE *f;
+ ImageStream *imgStr;
+ Guchar *p;
+ GfxRGB rgb;
+ int x, y;
+ int c;
+ int size, i;
+
+ // dump JPEG file
+ if (dumpJPEG && str->getKind() == strDCT &&
+ colorMap->getNumPixelComps() == 3 &&
+ !inlineImg) {
+
+ // open the image file
+ sprintf(fileName, "%s-%03d.jpg", fileRoot, imgNum);
+ ++imgNum;
+ if (!(f = fopen(fileName, "wb"))) {
+ error(-1, "Couldn't open image file '%s'", fileName);
+ return;
+ }
+
+ // initialize stream
+ str = ((DCTStream *)str)->getRawStream();
+ str->reset();
+
+ // copy the stream
+ while ((c = str->getChar()) != EOF)
+ fputc(c, f);
+
+ str->close();
+ fclose(f);
+
+ // dump PBM file
+ } else if (colorMap->getNumPixelComps() == 1 &&
+ colorMap->getBits() == 1) {
+
+ // open the image file and write the PBM header
+ sprintf(fileName, "%s-%03d.pbm", fileRoot, imgNum);
+ ++imgNum;
+ if (!(f = fopen(fileName, "wb"))) {
+ error(-1, "Couldn't open image file '%s'", fileName);
+ return;
+ }
+ fprintf(f, "P4\n");
+ fprintf(f, "%d %d\n", width, height);
+
+ // initialize stream
+ str->reset();
+
+ // copy the stream
+ size = height * ((width + 7) / 8);
+ for (i = 0; i < size; ++i) {
+ fputc(str->getChar() ^ 0xff, f);
+ }
+
+ str->close();
+ fclose(f);
+
+ // dump PPM file
+ } else {
+
+ // open the image file and write the PPM header
+ sprintf(fileName, "%s-%03d.ppm", fileRoot, imgNum);
+ ++imgNum;
+ if (!(f = fopen(fileName, "wb"))) {
+ error(-1, "Couldn't open image file '%s'", fileName);
+ return;
+ }
+ fprintf(f, "P6\n");
+ fprintf(f, "%d %d\n", width, height);
+ fprintf(f, "255\n");
+
+ // initialize stream
+ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+ colorMap->getBits());
+ imgStr->reset();
+
+ // for each line...
+ for (y = 0; y < height; ++y) {
+
+ // write the line
+ p = imgStr->getLine();
+ for (x = 0; x < width; ++x) {
+ colorMap->getRGB(p, &rgb);
+ fputc((int)(rgb.r * 255 + 0.5), f);
+ fputc((int)(rgb.g * 255 + 0.5), f);
+ fputc((int)(rgb.b * 255 + 0.5), f);
+ p += colorMap->getNumPixelComps();
+ }
+ }
+ delete imgStr;
+
+ fclose(f);
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cc b/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cc
deleted file mode 100644
index 6312cacae..000000000
--- a/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cc
+++ /dev/null
@@ -1,3513 +0,0 @@
-//========================================================================
-//
-// JBIG2Stream.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <limits.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdlib.h>
-#include "GList.h"
-#include "Error.h"
-#include "JBIG2Stream.h"
-
-//~ share these tables
-#include "Stream-CCITT.h"
-
-//------------------------------------------------------------------------
-
-static int contextSize[4] = { 16, 13, 10, 10 };
-static int refContextSize[2] = { 13, 10 };
-
-//------------------------------------------------------------------------
-// JBIG2ArithmeticDecoderStats
-//------------------------------------------------------------------------
-
-class JBIG2ArithmeticDecoderStats {
-public:
-
- JBIG2ArithmeticDecoderStats(int contextSizeA);
- ~JBIG2ArithmeticDecoderStats();
- JBIG2ArithmeticDecoderStats *copy();
- void reset();
- int getContextSize() { return contextSize; }
- void copyFrom(JBIG2ArithmeticDecoderStats *stats);
-
-private:
-
- Guchar *cxTab; // cxTab[cx] = (i[cx] << 1) + mps[cx]
- int contextSize;
-
- friend class JBIG2ArithmeticDecoder;
-};
-
-JBIG2ArithmeticDecoderStats::JBIG2ArithmeticDecoderStats(int contextSizeA) {
- contextSize = contextSizeA;
- cxTab = (Guchar *)gmalloc((1 << contextSize) * sizeof(Guchar));
- reset();
-}
-
-JBIG2ArithmeticDecoderStats::~JBIG2ArithmeticDecoderStats() {
- gfree(cxTab);
-}
-
-JBIG2ArithmeticDecoderStats *JBIG2ArithmeticDecoderStats::copy() {
- JBIG2ArithmeticDecoderStats *stats;
-
- stats = new JBIG2ArithmeticDecoderStats(contextSize);
- memcpy(stats->cxTab, cxTab, 1 << contextSize);
- return stats;
-}
-
-void JBIG2ArithmeticDecoderStats::reset() {
- memset(cxTab, 0, 1 << contextSize);
-}
-
-void JBIG2ArithmeticDecoderStats::copyFrom(
- JBIG2ArithmeticDecoderStats *stats) {
- memcpy(cxTab, stats->cxTab, 1 << contextSize);
-}
-
-//------------------------------------------------------------------------
-// JBIG2ArithmeticDecoder
-//------------------------------------------------------------------------
-
-class JBIG2ArithmeticDecoder {
-public:
-
- JBIG2ArithmeticDecoder();
- ~JBIG2ArithmeticDecoder();
- void setStream(Stream *strA) { str = strA; }
- void start();
- int decodeBit(Guint context, JBIG2ArithmeticDecoderStats *stats);
- int decodeByte(Guint context, JBIG2ArithmeticDecoderStats *stats);
-
- // Returns false for OOB, otherwise sets *<x> and returns true.
- GBool decodeInt(int *x, JBIG2ArithmeticDecoderStats *stats);
-
- Guint decodeIAID(Guint codeLen,
- JBIG2ArithmeticDecoderStats *stats);
-
-private:
-
- int decodeIntBit(JBIG2ArithmeticDecoderStats *stats);
- void byteIn();
-
- static Guint qeTab[47];
- static int nmpsTab[47];
- static int nlpsTab[47];
- static int switchTab[47];
-
- Guint buf0, buf1;
- Guint c, a;
- int ct;
-
- Guint prev; // for the integer decoder
-
- Stream *str;
-};
-
-Guint JBIG2ArithmeticDecoder::qeTab[47] = {
- 0x56010000, 0x34010000, 0x18010000, 0x0AC10000,
- 0x05210000, 0x02210000, 0x56010000, 0x54010000,
- 0x48010000, 0x38010000, 0x30010000, 0x24010000,
- 0x1C010000, 0x16010000, 0x56010000, 0x54010000,
- 0x51010000, 0x48010000, 0x38010000, 0x34010000,
- 0x30010000, 0x28010000, 0x24010000, 0x22010000,
- 0x1C010000, 0x18010000, 0x16010000, 0x14010000,
- 0x12010000, 0x11010000, 0x0AC10000, 0x09C10000,
- 0x08A10000, 0x05210000, 0x04410000, 0x02A10000,
- 0x02210000, 0x01410000, 0x01110000, 0x00850000,
- 0x00490000, 0x00250000, 0x00150000, 0x00090000,
- 0x00050000, 0x00010000, 0x56010000
-};
-
-int JBIG2ArithmeticDecoder::nmpsTab[47] = {
- 1, 2, 3, 4, 5, 38, 7, 8, 9, 10, 11, 12, 13, 29, 15, 16,
- 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46
-};
-
-int JBIG2ArithmeticDecoder::nlpsTab[47] = {
- 1, 6, 9, 12, 29, 33, 6, 14, 14, 14, 17, 18, 20, 21, 14, 14,
- 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
- 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46
-};
-
-int JBIG2ArithmeticDecoder::switchTab[47] = {
- 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-};
-
-JBIG2ArithmeticDecoder::JBIG2ArithmeticDecoder() {
- str = NULL;
-}
-
-JBIG2ArithmeticDecoder::~JBIG2ArithmeticDecoder() {
-}
-
-void JBIG2ArithmeticDecoder::start() {
- buf0 = (Guint)str->getChar() & 0xff;
- buf1 = (Guint)str->getChar() & 0xff;
-
- // INITDEC
- c = (buf0 ^ 0xff) << 16;
- byteIn();
- c <<= 7;
- ct -= 7;
- a = 0x80000000;
-}
-
-int JBIG2ArithmeticDecoder::decodeBit(Guint context,
- JBIG2ArithmeticDecoderStats *stats) {
- int bit;
- Guint qe;
- int iCX, mpsCX;
-
- iCX = stats->cxTab[context] >> 1;
- mpsCX = stats->cxTab[context] & 1;
- qe = qeTab[iCX];
- a -= qe;
- if (c < a) {
- if (a & 0x80000000) {
- bit = mpsCX;
- } else {
- // MPS_EXCHANGE
- if (a < qe) {
- bit = 1 - mpsCX;
- if (switchTab[iCX]) {
- stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
- } else {
- stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
- }
- } else {
- bit = mpsCX;
- stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
- }
- // RENORMD
- do {
- if (ct == 0) {
- byteIn();
- }
- a <<= 1;
- c <<= 1;
- --ct;
- } while (!(a & 0x80000000));
- }
- } else {
- c -= a;
- // LPS_EXCHANGE
- if (a < qe) {
- bit = mpsCX;
- stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
- } else {
- bit = 1 - mpsCX;
- if (switchTab[iCX]) {
- stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
- } else {
- stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
- }
- }
- a = qe;
- // RENORMD
- do {
- if (ct == 0) {
- byteIn();
- }
- a <<= 1;
- c <<= 1;
- --ct;
- } while (!(a & 0x80000000));
- }
- return bit;
-}
-
-int JBIG2ArithmeticDecoder::decodeByte(Guint context,
- JBIG2ArithmeticDecoderStats *stats) {
- int byte;
- int i;
-
- byte = 0;
- for (i = 0; i < 8; ++i) {
- byte = (byte << 1) | decodeBit(context, stats);
- }
- return byte;
-}
-
-GBool JBIG2ArithmeticDecoder::decodeInt(int *x,
- JBIG2ArithmeticDecoderStats *stats) {
- int s;
- Guint v;
- int i;
-
- prev = 1;
- s = decodeIntBit(stats);
- if (decodeIntBit(stats)) {
- if (decodeIntBit(stats)) {
- if (decodeIntBit(stats)) {
- if (decodeIntBit(stats)) {
- if (decodeIntBit(stats)) {
- v = 0;
- for (i = 0; i < 32; ++i) {
- v = (v << 1) | decodeIntBit(stats);
- }
- v += 4436;
- } else {
- v = 0;
- for (i = 0; i < 12; ++i) {
- v = (v << 1) | decodeIntBit(stats);
- }
- v += 340;
- }
- } else {
- v = 0;
- for (i = 0; i < 8; ++i) {
- v = (v << 1) | decodeIntBit(stats);
- }
- v += 84;
- }
- } else {
- v = 0;
- for (i = 0; i < 6; ++i) {
- v = (v << 1) | decodeIntBit(stats);
- }
- v += 20;
- }
- } else {
- v = decodeIntBit(stats);
- v = (v << 1) | decodeIntBit(stats);
- v = (v << 1) | decodeIntBit(stats);
- v = (v << 1) | decodeIntBit(stats);
- v += 4;
- }
- } else {
- v = decodeIntBit(stats);
- v = (v << 1) | decodeIntBit(stats);
- }
-
- if (s) {
- if (v == 0) {
- return gFalse;
- }
- *x = -(int)v;
- } else {
- *x = (int)v;
- }
- return gTrue;
-}
-
-int JBIG2ArithmeticDecoder::decodeIntBit(JBIG2ArithmeticDecoderStats *stats) {
- int bit;
-
- bit = decodeBit(prev, stats);
- if (prev < 0x100) {
- prev = (prev << 1) | bit;
- } else {
- prev = (((prev << 1) | bit) & 0x1ff) | 0x100;
- }
- return bit;
-}
-
-Guint JBIG2ArithmeticDecoder::decodeIAID(Guint codeLen,
- JBIG2ArithmeticDecoderStats *stats) {
- Guint i;
- int bit;
-
- prev = 1;
- for (i = 0; i < codeLen; ++i) {
- bit = decodeBit(prev, stats);
- prev = (prev << 1) | bit;
- }
- return prev - (1 << codeLen);
-}
-
-void JBIG2ArithmeticDecoder::byteIn() {
- if (buf0 == 0xff) {
- if (buf1 > 0x8f) {
- ct = 8;
- } else {
- buf0 = buf1;
- buf1 = (Guint)str->getChar() & 0xff;
- c = c + 0xfe00 - (buf0 << 9);
- ct = 7;
- }
- } else {
- buf0 = buf1;
- buf1 = (Guint)str->getChar() & 0xff;
- c = c + 0xff00 - (buf0 << 8);
- ct = 8;
- }
-}
-
-//------------------------------------------------------------------------
-// JBIG2HuffmanTable
-//------------------------------------------------------------------------
-
-#define jbig2HuffmanLOW 0xfffffffd
-#define jbig2HuffmanOOB 0xfffffffe
-#define jbig2HuffmanEOT 0xffffffff
-
-struct JBIG2HuffmanTable {
- int val;
- Guint prefixLen;
- Guint rangeLen; // can also be LOW, OOB, or EOT
- Guint prefix;
-};
-
-JBIG2HuffmanTable huffTableA[] = {
- { 0, 1, 4, 0x000 },
- { 16, 2, 8, 0x002 },
- { 272, 3, 16, 0x006 },
- { 65808, 3, 32, 0x007 },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableB[] = {
- { 0, 1, 0, 0x000 },
- { 1, 2, 0, 0x002 },
- { 2, 3, 0, 0x006 },
- { 3, 4, 3, 0x00e },
- { 11, 5, 6, 0x01e },
- { 75, 6, 32, 0x03e },
- { 0, 6, jbig2HuffmanOOB, 0x03f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableC[] = {
- { 0, 1, 0, 0x000 },
- { 1, 2, 0, 0x002 },
- { 2, 3, 0, 0x006 },
- { 3, 4, 3, 0x00e },
- { 11, 5, 6, 0x01e },
- { 0, 6, jbig2HuffmanOOB, 0x03e },
- { 75, 7, 32, 0x0fe },
- { -256, 8, 8, 0x0fe },
- { -257, 8, jbig2HuffmanLOW, 0x0ff },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableD[] = {
- { 1, 1, 0, 0x000 },
- { 2, 2, 0, 0x002 },
- { 3, 3, 0, 0x006 },
- { 4, 4, 3, 0x00e },
- { 12, 5, 6, 0x01e },
- { 76, 5, 32, 0x01f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableE[] = {
- { 1, 1, 0, 0x000 },
- { 2, 2, 0, 0x002 },
- { 3, 3, 0, 0x006 },
- { 4, 4, 3, 0x00e },
- { 12, 5, 6, 0x01e },
- { 76, 6, 32, 0x03e },
- { -255, 7, 8, 0x07e },
- { -256, 7, jbig2HuffmanLOW, 0x07f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableF[] = {
- { 0, 2, 7, 0x000 },
- { 128, 3, 7, 0x002 },
- { 256, 3, 8, 0x003 },
- { -1024, 4, 9, 0x008 },
- { -512, 4, 8, 0x009 },
- { -256, 4, 7, 0x00a },
- { -32, 4, 5, 0x00b },
- { 512, 4, 9, 0x00c },
- { 1024, 4, 10, 0x00d },
- { -2048, 5, 10, 0x01c },
- { -128, 5, 6, 0x01d },
- { -64, 5, 5, 0x01e },
- { -2049, 6, jbig2HuffmanLOW, 0x03e },
- { 2048, 6, 32, 0x03f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableG[] = {
- { -512, 3, 8, 0x000 },
- { 256, 3, 8, 0x001 },
- { 512, 3, 9, 0x002 },
- { 1024, 3, 10, 0x003 },
- { -1024, 4, 9, 0x008 },
- { -256, 4, 7, 0x009 },
- { -32, 4, 5, 0x00a },
- { 0, 4, 5, 0x00b },
- { 128, 4, 7, 0x00c },
- { -128, 5, 6, 0x01a },
- { -64, 5, 5, 0x01b },
- { 32, 5, 5, 0x01c },
- { 64, 5, 6, 0x01d },
- { -1025, 5, jbig2HuffmanLOW, 0x01e },
- { 2048, 5, 32, 0x01f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableH[] = {
- { 0, 2, 1, 0x000 },
- { 0, 2, jbig2HuffmanOOB, 0x001 },
- { 4, 3, 4, 0x004 },
- { -1, 4, 0, 0x00a },
- { 22, 4, 4, 0x00b },
- { 38, 4, 5, 0x00c },
- { 2, 5, 0, 0x01a },
- { 70, 5, 6, 0x01b },
- { 134, 5, 7, 0x01c },
- { 3, 6, 0, 0x03a },
- { 20, 6, 1, 0x03b },
- { 262, 6, 7, 0x03c },
- { 646, 6, 10, 0x03d },
- { -2, 7, 0, 0x07c },
- { 390, 7, 8, 0x07d },
- { -15, 8, 3, 0x0fc },
- { -5, 8, 1, 0x0fd },
- { -7, 9, 1, 0x1fc },
- { -3, 9, 0, 0x1fd },
- { -16, 9, jbig2HuffmanLOW, 0x1fe },
- { 1670, 9, 32, 0x1ff },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableI[] = {
- { 0, 2, jbig2HuffmanOOB, 0x000 },
- { -1, 3, 1, 0x002 },
- { 1, 3, 1, 0x003 },
- { 7, 3, 5, 0x004 },
- { -3, 4, 1, 0x00a },
- { 43, 4, 5, 0x00b },
- { 75, 4, 6, 0x00c },
- { 3, 5, 1, 0x01a },
- { 139, 5, 7, 0x01b },
- { 267, 5, 8, 0x01c },
- { 5, 6, 1, 0x03a },
- { 39, 6, 2, 0x03b },
- { 523, 6, 8, 0x03c },
- { 1291, 6, 11, 0x03d },
- { -5, 7, 1, 0x07c },
- { 779, 7, 9, 0x07d },
- { -31, 8, 4, 0x0fc },
- { -11, 8, 2, 0x0fd },
- { -15, 9, 2, 0x1fc },
- { -7, 9, 1, 0x1fd },
- { -32, 9, jbig2HuffmanLOW, 0x1fe },
- { 3339, 9, 32, 0x1ff },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableJ[] = {
- { -2, 2, 2, 0x000 },
- { 6, 2, 6, 0x001 },
- { 0, 2, jbig2HuffmanOOB, 0x002 },
- { -3, 5, 0, 0x018 },
- { 2, 5, 0, 0x019 },
- { 70, 5, 5, 0x01a },
- { 3, 6, 0, 0x036 },
- { 102, 6, 5, 0x037 },
- { 134, 6, 6, 0x038 },
- { 198, 6, 7, 0x039 },
- { 326, 6, 8, 0x03a },
- { 582, 6, 9, 0x03b },
- { 1094, 6, 10, 0x03c },
- { -21, 7, 4, 0x07a },
- { -4, 7, 0, 0x07b },
- { 4, 7, 0, 0x07c },
- { 2118, 7, 11, 0x07d },
- { -5, 8, 0, 0x0fc },
- { 5, 8, 0, 0x0fd },
- { -22, 8, jbig2HuffmanLOW, 0x0fe },
- { 4166, 8, 32, 0x0ff },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableK[] = {
- { 1, 1, 0, 0x000 },
- { 2, 2, 1, 0x002 },
- { 4, 4, 0, 0x00c },
- { 5, 4, 1, 0x00d },
- { 7, 5, 1, 0x01c },
- { 9, 5, 2, 0x01d },
- { 13, 6, 2, 0x03c },
- { 17, 7, 2, 0x07a },
- { 21, 7, 3, 0x07b },
- { 29, 7, 4, 0x07c },
- { 45, 7, 5, 0x07d },
- { 77, 7, 6, 0x07e },
- { 141, 7, 32, 0x07f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableL[] = {
- { 1, 1, 0, 0x000 },
- { 2, 2, 0, 0x002 },
- { 3, 3, 1, 0x006 },
- { 5, 5, 0, 0x01c },
- { 6, 5, 1, 0x01d },
- { 8, 6, 1, 0x03c },
- { 10, 7, 0, 0x07a },
- { 11, 7, 1, 0x07b },
- { 13, 7, 2, 0x07c },
- { 17, 7, 3, 0x07d },
- { 25, 7, 4, 0x07e },
- { 41, 8, 5, 0x0fe },
- { 73, 8, 32, 0x0ff },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableM[] = {
- { 1, 1, 0, 0x000 },
- { 2, 3, 0, 0x004 },
- { 7, 3, 3, 0x005 },
- { 3, 4, 0, 0x00c },
- { 5, 4, 1, 0x00d },
- { 4, 5, 0, 0x01c },
- { 15, 6, 1, 0x03a },
- { 17, 6, 2, 0x03b },
- { 21, 6, 3, 0x03c },
- { 29, 6, 4, 0x03d },
- { 45, 6, 5, 0x03e },
- { 77, 7, 6, 0x07e },
- { 141, 7, 32, 0x07f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableN[] = {
- { 0, 1, 0, 0x000 },
- { -2, 3, 0, 0x004 },
- { -1, 3, 0, 0x005 },
- { 1, 3, 0, 0x006 },
- { 2, 3, 0, 0x007 },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-JBIG2HuffmanTable huffTableO[] = {
- { 0, 1, 0, 0x000 },
- { -1, 3, 0, 0x004 },
- { 1, 3, 0, 0x005 },
- { -2, 4, 0, 0x00c },
- { 2, 4, 0, 0x00d },
- { -4, 5, 1, 0x01c },
- { 3, 5, 1, 0x01d },
- { -8, 6, 2, 0x03c },
- { 5, 6, 2, 0x03d },
- { -24, 7, 4, 0x07c },
- { 9, 7, 4, 0x07d },
- { -25, 7, jbig2HuffmanLOW, 0x07e },
- { 25, 7, 32, 0x07f },
- { 0, 0, jbig2HuffmanEOT, 0 }
-};
-
-//------------------------------------------------------------------------
-// JBIG2HuffmanDecoder
-//------------------------------------------------------------------------
-
-class JBIG2HuffmanDecoder {
-public:
-
- JBIG2HuffmanDecoder();
- ~JBIG2HuffmanDecoder();
- void setStream(Stream *strA) { str = strA; }
-
- void reset();
-
- // Returns false for OOB, otherwise sets *<x> and returns true.
- GBool decodeInt(int *x, JBIG2HuffmanTable *table);
-
- Guint readBits(Guint n);
- Guint readBit();
-
- // Sort the table by prefix length and assign prefix values.
- void buildTable(JBIG2HuffmanTable *table, Guint len);
-
-private:
-
- Stream *str;
- Guint buf;
- Guint bufLen;
-};
-
-JBIG2HuffmanDecoder::JBIG2HuffmanDecoder() {
- str = NULL;
- reset();
-}
-
-JBIG2HuffmanDecoder::~JBIG2HuffmanDecoder() {
-}
-
-void JBIG2HuffmanDecoder::reset() {
- buf = 0;
- bufLen = 0;
-}
-
-//~ optimize this
-GBool JBIG2HuffmanDecoder::decodeInt(int *x, JBIG2HuffmanTable *table) {
- Guint i, len, prefix;
-
- i = 0;
- len = 0;
- prefix = 0;
- while (table[i].rangeLen != jbig2HuffmanEOT) {
- //~ if buildTable removes the entries with prefixLen=0, this is unneeded
- if (table[i].prefixLen > 0) {
- while (len < table[i].prefixLen) {
- prefix = (prefix << 1) | readBit();
- ++len;
- }
- if (prefix == table[i].prefix) {
- if (table[i].rangeLen == jbig2HuffmanOOB) {
- return gFalse;
- }
- if (table[i].rangeLen == jbig2HuffmanLOW) {
- *x = table[i].val - readBits(32);
- } else if (table[i].rangeLen > 0) {
- *x = table[i].val + readBits(table[i].rangeLen);
- } else {
- *x = table[i].val;
- }
- return gTrue;
- }
- }
- ++i;
- }
- return gFalse;
-}
-
-Guint JBIG2HuffmanDecoder::readBits(Guint n) {
- Guint x, mask, nLeft;
-
- mask = (n == 32) ? 0xffffffff : ((1 << n) - 1);
- if (bufLen >= n) {
- x = (buf >> (bufLen - n)) & mask;
- bufLen -= n;
- } else {
- x = buf & ((1 << bufLen) - 1);
- nLeft = n - bufLen;
- bufLen = 0;
- while (nLeft >= 8) {
- x = (x << 8) | (str->getChar() & 0xff);
- nLeft -= 8;
- }
- if (nLeft > 0) {
- buf = str->getChar();
- bufLen = 8 - nLeft;
- x = (x << nLeft) | ((buf >> bufLen) & ((1 << nLeft) - 1));
- }
- }
- return x;
-}
-
-Guint JBIG2HuffmanDecoder::readBit() {
- if (bufLen == 0) {
- buf = str->getChar();
- bufLen = 8;
- }
- --bufLen;
- return (buf >> bufLen) & 1;
-}
-
-static int cmpHuffmanTabEntries(const void *p1, const void *p2) {
- return ((JBIG2HuffmanTable *)p1)->prefixLen
- - ((JBIG2HuffmanTable *)p2)->prefixLen;
-}
-
-//~ should remove entries with prefixLen = 0
-void JBIG2HuffmanDecoder::buildTable(JBIG2HuffmanTable *table, Guint len) {
- Guint i, prefix;
-
- qsort(table, len, sizeof(JBIG2HuffmanTable), &cmpHuffmanTabEntries);
- for (i = 0; i < len && table[i].prefixLen == 0; ++i) {
- table[i].prefix = 0;
- }
- prefix = 0;
- table[i++].prefix = prefix++;
- for (; i < len; ++i) {
- prefix <<= table[i].prefixLen - table[i-1].prefixLen;
- table[i].prefix = prefix++;
- }
-}
-
-//------------------------------------------------------------------------
-// JBIG2MMRDecoder
-//------------------------------------------------------------------------
-
-class JBIG2MMRDecoder {
-public:
-
- JBIG2MMRDecoder();
- ~JBIG2MMRDecoder();
- void setStream(Stream *strA) { str = strA; }
- void reset();
- int get2DCode();
- int getBlackCode();
- int getWhiteCode();
- Guint get24Bits();
- void skipTo(Guint length);
-
-private:
-
- Stream *str;
- Guint buf;
- Guint bufLen;
- Guint nBytesRead;
-};
-
-JBIG2MMRDecoder::JBIG2MMRDecoder() {
- str = NULL;
- reset();
-}
-
-JBIG2MMRDecoder::~JBIG2MMRDecoder() {
-}
-
-void JBIG2MMRDecoder::reset() {
- buf = 0;
- bufLen = 0;
- nBytesRead = 0;
-}
-
-int JBIG2MMRDecoder::get2DCode() {
- CCITTCode *p;
-
- if (bufLen == 0) {
- buf = str->getChar() & 0xff;
- bufLen = 8;
- ++nBytesRead;
- p = &twoDimTab1[(buf >> 1) & 0x7f];
- } else if (bufLen == 8) {
- p = &twoDimTab1[(buf >> 1) & 0x7f];
- } else {
- p = &twoDimTab1[(buf << (7 - bufLen)) & 0x7f];
- if (p->bits < 0 || p->bits > (int)bufLen) {
- buf = (buf << 8) | (str->getChar() & 0xff);
- bufLen += 8;
- ++nBytesRead;
- p = &twoDimTab1[(buf >> (bufLen - 7)) & 0x7f];
- }
- }
- if (p->bits < 0) {
- error(str->getPos(), "Bad two dim code in JBIG2 MMR stream");
- return 0;
- }
- bufLen -= p->bits;
- return p->n;
-}
-
-int JBIG2MMRDecoder::getWhiteCode() {
- CCITTCode *p;
- Guint code;
-
- if (bufLen == 0) {
- buf = str->getChar() & 0xff;
- bufLen = 8;
- ++nBytesRead;
- }
- while (1) {
- if (bufLen > 7 && ((buf >> (bufLen - 7)) & 0x7f) == 0) {
- if (bufLen <= 12) {
- code = buf << (12 - bufLen);
- } else {
- code = buf >> (bufLen - 12);
- }
- p = &whiteTab1[code & 0x1f];
- } else {
- if (bufLen <= 9) {
- code = buf << (9 - bufLen);
- } else {
- code = buf >> (bufLen - 9);
- }
- p = &whiteTab2[code & 0x1ff];
- }
- if (p->bits > 0 && p->bits < (int)bufLen) {
- bufLen -= p->bits;
- return p->n;
- }
- if (bufLen >= 12) {
- break;
- }
- buf = (buf << 8) | (str->getChar() & 0xff);
- bufLen += 8;
- ++nBytesRead;
- }
- error(str->getPos(), "Bad white code in JBIG2 MMR stream");
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- --bufLen;
- return 1;
-}
-
-int JBIG2MMRDecoder::getBlackCode() {
- CCITTCode *p;
- Guint code;
-
- if (bufLen == 0) {
- buf = str->getChar() & 0xff;
- bufLen = 8;
- ++nBytesRead;
- }
- while (1) {
- if (bufLen > 6 && ((buf >> (bufLen - 6)) & 0x3f) == 0) {
- if (bufLen <= 13) {
- code = buf << (13 - bufLen);
- } else {
- code = buf >> (bufLen - 13);
- }
- p = &blackTab1[code & 0x7f];
- } else if (bufLen > 4 && ((buf >> (bufLen - 4)) & 0x0f) == 0) {
- if (bufLen <= 12) {
- code = buf << (12 - bufLen);
- } else {
- code = buf >> (bufLen - 12);
- }
- p = &blackTab2[(code & 0xff) - 64];
- } else {
- if (bufLen <= 6) {
- code = buf << (6 - bufLen);
- } else {
- code = buf >> (bufLen - 6);
- }
- p = &blackTab3[code & 0x3f];
- }
- if (p->bits > 0 && p->bits < (int)bufLen) {
- bufLen -= p->bits;
- return p->n;
- }
- if (bufLen >= 13) {
- break;
- }
- buf = (buf << 8) | (str->getChar() & 0xff);
- bufLen += 8;
- ++nBytesRead;
- }
- error(str->getPos(), "Bad black code in JBIG2 MMR stream");
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- --bufLen;
- return 1;
-}
-
-Guint JBIG2MMRDecoder::get24Bits() {
- while (bufLen < 24) {
- buf = (buf << 8) | (str->getChar() & 0xff);
- bufLen += 8;
- ++nBytesRead;
- }
- return (buf >> (bufLen - 24)) & 0xffffff;
-}
-
-void JBIG2MMRDecoder::skipTo(Guint length) {
- while (nBytesRead < length) {
- str->getChar();
- ++nBytesRead;
- }
-}
-
-//------------------------------------------------------------------------
-// JBIG2Segment
-//------------------------------------------------------------------------
-
-enum JBIG2SegmentType {
- jbig2SegBitmap,
- jbig2SegSymbolDict,
- jbig2SegPatternDict,
- jbig2SegCodeTable
-};
-
-class JBIG2Segment {
-public:
-
- JBIG2Segment(Guint segNumA) { segNum = segNumA; }
- virtual ~JBIG2Segment() {}
- void setSegNum(Guint segNumA) { segNum = segNumA; }
- Guint getSegNum() { return segNum; }
- virtual JBIG2SegmentType getType() = 0;
-
-private:
-
- Guint segNum;
-};
-
-//------------------------------------------------------------------------
-// JBIG2Bitmap
-//------------------------------------------------------------------------
-
-class JBIG2Bitmap: public JBIG2Segment {
-public:
-
- JBIG2Bitmap(Guint segNumA, int wA, int hA);
- virtual ~JBIG2Bitmap();
- virtual JBIG2SegmentType getType() { return jbig2SegBitmap; }
- JBIG2Bitmap *copy() { return new JBIG2Bitmap(0, this); }
- JBIG2Bitmap *getSlice(Guint x, Guint y, Guint wA, Guint hA);
- void expand(int newH, Guint pixel);
- void clearToZero();
- void clearToOne();
- int getWidth() { return w; }
- int getHeight() { return h; }
- int getPixel(int x, int y)
- { return (x < 0 || x >= w || y < 0 || y >= h) ? 0 :
- (data[y * line + (x >> 3)] >> (7 - (x & 7))) & 1; }
- void setPixel(int x, int y)
- { data[y * line + (x >> 3)] |= 1 << (7 - (x & 7)); }
- void clearPixel(int x, int y)
- { data[y * line + (x >> 3)] &= 0x7f7f >> (x & 7); }
- void duplicateRow(int yDest, int ySrc);
- void combine(JBIG2Bitmap *bitmap, int x, int y, Guint combOp);
- Guchar *getDataPtr() { return data; }
- int getDataSize() { return h * line; }
-
-private:
-
- JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap);
-
- int w, h, line;
- Guchar *data;
-};
-
-JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
- JBIG2Segment(segNumA)
-{
- w = wA;
- h = hA;
- line = (wA + 7) >> 3;
-
- if (h < 0 || line <= 0 || h >= (INT_MAX - 1)/ line) {
- error(-1, "invalid width/height");
- data = NULL;
- return;
- }
-
- // need to allocate one extra guard byte for use in combine()
- data = (Guchar *)gmalloc(h * line + 1);
-}
-
-JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap):
- JBIG2Segment(segNumA)
-{
- w = bitmap->w;
- h = bitmap->h;
- line = bitmap->line;
-
- if (h < 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
- error(-1, "invalid width/height");
- data = NULL;
- return;
- }
-
- // need to allocate one extra guard byte for use in combine()
- data = (Guchar *)gmalloc(h * line + 1);
- memcpy(data, bitmap->data, h * line);
-}
-
-JBIG2Bitmap::~JBIG2Bitmap() {
- gfree(data);
-}
-
-//~ optimize this
-JBIG2Bitmap *JBIG2Bitmap::getSlice(Guint x, Guint y, Guint wA, Guint hA) {
- JBIG2Bitmap *slice;
- Guint xx, yy;
-
- slice = new JBIG2Bitmap(0, wA, hA);
- slice->clearToZero();
- for (yy = 0; yy < hA; ++yy) {
- for (xx = 0; xx < wA; ++xx) {
- if (getPixel(x + xx, y + yy)) {
- slice->setPixel(xx, yy);
- }
- }
- }
- return slice;
-}
-
-void JBIG2Bitmap::expand(int newH, Guint pixel) {
- if (newH <= h || line <= 0 || newH >= (INT_MAX-1) / line) {
- error(-1, "invalid width/height");
- gfree(data);
- data = NULL;
- return;
- }
- /* need to allocate one extra guard byte for use in combine() */
- data = (Guchar *)grealloc(data, newH * line + 1);
- if (pixel) {
- memset(data + h * line, 0xff, (newH - h) * line);
- } else {
- memset(data + h * line, 0x00, (newH - h) * line);
- }
- h = newH;
-}
-
-void JBIG2Bitmap::clearToZero() {
- memset(data, 0, h * line);
-}
-
-void JBIG2Bitmap::clearToOne() {
- memset(data, 0xff, h * line);
-}
-
-void JBIG2Bitmap::duplicateRow(int yDest, int ySrc) {
- memcpy(data + yDest * line, data + ySrc * line, line);
-}
-
-void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y,
- Guint combOp) {
- int x0, x1, y0, y1, xx, yy;
- Guchar *srcPtr, *destPtr;
- Guint src0, src1, src, dest, s1, s2, m1, m2, m3;
- GBool oneByte;
-
- if (y < 0) {
- y0 = -y;
- } else {
- y0 = 0;
- }
- if (y + bitmap->h > h) {
- y1 = h - y;
- } else {
- y1 = bitmap->h;
- }
- if (y0 >= y1) {
- return;
- }
-
- if (x >= 0) {
- x0 = x & ~7;
- } else {
- x0 = 0;
- }
- x1 = x + bitmap->w;
- if (x1 > w) {
- x1 = w;
- }
- if (x0 >= x1) {
- return;
- }
-
- s1 = x & 7;
- s2 = 8 - s1;
- m1 = 0xff >> (x1 & 7);
- m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7));
- m3 = (0xff >> s1) & m2;
-
- oneByte = x0 == ((x1 - 1) & ~7);
-
- for (yy = y0; yy < y1; ++yy) {
-
- // one byte per line -- need to mask both left and right side
- if (oneByte) {
- if (x >= 0) {
- destPtr = data + (y + yy) * line + (x >> 3);
- srcPtr = bitmap->data + yy * bitmap->line;
- dest = *destPtr;
- src1 = *srcPtr;
- switch (combOp) {
- case 0: // or
- dest |= (src1 >> s1) & m2;
- break;
- case 1: // and
- dest &= ((0xff00 | src1) >> s1) | m1;
- break;
- case 2: // xor
- dest ^= (src1 >> s1) & m2;
- break;
- case 3: // xnor
- dest ^= ((src1 ^ 0xff) >> s1) & m2;
- break;
- case 4: // replace
- dest = (dest & ~m3) | ((src1 >> s1) & m3);
- break;
- }
- *destPtr = dest;
- } else {
- destPtr = data + (y + yy) * line;
- srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
- dest = *destPtr;
- src1 = *srcPtr;
- switch (combOp) {
- case 0: // or
- dest |= src1 & m2;
- break;
- case 1: // and
- dest &= src1 | m1;
- break;
- case 2: // xor
- dest ^= src1 & m2;
- break;
- case 3: // xnor
- dest ^= (src1 ^ 0xff) & m2;
- break;
- case 4: // replace
- dest = (src1 & m2) | (dest & m1);
- break;
- }
- *destPtr = dest;
- }
-
- // multiple bytes per line -- need to mask left side of left-most
- // byte and right side of right-most byte
- } else {
-
- // left-most byte
- if (x >= 0) {
- destPtr = data + (y + yy) * line + (x >> 3);
- srcPtr = bitmap->data + yy * bitmap->line;
- src1 = *srcPtr++;
- dest = *destPtr;
- switch (combOp) {
- case 0: // or
- dest |= src1 >> s1;
- break;
- case 1: // and
- dest &= (0xff00 | src1) >> s1;
- break;
- case 2: // xor
- dest ^= src1 >> s1;
- break;
- case 3: // xnor
- dest ^= (src1 ^ 0xff) >> s1;
- break;
- case 4: // replace
- dest = (dest & (0xff << s2)) | (src1 >> s1);
- break;
- }
- *destPtr++ = dest;
- xx = x0 + 8;
- } else {
- destPtr = data + (y + yy) * line;
- srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
- src1 = *srcPtr++;
- xx = x0;
- }
-
- // middle bytes
- for (; xx < x1 - 8; xx += 8) {
- dest = *destPtr;
- src0 = src1;
- src1 = *srcPtr++;
- src = (((src0 << 8) | src1) >> s1) & 0xff;
- switch (combOp) {
- case 0: // or
- dest |= src;
- break;
- case 1: // and
- dest &= src;
- break;
- case 2: // xor
- dest ^= src;
- break;
- case 3: // xnor
- dest ^= src ^ 0xff;
- break;
- case 4: // replace
- dest = src;
- break;
- }
- *destPtr++ = dest;
- }
-
- // right-most byte
- dest = *destPtr;
- src0 = src1;
- src1 = *srcPtr++;
- src = (((src0 << 8) | src1) >> s1) & 0xff;
- switch (combOp) {
- case 0: // or
- dest |= src & m2;
- break;
- case 1: // and
- dest &= src | m1;
- break;
- case 2: // xor
- dest ^= src & m2;
- break;
- case 3: // xnor
- dest ^= (src ^ 0xff) & m2;
- break;
- case 4: // replace
- dest = (src & m2) | (dest & m1);
- break;
- }
- *destPtr = dest;
- }
- }
-}
-
-//------------------------------------------------------------------------
-// JBIG2SymbolDict
-//------------------------------------------------------------------------
-
-class JBIG2SymbolDict: public JBIG2Segment {
-public:
-
- JBIG2SymbolDict(Guint segNumA, Guint sizeA);
- virtual ~JBIG2SymbolDict();
- virtual JBIG2SegmentType getType() { return jbig2SegSymbolDict; }
- Guint getSize() { return size; }
- void setBitmap(Guint idx, JBIG2Bitmap *bitmap) { bitmaps[idx] = bitmap; }
- JBIG2Bitmap *getBitmap(Guint idx) { return bitmaps[idx]; }
- void setGenericRegionStats(JBIG2ArithmeticDecoderStats *stats)
- { genericRegionStats = stats; }
- void setRefinementRegionStats(JBIG2ArithmeticDecoderStats *stats)
- { refinementRegionStats = stats; }
- JBIG2ArithmeticDecoderStats *getGenericRegionStats()
- { return genericRegionStats; }
- JBIG2ArithmeticDecoderStats *getRefinementRegionStats()
- { return refinementRegionStats; }
-
-private:
-
- Guint size;
- JBIG2Bitmap **bitmaps;
- JBIG2ArithmeticDecoderStats *genericRegionStats;
- JBIG2ArithmeticDecoderStats *refinementRegionStats;
-};
-
-JBIG2SymbolDict::JBIG2SymbolDict(Guint segNumA, Guint sizeA):
- JBIG2Segment(segNumA)
-{
- size = sizeA;
- bitmaps = (JBIG2Bitmap **)gmalloc(size * sizeof(JBIG2Bitmap *));
- genericRegionStats = NULL;
- refinementRegionStats = NULL;
-}
-
-JBIG2SymbolDict::~JBIG2SymbolDict() {
- Guint i;
-
- for (i = 0; i < size; ++i) {
- delete bitmaps[i];
- }
- gfree(bitmaps);
- if (genericRegionStats) {
- delete genericRegionStats;
- }
- if (refinementRegionStats) {
- delete refinementRegionStats;
- }
-}
-
-//------------------------------------------------------------------------
-// JBIG2PatternDict
-//------------------------------------------------------------------------
-
-class JBIG2PatternDict: public JBIG2Segment {
-public:
-
- JBIG2PatternDict(Guint segNumA, Guint sizeA);
- virtual ~JBIG2PatternDict();
- virtual JBIG2SegmentType getType() { return jbig2SegPatternDict; }
- Guint getSize() { return size; }
- void setBitmap(Guint idx, JBIG2Bitmap *bitmap) { bitmaps[idx] = bitmap; }
- JBIG2Bitmap *getBitmap(Guint idx) { return bitmaps[idx]; }
-
-private:
-
- Guint size;
- JBIG2Bitmap **bitmaps;
-};
-
-JBIG2PatternDict::JBIG2PatternDict(Guint segNumA, Guint sizeA):
- JBIG2Segment(segNumA)
-{
- size = sizeA;
- bitmaps = (JBIG2Bitmap **)gmalloc(size * sizeof(JBIG2Bitmap *));
-}
-
-JBIG2PatternDict::~JBIG2PatternDict() {
- Guint i;
-
- for (i = 0; i < size; ++i) {
- delete bitmaps[i];
- }
- gfree(bitmaps);
-}
-
-//------------------------------------------------------------------------
-// JBIG2CodeTable
-//------------------------------------------------------------------------
-
-class JBIG2CodeTable: public JBIG2Segment {
-public:
-
- JBIG2CodeTable(Guint segNumA, JBIG2HuffmanTable *tableA);
- virtual ~JBIG2CodeTable();
- virtual JBIG2SegmentType getType() { return jbig2SegCodeTable; }
- JBIG2HuffmanTable *getHuffTable() { return table; }
-
-private:
-
- JBIG2HuffmanTable *table;
-};
-
-JBIG2CodeTable::JBIG2CodeTable(Guint segNumA, JBIG2HuffmanTable *tableA):
- JBIG2Segment(segNumA)
-{
- table = tableA;
-}
-
-JBIG2CodeTable::~JBIG2CodeTable() {
- gfree(table);
-}
-
-//------------------------------------------------------------------------
-// JBIG2Stream
-//------------------------------------------------------------------------
-
-JBIG2Stream::JBIG2Stream(Stream *strA, Object *globalsStream):
- FilterStream(strA)
-{
- pageBitmap = NULL;
-
- arithDecoder = new JBIG2ArithmeticDecoder();
- genericRegionStats = new JBIG2ArithmeticDecoderStats(1);
- refinementRegionStats = new JBIG2ArithmeticDecoderStats(1);
- iadhStats = new JBIG2ArithmeticDecoderStats(9);
- iadwStats = new JBIG2ArithmeticDecoderStats(9);
- iaexStats = new JBIG2ArithmeticDecoderStats(9);
- iaaiStats = new JBIG2ArithmeticDecoderStats(9);
- iadtStats = new JBIG2ArithmeticDecoderStats(9);
- iaitStats = new JBIG2ArithmeticDecoderStats(9);
- iafsStats = new JBIG2ArithmeticDecoderStats(9);
- iadsStats = new JBIG2ArithmeticDecoderStats(9);
- iardxStats = new JBIG2ArithmeticDecoderStats(9);
- iardyStats = new JBIG2ArithmeticDecoderStats(9);
- iardwStats = new JBIG2ArithmeticDecoderStats(9);
- iardhStats = new JBIG2ArithmeticDecoderStats(9);
- iariStats = new JBIG2ArithmeticDecoderStats(9);
- iaidStats = new JBIG2ArithmeticDecoderStats(1);
- huffDecoder = new JBIG2HuffmanDecoder();
- mmrDecoder = new JBIG2MMRDecoder();
-
- segments = new GList();
- if (globalsStream->isStream()) {
- curStr = globalsStream->getStream();
- curStr->reset();
- arithDecoder->setStream(curStr);
- huffDecoder->setStream(curStr);
- mmrDecoder->setStream(curStr);
- readSegments();
- }
- globalSegments = segments;
-
- segments = NULL;
- curStr = NULL;
- dataPtr = dataEnd = NULL;
-}
-
-JBIG2Stream::~JBIG2Stream() {
- delete arithDecoder;
- delete genericRegionStats;
- delete refinementRegionStats;
- delete iadhStats;
- delete iadwStats;
- delete iaexStats;
- delete iaaiStats;
- delete iadtStats;
- delete iaitStats;
- delete iafsStats;
- delete iadsStats;
- delete iardxStats;
- delete iardyStats;
- delete iardwStats;
- delete iardhStats;
- delete iariStats;
- delete iaidStats;
- delete huffDecoder;
- delete mmrDecoder;
- if (pageBitmap) {
- delete pageBitmap;
- }
- if (segments) {
- deleteGList(segments, JBIG2Segment);
- }
- if (globalSegments) {
- deleteGList(globalSegments, JBIG2Segment);
- }
- delete str;
-}
-
-void JBIG2Stream::reset() {
- if (pageBitmap) {
- delete pageBitmap;
- pageBitmap = NULL;
- }
- if (segments) {
- deleteGList(segments, JBIG2Segment);
- }
- segments = new GList();
-
- curStr = str;
- curStr->reset();
- arithDecoder->setStream(curStr);
- huffDecoder->setStream(curStr);
- mmrDecoder->setStream(curStr);
- readSegments();
-
- if (pageBitmap) {
- dataPtr = pageBitmap->getDataPtr();
- dataEnd = dataPtr + pageBitmap->getDataSize();
- } else {
- dataPtr = NULL;
- }
-}
-
-int JBIG2Stream::getChar() {
- if (dataPtr && dataPtr < dataEnd) {
- return (*dataPtr++ ^ 0xff) & 0xff;
- }
- return EOF;
-}
-
-int JBIG2Stream::lookChar() {
- if (dataPtr && dataPtr < dataEnd) {
- return (*dataPtr ^ 0xff) & 0xff;
- }
- return EOF;
-}
-
-GString *JBIG2Stream::getPSFilter(const char */*indent*/) {
- return NULL;
-}
-
-GBool JBIG2Stream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-void JBIG2Stream::readSegments() {
- Guint segNum, segFlags, segType, page, segLength;
- Guint refFlags, nRefSegs;
- Guint *refSegs;
- int c1, c2, c3;
- Guint i;
-
- while (readULong(&segNum)) {
-
- // segment header flags
- if (!readUByte(&segFlags)) {
- goto eofError1;
- }
- segType = segFlags & 0x3f;
-
- // referred-to segment count and retention flags
- if (!readUByte(&refFlags)) {
- goto eofError1;
- }
- nRefSegs = refFlags >> 5;
- if (nRefSegs == 7) {
- if ((c1 = curStr->getChar()) == EOF ||
- (c2 = curStr->getChar()) == EOF ||
- (c3 = curStr->getChar()) == EOF) {
- goto eofError1;
- }
- refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
- nRefSegs = refFlags & 0x1fffffff;
- for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
- c1 = curStr->getChar();
- }
- }
-
- // referred-to segment numbers
- refSegs = (Guint *)gmalloc(nRefSegs * sizeof(Guint));
- if (segNum <= 256) {
- for (i = 0; i < nRefSegs; ++i) {
- if (!readUByte(&refSegs[i])) {
- goto eofError2;
- }
- }
- } else if (segNum <= 65536) {
- for (i = 0; i < nRefSegs; ++i) {
- if (!readUWord(&refSegs[i])) {
- goto eofError2;
- }
- }
- } else {
- for (i = 0; i < nRefSegs; ++i) {
- if (!readULong(&refSegs[i])) {
- goto eofError2;
- }
- }
- }
-
- // segment page association
- if (segFlags & 0x40) {
- if (!readULong(&page)) {
- goto eofError2;
- }
- } else {
- if (!readUByte(&page)) {
- goto eofError2;
- }
- }
-
- // segment data length
- if (!readULong(&segLength)) {
- goto eofError2;
- }
-
- // read the segment data
- switch (segType) {
- case 0:
- readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs);
- break;
- case 4:
- readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
- break;
- case 6:
- readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
- break;
- case 7:
- readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
- break;
- case 16:
- readPatternDictSeg(segNum, segLength);
- break;
- case 20:
- readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
- refSegs, nRefSegs);
- break;
- case 22:
- readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
- refSegs, nRefSegs);
- break;
- case 23:
- readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
- refSegs, nRefSegs);
- break;
- case 36:
- readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
- break;
- case 38:
- readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
- break;
- case 39:
- readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
- break;
- case 40:
- readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
- refSegs, nRefSegs);
- break;
- case 42:
- readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
- refSegs, nRefSegs);
- break;
- case 43:
- readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
- refSegs, nRefSegs);
- break;
- case 48:
- readPageInfoSeg(segLength);
- break;
- case 50:
- readEndOfStripeSeg(segLength);
- break;
- case 52:
- readProfilesSeg(segLength);
- break;
- case 53:
- readCodeTableSeg(segNum, segLength);
- break;
- case 62:
- readExtensionSeg(segLength);
- break;
- default:
- error(getPos(), "Unknown segment type in JBIG2 stream");
- for (i = 0; i < segLength; ++i) {
- if ((c1 = curStr->getChar()) == EOF) {
- goto eofError2;
- }
- }
- break;
- }
-
- gfree(refSegs);
- }
-
- return;
-
- eofError2:
- gfree(refSegs);
- eofError1:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readSymbolDictSeg(Guint segNum, Guint /*length*/,
- Guint *refSegs, Guint nRefSegs) {
- JBIG2SymbolDict *symbolDict;
- JBIG2HuffmanTable *huffDHTable, *huffDWTable;
- JBIG2HuffmanTable *huffBMSizeTable, *huffAggInstTable;
- JBIG2Segment *seg;
- GList *codeTables;
- JBIG2SymbolDict *inputSymbolDict;
- Guint flags, sdTemplate, sdrTemplate, huff, refAgg;
- Guint huffDH, huffDW, huffBMSize, huffAggInst;
- Guint contextUsed, contextRetained;
- int sdATX[4], sdATY[4], sdrATX[2], sdrATY[2];
- Guint numExSyms, numNewSyms, numInputSyms, symCodeLen;
- JBIG2Bitmap **bitmaps;
- JBIG2Bitmap *collBitmap, *refBitmap;
- Guint *symWidths;
- Guint symHeight, symWidth, totalWidth, x, symID;
- int dh, dw, refAggNum, refDX, refDY, bmSize;
- GBool ex;
- int run, cnt;
- Guint i, j, k;
- Guchar *p;
-
- // symbol dictionary flags
- if (!readUWord(&flags)) {
- goto eofError;
- }
- sdTemplate = (flags >> 10) & 3;
- sdrTemplate = (flags >> 12) & 1;
- huff = flags & 1;
- refAgg = (flags >> 1) & 1;
- huffDH = (flags >> 2) & 3;
- huffDW = (flags >> 4) & 3;
- huffBMSize = (flags >> 6) & 1;
- huffAggInst = (flags >> 7) & 1;
- contextUsed = (flags >> 8) & 1;
- contextRetained = (flags >> 9) & 1;
-
- // symbol dictionary AT flags
- if (!huff) {
- if (sdTemplate == 0) {
- if (!readByte(&sdATX[0]) ||
- !readByte(&sdATY[0]) ||
- !readByte(&sdATX[1]) ||
- !readByte(&sdATY[1]) ||
- !readByte(&sdATX[2]) ||
- !readByte(&sdATY[2]) ||
- !readByte(&sdATX[3]) ||
- !readByte(&sdATY[3])) {
- goto eofError;
- }
- } else {
- if (!readByte(&sdATX[0]) ||
- !readByte(&sdATY[0])) {
- goto eofError;
- }
- }
- }
-
- // symbol dictionary refinement AT flags
- if (refAgg && !sdrTemplate) {
- if (!readByte(&sdrATX[0]) ||
- !readByte(&sdrATY[0]) ||
- !readByte(&sdrATX[1]) ||
- !readByte(&sdrATY[1])) {
- goto eofError;
- }
- }
-
- // SDNUMEXSYMS and SDNUMNEWSYMS
- if (!readULong(&numExSyms) || !readULong(&numNewSyms)) {
- goto eofError;
- }
-
- // get referenced segments: input symbol dictionaries and code tables
- codeTables = new GList();
- numInputSyms = 0;
- for (i = 0; i < nRefSegs; ++i) {
- seg = findSegment(refSegs[i]);
- if (seg->getType() == jbig2SegSymbolDict) {
- numInputSyms += ((JBIG2SymbolDict *)seg)->getSize();
- } else if (seg->getType() == jbig2SegCodeTable) {
- codeTables->append(seg);
- }
- }
-
- // compute symbol code length
- symCodeLen = 0;
- i = 1;
- while (i < numInputSyms + numNewSyms) {
- ++symCodeLen;
- i <<= 1;
- }
-
- // get the input symbol bitmaps
- bitmaps = (JBIG2Bitmap **)gmalloc((numInputSyms + numNewSyms) *
- sizeof(JBIG2Bitmap *));
- k = 0;
- inputSymbolDict = NULL;
- for (i = 0; i < nRefSegs; ++i) {
- seg = findSegment(refSegs[i]);
- if (seg->getType() == jbig2SegSymbolDict) {
- inputSymbolDict = (JBIG2SymbolDict *)seg;
- for (j = 0; j < inputSymbolDict->getSize(); ++j) {
- bitmaps[k++] = inputSymbolDict->getBitmap(j);
- }
- }
- }
-
- // get the Huffman tables
- huffDHTable = huffDWTable = NULL; // make gcc happy
- huffBMSizeTable = huffAggInstTable = NULL; // make gcc happy
- i = 0;
- if (huff) {
- if (huffDH == 0) {
- huffDHTable = huffTableD;
- } else if (huffDH == 1) {
- huffDHTable = huffTableE;
- } else {
- huffDHTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffDW == 0) {
- huffDWTable = huffTableB;
- } else if (huffDW == 1) {
- huffDWTable = huffTableC;
- } else {
- huffDWTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffBMSize == 0) {
- huffBMSizeTable = huffTableA;
- } else {
- huffBMSizeTable =
- ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffAggInst == 0) {
- huffAggInstTable = huffTableA;
- } else {
- huffAggInstTable =
- ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- }
- delete codeTables;
-
- // set up the Huffman decoder
- if (huff) {
- huffDecoder->reset();
-
- // set up the arithmetic decoder
- } else {
- if (contextUsed && inputSymbolDict) {
- resetGenericStats(sdTemplate, inputSymbolDict->getGenericRegionStats());
- if (refAgg) {
- resetRefinementStats(sdrTemplate,
- inputSymbolDict->getRefinementRegionStats());
- }
- } else {
- resetGenericStats(sdTemplate, NULL);
- if (refAgg) {
- resetRefinementStats(sdrTemplate, NULL);
- }
- }
- resetIntStats(symCodeLen);
- arithDecoder->start();
- }
-
- // allocate symbol widths storage
- symWidths = NULL;
- if (huff && !refAgg) {
- symWidths = (Guint *)gmalloc(numNewSyms * sizeof(Guint));
- }
-
- symHeight = 0;
- i = 0;
- while (i < numNewSyms) {
-
- // read the height class delta height
- if (huff) {
- huffDecoder->decodeInt(&dh, huffDHTable);
- } else {
- arithDecoder->decodeInt(&dh, iadhStats);
- }
- symHeight += dh;
- symWidth = 0;
- totalWidth = 0;
- j = i;
-
- // read the symbols in this height class
- while (1) {
-
- // read the delta width
- if (huff) {
- if (!huffDecoder->decodeInt(&dw, huffDWTable)) {
- break;
- }
- } else {
- if (!arithDecoder->decodeInt(&dw, iadwStats)) {
- break;
- }
- }
- symWidth += dw;
-
- // using a collective bitmap, so don't read a bitmap here
- if (huff && !refAgg) {
- symWidths[i] = symWidth;
- totalWidth += symWidth;
-
- // refinement/aggregate coding
- } else if (refAgg) {
- if (huff) {
- if (!huffDecoder->decodeInt(&refAggNum, huffAggInstTable)) {
- break;
- }
- } else {
- if (!arithDecoder->decodeInt(&refAggNum, iaaiStats)) {
- break;
- }
- }
- if (refAggNum == 1) {
- if (huff) {
- symID = huffDecoder->readBits(symCodeLen);
- huffDecoder->decodeInt(&refDX, huffTableO);
- huffDecoder->decodeInt(&refDY, huffTableO);
- huffDecoder->decodeInt(&bmSize, huffTableA);
- huffDecoder->reset();
- arithDecoder->start();
- } else {
- symID = arithDecoder->decodeIAID(symCodeLen, iaidStats);
- arithDecoder->decodeInt(&refDX, iardxStats);
- arithDecoder->decodeInt(&refDY, iardyStats);
- }
- refBitmap = bitmaps[symID];
- bitmaps[numInputSyms + i] =
- readGenericRefinementRegion(symWidth, symHeight,
- sdrTemplate, gFalse,
- refBitmap, refDX, refDY,
- sdrATX, sdrATY);
- //~ do we need to use the bmSize value here (in Huffman mode)?
- } else {
- bitmaps[numInputSyms + i] =
- readTextRegion(huff, gTrue, symWidth, symHeight,
- refAggNum, 0, numInputSyms + i, NULL,
- symCodeLen, bitmaps, 0, 0, 0, 1, 0,
- huffTableF, huffTableH, huffTableK, huffTableO,
- huffTableO, huffTableO, huffTableO, huffTableA,
- sdrTemplate, sdrATX, sdrATY);
- }
-
- // non-ref/agg coding
- } else {
- bitmaps[numInputSyms + i] =
- readGenericBitmap(gFalse, symWidth, symHeight,
- sdTemplate, gFalse, gFalse, NULL,
- sdATX, sdATY, 0);
- }
-
- ++i;
- }
-
- // read the collective bitmap
- if (huff && !refAgg) {
- huffDecoder->decodeInt(&bmSize, huffBMSizeTable);
- if (huff) {
- huffDecoder->reset();
- }
- if (bmSize == 0) {
- collBitmap = new JBIG2Bitmap(0, totalWidth, symHeight);
- bmSize = symHeight * ((totalWidth + 7) >> 3);
- p = collBitmap->getDataPtr();
- for (k = 0; k < (Guint)bmSize; ++k) {
- *p++ = str->getChar();
- }
- } else {
- collBitmap = readGenericBitmap(gTrue, totalWidth, symHeight,
- 0, gFalse, gFalse, NULL, NULL, NULL,
- bmSize);
- }
- x = 0;
- for (; j < i; ++j) {
- bitmaps[numInputSyms + j] =
- collBitmap->getSlice(x, 0, symWidths[j], symHeight);
- x += symWidths[j];
- }
- delete collBitmap;
- }
- }
-
- // create the symbol dict object
- symbolDict = new JBIG2SymbolDict(segNum, numExSyms);
-
- // exported symbol list
- i = j = 0;
- ex = gFalse;
- while (i < numInputSyms + numNewSyms) {
- if (huff) {
- huffDecoder->decodeInt(&run, huffTableA);
- } else {
- arithDecoder->decodeInt(&run, iaexStats);
- }
- if (ex) {
- for (cnt = 0; cnt < run; ++cnt) {
- symbolDict->setBitmap(j++, bitmaps[i++]->copy());
- }
- } else {
- i += run;
- }
- ex = !ex;
- }
-
- for (i = 0; i < numNewSyms; ++i) {
- delete bitmaps[numInputSyms + i];
- }
- gfree(bitmaps);
- if (symWidths) {
- gfree(symWidths);
- }
-
- // save the arithmetic decoder stats
- if (!huff && contextRetained) {
- symbolDict->setGenericRegionStats(genericRegionStats->copy());
- if (refAgg) {
- symbolDict->setRefinementRegionStats(refinementRegionStats->copy());
- }
- }
-
- // store the new symbol dict
- segments->append(symbolDict);
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readTextRegionSeg(Guint segNum, GBool imm,
- GBool /*lossless*/, Guint /*length*/,
- Guint *refSegs, Guint nRefSegs) {
- JBIG2Bitmap *bitmap;
- JBIG2HuffmanTable runLengthTab[36];
- JBIG2HuffmanTable *symCodeTab;
- JBIG2HuffmanTable *huffFSTable, *huffDSTable, *huffDTTable;
- JBIG2HuffmanTable *huffRDWTable, *huffRDHTable;
- JBIG2HuffmanTable *huffRDXTable, *huffRDYTable, *huffRSizeTable;
- JBIG2Segment *seg;
- GList *codeTables;
- JBIG2SymbolDict *symbolDict;
- JBIG2Bitmap **syms;
- Guint w, h, x, y, segInfoFlags, extCombOp;
- Guint flags, huff, refine, logStrips, refCorner, transposed;
- Guint combOp, defPixel, sOffset, templ;
- Guint huffFlags, huffFS, huffDS, huffDT;
- Guint huffRDW, huffRDH, huffRDX, huffRDY, huffRSize;
- Guint numInstances, numSyms, symCodeLen;
- int atx[2], aty[2];
- Guint i, k, kk;
- int j;
-
- // region segment info field
- if (!readULong(&w) || !readULong(&h) ||
- !readULong(&x) || !readULong(&y) ||
- !readUByte(&segInfoFlags)) {
- goto eofError;
- }
- extCombOp = segInfoFlags & 7;
-
- // rest of the text region header
- if (!readUWord(&flags)) {
- goto eofError;
- }
- huff = flags & 1;
- refine = (flags >> 1) & 1;
- logStrips = (flags >> 2) & 3;
- refCorner = (flags >> 4) & 3;
- transposed = (flags >> 6) & 1;
- combOp = (flags >> 7) & 3;
- defPixel = (flags >> 9) & 1;
- sOffset = (flags >> 10) & 0x1f;
- templ = (flags >> 15) & 1;
- huffFS = huffDS = huffDT = 0; // make gcc happy
- huffRDW = huffRDH = huffRDX = huffRDY = huffRSize = 0; // make gcc happy
- if (huff) {
- if (!readUWord(&huffFlags)) {
- goto eofError;
- }
- huffFS = huffFlags & 3;
- huffDS = (huffFlags >> 2) & 3;
- huffDT = (huffFlags >> 4) & 3;
- huffRDW = (huffFlags >> 6) & 3;
- huffRDH = (huffFlags >> 8) & 3;
- huffRDX = (huffFlags >> 10) & 3;
- huffRDY = (huffFlags >> 12) & 3;
- huffRSize = (huffFlags >> 14) & 1;
- }
- if (refine && templ == 0) {
- if (!readByte(&atx[0]) || !readByte(&aty[0]) ||
- !readByte(&atx[1]) || !readByte(&aty[1])) {
- goto eofError;
- }
- }
- if (!readULong(&numInstances)) {
- goto eofError;
- }
-
- // get symbol dictionaries and tables
- codeTables = new GList();
- numSyms = 0;
- for (i = 0; i < nRefSegs; ++i) {
- seg = findSegment(refSegs[i]);
- if (seg->getType() == jbig2SegSymbolDict) {
- numSyms += ((JBIG2SymbolDict *)seg)->getSize();
- } else if (seg->getType() == jbig2SegCodeTable) {
- codeTables->append(seg);
- }
- }
- symCodeLen = 0;
- i = 1;
- while (i < numSyms) {
- ++symCodeLen;
- i <<= 1;
- }
-
- // get the symbol bitmaps
- syms = (JBIG2Bitmap **)gmalloc(numSyms * sizeof(JBIG2Bitmap *));
- kk = 0;
- for (i = 0; i < nRefSegs; ++i) {
- seg = findSegment(refSegs[i]);
- if (seg->getType() == jbig2SegSymbolDict) {
- symbolDict = (JBIG2SymbolDict *)seg;
- for (k = 0; k < symbolDict->getSize(); ++k) {
- syms[kk++] = symbolDict->getBitmap(k);
- }
- }
- }
-
- // get the Huffman tables
- huffFSTable = huffDSTable = huffDTTable = NULL; // make gcc happy
- huffRDWTable = huffRDHTable = NULL; // make gcc happy
- huffRDXTable = huffRDYTable = huffRSizeTable = NULL; // make gcc happy
- i = 0;
- if (huff) {
- if (huffFS == 0) {
- huffFSTable = huffTableF;
- } else if (huffFS == 1) {
- huffFSTable = huffTableG;
- } else {
- huffFSTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffDS == 0) {
- huffDSTable = huffTableH;
- } else if (huffDS == 1) {
- huffDSTable = huffTableI;
- } else if (huffDS == 2) {
- huffDSTable = huffTableJ;
- } else {
- huffDSTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffDT == 0) {
- huffDTTable = huffTableK;
- } else if (huffDT == 1) {
- huffDTTable = huffTableL;
- } else if (huffDT == 2) {
- huffDTTable = huffTableM;
- } else {
- huffDTTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffRDW == 0) {
- huffRDWTable = huffTableN;
- } else if (huffRDW == 1) {
- huffRDWTable = huffTableO;
- } else {
- huffRDWTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffRDH == 0) {
- huffRDHTable = huffTableN;
- } else if (huffRDH == 1) {
- huffRDHTable = huffTableO;
- } else {
- huffRDHTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffRDX == 0) {
- huffRDXTable = huffTableN;
- } else if (huffRDX == 1) {
- huffRDXTable = huffTableO;
- } else {
- huffRDXTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffRDY == 0) {
- huffRDYTable = huffTableN;
- } else if (huffRDY == 1) {
- huffRDYTable = huffTableO;
- } else {
- huffRDYTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- if (huffRSize == 0) {
- huffRSizeTable = huffTableA;
- } else {
- huffRSizeTable =
- ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
- }
- }
- delete codeTables;
-
- // symbol ID Huffman decoding table
- if (huff) {
- huffDecoder->reset();
- for (i = 0; i < 32; ++i) {
- runLengthTab[i].val = i;
- runLengthTab[i].prefixLen = huffDecoder->readBits(4);
- runLengthTab[i].rangeLen = 0;
- }
- runLengthTab[32].val = 0x103;
- runLengthTab[32].prefixLen = huffDecoder->readBits(4);
- runLengthTab[32].rangeLen = 2;
- runLengthTab[33].val = 0x203;
- runLengthTab[33].prefixLen = huffDecoder->readBits(4);
- runLengthTab[33].rangeLen = 3;
- runLengthTab[34].val = 0x20b;
- runLengthTab[34].prefixLen = huffDecoder->readBits(4);
- runLengthTab[34].rangeLen = 7;
- runLengthTab[35].rangeLen = jbig2HuffmanEOT;
- huffDecoder->buildTable(runLengthTab, 35);
- symCodeTab = (JBIG2HuffmanTable *)gmalloc((numSyms + 1) *
- sizeof(JBIG2HuffmanTable));
- for (i = 0; i < numSyms; ++i) {
- symCodeTab[i].val = i;
- symCodeTab[i].rangeLen = 0;
- }
- i = 0;
- while (i < numSyms) {
- huffDecoder->decodeInt(&j, runLengthTab);
- if (j > 0x200) {
- for (j -= 0x200; j && i < numSyms; --j) {
- symCodeTab[i++].prefixLen = 0;
- }
- } else if (j > 0x100) {
- for (j -= 0x100; j && i < numSyms; --j) {
- symCodeTab[i].prefixLen = symCodeTab[i-1].prefixLen;
- ++i;
- }
- } else {
- symCodeTab[i++].prefixLen = j;
- }
-
- }
- symCodeTab[numSyms].rangeLen = jbig2HuffmanEOT;
- huffDecoder->buildTable(symCodeTab, numSyms);
- huffDecoder->reset();
-
- // set up the arithmetic decoder
- } else {
- symCodeTab = NULL;
- resetIntStats(symCodeLen);
- if (refine) {
- resetRefinementStats(templ, NULL);
- }
- arithDecoder->start();
- }
-
- bitmap = readTextRegion(huff, refine, w, h, numInstances,
- logStrips, numSyms, symCodeTab, symCodeLen, syms,
- defPixel, combOp, transposed, refCorner, sOffset,
- huffFSTable, huffDSTable, huffDTTable,
- huffRDWTable, huffRDHTable,
- huffRDXTable, huffRDYTable, huffRSizeTable,
- templ, atx, aty);
-
- gfree(syms);
-
- // combine the region bitmap into the page bitmap
- if (imm) {
- if (pageH == 0xffffffff && y + h > curPageH) {
- pageBitmap->expand(y + h, pageDefPixel);
- }
- pageBitmap->combine(bitmap, x, y, extCombOp);
- delete bitmap;
-
- // store the region bitmap
- } else {
- bitmap->setSegNum(segNum);
- segments->append(bitmap);
- }
-
- // clean up the Huffman decoder
- if (huff) {
- gfree(symCodeTab);
- }
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-JBIG2Bitmap *JBIG2Stream::readTextRegion(GBool huff, GBool refine,
- int w, int h,
- Guint numInstances,
- Guint logStrips,
- int /*numSyms*/,
- JBIG2HuffmanTable *symCodeTab,
- Guint symCodeLen,
- JBIG2Bitmap **syms,
- Guint defPixel, Guint combOp,
- Guint transposed, Guint refCorner,
- Guint sOffset,
- JBIG2HuffmanTable *huffFSTable,
- JBIG2HuffmanTable *huffDSTable,
- JBIG2HuffmanTable *huffDTTable,
- JBIG2HuffmanTable *huffRDWTable,
- JBIG2HuffmanTable *huffRDHTable,
- JBIG2HuffmanTable *huffRDXTable,
- JBIG2HuffmanTable *huffRDYTable,
- JBIG2HuffmanTable *huffRSizeTable,
- Guint templ,
- int *atx, int *aty) {
- JBIG2Bitmap *bitmap;
- JBIG2Bitmap *symbolBitmap;
- Guint strips;
- int t, dt, tt, s, ds, sFirst, j;
- int rdw, rdh, rdx, rdy, ri, refDX, refDY, bmSize;
- Guint symID, inst, bw, bh;
-
- strips = 1 << logStrips;
-
- if (w < 0 || h <= 0 || w >= INT_MAX / h) {
- error(-1, "invalid width/height");
- return NULL;
- }
-
- // allocate the bitmap
- bitmap = new JBIG2Bitmap(0, w, h);
- if (defPixel) {
- bitmap->clearToOne();
- } else {
- bitmap->clearToZero();
- }
-
- // decode initial T value
- if (huff) {
- huffDecoder->decodeInt(&t, huffDTTable);
- } else {
- arithDecoder->decodeInt(&t, iadtStats);
- }
- t *= -strips;
-
- inst = 0;
- sFirst = 0;
- while (inst < numInstances) {
-
- // decode delta-T
- if (huff) {
- huffDecoder->decodeInt(&dt, huffDTTable);
- } else {
- arithDecoder->decodeInt(&dt, iadtStats);
- }
- t += dt * strips;
-
- // first S value
- if (huff) {
- huffDecoder->decodeInt(&ds, huffFSTable);
- } else {
- arithDecoder->decodeInt(&ds, iafsStats);
- }
- sFirst += ds;
- s = sFirst;
-
- // read the instances
- while (1) {
-
- // T value
- if (strips == 1) {
- dt = 0;
- } else if (huff) {
- dt = huffDecoder->readBits(logStrips);
- } else {
- arithDecoder->decodeInt(&dt, iaitStats);
- }
- tt = t + dt;
-
- // symbol ID
- if (huff) {
- if (symCodeTab) {
- huffDecoder->decodeInt(&j, symCodeTab);
- symID = (Guint)j;
- } else {
- symID = huffDecoder->readBits(symCodeLen);
- }
- } else {
- symID = arithDecoder->decodeIAID(symCodeLen, iaidStats);
- }
-
- // get the symbol bitmap
- symbolBitmap = NULL;
- if (refine) {
- if (huff) {
- ri = (int)huffDecoder->readBit();
- } else {
- arithDecoder->decodeInt(&ri, iariStats);
- }
- } else {
- ri = 0;
- }
- if (ri) {
- if (huff) {
- huffDecoder->decodeInt(&rdw, huffRDWTable);
- huffDecoder->decodeInt(&rdh, huffRDHTable);
- huffDecoder->decodeInt(&rdx, huffRDXTable);
- huffDecoder->decodeInt(&rdy, huffRDYTable);
- huffDecoder->decodeInt(&bmSize, huffRSizeTable);
- huffDecoder->reset();
- arithDecoder->start();
- } else {
- arithDecoder->decodeInt(&rdw, iardwStats);
- arithDecoder->decodeInt(&rdh, iardhStats);
- arithDecoder->decodeInt(&rdx, iardxStats);
- arithDecoder->decodeInt(&rdy, iardyStats);
- }
- refDX = ((rdw >= 0) ? rdw : rdw - 1) / 2 + rdx;
- refDY = ((rdh >= 0) ? rdh : rdh - 1) / 2 + rdy;
-
- symbolBitmap =
- readGenericRefinementRegion(rdw + syms[symID]->getWidth(),
- rdh + syms[symID]->getHeight(),
- templ, gFalse, syms[symID],
- refDX, refDY, atx, aty);
- //~ do we need to use the bmSize value here (in Huffman mode)?
- } else {
- symbolBitmap = syms[symID];
- }
-
- // combine the symbol bitmap into the region bitmap
- //~ something is wrong here - refCorner shouldn't degenerate into
- //~ two cases
- bw = symbolBitmap->getWidth() - 1;
- bh = symbolBitmap->getHeight() - 1;
- if (transposed) {
- switch (refCorner) {
- case 0: // bottom left
- bitmap->combine(symbolBitmap, tt, s, combOp);
- break;
- case 1: // top left
- bitmap->combine(symbolBitmap, tt, s, combOp);
- break;
- case 2: // bottom right
- bitmap->combine(symbolBitmap, tt - bw, s, combOp);
- break;
- case 3: // top right
- bitmap->combine(symbolBitmap, tt - bw, s, combOp);
- break;
- }
- s += bh;
- } else {
- switch (refCorner) {
- case 0: // bottom left
- bitmap->combine(symbolBitmap, s, tt - bh, combOp);
- break;
- case 1: // top left
- bitmap->combine(symbolBitmap, s, tt, combOp);
- break;
- case 2: // bottom right
- bitmap->combine(symbolBitmap, s, tt - bh, combOp);
- break;
- case 3: // top right
- bitmap->combine(symbolBitmap, s, tt, combOp);
- break;
- }
- s += bw;
- }
- if (ri) {
- delete symbolBitmap;
- }
-
- // next instance
- ++inst;
-
- // next S value
- if (huff) {
- if (!huffDecoder->decodeInt(&ds, huffDSTable)) {
- break;
- }
- } else {
- if (!arithDecoder->decodeInt(&ds, iadsStats)) {
- break;
- }
- }
- s += sOffset + ds;
- }
- }
-
- return bitmap;
-}
-
-void JBIG2Stream::readPatternDictSeg(Guint segNum, Guint length) {
- JBIG2PatternDict *patternDict;
- JBIG2Bitmap *bitmap;
- Guint flags, patternW, patternH, grayMax, templ, mmr;
- int atx[4], aty[4];
- Guint i, x;
-
- // halftone dictionary flags, pattern width and height, max gray value
- if (!readUByte(&flags) ||
- !readUByte(&patternW) ||
- !readUByte(&patternH) ||
- !readULong(&grayMax)) {
- goto eofError;
- }
- templ = (flags >> 1) & 3;
- mmr = flags & 1;
-
- // set up the arithmetic decoder
- if (!mmr) {
- resetGenericStats(templ, NULL);
- arithDecoder->start();
- }
-
- // read the bitmap
- atx[0] = -patternW; aty[0] = 0;
- atx[1] = -3; aty[1] = -1;
- atx[2] = 2; aty[2] = -2;
- atx[3] = -2; aty[3] = -2;
- bitmap = readGenericBitmap(mmr, (grayMax + 1) * patternW, patternH,
- templ, gFalse, gFalse, NULL,
- atx, aty, length - 7);
-
- // create the pattern dict object
- patternDict = new JBIG2PatternDict(segNum, grayMax + 1);
-
- // split up the bitmap
- x = 0;
- for (i = 0; i <= grayMax; ++i) {
- patternDict->setBitmap(i, bitmap->getSlice(x, 0, patternW, patternH));
- x += patternW;
- }
-
- // free memory
- delete bitmap;
-
- // store the new pattern dict
- segments->append(patternDict);
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readHalftoneRegionSeg(Guint segNum, GBool imm,
- GBool /*lossless*/, Guint /*length*/,
- Guint *refSegs, Guint nRefSegs) {
- JBIG2Bitmap *bitmap;
- JBIG2Segment *seg;
- JBIG2PatternDict *patternDict;
- JBIG2Bitmap *skipBitmap;
- Guint *grayImg;
- JBIG2Bitmap *grayBitmap;
- JBIG2Bitmap *patternBitmap;
- Guint w, h, x, y, segInfoFlags, extCombOp;
- Guint flags, mmr, templ, enableSkip, combOp;
- Guint gridW, gridH, stepX, stepY, patW, patH;
- int atx[4], aty[4];
- int gridX, gridY, xx, yy, bit, j;
- Guint bpp, m, n, i;
-
- // region segment info field
- if (!readULong(&w) || !readULong(&h) ||
- !readULong(&x) || !readULong(&y) ||
- !readUByte(&segInfoFlags)) {
- goto eofError;
- }
- extCombOp = segInfoFlags & 7;
-
- // rest of the halftone region header
- if (!readUByte(&flags)) {
- goto eofError;
- }
- mmr = flags & 1;
- templ = (flags >> 1) & 3;
- enableSkip = (flags >> 3) & 1;
- combOp = (flags >> 4) & 7;
- if (!readULong(&gridW) || !readULong(&gridH) ||
- !readLong(&gridX) || !readLong(&gridY) ||
- !readUWord(&stepX) || !readUWord(&stepY)) {
- goto eofError;
- }
-
- // get pattern dictionary
- if (nRefSegs != 1) {
- error(getPos(), "Bad symbol dictionary reference in JBIG2 halftone segment");
- return;
- }
- seg = findSegment(refSegs[0]);
- if (seg->getType() != jbig2SegPatternDict) {
- error(getPos(), "Bad symbol dictionary reference in JBIG2 halftone segment");
- return;
- }
- if (gridH == 0 || gridW >= INT_MAX / gridH) {
- error(getPos(), "Bad size in JBIG2 halftone segment");
- return;
- }
- if (w == 0 || h >= INT_MAX / w) {
- error(getPos(), "Bad size in JBIG2 bitmap segment");
- return;
- }
-
- patternDict = (JBIG2PatternDict *)seg;
- bpp = 0;
- i = 1;
- while (i < patternDict->getSize()) {
- ++bpp;
- i <<= 1;
- }
- patW = patternDict->getBitmap(0)->getWidth();
- patH = patternDict->getBitmap(0)->getHeight();
-
- // set up the arithmetic decoder
- if (!mmr) {
- resetGenericStats(templ, NULL);
- arithDecoder->start();
- }
-
- // allocate the bitmap
- bitmap = new JBIG2Bitmap(segNum, w, h);
- if (flags & 0x80) { // HDEFPIXEL
- bitmap->clearToOne();
- } else {
- bitmap->clearToZero();
- }
-
- // compute the skip bitmap
- skipBitmap = NULL;
- if (enableSkip) {
- skipBitmap = new JBIG2Bitmap(0, gridW, gridH);
- skipBitmap->clearToZero();
- for (m = 0; m < gridH; ++m) {
- xx = gridX + m * stepY;
- yy = gridY + m * stepX;
- for (n = 0; n < gridW; ++n) {
- if (((xx + (int)patW) >> 8) <= 0 || (xx >> 8) >= (int)w ||
- ((yy + (int)patH) >> 8) <= 0 || (yy >> 8) >= (int)h) {
- skipBitmap->setPixel(n, m);
- }
- }
- }
- }
-
- // read the gray-scale image
- grayImg = (Guint *)gmalloc(gridW * gridH * sizeof(Guint));
- memset(grayImg, 0, gridW * gridH * sizeof(Guint));
- atx[0] = templ <= 1 ? 3 : 2; aty[0] = -1;
- atx[1] = -3; aty[1] = -1;
- atx[2] = 2; aty[2] = -2;
- atx[3] = -2; aty[3] = -2;
- for (j = bpp - 1; j >= 0; --j) {
- grayBitmap = readGenericBitmap(mmr, gridW, gridH, templ, gFalse,
- enableSkip, skipBitmap, atx, aty, -1);
- i = 0;
- for (m = 0; m < gridH; ++m) {
- for (n = 0; n < gridW; ++n) {
- bit = grayBitmap->getPixel(n, m) ^ (grayImg[i] & 1);
- grayImg[i] = (grayImg[i] << 1) | bit;
- ++i;
- }
- }
- delete grayBitmap;
- }
-
- // decode the image
- i = 0;
- for (m = 0; m < gridH; ++m) {
- xx = gridX + m * stepY;
- yy = gridY + m * stepX;
- for (n = 0; n < gridW; ++n) {
- if (!(enableSkip && skipBitmap->getPixel(n, m))) {
- patternBitmap = patternDict->getBitmap(grayImg[i]);
- bitmap->combine(patternBitmap, xx >> 8, yy >> 8, combOp);
- }
- xx += stepX;
- yy -= stepY;
- ++i;
- }
- }
-
- gfree(grayImg);
-
- // combine the region bitmap into the page bitmap
- if (imm) {
- if (pageH == 0xffffffff && y + h > curPageH) {
- pageBitmap->expand(y + h, pageDefPixel);
- }
- pageBitmap->combine(bitmap, x, y, extCombOp);
- delete bitmap;
-
- // store the region bitmap
- } else {
- segments->append(bitmap);
- }
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readGenericRegionSeg(Guint segNum, GBool imm,
- GBool /*lossless*/, Guint length) {
- JBIG2Bitmap *bitmap;
- Guint w, h, x, y, segInfoFlags, extCombOp;
- Guint flags, mmr, templ, tpgdOn;
- int atx[4], aty[4];
-
- // region segment info field
- if (!readULong(&w) || !readULong(&h) ||
- !readULong(&x) || !readULong(&y) ||
- !readUByte(&segInfoFlags)) {
- goto eofError;
- }
- extCombOp = segInfoFlags & 7;
-
- // rest of the generic region segment header
- if (!readUByte(&flags)) {
- goto eofError;
- }
- mmr = flags & 1;
- templ = (flags >> 1) & 3;
- tpgdOn = (flags >> 3) & 1;
-
- // AT flags
- if (!mmr) {
- if (templ == 0) {
- if (!readByte(&atx[0]) ||
- !readByte(&aty[0]) ||
- !readByte(&atx[1]) ||
- !readByte(&aty[1]) ||
- !readByte(&atx[2]) ||
- !readByte(&aty[2]) ||
- !readByte(&atx[3]) ||
- !readByte(&aty[3])) {
- goto eofError;
- }
- } else {
- if (!readByte(&atx[0]) ||
- !readByte(&aty[0])) {
- goto eofError;
- }
- }
- }
-
- // set up the arithmetic decoder
- if (!mmr) {
- resetGenericStats(templ, NULL);
- arithDecoder->start();
- }
-
- // read the bitmap
- bitmap = readGenericBitmap(mmr, w, h, templ, tpgdOn, gFalse,
- NULL, atx, aty, mmr ? 0 : length - 18);
-
- // combine the region bitmap into the page bitmap
- if (imm) {
- if (pageH == 0xffffffff && y + h > curPageH) {
- pageBitmap->expand(y + h, pageDefPixel);
- }
- pageBitmap->combine(bitmap, x, y, extCombOp);
- delete bitmap;
-
- // store the region bitmap
- } else {
- bitmap->setSegNum(segNum);
- segments->append(bitmap);
- }
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-JBIG2Bitmap *JBIG2Stream::readGenericBitmap(GBool mmr, int w, int h,
- int templ, GBool tpgdOn,
- GBool useSkip, JBIG2Bitmap *skip,
- int *atx, int *aty,
- int mmrDataLength) {
- JBIG2Bitmap *bitmap;
- GBool ltp;
- Guint ltpCX, cx, cx0, cx1, cx2;
- int *refLine, *codingLine;
- int code1, code2, code3;
- int x, y, a0, pix, i, refI, codingI;
-
- bitmap = new JBIG2Bitmap(0, w, h);
- bitmap->clearToZero();
-
- //----- MMR decode
-
- if (mmr) {
-
- mmrDecoder->reset();
- refLine = (int *)gmalloc((w + 2) * sizeof(int));
- codingLine = (int *)gmalloc((w + 2) * sizeof(int));
- codingLine[0] = codingLine[1] = w;
-
- for (y = 0; y < h; ++y) {
-
- // copy coding line to ref line
- for (i = 0; codingLine[i] < w; ++i) {
- refLine[i] = codingLine[i];
- }
- refLine[i] = refLine[i + 1] = w;
-
- // decode a line
- refI = 0; // b1 = refLine[refI]
- codingI = 0; // a1 = codingLine[codingI]
- a0 = 0;
- do {
- code1 = mmrDecoder->get2DCode();
- switch (code1) {
- case twoDimPass:
- if (refLine[refI] < w) {
- a0 = refLine[refI + 1];
- refI += 2;
- }
- break;
- case twoDimHoriz:
- if (codingI & 1) {
- code1 = 0;
- do {
- code1 += code3 = mmrDecoder->getBlackCode();
- } while (code3 >= 64);
- code2 = 0;
- do {
- code2 += code3 = mmrDecoder->getWhiteCode();
- } while (code3 >= 64);
- } else {
- code1 = 0;
- do {
- code1 += code3 = mmrDecoder->getWhiteCode();
- } while (code3 >= 64);
- code2 = 0;
- do {
- code2 += code3 = mmrDecoder->getBlackCode();
- } while (code3 >= 64);
- }
- a0 = codingLine[codingI++] = a0 + code1;
- a0 = codingLine[codingI++] = a0 + code2;
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- break;
- case twoDimVert0:
- a0 = codingLine[codingI++] = refLine[refI];
- if (refLine[refI] < w) {
- ++refI;
- }
- break;
- case twoDimVertR1:
- a0 = codingLine[codingI++] = refLine[refI] + 1;
- if (refLine[refI] < w) {
- ++refI;
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- }
- break;
- case twoDimVertR2:
- a0 = codingLine[codingI++] = refLine[refI] + 2;
- if (refLine[refI] < w) {
- ++refI;
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- }
- break;
- case twoDimVertR3:
- a0 = codingLine[codingI++] = refLine[refI] + 3;
- if (refLine[refI] < w) {
- ++refI;
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- }
- break;
- case twoDimVertL1:
- a0 = codingLine[codingI++] = refLine[refI] - 1;
- if (refI > 0) {
- --refI;
- } else {
- ++refI;
- }
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- break;
- case twoDimVertL2:
- a0 = codingLine[codingI++] = refLine[refI] - 2;
- if (refI > 0) {
- --refI;
- } else {
- ++refI;
- }
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- break;
- case twoDimVertL3:
- a0 = codingLine[codingI++] = refLine[refI] - 3;
- if (refI > 0) {
- --refI;
- } else {
- ++refI;
- }
- while (refLine[refI] <= a0 && refLine[refI] < w) {
- refI += 2;
- }
- break;
- default:
- error(getPos(), "Illegal code in JBIG2 MMR bitmap data");
- break;
- }
- } while (a0 < w);
- codingLine[codingI++] = w;
-
- // convert the run lengths to a bitmap line
- i = 0;
- while (codingLine[i] < w) {
- for (x = codingLine[i]; x < codingLine[i+1]; ++x) {
- bitmap->setPixel(x, y);
- }
- i += 2;
- }
- }
-
- if (mmrDataLength >= 0) {
- mmrDecoder->skipTo(mmrDataLength);
- } else {
- if (mmrDecoder->get24Bits() != 0x001001) {
- error(getPos(), "Missing EOFB in JBIG2 MMR bitmap data");
- }
- }
-
- gfree(refLine);
- gfree(codingLine);
-
- //----- arithmetic decode
-
- } else {
- // set up the typical row context
- ltpCX = 0; // make gcc happy
- if (tpgdOn) {
- switch (templ) {
- case 0:
- ltpCX = 0x3953; // 001 11001 0101 0011
- break;
- case 1:
- ltpCX = 0x079a; // 0011 11001 101 0
- break;
- case 2:
- ltpCX = 0x0e3; // 001 1100 01 1
- break;
- case 3:
- ltpCX = 0x18a; // 01100 0101 1
- break;
- }
- }
-
- ltp = 0;
- cx = cx0 = cx1 = cx2 = 0; // make gcc happy
- for (y = 0; y < h; ++y) {
-
- // check for a "typical" (duplicate) row
- if (tpgdOn) {
- if (arithDecoder->decodeBit(ltpCX, genericRegionStats)) {
- ltp = !ltp;
- }
- if (ltp) {
- bitmap->duplicateRow(y, y-1);
- continue;
- }
- }
-
- // set up the context
- switch (templ) {
- case 0:
- cx0 = (bitmap->getPixel(0, y-2) << 1) |
- bitmap->getPixel(1, y-2);
- cx1 = (bitmap->getPixel(0, y-1) << 2) |
- (bitmap->getPixel(1, y-1) << 1) |
- bitmap->getPixel(2, y-1);
- cx2 = 0;
- break;
- case 1:
- cx0 = (bitmap->getPixel(0, y-2) << 2) |
- (bitmap->getPixel(1, y-2) << 1) |
- bitmap->getPixel(2, y-2);
- cx1 = (bitmap->getPixel(0, y-1) << 2) |
- (bitmap->getPixel(1, y-1) << 1) |
- bitmap->getPixel(2, y-1);
- cx2 = 0;
- break;
- case 2:
- cx0 = (bitmap->getPixel(0, y-2) << 1) |
- bitmap->getPixel(1, y-2);
- cx1 = (bitmap->getPixel(0, y-1) << 1) |
- bitmap->getPixel(1, y-1);
- cx2 = 0;
- break;
- case 3:
- cx1 = (bitmap->getPixel(0, y-1) << 1) |
- bitmap->getPixel(1, y-1);
- cx2 = 0;
- break;
- }
-
- // decode the row
- for (x = 0; x < w; ++x) {
-
- // check for a skipped pixel
- if (useSkip && skip->getPixel(x, y)) {
- pix = 0;
-
- } else {
-
- // build the context
- switch (templ) {
- case 0:
- cx = (cx0 << 13) | (cx1 << 8) | (cx2 << 4) |
- (bitmap->getPixel(x + atx[0], y + aty[0]) << 3) |
- (bitmap->getPixel(x + atx[1], y + aty[1]) << 2) |
- (bitmap->getPixel(x + atx[2], y + aty[2]) << 1) |
- bitmap->getPixel(x + atx[3], y + aty[3]);
- break;
- case 1:
- cx = (cx0 << 9) | (cx1 << 4) | (cx2 << 1) |
- bitmap->getPixel(x + atx[0], y + aty[0]);
- break;
- case 2:
- cx = (cx0 << 7) | (cx1 << 3) | (cx2 << 1) |
- bitmap->getPixel(x + atx[0], y + aty[0]);
- break;
- case 3:
- cx = (cx1 << 5) | (cx2 << 1) |
- bitmap->getPixel(x + atx[0], y + aty[0]);
- break;
- }
-
- // decode the pixel
- if ((pix = arithDecoder->decodeBit(cx, genericRegionStats))) {
- bitmap->setPixel(x, y);
- }
- }
-
- // update the context
- switch (templ) {
- case 0:
- cx0 = ((cx0 << 1) | bitmap->getPixel(x+2, y-2)) & 0x07;
- cx1 = ((cx1 << 1) | bitmap->getPixel(x+3, y-1)) & 0x1f;
- cx2 = ((cx2 << 1) | pix) & 0x0f;
- break;
- case 1:
- cx0 = ((cx0 << 1) | bitmap->getPixel(x+3, y-2)) & 0x0f;
- cx1 = ((cx1 << 1) | bitmap->getPixel(x+3, y-1)) & 0x1f;
- cx2 = ((cx2 << 1) | pix) & 0x07;
- break;
- case 2:
- cx0 = ((cx0 << 1) | bitmap->getPixel(x+2, y-2)) & 0x07;
- cx1 = ((cx1 << 1) | bitmap->getPixel(x+2, y-1)) & 0x0f;
- cx2 = ((cx2 << 1) | pix) & 0x03;
- break;
- case 3:
- cx1 = ((cx1 << 1) | bitmap->getPixel(x+2, y-1)) & 0x1f;
- cx2 = ((cx2 << 1) | pix) & 0x0f;
- break;
- }
- }
- }
- }
-
- return bitmap;
-}
-
-void JBIG2Stream::readGenericRefinementRegionSeg(Guint segNum, GBool imm,
- GBool /*lossless*/, Guint /*length*/,
- Guint *refSegs,
- Guint nRefSegs) {
- JBIG2Bitmap *bitmap, *refBitmap;
- Guint w, h, x, y, segInfoFlags, extCombOp;
- Guint flags, templ, tpgrOn;
- int atx[2], aty[2];
- JBIG2Segment *seg;
-
- // region segment info field
- if (!readULong(&w) || !readULong(&h) ||
- !readULong(&x) || !readULong(&y) ||
- !readUByte(&segInfoFlags)) {
- goto eofError;
- }
- extCombOp = segInfoFlags & 7;
-
- // rest of the generic refinement region segment header
- if (!readUByte(&flags)) {
- goto eofError;
- }
- templ = flags & 1;
- tpgrOn = (flags >> 1) & 1;
-
- // AT flags
- if (!templ) {
- if (!readByte(&atx[0]) || !readByte(&aty[0]) ||
- !readByte(&atx[1]) || !readByte(&aty[1])) {
- goto eofError;
- }
- }
-
- // resize the page bitmap if needed
- if (nRefSegs == 0 || imm) {
- if (pageH == 0xffffffff && y + h > curPageH) {
- pageBitmap->expand(y + h, pageDefPixel);
- }
- }
-
- // get referenced bitmap
- if (nRefSegs > 1) {
- error(getPos(), "Bad reference in JBIG2 generic refinement segment");
- return;
- }
- if (nRefSegs == 1) {
- seg = findSegment(refSegs[0]);
- if (seg->getType() != jbig2SegBitmap) {
- error(getPos(), "Bad bitmap reference in JBIG2 generic refinement segment");
- return;
- }
- refBitmap = (JBIG2Bitmap *)seg;
- } else {
- refBitmap = pageBitmap->getSlice(x, y, w, h);
- }
-
- // set up the arithmetic decoder
- resetRefinementStats(templ, NULL);
- arithDecoder->start();
-
- // read
- bitmap = readGenericRefinementRegion(w, h, templ, tpgrOn,
- refBitmap, 0, 0, atx, aty);
-
- // combine the region bitmap into the page bitmap
- if (imm) {
- pageBitmap->combine(bitmap, x, y, extCombOp);
- delete bitmap;
-
- // store the region bitmap
- } else {
- bitmap->setSegNum(segNum);
- segments->append(bitmap);
- }
-
- // delete the referenced bitmap
- if (nRefSegs == 1) {
- discardSegment(refSegs[0]);
- } else {
- delete refBitmap;
- }
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-JBIG2Bitmap *JBIG2Stream::readGenericRefinementRegion(int w, int h,
- int templ, GBool tpgrOn,
- JBIG2Bitmap *refBitmap,
- int refDX, int refDY,
- int *atx, int *aty) {
- JBIG2Bitmap *bitmap;
- GBool ltp;
- Guint ltpCX, cx, cx0, cx2, cx3, cx4, tpgrCX0, tpgrCX1, tpgrCX2;
- int x, y, pix;
-
- if (w < 0 || h <= 0 || w >= INT_MAX / h) {
- error(-1, "invalid width/height");
- return NULL;
- }
-
- bitmap = new JBIG2Bitmap(0, w, h);
- bitmap->clearToZero();
-
- // set up the typical row context
- if (templ) {
- ltpCX = 0x008;
- } else {
- ltpCX = 0x0010;
- }
-
- ltp = 0;
- for (y = 0; y < h; ++y) {
-
- // set up the context
- if (templ) {
- cx0 = bitmap->getPixel(0, y-1);
- cx2 = 0; // unused
- cx3 = (refBitmap->getPixel(-1-refDX, y-refDY) << 1) |
- refBitmap->getPixel(-refDX, y-refDY);
- cx4 = refBitmap->getPixel(-refDX, y+1-refDY);
- } else {
- cx0 = bitmap->getPixel(0, y-1);
- cx2 = refBitmap->getPixel(-refDX, y-1-refDY);
- cx3 = (refBitmap->getPixel(-1-refDX, y-refDY) << 1) |
- refBitmap->getPixel(-refDX, y-refDY);
- cx4 = (refBitmap->getPixel(-1-refDX, y+1-refDY) << 1) |
- refBitmap->getPixel(-refDX, y+1-refDY);
- }
-
- // set up the typical prediction context
- tpgrCX0 = tpgrCX1 = tpgrCX2 = 0; // make gcc happy
- if (tpgrOn) {
- tpgrCX0 = (refBitmap->getPixel(-1-refDX, y-1-refDY) << 2) |
- (refBitmap->getPixel(-refDX, y-1-refDY) << 1) |
- refBitmap->getPixel(1-refDX, y-1-refDY);
- tpgrCX1 = (refBitmap->getPixel(-1-refDX, y-refDY) << 2) |
- (refBitmap->getPixel(-refDX, y-refDY) << 1) |
- refBitmap->getPixel(1-refDX, y-refDY);
- tpgrCX2 = (refBitmap->getPixel(-1-refDX, y+1-refDY) << 2) |
- (refBitmap->getPixel(-refDX, y+1-refDY) << 1) |
- refBitmap->getPixel(1-refDX, y+1-refDY);
- }
-
- for (x = 0; x < w; ++x) {
-
- // update the context
- if (templ) {
- cx0 = ((cx0 << 1) | bitmap->getPixel(x+1, y-1)) & 7;
- cx3 = ((cx3 << 1) | refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
- cx4 = ((cx4 << 1) | refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 3;
- } else {
- cx0 = ((cx0 << 1) | bitmap->getPixel(x+1, y-1)) & 3;
- cx2 = ((cx2 << 1) | refBitmap->getPixel(x+1-refDX, y-1-refDY)) & 3;
- cx3 = ((cx3 << 1) | refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
- cx4 = ((cx4 << 1) | refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 7;
- }
-
- if (tpgrOn) {
- // update the typical predictor context
- tpgrCX0 = ((tpgrCX0 << 1) |
- refBitmap->getPixel(x+1-refDX, y-1-refDY)) & 7;
- tpgrCX1 = ((tpgrCX1 << 1) |
- refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
- tpgrCX2 = ((tpgrCX2 << 1) |
- refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 7;
-
- // check for a "typical" pixel
- if (arithDecoder->decodeBit(ltpCX, refinementRegionStats)) {
- ltp = !ltp;
- }
- if (tpgrCX0 == 0 && tpgrCX1 == 0 && tpgrCX2 == 0) {
- bitmap->clearPixel(x, y);
- continue;
- } else if (tpgrCX0 == 7 && tpgrCX1 == 7 && tpgrCX2 == 7) {
- bitmap->setPixel(x, y);
- continue;
- }
- }
-
- // build the context
- if (templ) {
- cx = (cx0 << 7) | (bitmap->getPixel(x-1, y) << 6) |
- (refBitmap->getPixel(x-refDX, y-1-refDY) << 5) |
- (cx3 << 2) | cx4;
- } else {
- cx = (cx0 << 11) | (bitmap->getPixel(x-1, y) << 10) |
- (cx2 << 8) | (cx3 << 5) | (cx4 << 2) |
- (bitmap->getPixel(x+atx[0], y+aty[0]) << 1) |
- refBitmap->getPixel(x+atx[1]-refDX, y+aty[1]-refDY);
- }
-
- // decode the pixel
- if ((pix = arithDecoder->decodeBit(cx, refinementRegionStats))) {
- bitmap->setPixel(x, y);
- }
- }
- }
-
- return bitmap;
-}
-
-void JBIG2Stream::readPageInfoSeg(Guint /*length*/) {
- Guint xRes, yRes, flags, striping;
-
- if (!readULong(&pageW) || !readULong(&pageH) ||
- !readULong(&xRes) || !readULong(&yRes) ||
- !readUByte(&flags) || !readUWord(&striping)) {
- goto eofError;
- }
- pageDefPixel = (flags >> 2) & 1;
- defCombOp = (flags >> 3) & 3;
-
- // allocate the page bitmap
- if (pageH == 0xffffffff) {
- curPageH = striping & 0x7fff;
- } else {
- curPageH = pageH;
- }
- pageBitmap = new JBIG2Bitmap(0, pageW, curPageH);
-
- // default pixel value
- if (pageDefPixel) {
- pageBitmap->clearToOne();
- } else {
- pageBitmap->clearToZero();
- }
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readEndOfStripeSeg(Guint length) {
- Guint i;
-
- // skip the segment
- for (i = 0; i < length; ++i) {
- curStr->getChar();
- }
-}
-
-void JBIG2Stream::readProfilesSeg(Guint length) {
- Guint i;
-
- // skip the segment
- for (i = 0; i < length; ++i) {
- curStr->getChar();
- }
-}
-
-void JBIG2Stream::readCodeTableSeg(Guint segNum, Guint /*length*/) {
- JBIG2HuffmanTable *huffTab;
- Guint flags, oob, prefixBits, rangeBits;
- int lowVal, highVal, val;
- Guint huffTabSize, i;
-
- if (!readUByte(&flags) || !readLong(&lowVal) || !readLong(&highVal)) {
- goto eofError;
- }
- oob = flags & 1;
- prefixBits = (flags >> 1) & 7;
- rangeBits = (flags >> 4) & 7;
-
- huffDecoder->reset();
- huffTabSize = 8;
- huffTab = (JBIG2HuffmanTable *)
- gmalloc(huffTabSize * sizeof(JBIG2HuffmanTable));
- i = 0;
- val = lowVal;
- while (val < highVal) {
- if (i == huffTabSize) {
- huffTabSize *= 2;
- huffTab = (JBIG2HuffmanTable *)
- grealloc(huffTab, huffTabSize * sizeof(JBIG2HuffmanTable));
- }
- huffTab[i].val = val;
- huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
- huffTab[i].rangeLen = huffDecoder->readBits(rangeBits);
- val += 1 << huffTab[i].rangeLen;
- ++i;
- }
- if (i + oob + 3 > huffTabSize) {
- huffTabSize = i + oob + 3;
- huffTab = (JBIG2HuffmanTable *)
- grealloc(huffTab, huffTabSize * sizeof(JBIG2HuffmanTable));
- }
- huffTab[i].val = lowVal - 1;
- huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
- huffTab[i].rangeLen = jbig2HuffmanLOW;
- ++i;
- huffTab[i].val = highVal;
- huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
- huffTab[i].rangeLen = 32;
- ++i;
- if (oob) {
- huffTab[i].val = 0;
- huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
- huffTab[i].rangeLen = jbig2HuffmanOOB;
- ++i;
- }
- huffTab[i].val = 0;
- huffTab[i].prefixLen = 0;
- huffTab[i].rangeLen = jbig2HuffmanEOT;
- ++i;
- huffDecoder->buildTable(huffTab, i);
-
- // create and store the new table segment
- segments->append(new JBIG2CodeTable(segNum, huffTab));
-
- return;
-
- eofError:
- error(getPos(), "Unexpected EOF in JBIG2 stream");
-}
-
-void JBIG2Stream::readExtensionSeg(Guint length) {
- Guint i;
-
- // skip the segment
- for (i = 0; i < length; ++i) {
- curStr->getChar();
- }
-}
-
-JBIG2Segment *JBIG2Stream::findSegment(Guint segNum) {
- JBIG2Segment *seg;
- int i;
-
- for (i = 0; i < globalSegments->getLength(); ++i) {
- seg = (JBIG2Segment *)globalSegments->get(i);
- if (seg->getSegNum() == segNum) {
- return seg;
- }
- }
- for (i = 0; i < segments->getLength(); ++i) {
- seg = (JBIG2Segment *)segments->get(i);
- if (seg->getSegNum() == segNum) {
- return seg;
- }
- }
- return NULL;
-}
-
-void JBIG2Stream::discardSegment(Guint segNum) {
- JBIG2Segment *seg;
- int i;
-
- for (i = 0; i < globalSegments->getLength(); ++i) {
- seg = (JBIG2Segment *)globalSegments->get(i);
- if (seg->getSegNum() == segNum) {
- globalSegments->del(i);
- return;
- }
- }
- for (i = 0; i < segments->getLength(); ++i) {
- seg = (JBIG2Segment *)segments->get(i);
- if (seg->getSegNum() == segNum) {
- globalSegments->del(i);
- return;
- }
- }
-}
-
-void JBIG2Stream::resetGenericStats(Guint templ,
- JBIG2ArithmeticDecoderStats *prevStats) {
- int size;
-
- size = contextSize[templ];
- if (prevStats && prevStats->getContextSize() == size) {
- if (genericRegionStats->getContextSize() == size) {
- genericRegionStats->copyFrom(prevStats);
- } else {
- delete genericRegionStats;
- genericRegionStats = prevStats->copy();
- }
- } else {
- if (genericRegionStats->getContextSize() == size) {
- genericRegionStats->reset();
- } else {
- delete genericRegionStats;
- genericRegionStats = new JBIG2ArithmeticDecoderStats(size);
- }
- }
-}
-
-void JBIG2Stream::resetRefinementStats(
- Guint templ,
- JBIG2ArithmeticDecoderStats *prevStats) {
- int size;
-
- size = refContextSize[templ];
- if (prevStats && prevStats->getContextSize() == size) {
- if (refinementRegionStats->getContextSize() == size) {
- refinementRegionStats->copyFrom(prevStats);
- } else {
- delete refinementRegionStats;
- refinementRegionStats = prevStats->copy();
- }
- } else {
- if (refinementRegionStats->getContextSize() == size) {
- refinementRegionStats->reset();
- } else {
- delete refinementRegionStats;
- refinementRegionStats = new JBIG2ArithmeticDecoderStats(size);
- }
- }
-}
-
-void JBIG2Stream::resetIntStats(int symCodeLen) {
- iadhStats->reset();
- iadwStats->reset();
- iaexStats->reset();
- iaaiStats->reset();
- iadtStats->reset();
- iaitStats->reset();
- iafsStats->reset();
- iadsStats->reset();
- iardxStats->reset();
- iardyStats->reset();
- iardwStats->reset();
- iardhStats->reset();
- iariStats->reset();
- if (iaidStats->getContextSize() == symCodeLen + 1) {
- iaidStats->reset();
- } else {
- delete iaidStats;
- iaidStats = new JBIG2ArithmeticDecoderStats(symCodeLen + 1);
- }
-}
-
-GBool JBIG2Stream::readUByte(Guint *x) {
- int c0;
-
- if ((c0 = curStr->getChar()) == EOF) {
- return gFalse;
- }
- *x = (Guint)c0;
- return gTrue;
-}
-
-GBool JBIG2Stream::readByte(int *x) {
- int c0;
-
- if ((c0 = curStr->getChar()) == EOF) {
- return gFalse;
- }
- *x = c0;
- if (c0 & 0x80) {
- *x |= -1 - 0xff;
- }
- return gTrue;
-}
-
-GBool JBIG2Stream::readUWord(Guint *x) {
- int c0, c1;
-
- if ((c0 = curStr->getChar()) == EOF ||
- (c1 = curStr->getChar()) == EOF) {
- return gFalse;
- }
- *x = (Guint)((c0 << 8) | c1);
- return gTrue;
-}
-
-GBool JBIG2Stream::readULong(Guint *x) {
- int c0, c1, c2, c3;
-
- if ((c0 = curStr->getChar()) == EOF ||
- (c1 = curStr->getChar()) == EOF ||
- (c2 = curStr->getChar()) == EOF ||
- (c3 = curStr->getChar()) == EOF) {
- return gFalse;
- }
- *x = (Guint)((c0 << 24) | (c1 << 16) | (c2 << 8) | c3);
- return gTrue;
-}
-
-GBool JBIG2Stream::readLong(int *x) {
- int c0, c1, c2, c3;
-
- if ((c0 = curStr->getChar()) == EOF ||
- (c1 = curStr->getChar()) == EOF ||
- (c2 = curStr->getChar()) == EOF ||
- (c3 = curStr->getChar()) == EOF) {
- return gFalse;
- }
- *x = ((c0 << 24) | (c1 << 16) | (c2 << 8) | c3);
- if (c0 & 0x80) {
- *x |= -1 - 0xffffffff;
- }
- return gTrue;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cpp b/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cpp
new file mode 100644
index 000000000..fefab4a7e
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/JBIG2Stream.cpp
@@ -0,0 +1,3513 @@
+//========================================================================
+//
+// JBIG2Stream.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <limits.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdlib.h>
+#include "GList.h"
+#include "Error.h"
+#include "JBIG2Stream.h"
+
+//~ share these tables
+#include "Stream-CCITT.h"
+
+//------------------------------------------------------------------------
+
+static int contextSize[4] = { 16, 13, 10, 10 };
+static int refContextSize[2] = { 13, 10 };
+
+//------------------------------------------------------------------------
+// JBIG2ArithmeticDecoderStats
+//------------------------------------------------------------------------
+
+class JBIG2ArithmeticDecoderStats {
+public:
+
+ JBIG2ArithmeticDecoderStats(int contextSizeA);
+ ~JBIG2ArithmeticDecoderStats();
+ JBIG2ArithmeticDecoderStats *copy();
+ void reset();
+ int getContextSize() { return contextSize; }
+ void copyFrom(JBIG2ArithmeticDecoderStats *stats);
+
+private:
+
+ Guchar *cxTab; // cxTab[cx] = (i[cx] << 1) + mps[cx]
+ int contextSize;
+
+ friend class JBIG2ArithmeticDecoder;
+};
+
+JBIG2ArithmeticDecoderStats::JBIG2ArithmeticDecoderStats(int contextSizeA) {
+ contextSize = contextSizeA;
+ cxTab = (Guchar *)gmalloc((1 << contextSize) * sizeof(Guchar));
+ reset();
+}
+
+JBIG2ArithmeticDecoderStats::~JBIG2ArithmeticDecoderStats() {
+ gfree(cxTab);
+}
+
+JBIG2ArithmeticDecoderStats *JBIG2ArithmeticDecoderStats::copy() {
+ JBIG2ArithmeticDecoderStats *stats;
+
+ stats = new JBIG2ArithmeticDecoderStats(contextSize);
+ memcpy(stats->cxTab, cxTab, 1 << contextSize);
+ return stats;
+}
+
+void JBIG2ArithmeticDecoderStats::reset() {
+ memset(cxTab, 0, 1 << contextSize);
+}
+
+void JBIG2ArithmeticDecoderStats::copyFrom(
+ JBIG2ArithmeticDecoderStats *stats) {
+ memcpy(cxTab, stats->cxTab, 1 << contextSize);
+}
+
+//------------------------------------------------------------------------
+// JBIG2ArithmeticDecoder
+//------------------------------------------------------------------------
+
+class JBIG2ArithmeticDecoder {
+public:
+
+ JBIG2ArithmeticDecoder();
+ ~JBIG2ArithmeticDecoder();
+ void setStream(Stream *strA) { str = strA; }
+ void start();
+ int decodeBit(Guint context, JBIG2ArithmeticDecoderStats *stats);
+ int decodeByte(Guint context, JBIG2ArithmeticDecoderStats *stats);
+
+ // Returns false for OOB, otherwise sets *<x> and returns true.
+ GBool decodeInt(int *x, JBIG2ArithmeticDecoderStats *stats);
+
+ Guint decodeIAID(Guint codeLen,
+ JBIG2ArithmeticDecoderStats *stats);
+
+private:
+
+ int decodeIntBit(JBIG2ArithmeticDecoderStats *stats);
+ void byteIn();
+
+ static Guint qeTab[47];
+ static int nmpsTab[47];
+ static int nlpsTab[47];
+ static int switchTab[47];
+
+ Guint buf0, buf1;
+ Guint c, a;
+ int ct;
+
+ Guint prev; // for the integer decoder
+
+ Stream *str;
+};
+
+Guint JBIG2ArithmeticDecoder::qeTab[47] = {
+ 0x56010000, 0x34010000, 0x18010000, 0x0AC10000,
+ 0x05210000, 0x02210000, 0x56010000, 0x54010000,
+ 0x48010000, 0x38010000, 0x30010000, 0x24010000,
+ 0x1C010000, 0x16010000, 0x56010000, 0x54010000,
+ 0x51010000, 0x48010000, 0x38010000, 0x34010000,
+ 0x30010000, 0x28010000, 0x24010000, 0x22010000,
+ 0x1C010000, 0x18010000, 0x16010000, 0x14010000,
+ 0x12010000, 0x11010000, 0x0AC10000, 0x09C10000,
+ 0x08A10000, 0x05210000, 0x04410000, 0x02A10000,
+ 0x02210000, 0x01410000, 0x01110000, 0x00850000,
+ 0x00490000, 0x00250000, 0x00150000, 0x00090000,
+ 0x00050000, 0x00010000, 0x56010000
+};
+
+int JBIG2ArithmeticDecoder::nmpsTab[47] = {
+ 1, 2, 3, 4, 5, 38, 7, 8, 9, 10, 11, 12, 13, 29, 15, 16,
+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 45, 46
+};
+
+int JBIG2ArithmeticDecoder::nlpsTab[47] = {
+ 1, 6, 9, 12, 29, 33, 6, 14, 14, 14, 17, 18, 20, 21, 14, 14,
+ 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
+ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46
+};
+
+int JBIG2ArithmeticDecoder::switchTab[47] = {
+ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+JBIG2ArithmeticDecoder::JBIG2ArithmeticDecoder() {
+ str = NULL;
+}
+
+JBIG2ArithmeticDecoder::~JBIG2ArithmeticDecoder() {
+}
+
+void JBIG2ArithmeticDecoder::start() {
+ buf0 = (Guint)str->getChar() & 0xff;
+ buf1 = (Guint)str->getChar() & 0xff;
+
+ // INITDEC
+ c = (buf0 ^ 0xff) << 16;
+ byteIn();
+ c <<= 7;
+ ct -= 7;
+ a = 0x80000000;
+}
+
+int JBIG2ArithmeticDecoder::decodeBit(Guint context,
+ JBIG2ArithmeticDecoderStats *stats) {
+ int bit;
+ Guint qe;
+ int iCX, mpsCX;
+
+ iCX = stats->cxTab[context] >> 1;
+ mpsCX = stats->cxTab[context] & 1;
+ qe = qeTab[iCX];
+ a -= qe;
+ if (c < a) {
+ if (a & 0x80000000) {
+ bit = mpsCX;
+ } else {
+ // MPS_EXCHANGE
+ if (a < qe) {
+ bit = 1 - mpsCX;
+ if (switchTab[iCX]) {
+ stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
+ } else {
+ stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
+ }
+ } else {
+ bit = mpsCX;
+ stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
+ }
+ // RENORMD
+ do {
+ if (ct == 0) {
+ byteIn();
+ }
+ a <<= 1;
+ c <<= 1;
+ --ct;
+ } while (!(a & 0x80000000));
+ }
+ } else {
+ c -= a;
+ // LPS_EXCHANGE
+ if (a < qe) {
+ bit = mpsCX;
+ stats->cxTab[context] = (nmpsTab[iCX] << 1) | mpsCX;
+ } else {
+ bit = 1 - mpsCX;
+ if (switchTab[iCX]) {
+ stats->cxTab[context] = (nlpsTab[iCX] << 1) | (1 - mpsCX);
+ } else {
+ stats->cxTab[context] = (nlpsTab[iCX] << 1) | mpsCX;
+ }
+ }
+ a = qe;
+ // RENORMD
+ do {
+ if (ct == 0) {
+ byteIn();
+ }
+ a <<= 1;
+ c <<= 1;
+ --ct;
+ } while (!(a & 0x80000000));
+ }
+ return bit;
+}
+
+int JBIG2ArithmeticDecoder::decodeByte(Guint context,
+ JBIG2ArithmeticDecoderStats *stats) {
+ int byte;
+ int i;
+
+ byte = 0;
+ for (i = 0; i < 8; ++i) {
+ byte = (byte << 1) | decodeBit(context, stats);
+ }
+ return byte;
+}
+
+GBool JBIG2ArithmeticDecoder::decodeInt(int *x,
+ JBIG2ArithmeticDecoderStats *stats) {
+ int s;
+ Guint v;
+ int i;
+
+ prev = 1;
+ s = decodeIntBit(stats);
+ if (decodeIntBit(stats)) {
+ if (decodeIntBit(stats)) {
+ if (decodeIntBit(stats)) {
+ if (decodeIntBit(stats)) {
+ if (decodeIntBit(stats)) {
+ v = 0;
+ for (i = 0; i < 32; ++i) {
+ v = (v << 1) | decodeIntBit(stats);
+ }
+ v += 4436;
+ } else {
+ v = 0;
+ for (i = 0; i < 12; ++i) {
+ v = (v << 1) | decodeIntBit(stats);
+ }
+ v += 340;
+ }
+ } else {
+ v = 0;
+ for (i = 0; i < 8; ++i) {
+ v = (v << 1) | decodeIntBit(stats);
+ }
+ v += 84;
+ }
+ } else {
+ v = 0;
+ for (i = 0; i < 6; ++i) {
+ v = (v << 1) | decodeIntBit(stats);
+ }
+ v += 20;
+ }
+ } else {
+ v = decodeIntBit(stats);
+ v = (v << 1) | decodeIntBit(stats);
+ v = (v << 1) | decodeIntBit(stats);
+ v = (v << 1) | decodeIntBit(stats);
+ v += 4;
+ }
+ } else {
+ v = decodeIntBit(stats);
+ v = (v << 1) | decodeIntBit(stats);
+ }
+
+ if (s) {
+ if (v == 0) {
+ return gFalse;
+ }
+ *x = -(int)v;
+ } else {
+ *x = (int)v;
+ }
+ return gTrue;
+}
+
+int JBIG2ArithmeticDecoder::decodeIntBit(JBIG2ArithmeticDecoderStats *stats) {
+ int bit;
+
+ bit = decodeBit(prev, stats);
+ if (prev < 0x100) {
+ prev = (prev << 1) | bit;
+ } else {
+ prev = (((prev << 1) | bit) & 0x1ff) | 0x100;
+ }
+ return bit;
+}
+
+Guint JBIG2ArithmeticDecoder::decodeIAID(Guint codeLen,
+ JBIG2ArithmeticDecoderStats *stats) {
+ Guint i;
+ int bit;
+
+ prev = 1;
+ for (i = 0; i < codeLen; ++i) {
+ bit = decodeBit(prev, stats);
+ prev = (prev << 1) | bit;
+ }
+ return prev - (1 << codeLen);
+}
+
+void JBIG2ArithmeticDecoder::byteIn() {
+ if (buf0 == 0xff) {
+ if (buf1 > 0x8f) {
+ ct = 8;
+ } else {
+ buf0 = buf1;
+ buf1 = (Guint)str->getChar() & 0xff;
+ c = c + 0xfe00 - (buf0 << 9);
+ ct = 7;
+ }
+ } else {
+ buf0 = buf1;
+ buf1 = (Guint)str->getChar() & 0xff;
+ c = c + 0xff00 - (buf0 << 8);
+ ct = 8;
+ }
+}
+
+//------------------------------------------------------------------------
+// JBIG2HuffmanTable
+//------------------------------------------------------------------------
+
+#define jbig2HuffmanLOW 0xfffffffd
+#define jbig2HuffmanOOB 0xfffffffe
+#define jbig2HuffmanEOT 0xffffffff
+
+struct JBIG2HuffmanTable {
+ int val;
+ Guint prefixLen;
+ Guint rangeLen; // can also be LOW, OOB, or EOT
+ Guint prefix;
+};
+
+JBIG2HuffmanTable huffTableA[] = {
+ { 0, 1, 4, 0x000 },
+ { 16, 2, 8, 0x002 },
+ { 272, 3, 16, 0x006 },
+ { 65808, 3, 32, 0x007 },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableB[] = {
+ { 0, 1, 0, 0x000 },
+ { 1, 2, 0, 0x002 },
+ { 2, 3, 0, 0x006 },
+ { 3, 4, 3, 0x00e },
+ { 11, 5, 6, 0x01e },
+ { 75, 6, 32, 0x03e },
+ { 0, 6, jbig2HuffmanOOB, 0x03f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableC[] = {
+ { 0, 1, 0, 0x000 },
+ { 1, 2, 0, 0x002 },
+ { 2, 3, 0, 0x006 },
+ { 3, 4, 3, 0x00e },
+ { 11, 5, 6, 0x01e },
+ { 0, 6, jbig2HuffmanOOB, 0x03e },
+ { 75, 7, 32, 0x0fe },
+ { -256, 8, 8, 0x0fe },
+ { -257, 8, jbig2HuffmanLOW, 0x0ff },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableD[] = {
+ { 1, 1, 0, 0x000 },
+ { 2, 2, 0, 0x002 },
+ { 3, 3, 0, 0x006 },
+ { 4, 4, 3, 0x00e },
+ { 12, 5, 6, 0x01e },
+ { 76, 5, 32, 0x01f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableE[] = {
+ { 1, 1, 0, 0x000 },
+ { 2, 2, 0, 0x002 },
+ { 3, 3, 0, 0x006 },
+ { 4, 4, 3, 0x00e },
+ { 12, 5, 6, 0x01e },
+ { 76, 6, 32, 0x03e },
+ { -255, 7, 8, 0x07e },
+ { -256, 7, jbig2HuffmanLOW, 0x07f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableF[] = {
+ { 0, 2, 7, 0x000 },
+ { 128, 3, 7, 0x002 },
+ { 256, 3, 8, 0x003 },
+ { -1024, 4, 9, 0x008 },
+ { -512, 4, 8, 0x009 },
+ { -256, 4, 7, 0x00a },
+ { -32, 4, 5, 0x00b },
+ { 512, 4, 9, 0x00c },
+ { 1024, 4, 10, 0x00d },
+ { -2048, 5, 10, 0x01c },
+ { -128, 5, 6, 0x01d },
+ { -64, 5, 5, 0x01e },
+ { -2049, 6, jbig2HuffmanLOW, 0x03e },
+ { 2048, 6, 32, 0x03f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableG[] = {
+ { -512, 3, 8, 0x000 },
+ { 256, 3, 8, 0x001 },
+ { 512, 3, 9, 0x002 },
+ { 1024, 3, 10, 0x003 },
+ { -1024, 4, 9, 0x008 },
+ { -256, 4, 7, 0x009 },
+ { -32, 4, 5, 0x00a },
+ { 0, 4, 5, 0x00b },
+ { 128, 4, 7, 0x00c },
+ { -128, 5, 6, 0x01a },
+ { -64, 5, 5, 0x01b },
+ { 32, 5, 5, 0x01c },
+ { 64, 5, 6, 0x01d },
+ { -1025, 5, jbig2HuffmanLOW, 0x01e },
+ { 2048, 5, 32, 0x01f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableH[] = {
+ { 0, 2, 1, 0x000 },
+ { 0, 2, jbig2HuffmanOOB, 0x001 },
+ { 4, 3, 4, 0x004 },
+ { -1, 4, 0, 0x00a },
+ { 22, 4, 4, 0x00b },
+ { 38, 4, 5, 0x00c },
+ { 2, 5, 0, 0x01a },
+ { 70, 5, 6, 0x01b },
+ { 134, 5, 7, 0x01c },
+ { 3, 6, 0, 0x03a },
+ { 20, 6, 1, 0x03b },
+ { 262, 6, 7, 0x03c },
+ { 646, 6, 10, 0x03d },
+ { -2, 7, 0, 0x07c },
+ { 390, 7, 8, 0x07d },
+ { -15, 8, 3, 0x0fc },
+ { -5, 8, 1, 0x0fd },
+ { -7, 9, 1, 0x1fc },
+ { -3, 9, 0, 0x1fd },
+ { -16, 9, jbig2HuffmanLOW, 0x1fe },
+ { 1670, 9, 32, 0x1ff },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableI[] = {
+ { 0, 2, jbig2HuffmanOOB, 0x000 },
+ { -1, 3, 1, 0x002 },
+ { 1, 3, 1, 0x003 },
+ { 7, 3, 5, 0x004 },
+ { -3, 4, 1, 0x00a },
+ { 43, 4, 5, 0x00b },
+ { 75, 4, 6, 0x00c },
+ { 3, 5, 1, 0x01a },
+ { 139, 5, 7, 0x01b },
+ { 267, 5, 8, 0x01c },
+ { 5, 6, 1, 0x03a },
+ { 39, 6, 2, 0x03b },
+ { 523, 6, 8, 0x03c },
+ { 1291, 6, 11, 0x03d },
+ { -5, 7, 1, 0x07c },
+ { 779, 7, 9, 0x07d },
+ { -31, 8, 4, 0x0fc },
+ { -11, 8, 2, 0x0fd },
+ { -15, 9, 2, 0x1fc },
+ { -7, 9, 1, 0x1fd },
+ { -32, 9, jbig2HuffmanLOW, 0x1fe },
+ { 3339, 9, 32, 0x1ff },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableJ[] = {
+ { -2, 2, 2, 0x000 },
+ { 6, 2, 6, 0x001 },
+ { 0, 2, jbig2HuffmanOOB, 0x002 },
+ { -3, 5, 0, 0x018 },
+ { 2, 5, 0, 0x019 },
+ { 70, 5, 5, 0x01a },
+ { 3, 6, 0, 0x036 },
+ { 102, 6, 5, 0x037 },
+ { 134, 6, 6, 0x038 },
+ { 198, 6, 7, 0x039 },
+ { 326, 6, 8, 0x03a },
+ { 582, 6, 9, 0x03b },
+ { 1094, 6, 10, 0x03c },
+ { -21, 7, 4, 0x07a },
+ { -4, 7, 0, 0x07b },
+ { 4, 7, 0, 0x07c },
+ { 2118, 7, 11, 0x07d },
+ { -5, 8, 0, 0x0fc },
+ { 5, 8, 0, 0x0fd },
+ { -22, 8, jbig2HuffmanLOW, 0x0fe },
+ { 4166, 8, 32, 0x0ff },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableK[] = {
+ { 1, 1, 0, 0x000 },
+ { 2, 2, 1, 0x002 },
+ { 4, 4, 0, 0x00c },
+ { 5, 4, 1, 0x00d },
+ { 7, 5, 1, 0x01c },
+ { 9, 5, 2, 0x01d },
+ { 13, 6, 2, 0x03c },
+ { 17, 7, 2, 0x07a },
+ { 21, 7, 3, 0x07b },
+ { 29, 7, 4, 0x07c },
+ { 45, 7, 5, 0x07d },
+ { 77, 7, 6, 0x07e },
+ { 141, 7, 32, 0x07f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableL[] = {
+ { 1, 1, 0, 0x000 },
+ { 2, 2, 0, 0x002 },
+ { 3, 3, 1, 0x006 },
+ { 5, 5, 0, 0x01c },
+ { 6, 5, 1, 0x01d },
+ { 8, 6, 1, 0x03c },
+ { 10, 7, 0, 0x07a },
+ { 11, 7, 1, 0x07b },
+ { 13, 7, 2, 0x07c },
+ { 17, 7, 3, 0x07d },
+ { 25, 7, 4, 0x07e },
+ { 41, 8, 5, 0x0fe },
+ { 73, 8, 32, 0x0ff },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableM[] = {
+ { 1, 1, 0, 0x000 },
+ { 2, 3, 0, 0x004 },
+ { 7, 3, 3, 0x005 },
+ { 3, 4, 0, 0x00c },
+ { 5, 4, 1, 0x00d },
+ { 4, 5, 0, 0x01c },
+ { 15, 6, 1, 0x03a },
+ { 17, 6, 2, 0x03b },
+ { 21, 6, 3, 0x03c },
+ { 29, 6, 4, 0x03d },
+ { 45, 6, 5, 0x03e },
+ { 77, 7, 6, 0x07e },
+ { 141, 7, 32, 0x07f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableN[] = {
+ { 0, 1, 0, 0x000 },
+ { -2, 3, 0, 0x004 },
+ { -1, 3, 0, 0x005 },
+ { 1, 3, 0, 0x006 },
+ { 2, 3, 0, 0x007 },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+JBIG2HuffmanTable huffTableO[] = {
+ { 0, 1, 0, 0x000 },
+ { -1, 3, 0, 0x004 },
+ { 1, 3, 0, 0x005 },
+ { -2, 4, 0, 0x00c },
+ { 2, 4, 0, 0x00d },
+ { -4, 5, 1, 0x01c },
+ { 3, 5, 1, 0x01d },
+ { -8, 6, 2, 0x03c },
+ { 5, 6, 2, 0x03d },
+ { -24, 7, 4, 0x07c },
+ { 9, 7, 4, 0x07d },
+ { -25, 7, jbig2HuffmanLOW, 0x07e },
+ { 25, 7, 32, 0x07f },
+ { 0, 0, jbig2HuffmanEOT, 0 }
+};
+
+//------------------------------------------------------------------------
+// JBIG2HuffmanDecoder
+//------------------------------------------------------------------------
+
+class JBIG2HuffmanDecoder {
+public:
+
+ JBIG2HuffmanDecoder();
+ ~JBIG2HuffmanDecoder();
+ void setStream(Stream *strA) { str = strA; }
+
+ void reset();
+
+ // Returns false for OOB, otherwise sets *<x> and returns true.
+ GBool decodeInt(int *x, JBIG2HuffmanTable *table);
+
+ Guint readBits(Guint n);
+ Guint readBit();
+
+ // Sort the table by prefix length and assign prefix values.
+ void buildTable(JBIG2HuffmanTable *table, Guint len);
+
+private:
+
+ Stream *str;
+ Guint buf;
+ Guint bufLen;
+};
+
+JBIG2HuffmanDecoder::JBIG2HuffmanDecoder() {
+ str = NULL;
+ reset();
+}
+
+JBIG2HuffmanDecoder::~JBIG2HuffmanDecoder() {
+}
+
+void JBIG2HuffmanDecoder::reset() {
+ buf = 0;
+ bufLen = 0;
+}
+
+//~ optimize this
+GBool JBIG2HuffmanDecoder::decodeInt(int *x, JBIG2HuffmanTable *table) {
+ Guint i, len, prefix;
+
+ i = 0;
+ len = 0;
+ prefix = 0;
+ while (table[i].rangeLen != jbig2HuffmanEOT) {
+ //~ if buildTable removes the entries with prefixLen=0, this is unneeded
+ if (table[i].prefixLen > 0) {
+ while (len < table[i].prefixLen) {
+ prefix = (prefix << 1) | readBit();
+ ++len;
+ }
+ if (prefix == table[i].prefix) {
+ if (table[i].rangeLen == jbig2HuffmanOOB) {
+ return gFalse;
+ }
+ if (table[i].rangeLen == jbig2HuffmanLOW) {
+ *x = table[i].val - readBits(32);
+ } else if (table[i].rangeLen > 0) {
+ *x = table[i].val + readBits(table[i].rangeLen);
+ } else {
+ *x = table[i].val;
+ }
+ return gTrue;
+ }
+ }
+ ++i;
+ }
+ return gFalse;
+}
+
+Guint JBIG2HuffmanDecoder::readBits(Guint n) {
+ Guint x, mask, nLeft;
+
+ mask = (n == 32) ? 0xffffffff : ((1 << n) - 1);
+ if (bufLen >= n) {
+ x = (buf >> (bufLen - n)) & mask;
+ bufLen -= n;
+ } else {
+ x = buf & ((1 << bufLen) - 1);
+ nLeft = n - bufLen;
+ bufLen = 0;
+ while (nLeft >= 8) {
+ x = (x << 8) | (str->getChar() & 0xff);
+ nLeft -= 8;
+ }
+ if (nLeft > 0) {
+ buf = str->getChar();
+ bufLen = 8 - nLeft;
+ x = (x << nLeft) | ((buf >> bufLen) & ((1 << nLeft) - 1));
+ }
+ }
+ return x;
+}
+
+Guint JBIG2HuffmanDecoder::readBit() {
+ if (bufLen == 0) {
+ buf = str->getChar();
+ bufLen = 8;
+ }
+ --bufLen;
+ return (buf >> bufLen) & 1;
+}
+
+static int cmpHuffmanTabEntries(const void *p1, const void *p2) {
+ return ((JBIG2HuffmanTable *)p1)->prefixLen
+ - ((JBIG2HuffmanTable *)p2)->prefixLen;
+}
+
+//~ should remove entries with prefixLen = 0
+void JBIG2HuffmanDecoder::buildTable(JBIG2HuffmanTable *table, Guint len) {
+ Guint i, prefix;
+
+ qsort(table, len, sizeof(JBIG2HuffmanTable), &cmpHuffmanTabEntries);
+ for (i = 0; i < len && table[i].prefixLen == 0; ++i) {
+ table[i].prefix = 0;
+ }
+ prefix = 0;
+ table[i++].prefix = prefix++;
+ for (; i < len; ++i) {
+ prefix <<= table[i].prefixLen - table[i-1].prefixLen;
+ table[i].prefix = prefix++;
+ }
+}
+
+//------------------------------------------------------------------------
+// JBIG2MMRDecoder
+//------------------------------------------------------------------------
+
+class JBIG2MMRDecoder {
+public:
+
+ JBIG2MMRDecoder();
+ ~JBIG2MMRDecoder();
+ void setStream(Stream *strA) { str = strA; }
+ void reset();
+ int get2DCode();
+ int getBlackCode();
+ int getWhiteCode();
+ Guint get24Bits();
+ void skipTo(Guint length);
+
+private:
+
+ Stream *str;
+ Guint buf;
+ Guint bufLen;
+ Guint nBytesRead;
+};
+
+JBIG2MMRDecoder::JBIG2MMRDecoder() {
+ str = NULL;
+ reset();
+}
+
+JBIG2MMRDecoder::~JBIG2MMRDecoder() {
+}
+
+void JBIG2MMRDecoder::reset() {
+ buf = 0;
+ bufLen = 0;
+ nBytesRead = 0;
+}
+
+int JBIG2MMRDecoder::get2DCode() {
+ CCITTCode *p;
+
+ if (bufLen == 0) {
+ buf = str->getChar() & 0xff;
+ bufLen = 8;
+ ++nBytesRead;
+ p = &twoDimTab1[(buf >> 1) & 0x7f];
+ } else if (bufLen == 8) {
+ p = &twoDimTab1[(buf >> 1) & 0x7f];
+ } else {
+ p = &twoDimTab1[(buf << (7 - bufLen)) & 0x7f];
+ if (p->bits < 0 || p->bits > (int)bufLen) {
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bufLen += 8;
+ ++nBytesRead;
+ p = &twoDimTab1[(buf >> (bufLen - 7)) & 0x7f];
+ }
+ }
+ if (p->bits < 0) {
+ error(str->getPos(), "Bad two dim code in JBIG2 MMR stream");
+ return 0;
+ }
+ bufLen -= p->bits;
+ return p->n;
+}
+
+int JBIG2MMRDecoder::getWhiteCode() {
+ CCITTCode *p;
+ Guint code;
+
+ if (bufLen == 0) {
+ buf = str->getChar() & 0xff;
+ bufLen = 8;
+ ++nBytesRead;
+ }
+ while (1) {
+ if (bufLen > 7 && ((buf >> (bufLen - 7)) & 0x7f) == 0) {
+ if (bufLen <= 12) {
+ code = buf << (12 - bufLen);
+ } else {
+ code = buf >> (bufLen - 12);
+ }
+ p = &whiteTab1[code & 0x1f];
+ } else {
+ if (bufLen <= 9) {
+ code = buf << (9 - bufLen);
+ } else {
+ code = buf >> (bufLen - 9);
+ }
+ p = &whiteTab2[code & 0x1ff];
+ }
+ if (p->bits > 0 && p->bits < (int)bufLen) {
+ bufLen -= p->bits;
+ return p->n;
+ }
+ if (bufLen >= 12) {
+ break;
+ }
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bufLen += 8;
+ ++nBytesRead;
+ }
+ error(str->getPos(), "Bad white code in JBIG2 MMR stream");
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ --bufLen;
+ return 1;
+}
+
+int JBIG2MMRDecoder::getBlackCode() {
+ CCITTCode *p;
+ Guint code;
+
+ if (bufLen == 0) {
+ buf = str->getChar() & 0xff;
+ bufLen = 8;
+ ++nBytesRead;
+ }
+ while (1) {
+ if (bufLen > 6 && ((buf >> (bufLen - 6)) & 0x3f) == 0) {
+ if (bufLen <= 13) {
+ code = buf << (13 - bufLen);
+ } else {
+ code = buf >> (bufLen - 13);
+ }
+ p = &blackTab1[code & 0x7f];
+ } else if (bufLen > 4 && ((buf >> (bufLen - 4)) & 0x0f) == 0) {
+ if (bufLen <= 12) {
+ code = buf << (12 - bufLen);
+ } else {
+ code = buf >> (bufLen - 12);
+ }
+ p = &blackTab2[(code & 0xff) - 64];
+ } else {
+ if (bufLen <= 6) {
+ code = buf << (6 - bufLen);
+ } else {
+ code = buf >> (bufLen - 6);
+ }
+ p = &blackTab3[code & 0x3f];
+ }
+ if (p->bits > 0 && p->bits < (int)bufLen) {
+ bufLen -= p->bits;
+ return p->n;
+ }
+ if (bufLen >= 13) {
+ break;
+ }
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bufLen += 8;
+ ++nBytesRead;
+ }
+ error(str->getPos(), "Bad black code in JBIG2 MMR stream");
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ --bufLen;
+ return 1;
+}
+
+Guint JBIG2MMRDecoder::get24Bits() {
+ while (bufLen < 24) {
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bufLen += 8;
+ ++nBytesRead;
+ }
+ return (buf >> (bufLen - 24)) & 0xffffff;
+}
+
+void JBIG2MMRDecoder::skipTo(Guint length) {
+ while (nBytesRead < length) {
+ str->getChar();
+ ++nBytesRead;
+ }
+}
+
+//------------------------------------------------------------------------
+// JBIG2Segment
+//------------------------------------------------------------------------
+
+enum JBIG2SegmentType {
+ jbig2SegBitmap,
+ jbig2SegSymbolDict,
+ jbig2SegPatternDict,
+ jbig2SegCodeTable
+};
+
+class JBIG2Segment {
+public:
+
+ JBIG2Segment(Guint segNumA) { segNum = segNumA; }
+ virtual ~JBIG2Segment() {}
+ void setSegNum(Guint segNumA) { segNum = segNumA; }
+ Guint getSegNum() { return segNum; }
+ virtual JBIG2SegmentType getType() = 0;
+
+private:
+
+ Guint segNum;
+};
+
+//------------------------------------------------------------------------
+// JBIG2Bitmap
+//------------------------------------------------------------------------
+
+class JBIG2Bitmap: public JBIG2Segment {
+public:
+
+ JBIG2Bitmap(Guint segNumA, int wA, int hA);
+ virtual ~JBIG2Bitmap();
+ virtual JBIG2SegmentType getType() { return jbig2SegBitmap; }
+ JBIG2Bitmap *copy() { return new JBIG2Bitmap(0, this); }
+ JBIG2Bitmap *getSlice(Guint x, Guint y, Guint wA, Guint hA);
+ void expand(int newH, Guint pixel);
+ void clearToZero();
+ void clearToOne();
+ int getWidth() { return w; }
+ int getHeight() { return h; }
+ int getPixel(int x, int y)
+ { return (x < 0 || x >= w || y < 0 || y >= h) ? 0 :
+ (data[y * line + (x >> 3)] >> (7 - (x & 7))) & 1; }
+ void setPixel(int x, int y)
+ { data[y * line + (x >> 3)] |= 1 << (7 - (x & 7)); }
+ void clearPixel(int x, int y)
+ { data[y * line + (x >> 3)] &= 0x7f7f >> (x & 7); }
+ void duplicateRow(int yDest, int ySrc);
+ void combine(JBIG2Bitmap *bitmap, int x, int y, Guint combOp);
+ Guchar *getDataPtr() { return data; }
+ int getDataSize() { return h * line; }
+
+private:
+
+ JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap);
+
+ int w, h, line;
+ Guchar *data;
+};
+
+JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA):
+ JBIG2Segment(segNumA)
+{
+ w = wA;
+ h = hA;
+ line = (wA + 7) >> 3;
+
+ if (h < 0 || line <= 0 || h >= (INT_MAX - 1)/ line) {
+ error(-1, "invalid width/height");
+ data = NULL;
+ return;
+ }
+
+ // need to allocate one extra guard byte for use in combine()
+ data = (Guchar *)gmalloc(h * line + 1);
+}
+
+JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap):
+ JBIG2Segment(segNumA)
+{
+ w = bitmap->w;
+ h = bitmap->h;
+ line = bitmap->line;
+
+ if (h < 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
+ error(-1, "invalid width/height");
+ data = NULL;
+ return;
+ }
+
+ // need to allocate one extra guard byte for use in combine()
+ data = (Guchar *)gmalloc(h * line + 1);
+ memcpy(data, bitmap->data, h * line);
+}
+
+JBIG2Bitmap::~JBIG2Bitmap() {
+ gfree(data);
+}
+
+//~ optimize this
+JBIG2Bitmap *JBIG2Bitmap::getSlice(Guint x, Guint y, Guint wA, Guint hA) {
+ JBIG2Bitmap *slice;
+ Guint xx, yy;
+
+ slice = new JBIG2Bitmap(0, wA, hA);
+ slice->clearToZero();
+ for (yy = 0; yy < hA; ++yy) {
+ for (xx = 0; xx < wA; ++xx) {
+ if (getPixel(x + xx, y + yy)) {
+ slice->setPixel(xx, yy);
+ }
+ }
+ }
+ return slice;
+}
+
+void JBIG2Bitmap::expand(int newH, Guint pixel) {
+ if (newH <= h || line <= 0 || newH >= (INT_MAX-1) / line) {
+ error(-1, "invalid width/height");
+ gfree(data);
+ data = NULL;
+ return;
+ }
+ /* need to allocate one extra guard byte for use in combine() */
+ data = (Guchar *)grealloc(data, newH * line + 1);
+ if (pixel) {
+ memset(data + h * line, 0xff, (newH - h) * line);
+ } else {
+ memset(data + h * line, 0x00, (newH - h) * line);
+ }
+ h = newH;
+}
+
+void JBIG2Bitmap::clearToZero() {
+ memset(data, 0, h * line);
+}
+
+void JBIG2Bitmap::clearToOne() {
+ memset(data, 0xff, h * line);
+}
+
+void JBIG2Bitmap::duplicateRow(int yDest, int ySrc) {
+ memcpy(data + yDest * line, data + ySrc * line, line);
+}
+
+void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y,
+ Guint combOp) {
+ int x0, x1, y0, y1, xx, yy;
+ Guchar *srcPtr, *destPtr;
+ Guint src0, src1, src, dest, s1, s2, m1, m2, m3;
+ GBool oneByte;
+
+ if (y < 0) {
+ y0 = -y;
+ } else {
+ y0 = 0;
+ }
+ if (y + bitmap->h > h) {
+ y1 = h - y;
+ } else {
+ y1 = bitmap->h;
+ }
+ if (y0 >= y1) {
+ return;
+ }
+
+ if (x >= 0) {
+ x0 = x & ~7;
+ } else {
+ x0 = 0;
+ }
+ x1 = x + bitmap->w;
+ if (x1 > w) {
+ x1 = w;
+ }
+ if (x0 >= x1) {
+ return;
+ }
+
+ s1 = x & 7;
+ s2 = 8 - s1;
+ m1 = 0xff >> (x1 & 7);
+ m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7));
+ m3 = (0xff >> s1) & m2;
+
+ oneByte = x0 == ((x1 - 1) & ~7);
+
+ for (yy = y0; yy < y1; ++yy) {
+
+ // one byte per line -- need to mask both left and right side
+ if (oneByte) {
+ if (x >= 0) {
+ destPtr = data + (y + yy) * line + (x >> 3);
+ srcPtr = bitmap->data + yy * bitmap->line;
+ dest = *destPtr;
+ src1 = *srcPtr;
+ switch (combOp) {
+ case 0: // or
+ dest |= (src1 >> s1) & m2;
+ break;
+ case 1: // and
+ dest &= ((0xff00 | src1) >> s1) | m1;
+ break;
+ case 2: // xor
+ dest ^= (src1 >> s1) & m2;
+ break;
+ case 3: // xnor
+ dest ^= ((src1 ^ 0xff) >> s1) & m2;
+ break;
+ case 4: // replace
+ dest = (dest & ~m3) | ((src1 >> s1) & m3);
+ break;
+ }
+ *destPtr = dest;
+ } else {
+ destPtr = data + (y + yy) * line;
+ srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
+ dest = *destPtr;
+ src1 = *srcPtr;
+ switch (combOp) {
+ case 0: // or
+ dest |= src1 & m2;
+ break;
+ case 1: // and
+ dest &= src1 | m1;
+ break;
+ case 2: // xor
+ dest ^= src1 & m2;
+ break;
+ case 3: // xnor
+ dest ^= (src1 ^ 0xff) & m2;
+ break;
+ case 4: // replace
+ dest = (src1 & m2) | (dest & m1);
+ break;
+ }
+ *destPtr = dest;
+ }
+
+ // multiple bytes per line -- need to mask left side of left-most
+ // byte and right side of right-most byte
+ } else {
+
+ // left-most byte
+ if (x >= 0) {
+ destPtr = data + (y + yy) * line + (x >> 3);
+ srcPtr = bitmap->data + yy * bitmap->line;
+ src1 = *srcPtr++;
+ dest = *destPtr;
+ switch (combOp) {
+ case 0: // or
+ dest |= src1 >> s1;
+ break;
+ case 1: // and
+ dest &= (0xff00 | src1) >> s1;
+ break;
+ case 2: // xor
+ dest ^= src1 >> s1;
+ break;
+ case 3: // xnor
+ dest ^= (src1 ^ 0xff) >> s1;
+ break;
+ case 4: // replace
+ dest = (dest & (0xff << s2)) | (src1 >> s1);
+ break;
+ }
+ *destPtr++ = dest;
+ xx = x0 + 8;
+ } else {
+ destPtr = data + (y + yy) * line;
+ srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
+ src1 = *srcPtr++;
+ xx = x0;
+ }
+
+ // middle bytes
+ for (; xx < x1 - 8; xx += 8) {
+ dest = *destPtr;
+ src0 = src1;
+ src1 = *srcPtr++;
+ src = (((src0 << 8) | src1) >> s1) & 0xff;
+ switch (combOp) {
+ case 0: // or
+ dest |= src;
+ break;
+ case 1: // and
+ dest &= src;
+ break;
+ case 2: // xor
+ dest ^= src;
+ break;
+ case 3: // xnor
+ dest ^= src ^ 0xff;
+ break;
+ case 4: // replace
+ dest = src;
+ break;
+ }
+ *destPtr++ = dest;
+ }
+
+ // right-most byte
+ dest = *destPtr;
+ src0 = src1;
+ src1 = *srcPtr++;
+ src = (((src0 << 8) | src1) >> s1) & 0xff;
+ switch (combOp) {
+ case 0: // or
+ dest |= src & m2;
+ break;
+ case 1: // and
+ dest &= src | m1;
+ break;
+ case 2: // xor
+ dest ^= src & m2;
+ break;
+ case 3: // xnor
+ dest ^= (src ^ 0xff) & m2;
+ break;
+ case 4: // replace
+ dest = (src & m2) | (dest & m1);
+ break;
+ }
+ *destPtr = dest;
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// JBIG2SymbolDict
+//------------------------------------------------------------------------
+
+class JBIG2SymbolDict: public JBIG2Segment {
+public:
+
+ JBIG2SymbolDict(Guint segNumA, Guint sizeA);
+ virtual ~JBIG2SymbolDict();
+ virtual JBIG2SegmentType getType() { return jbig2SegSymbolDict; }
+ Guint getSize() { return size; }
+ void setBitmap(Guint idx, JBIG2Bitmap *bitmap) { bitmaps[idx] = bitmap; }
+ JBIG2Bitmap *getBitmap(Guint idx) { return bitmaps[idx]; }
+ void setGenericRegionStats(JBIG2ArithmeticDecoderStats *stats)
+ { genericRegionStats = stats; }
+ void setRefinementRegionStats(JBIG2ArithmeticDecoderStats *stats)
+ { refinementRegionStats = stats; }
+ JBIG2ArithmeticDecoderStats *getGenericRegionStats()
+ { return genericRegionStats; }
+ JBIG2ArithmeticDecoderStats *getRefinementRegionStats()
+ { return refinementRegionStats; }
+
+private:
+
+ Guint size;
+ JBIG2Bitmap **bitmaps;
+ JBIG2ArithmeticDecoderStats *genericRegionStats;
+ JBIG2ArithmeticDecoderStats *refinementRegionStats;
+};
+
+JBIG2SymbolDict::JBIG2SymbolDict(Guint segNumA, Guint sizeA):
+ JBIG2Segment(segNumA)
+{
+ size = sizeA;
+ bitmaps = (JBIG2Bitmap **)gmalloc(size * sizeof(JBIG2Bitmap *));
+ genericRegionStats = NULL;
+ refinementRegionStats = NULL;
+}
+
+JBIG2SymbolDict::~JBIG2SymbolDict() {
+ Guint i;
+
+ for (i = 0; i < size; ++i) {
+ delete bitmaps[i];
+ }
+ gfree(bitmaps);
+ if (genericRegionStats) {
+ delete genericRegionStats;
+ }
+ if (refinementRegionStats) {
+ delete refinementRegionStats;
+ }
+}
+
+//------------------------------------------------------------------------
+// JBIG2PatternDict
+//------------------------------------------------------------------------
+
+class JBIG2PatternDict: public JBIG2Segment {
+public:
+
+ JBIG2PatternDict(Guint segNumA, Guint sizeA);
+ virtual ~JBIG2PatternDict();
+ virtual JBIG2SegmentType getType() { return jbig2SegPatternDict; }
+ Guint getSize() { return size; }
+ void setBitmap(Guint idx, JBIG2Bitmap *bitmap) { bitmaps[idx] = bitmap; }
+ JBIG2Bitmap *getBitmap(Guint idx) { return bitmaps[idx]; }
+
+private:
+
+ Guint size;
+ JBIG2Bitmap **bitmaps;
+};
+
+JBIG2PatternDict::JBIG2PatternDict(Guint segNumA, Guint sizeA):
+ JBIG2Segment(segNumA)
+{
+ size = sizeA;
+ bitmaps = (JBIG2Bitmap **)gmalloc(size * sizeof(JBIG2Bitmap *));
+}
+
+JBIG2PatternDict::~JBIG2PatternDict() {
+ Guint i;
+
+ for (i = 0; i < size; ++i) {
+ delete bitmaps[i];
+ }
+ gfree(bitmaps);
+}
+
+//------------------------------------------------------------------------
+// JBIG2CodeTable
+//------------------------------------------------------------------------
+
+class JBIG2CodeTable: public JBIG2Segment {
+public:
+
+ JBIG2CodeTable(Guint segNumA, JBIG2HuffmanTable *tableA);
+ virtual ~JBIG2CodeTable();
+ virtual JBIG2SegmentType getType() { return jbig2SegCodeTable; }
+ JBIG2HuffmanTable *getHuffTable() { return table; }
+
+private:
+
+ JBIG2HuffmanTable *table;
+};
+
+JBIG2CodeTable::JBIG2CodeTable(Guint segNumA, JBIG2HuffmanTable *tableA):
+ JBIG2Segment(segNumA)
+{
+ table = tableA;
+}
+
+JBIG2CodeTable::~JBIG2CodeTable() {
+ gfree(table);
+}
+
+//------------------------------------------------------------------------
+// JBIG2Stream
+//------------------------------------------------------------------------
+
+JBIG2Stream::JBIG2Stream(Stream *strA, Object *globalsStream):
+ FilterStream(strA)
+{
+ pageBitmap = NULL;
+
+ arithDecoder = new JBIG2ArithmeticDecoder();
+ genericRegionStats = new JBIG2ArithmeticDecoderStats(1);
+ refinementRegionStats = new JBIG2ArithmeticDecoderStats(1);
+ iadhStats = new JBIG2ArithmeticDecoderStats(9);
+ iadwStats = new JBIG2ArithmeticDecoderStats(9);
+ iaexStats = new JBIG2ArithmeticDecoderStats(9);
+ iaaiStats = new JBIG2ArithmeticDecoderStats(9);
+ iadtStats = new JBIG2ArithmeticDecoderStats(9);
+ iaitStats = new JBIG2ArithmeticDecoderStats(9);
+ iafsStats = new JBIG2ArithmeticDecoderStats(9);
+ iadsStats = new JBIG2ArithmeticDecoderStats(9);
+ iardxStats = new JBIG2ArithmeticDecoderStats(9);
+ iardyStats = new JBIG2ArithmeticDecoderStats(9);
+ iardwStats = new JBIG2ArithmeticDecoderStats(9);
+ iardhStats = new JBIG2ArithmeticDecoderStats(9);
+ iariStats = new JBIG2ArithmeticDecoderStats(9);
+ iaidStats = new JBIG2ArithmeticDecoderStats(1);
+ huffDecoder = new JBIG2HuffmanDecoder();
+ mmrDecoder = new JBIG2MMRDecoder();
+
+ segments = new GList();
+ if (globalsStream->isStream()) {
+ curStr = globalsStream->getStream();
+ curStr->reset();
+ arithDecoder->setStream(curStr);
+ huffDecoder->setStream(curStr);
+ mmrDecoder->setStream(curStr);
+ readSegments();
+ }
+ globalSegments = segments;
+
+ segments = NULL;
+ curStr = NULL;
+ dataPtr = dataEnd = NULL;
+}
+
+JBIG2Stream::~JBIG2Stream() {
+ delete arithDecoder;
+ delete genericRegionStats;
+ delete refinementRegionStats;
+ delete iadhStats;
+ delete iadwStats;
+ delete iaexStats;
+ delete iaaiStats;
+ delete iadtStats;
+ delete iaitStats;
+ delete iafsStats;
+ delete iadsStats;
+ delete iardxStats;
+ delete iardyStats;
+ delete iardwStats;
+ delete iardhStats;
+ delete iariStats;
+ delete iaidStats;
+ delete huffDecoder;
+ delete mmrDecoder;
+ if (pageBitmap) {
+ delete pageBitmap;
+ }
+ if (segments) {
+ deleteGList(segments, JBIG2Segment);
+ }
+ if (globalSegments) {
+ deleteGList(globalSegments, JBIG2Segment);
+ }
+ delete str;
+}
+
+void JBIG2Stream::reset() {
+ if (pageBitmap) {
+ delete pageBitmap;
+ pageBitmap = NULL;
+ }
+ if (segments) {
+ deleteGList(segments, JBIG2Segment);
+ }
+ segments = new GList();
+
+ curStr = str;
+ curStr->reset();
+ arithDecoder->setStream(curStr);
+ huffDecoder->setStream(curStr);
+ mmrDecoder->setStream(curStr);
+ readSegments();
+
+ if (pageBitmap) {
+ dataPtr = pageBitmap->getDataPtr();
+ dataEnd = dataPtr + pageBitmap->getDataSize();
+ } else {
+ dataPtr = NULL;
+ }
+}
+
+int JBIG2Stream::getChar() {
+ if (dataPtr && dataPtr < dataEnd) {
+ return (*dataPtr++ ^ 0xff) & 0xff;
+ }
+ return EOF;
+}
+
+int JBIG2Stream::lookChar() {
+ if (dataPtr && dataPtr < dataEnd) {
+ return (*dataPtr ^ 0xff) & 0xff;
+ }
+ return EOF;
+}
+
+GString *JBIG2Stream::getPSFilter(const char */*indent*/) {
+ return NULL;
+}
+
+GBool JBIG2Stream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+void JBIG2Stream::readSegments() {
+ Guint segNum, segFlags, segType, page, segLength;
+ Guint refFlags, nRefSegs;
+ Guint *refSegs;
+ int c1, c2, c3;
+ Guint i;
+
+ while (readULong(&segNum)) {
+
+ // segment header flags
+ if (!readUByte(&segFlags)) {
+ goto eofError1;
+ }
+ segType = segFlags & 0x3f;
+
+ // referred-to segment count and retention flags
+ if (!readUByte(&refFlags)) {
+ goto eofError1;
+ }
+ nRefSegs = refFlags >> 5;
+ if (nRefSegs == 7) {
+ if ((c1 = curStr->getChar()) == EOF ||
+ (c2 = curStr->getChar()) == EOF ||
+ (c3 = curStr->getChar()) == EOF) {
+ goto eofError1;
+ }
+ refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
+ nRefSegs = refFlags & 0x1fffffff;
+ for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
+ c1 = curStr->getChar();
+ }
+ }
+
+ // referred-to segment numbers
+ refSegs = (Guint *)gmalloc(nRefSegs * sizeof(Guint));
+ if (segNum <= 256) {
+ for (i = 0; i < nRefSegs; ++i) {
+ if (!readUByte(&refSegs[i])) {
+ goto eofError2;
+ }
+ }
+ } else if (segNum <= 65536) {
+ for (i = 0; i < nRefSegs; ++i) {
+ if (!readUWord(&refSegs[i])) {
+ goto eofError2;
+ }
+ }
+ } else {
+ for (i = 0; i < nRefSegs; ++i) {
+ if (!readULong(&refSegs[i])) {
+ goto eofError2;
+ }
+ }
+ }
+
+ // segment page association
+ if (segFlags & 0x40) {
+ if (!readULong(&page)) {
+ goto eofError2;
+ }
+ } else {
+ if (!readUByte(&page)) {
+ goto eofError2;
+ }
+ }
+
+ // segment data length
+ if (!readULong(&segLength)) {
+ goto eofError2;
+ }
+
+ // read the segment data
+ switch (segType) {
+ case 0:
+ readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs);
+ break;
+ case 4:
+ readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
+ break;
+ case 6:
+ readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
+ break;
+ case 7:
+ readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
+ break;
+ case 16:
+ readPatternDictSeg(segNum, segLength);
+ break;
+ case 20:
+ readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 22:
+ readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 23:
+ readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 36:
+ readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
+ break;
+ case 38:
+ readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
+ break;
+ case 39:
+ readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
+ break;
+ case 40:
+ readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 42:
+ readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 43:
+ readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
+ refSegs, nRefSegs);
+ break;
+ case 48:
+ readPageInfoSeg(segLength);
+ break;
+ case 50:
+ readEndOfStripeSeg(segLength);
+ break;
+ case 52:
+ readProfilesSeg(segLength);
+ break;
+ case 53:
+ readCodeTableSeg(segNum, segLength);
+ break;
+ case 62:
+ readExtensionSeg(segLength);
+ break;
+ default:
+ error(getPos(), "Unknown segment type in JBIG2 stream");
+ for (i = 0; i < segLength; ++i) {
+ if ((c1 = curStr->getChar()) == EOF) {
+ goto eofError2;
+ }
+ }
+ break;
+ }
+
+ gfree(refSegs);
+ }
+
+ return;
+
+ eofError2:
+ gfree(refSegs);
+ eofError1:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readSymbolDictSeg(Guint segNum, Guint /*length*/,
+ Guint *refSegs, Guint nRefSegs) {
+ JBIG2SymbolDict *symbolDict;
+ JBIG2HuffmanTable *huffDHTable, *huffDWTable;
+ JBIG2HuffmanTable *huffBMSizeTable, *huffAggInstTable;
+ JBIG2Segment *seg;
+ GList *codeTables;
+ JBIG2SymbolDict *inputSymbolDict;
+ Guint flags, sdTemplate, sdrTemplate, huff, refAgg;
+ Guint huffDH, huffDW, huffBMSize, huffAggInst;
+ Guint contextUsed, contextRetained;
+ int sdATX[4], sdATY[4], sdrATX[2], sdrATY[2];
+ Guint numExSyms, numNewSyms, numInputSyms, symCodeLen;
+ JBIG2Bitmap **bitmaps;
+ JBIG2Bitmap *collBitmap, *refBitmap;
+ Guint *symWidths;
+ Guint symHeight, symWidth, totalWidth, x, symID;
+ int dh, dw, refAggNum, refDX, refDY, bmSize;
+ GBool ex;
+ int run, cnt;
+ Guint i, j, k;
+ Guchar *p;
+
+ // symbol dictionary flags
+ if (!readUWord(&flags)) {
+ goto eofError;
+ }
+ sdTemplate = (flags >> 10) & 3;
+ sdrTemplate = (flags >> 12) & 1;
+ huff = flags & 1;
+ refAgg = (flags >> 1) & 1;
+ huffDH = (flags >> 2) & 3;
+ huffDW = (flags >> 4) & 3;
+ huffBMSize = (flags >> 6) & 1;
+ huffAggInst = (flags >> 7) & 1;
+ contextUsed = (flags >> 8) & 1;
+ contextRetained = (flags >> 9) & 1;
+
+ // symbol dictionary AT flags
+ if (!huff) {
+ if (sdTemplate == 0) {
+ if (!readByte(&sdATX[0]) ||
+ !readByte(&sdATY[0]) ||
+ !readByte(&sdATX[1]) ||
+ !readByte(&sdATY[1]) ||
+ !readByte(&sdATX[2]) ||
+ !readByte(&sdATY[2]) ||
+ !readByte(&sdATX[3]) ||
+ !readByte(&sdATY[3])) {
+ goto eofError;
+ }
+ } else {
+ if (!readByte(&sdATX[0]) ||
+ !readByte(&sdATY[0])) {
+ goto eofError;
+ }
+ }
+ }
+
+ // symbol dictionary refinement AT flags
+ if (refAgg && !sdrTemplate) {
+ if (!readByte(&sdrATX[0]) ||
+ !readByte(&sdrATY[0]) ||
+ !readByte(&sdrATX[1]) ||
+ !readByte(&sdrATY[1])) {
+ goto eofError;
+ }
+ }
+
+ // SDNUMEXSYMS and SDNUMNEWSYMS
+ if (!readULong(&numExSyms) || !readULong(&numNewSyms)) {
+ goto eofError;
+ }
+
+ // get referenced segments: input symbol dictionaries and code tables
+ codeTables = new GList();
+ numInputSyms = 0;
+ for (i = 0; i < nRefSegs; ++i) {
+ seg = findSegment(refSegs[i]);
+ if (seg->getType() == jbig2SegSymbolDict) {
+ numInputSyms += ((JBIG2SymbolDict *)seg)->getSize();
+ } else if (seg->getType() == jbig2SegCodeTable) {
+ codeTables->append(seg);
+ }
+ }
+
+ // compute symbol code length
+ symCodeLen = 0;
+ i = 1;
+ while (i < numInputSyms + numNewSyms) {
+ ++symCodeLen;
+ i <<= 1;
+ }
+
+ // get the input symbol bitmaps
+ bitmaps = (JBIG2Bitmap **)gmalloc((numInputSyms + numNewSyms) *
+ sizeof(JBIG2Bitmap *));
+ k = 0;
+ inputSymbolDict = NULL;
+ for (i = 0; i < nRefSegs; ++i) {
+ seg = findSegment(refSegs[i]);
+ if (seg->getType() == jbig2SegSymbolDict) {
+ inputSymbolDict = (JBIG2SymbolDict *)seg;
+ for (j = 0; j < inputSymbolDict->getSize(); ++j) {
+ bitmaps[k++] = inputSymbolDict->getBitmap(j);
+ }
+ }
+ }
+
+ // get the Huffman tables
+ huffDHTable = huffDWTable = NULL; // make gcc happy
+ huffBMSizeTable = huffAggInstTable = NULL; // make gcc happy
+ i = 0;
+ if (huff) {
+ if (huffDH == 0) {
+ huffDHTable = huffTableD;
+ } else if (huffDH == 1) {
+ huffDHTable = huffTableE;
+ } else {
+ huffDHTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffDW == 0) {
+ huffDWTable = huffTableB;
+ } else if (huffDW == 1) {
+ huffDWTable = huffTableC;
+ } else {
+ huffDWTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffBMSize == 0) {
+ huffBMSizeTable = huffTableA;
+ } else {
+ huffBMSizeTable =
+ ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffAggInst == 0) {
+ huffAggInstTable = huffTableA;
+ } else {
+ huffAggInstTable =
+ ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ }
+ delete codeTables;
+
+ // set up the Huffman decoder
+ if (huff) {
+ huffDecoder->reset();
+
+ // set up the arithmetic decoder
+ } else {
+ if (contextUsed && inputSymbolDict) {
+ resetGenericStats(sdTemplate, inputSymbolDict->getGenericRegionStats());
+ if (refAgg) {
+ resetRefinementStats(sdrTemplate,
+ inputSymbolDict->getRefinementRegionStats());
+ }
+ } else {
+ resetGenericStats(sdTemplate, NULL);
+ if (refAgg) {
+ resetRefinementStats(sdrTemplate, NULL);
+ }
+ }
+ resetIntStats(symCodeLen);
+ arithDecoder->start();
+ }
+
+ // allocate symbol widths storage
+ symWidths = NULL;
+ if (huff && !refAgg) {
+ symWidths = (Guint *)gmalloc(numNewSyms * sizeof(Guint));
+ }
+
+ symHeight = 0;
+ i = 0;
+ while (i < numNewSyms) {
+
+ // read the height class delta height
+ if (huff) {
+ huffDecoder->decodeInt(&dh, huffDHTable);
+ } else {
+ arithDecoder->decodeInt(&dh, iadhStats);
+ }
+ symHeight += dh;
+ symWidth = 0;
+ totalWidth = 0;
+ j = i;
+
+ // read the symbols in this height class
+ while (1) {
+
+ // read the delta width
+ if (huff) {
+ if (!huffDecoder->decodeInt(&dw, huffDWTable)) {
+ break;
+ }
+ } else {
+ if (!arithDecoder->decodeInt(&dw, iadwStats)) {
+ break;
+ }
+ }
+ symWidth += dw;
+
+ // using a collective bitmap, so don't read a bitmap here
+ if (huff && !refAgg) {
+ symWidths[i] = symWidth;
+ totalWidth += symWidth;
+
+ // refinement/aggregate coding
+ } else if (refAgg) {
+ if (huff) {
+ if (!huffDecoder->decodeInt(&refAggNum, huffAggInstTable)) {
+ break;
+ }
+ } else {
+ if (!arithDecoder->decodeInt(&refAggNum, iaaiStats)) {
+ break;
+ }
+ }
+ if (refAggNum == 1) {
+ if (huff) {
+ symID = huffDecoder->readBits(symCodeLen);
+ huffDecoder->decodeInt(&refDX, huffTableO);
+ huffDecoder->decodeInt(&refDY, huffTableO);
+ huffDecoder->decodeInt(&bmSize, huffTableA);
+ huffDecoder->reset();
+ arithDecoder->start();
+ } else {
+ symID = arithDecoder->decodeIAID(symCodeLen, iaidStats);
+ arithDecoder->decodeInt(&refDX, iardxStats);
+ arithDecoder->decodeInt(&refDY, iardyStats);
+ }
+ refBitmap = bitmaps[symID];
+ bitmaps[numInputSyms + i] =
+ readGenericRefinementRegion(symWidth, symHeight,
+ sdrTemplate, gFalse,
+ refBitmap, refDX, refDY,
+ sdrATX, sdrATY);
+ //~ do we need to use the bmSize value here (in Huffman mode)?
+ } else {
+ bitmaps[numInputSyms + i] =
+ readTextRegion(huff, gTrue, symWidth, symHeight,
+ refAggNum, 0, numInputSyms + i, NULL,
+ symCodeLen, bitmaps, 0, 0, 0, 1, 0,
+ huffTableF, huffTableH, huffTableK, huffTableO,
+ huffTableO, huffTableO, huffTableO, huffTableA,
+ sdrTemplate, sdrATX, sdrATY);
+ }
+
+ // non-ref/agg coding
+ } else {
+ bitmaps[numInputSyms + i] =
+ readGenericBitmap(gFalse, symWidth, symHeight,
+ sdTemplate, gFalse, gFalse, NULL,
+ sdATX, sdATY, 0);
+ }
+
+ ++i;
+ }
+
+ // read the collective bitmap
+ if (huff && !refAgg) {
+ huffDecoder->decodeInt(&bmSize, huffBMSizeTable);
+ if (huff) {
+ huffDecoder->reset();
+ }
+ if (bmSize == 0) {
+ collBitmap = new JBIG2Bitmap(0, totalWidth, symHeight);
+ bmSize = symHeight * ((totalWidth + 7) >> 3);
+ p = collBitmap->getDataPtr();
+ for (k = 0; k < (Guint)bmSize; ++k) {
+ *p++ = str->getChar();
+ }
+ } else {
+ collBitmap = readGenericBitmap(gTrue, totalWidth, symHeight,
+ 0, gFalse, gFalse, NULL, NULL, NULL,
+ bmSize);
+ }
+ x = 0;
+ for (; j < i; ++j) {
+ bitmaps[numInputSyms + j] =
+ collBitmap->getSlice(x, 0, symWidths[j], symHeight);
+ x += symWidths[j];
+ }
+ delete collBitmap;
+ }
+ }
+
+ // create the symbol dict object
+ symbolDict = new JBIG2SymbolDict(segNum, numExSyms);
+
+ // exported symbol list
+ i = j = 0;
+ ex = gFalse;
+ while (i < numInputSyms + numNewSyms) {
+ if (huff) {
+ huffDecoder->decodeInt(&run, huffTableA);
+ } else {
+ arithDecoder->decodeInt(&run, iaexStats);
+ }
+ if (ex) {
+ for (cnt = 0; cnt < run; ++cnt) {
+ symbolDict->setBitmap(j++, bitmaps[i++]->copy());
+ }
+ } else {
+ i += run;
+ }
+ ex = !ex;
+ }
+
+ for (i = 0; i < numNewSyms; ++i) {
+ delete bitmaps[numInputSyms + i];
+ }
+ gfree(bitmaps);
+ if (symWidths) {
+ gfree(symWidths);
+ }
+
+ // save the arithmetic decoder stats
+ if (!huff && contextRetained) {
+ symbolDict->setGenericRegionStats(genericRegionStats->copy());
+ if (refAgg) {
+ symbolDict->setRefinementRegionStats(refinementRegionStats->copy());
+ }
+ }
+
+ // store the new symbol dict
+ segments->append(symbolDict);
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readTextRegionSeg(Guint segNum, GBool imm,
+ GBool /*lossless*/, Guint /*length*/,
+ Guint *refSegs, Guint nRefSegs) {
+ JBIG2Bitmap *bitmap;
+ JBIG2HuffmanTable runLengthTab[36];
+ JBIG2HuffmanTable *symCodeTab;
+ JBIG2HuffmanTable *huffFSTable, *huffDSTable, *huffDTTable;
+ JBIG2HuffmanTable *huffRDWTable, *huffRDHTable;
+ JBIG2HuffmanTable *huffRDXTable, *huffRDYTable, *huffRSizeTable;
+ JBIG2Segment *seg;
+ GList *codeTables;
+ JBIG2SymbolDict *symbolDict;
+ JBIG2Bitmap **syms;
+ Guint w, h, x, y, segInfoFlags, extCombOp;
+ Guint flags, huff, refine, logStrips, refCorner, transposed;
+ Guint combOp, defPixel, sOffset, templ;
+ Guint huffFlags, huffFS, huffDS, huffDT;
+ Guint huffRDW, huffRDH, huffRDX, huffRDY, huffRSize;
+ Guint numInstances, numSyms, symCodeLen;
+ int atx[2], aty[2];
+ Guint i, k, kk;
+ int j;
+
+ // region segment info field
+ if (!readULong(&w) || !readULong(&h) ||
+ !readULong(&x) || !readULong(&y) ||
+ !readUByte(&segInfoFlags)) {
+ goto eofError;
+ }
+ extCombOp = segInfoFlags & 7;
+
+ // rest of the text region header
+ if (!readUWord(&flags)) {
+ goto eofError;
+ }
+ huff = flags & 1;
+ refine = (flags >> 1) & 1;
+ logStrips = (flags >> 2) & 3;
+ refCorner = (flags >> 4) & 3;
+ transposed = (flags >> 6) & 1;
+ combOp = (flags >> 7) & 3;
+ defPixel = (flags >> 9) & 1;
+ sOffset = (flags >> 10) & 0x1f;
+ templ = (flags >> 15) & 1;
+ huffFS = huffDS = huffDT = 0; // make gcc happy
+ huffRDW = huffRDH = huffRDX = huffRDY = huffRSize = 0; // make gcc happy
+ if (huff) {
+ if (!readUWord(&huffFlags)) {
+ goto eofError;
+ }
+ huffFS = huffFlags & 3;
+ huffDS = (huffFlags >> 2) & 3;
+ huffDT = (huffFlags >> 4) & 3;
+ huffRDW = (huffFlags >> 6) & 3;
+ huffRDH = (huffFlags >> 8) & 3;
+ huffRDX = (huffFlags >> 10) & 3;
+ huffRDY = (huffFlags >> 12) & 3;
+ huffRSize = (huffFlags >> 14) & 1;
+ }
+ if (refine && templ == 0) {
+ if (!readByte(&atx[0]) || !readByte(&aty[0]) ||
+ !readByte(&atx[1]) || !readByte(&aty[1])) {
+ goto eofError;
+ }
+ }
+ if (!readULong(&numInstances)) {
+ goto eofError;
+ }
+
+ // get symbol dictionaries and tables
+ codeTables = new GList();
+ numSyms = 0;
+ for (i = 0; i < nRefSegs; ++i) {
+ seg = findSegment(refSegs[i]);
+ if (seg->getType() == jbig2SegSymbolDict) {
+ numSyms += ((JBIG2SymbolDict *)seg)->getSize();
+ } else if (seg->getType() == jbig2SegCodeTable) {
+ codeTables->append(seg);
+ }
+ }
+ symCodeLen = 0;
+ i = 1;
+ while (i < numSyms) {
+ ++symCodeLen;
+ i <<= 1;
+ }
+
+ // get the symbol bitmaps
+ syms = (JBIG2Bitmap **)gmalloc(numSyms * sizeof(JBIG2Bitmap *));
+ kk = 0;
+ for (i = 0; i < nRefSegs; ++i) {
+ seg = findSegment(refSegs[i]);
+ if (seg->getType() == jbig2SegSymbolDict) {
+ symbolDict = (JBIG2SymbolDict *)seg;
+ for (k = 0; k < symbolDict->getSize(); ++k) {
+ syms[kk++] = symbolDict->getBitmap(k);
+ }
+ }
+ }
+
+ // get the Huffman tables
+ huffFSTable = huffDSTable = huffDTTable = NULL; // make gcc happy
+ huffRDWTable = huffRDHTable = NULL; // make gcc happy
+ huffRDXTable = huffRDYTable = huffRSizeTable = NULL; // make gcc happy
+ i = 0;
+ if (huff) {
+ if (huffFS == 0) {
+ huffFSTable = huffTableF;
+ } else if (huffFS == 1) {
+ huffFSTable = huffTableG;
+ } else {
+ huffFSTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffDS == 0) {
+ huffDSTable = huffTableH;
+ } else if (huffDS == 1) {
+ huffDSTable = huffTableI;
+ } else if (huffDS == 2) {
+ huffDSTable = huffTableJ;
+ } else {
+ huffDSTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffDT == 0) {
+ huffDTTable = huffTableK;
+ } else if (huffDT == 1) {
+ huffDTTable = huffTableL;
+ } else if (huffDT == 2) {
+ huffDTTable = huffTableM;
+ } else {
+ huffDTTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffRDW == 0) {
+ huffRDWTable = huffTableN;
+ } else if (huffRDW == 1) {
+ huffRDWTable = huffTableO;
+ } else {
+ huffRDWTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffRDH == 0) {
+ huffRDHTable = huffTableN;
+ } else if (huffRDH == 1) {
+ huffRDHTable = huffTableO;
+ } else {
+ huffRDHTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffRDX == 0) {
+ huffRDXTable = huffTableN;
+ } else if (huffRDX == 1) {
+ huffRDXTable = huffTableO;
+ } else {
+ huffRDXTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffRDY == 0) {
+ huffRDYTable = huffTableN;
+ } else if (huffRDY == 1) {
+ huffRDYTable = huffTableO;
+ } else {
+ huffRDYTable = ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ if (huffRSize == 0) {
+ huffRSizeTable = huffTableA;
+ } else {
+ huffRSizeTable =
+ ((JBIG2CodeTable *)codeTables->get(i++))->getHuffTable();
+ }
+ }
+ delete codeTables;
+
+ // symbol ID Huffman decoding table
+ if (huff) {
+ huffDecoder->reset();
+ for (i = 0; i < 32; ++i) {
+ runLengthTab[i].val = i;
+ runLengthTab[i].prefixLen = huffDecoder->readBits(4);
+ runLengthTab[i].rangeLen = 0;
+ }
+ runLengthTab[32].val = 0x103;
+ runLengthTab[32].prefixLen = huffDecoder->readBits(4);
+ runLengthTab[32].rangeLen = 2;
+ runLengthTab[33].val = 0x203;
+ runLengthTab[33].prefixLen = huffDecoder->readBits(4);
+ runLengthTab[33].rangeLen = 3;
+ runLengthTab[34].val = 0x20b;
+ runLengthTab[34].prefixLen = huffDecoder->readBits(4);
+ runLengthTab[34].rangeLen = 7;
+ runLengthTab[35].rangeLen = jbig2HuffmanEOT;
+ huffDecoder->buildTable(runLengthTab, 35);
+ symCodeTab = (JBIG2HuffmanTable *)gmalloc((numSyms + 1) *
+ sizeof(JBIG2HuffmanTable));
+ for (i = 0; i < numSyms; ++i) {
+ symCodeTab[i].val = i;
+ symCodeTab[i].rangeLen = 0;
+ }
+ i = 0;
+ while (i < numSyms) {
+ huffDecoder->decodeInt(&j, runLengthTab);
+ if (j > 0x200) {
+ for (j -= 0x200; j && i < numSyms; --j) {
+ symCodeTab[i++].prefixLen = 0;
+ }
+ } else if (j > 0x100) {
+ for (j -= 0x100; j && i < numSyms; --j) {
+ symCodeTab[i].prefixLen = symCodeTab[i-1].prefixLen;
+ ++i;
+ }
+ } else {
+ symCodeTab[i++].prefixLen = j;
+ }
+
+ }
+ symCodeTab[numSyms].rangeLen = jbig2HuffmanEOT;
+ huffDecoder->buildTable(symCodeTab, numSyms);
+ huffDecoder->reset();
+
+ // set up the arithmetic decoder
+ } else {
+ symCodeTab = NULL;
+ resetIntStats(symCodeLen);
+ if (refine) {
+ resetRefinementStats(templ, NULL);
+ }
+ arithDecoder->start();
+ }
+
+ bitmap = readTextRegion(huff, refine, w, h, numInstances,
+ logStrips, numSyms, symCodeTab, symCodeLen, syms,
+ defPixel, combOp, transposed, refCorner, sOffset,
+ huffFSTable, huffDSTable, huffDTTable,
+ huffRDWTable, huffRDHTable,
+ huffRDXTable, huffRDYTable, huffRSizeTable,
+ templ, atx, aty);
+
+ gfree(syms);
+
+ // combine the region bitmap into the page bitmap
+ if (imm) {
+ if (pageH == 0xffffffff && y + h > curPageH) {
+ pageBitmap->expand(y + h, pageDefPixel);
+ }
+ pageBitmap->combine(bitmap, x, y, extCombOp);
+ delete bitmap;
+
+ // store the region bitmap
+ } else {
+ bitmap->setSegNum(segNum);
+ segments->append(bitmap);
+ }
+
+ // clean up the Huffman decoder
+ if (huff) {
+ gfree(symCodeTab);
+ }
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+JBIG2Bitmap *JBIG2Stream::readTextRegion(GBool huff, GBool refine,
+ int w, int h,
+ Guint numInstances,
+ Guint logStrips,
+ int /*numSyms*/,
+ JBIG2HuffmanTable *symCodeTab,
+ Guint symCodeLen,
+ JBIG2Bitmap **syms,
+ Guint defPixel, Guint combOp,
+ Guint transposed, Guint refCorner,
+ Guint sOffset,
+ JBIG2HuffmanTable *huffFSTable,
+ JBIG2HuffmanTable *huffDSTable,
+ JBIG2HuffmanTable *huffDTTable,
+ JBIG2HuffmanTable *huffRDWTable,
+ JBIG2HuffmanTable *huffRDHTable,
+ JBIG2HuffmanTable *huffRDXTable,
+ JBIG2HuffmanTable *huffRDYTable,
+ JBIG2HuffmanTable *huffRSizeTable,
+ Guint templ,
+ int *atx, int *aty) {
+ JBIG2Bitmap *bitmap;
+ JBIG2Bitmap *symbolBitmap;
+ Guint strips;
+ int t, dt, tt, s, ds, sFirst, j;
+ int rdw, rdh, rdx, rdy, ri, refDX, refDY, bmSize;
+ Guint symID, inst, bw, bh;
+
+ strips = 1 << logStrips;
+
+ if (w < 0 || h <= 0 || w >= INT_MAX / h) {
+ error(-1, "invalid width/height");
+ return NULL;
+ }
+
+ // allocate the bitmap
+ bitmap = new JBIG2Bitmap(0, w, h);
+ if (defPixel) {
+ bitmap->clearToOne();
+ } else {
+ bitmap->clearToZero();
+ }
+
+ // decode initial T value
+ if (huff) {
+ huffDecoder->decodeInt(&t, huffDTTable);
+ } else {
+ arithDecoder->decodeInt(&t, iadtStats);
+ }
+ t *= -strips;
+
+ inst = 0;
+ sFirst = 0;
+ while (inst < numInstances) {
+
+ // decode delta-T
+ if (huff) {
+ huffDecoder->decodeInt(&dt, huffDTTable);
+ } else {
+ arithDecoder->decodeInt(&dt, iadtStats);
+ }
+ t += dt * strips;
+
+ // first S value
+ if (huff) {
+ huffDecoder->decodeInt(&ds, huffFSTable);
+ } else {
+ arithDecoder->decodeInt(&ds, iafsStats);
+ }
+ sFirst += ds;
+ s = sFirst;
+
+ // read the instances
+ while (1) {
+
+ // T value
+ if (strips == 1) {
+ dt = 0;
+ } else if (huff) {
+ dt = huffDecoder->readBits(logStrips);
+ } else {
+ arithDecoder->decodeInt(&dt, iaitStats);
+ }
+ tt = t + dt;
+
+ // symbol ID
+ if (huff) {
+ if (symCodeTab) {
+ huffDecoder->decodeInt(&j, symCodeTab);
+ symID = (Guint)j;
+ } else {
+ symID = huffDecoder->readBits(symCodeLen);
+ }
+ } else {
+ symID = arithDecoder->decodeIAID(symCodeLen, iaidStats);
+ }
+
+ // get the symbol bitmap
+ symbolBitmap = NULL;
+ if (refine) {
+ if (huff) {
+ ri = (int)huffDecoder->readBit();
+ } else {
+ arithDecoder->decodeInt(&ri, iariStats);
+ }
+ } else {
+ ri = 0;
+ }
+ if (ri) {
+ if (huff) {
+ huffDecoder->decodeInt(&rdw, huffRDWTable);
+ huffDecoder->decodeInt(&rdh, huffRDHTable);
+ huffDecoder->decodeInt(&rdx, huffRDXTable);
+ huffDecoder->decodeInt(&rdy, huffRDYTable);
+ huffDecoder->decodeInt(&bmSize, huffRSizeTable);
+ huffDecoder->reset();
+ arithDecoder->start();
+ } else {
+ arithDecoder->decodeInt(&rdw, iardwStats);
+ arithDecoder->decodeInt(&rdh, iardhStats);
+ arithDecoder->decodeInt(&rdx, iardxStats);
+ arithDecoder->decodeInt(&rdy, iardyStats);
+ }
+ refDX = ((rdw >= 0) ? rdw : rdw - 1) / 2 + rdx;
+ refDY = ((rdh >= 0) ? rdh : rdh - 1) / 2 + rdy;
+
+ symbolBitmap =
+ readGenericRefinementRegion(rdw + syms[symID]->getWidth(),
+ rdh + syms[symID]->getHeight(),
+ templ, gFalse, syms[symID],
+ refDX, refDY, atx, aty);
+ //~ do we need to use the bmSize value here (in Huffman mode)?
+ } else {
+ symbolBitmap = syms[symID];
+ }
+
+ // combine the symbol bitmap into the region bitmap
+ //~ something is wrong here - refCorner shouldn't degenerate into
+ //~ two cases
+ bw = symbolBitmap->getWidth() - 1;
+ bh = symbolBitmap->getHeight() - 1;
+ if (transposed) {
+ switch (refCorner) {
+ case 0: // bottom left
+ bitmap->combine(symbolBitmap, tt, s, combOp);
+ break;
+ case 1: // top left
+ bitmap->combine(symbolBitmap, tt, s, combOp);
+ break;
+ case 2: // bottom right
+ bitmap->combine(symbolBitmap, tt - bw, s, combOp);
+ break;
+ case 3: // top right
+ bitmap->combine(symbolBitmap, tt - bw, s, combOp);
+ break;
+ }
+ s += bh;
+ } else {
+ switch (refCorner) {
+ case 0: // bottom left
+ bitmap->combine(symbolBitmap, s, tt - bh, combOp);
+ break;
+ case 1: // top left
+ bitmap->combine(symbolBitmap, s, tt, combOp);
+ break;
+ case 2: // bottom right
+ bitmap->combine(symbolBitmap, s, tt - bh, combOp);
+ break;
+ case 3: // top right
+ bitmap->combine(symbolBitmap, s, tt, combOp);
+ break;
+ }
+ s += bw;
+ }
+ if (ri) {
+ delete symbolBitmap;
+ }
+
+ // next instance
+ ++inst;
+
+ // next S value
+ if (huff) {
+ if (!huffDecoder->decodeInt(&ds, huffDSTable)) {
+ break;
+ }
+ } else {
+ if (!arithDecoder->decodeInt(&ds, iadsStats)) {
+ break;
+ }
+ }
+ s += sOffset + ds;
+ }
+ }
+
+ return bitmap;
+}
+
+void JBIG2Stream::readPatternDictSeg(Guint segNum, Guint length) {
+ JBIG2PatternDict *patternDict;
+ JBIG2Bitmap *bitmap;
+ Guint flags, patternW, patternH, grayMax, templ, mmr;
+ int atx[4], aty[4];
+ Guint i, x;
+
+ // halftone dictionary flags, pattern width and height, max gray value
+ if (!readUByte(&flags) ||
+ !readUByte(&patternW) ||
+ !readUByte(&patternH) ||
+ !readULong(&grayMax)) {
+ goto eofError;
+ }
+ templ = (flags >> 1) & 3;
+ mmr = flags & 1;
+
+ // set up the arithmetic decoder
+ if (!mmr) {
+ resetGenericStats(templ, NULL);
+ arithDecoder->start();
+ }
+
+ // read the bitmap
+ atx[0] = -patternW; aty[0] = 0;
+ atx[1] = -3; aty[1] = -1;
+ atx[2] = 2; aty[2] = -2;
+ atx[3] = -2; aty[3] = -2;
+ bitmap = readGenericBitmap(mmr, (grayMax + 1) * patternW, patternH,
+ templ, gFalse, gFalse, NULL,
+ atx, aty, length - 7);
+
+ // create the pattern dict object
+ patternDict = new JBIG2PatternDict(segNum, grayMax + 1);
+
+ // split up the bitmap
+ x = 0;
+ for (i = 0; i <= grayMax; ++i) {
+ patternDict->setBitmap(i, bitmap->getSlice(x, 0, patternW, patternH));
+ x += patternW;
+ }
+
+ // free memory
+ delete bitmap;
+
+ // store the new pattern dict
+ segments->append(patternDict);
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readHalftoneRegionSeg(Guint segNum, GBool imm,
+ GBool /*lossless*/, Guint /*length*/,
+ Guint *refSegs, Guint nRefSegs) {
+ JBIG2Bitmap *bitmap;
+ JBIG2Segment *seg;
+ JBIG2PatternDict *patternDict;
+ JBIG2Bitmap *skipBitmap;
+ Guint *grayImg;
+ JBIG2Bitmap *grayBitmap;
+ JBIG2Bitmap *patternBitmap;
+ Guint w, h, x, y, segInfoFlags, extCombOp;
+ Guint flags, mmr, templ, enableSkip, combOp;
+ Guint gridW, gridH, stepX, stepY, patW, patH;
+ int atx[4], aty[4];
+ int gridX, gridY, xx, yy, bit, j;
+ Guint bpp, m, n, i;
+
+ // region segment info field
+ if (!readULong(&w) || !readULong(&h) ||
+ !readULong(&x) || !readULong(&y) ||
+ !readUByte(&segInfoFlags)) {
+ goto eofError;
+ }
+ extCombOp = segInfoFlags & 7;
+
+ // rest of the halftone region header
+ if (!readUByte(&flags)) {
+ goto eofError;
+ }
+ mmr = flags & 1;
+ templ = (flags >> 1) & 3;
+ enableSkip = (flags >> 3) & 1;
+ combOp = (flags >> 4) & 7;
+ if (!readULong(&gridW) || !readULong(&gridH) ||
+ !readLong(&gridX) || !readLong(&gridY) ||
+ !readUWord(&stepX) || !readUWord(&stepY)) {
+ goto eofError;
+ }
+
+ // get pattern dictionary
+ if (nRefSegs != 1) {
+ error(getPos(), "Bad symbol dictionary reference in JBIG2 halftone segment");
+ return;
+ }
+ seg = findSegment(refSegs[0]);
+ if (seg->getType() != jbig2SegPatternDict) {
+ error(getPos(), "Bad symbol dictionary reference in JBIG2 halftone segment");
+ return;
+ }
+ if (gridH == 0 || gridW >= INT_MAX / gridH) {
+ error(getPos(), "Bad size in JBIG2 halftone segment");
+ return;
+ }
+ if (w == 0 || h >= INT_MAX / w) {
+ error(getPos(), "Bad size in JBIG2 bitmap segment");
+ return;
+ }
+
+ patternDict = (JBIG2PatternDict *)seg;
+ bpp = 0;
+ i = 1;
+ while (i < patternDict->getSize()) {
+ ++bpp;
+ i <<= 1;
+ }
+ patW = patternDict->getBitmap(0)->getWidth();
+ patH = patternDict->getBitmap(0)->getHeight();
+
+ // set up the arithmetic decoder
+ if (!mmr) {
+ resetGenericStats(templ, NULL);
+ arithDecoder->start();
+ }
+
+ // allocate the bitmap
+ bitmap = new JBIG2Bitmap(segNum, w, h);
+ if (flags & 0x80) { // HDEFPIXEL
+ bitmap->clearToOne();
+ } else {
+ bitmap->clearToZero();
+ }
+
+ // compute the skip bitmap
+ skipBitmap = NULL;
+ if (enableSkip) {
+ skipBitmap = new JBIG2Bitmap(0, gridW, gridH);
+ skipBitmap->clearToZero();
+ for (m = 0; m < gridH; ++m) {
+ xx = gridX + m * stepY;
+ yy = gridY + m * stepX;
+ for (n = 0; n < gridW; ++n) {
+ if (((xx + (int)patW) >> 8) <= 0 || (xx >> 8) >= (int)w ||
+ ((yy + (int)patH) >> 8) <= 0 || (yy >> 8) >= (int)h) {
+ skipBitmap->setPixel(n, m);
+ }
+ }
+ }
+ }
+
+ // read the gray-scale image
+ grayImg = (Guint *)gmalloc(gridW * gridH * sizeof(Guint));
+ memset(grayImg, 0, gridW * gridH * sizeof(Guint));
+ atx[0] = templ <= 1 ? 3 : 2; aty[0] = -1;
+ atx[1] = -3; aty[1] = -1;
+ atx[2] = 2; aty[2] = -2;
+ atx[3] = -2; aty[3] = -2;
+ for (j = bpp - 1; j >= 0; --j) {
+ grayBitmap = readGenericBitmap(mmr, gridW, gridH, templ, gFalse,
+ enableSkip, skipBitmap, atx, aty, -1);
+ i = 0;
+ for (m = 0; m < gridH; ++m) {
+ for (n = 0; n < gridW; ++n) {
+ bit = grayBitmap->getPixel(n, m) ^ (grayImg[i] & 1);
+ grayImg[i] = (grayImg[i] << 1) | bit;
+ ++i;
+ }
+ }
+ delete grayBitmap;
+ }
+
+ // decode the image
+ i = 0;
+ for (m = 0; m < gridH; ++m) {
+ xx = gridX + m * stepY;
+ yy = gridY + m * stepX;
+ for (n = 0; n < gridW; ++n) {
+ if (!(enableSkip && skipBitmap->getPixel(n, m))) {
+ patternBitmap = patternDict->getBitmap(grayImg[i]);
+ bitmap->combine(patternBitmap, xx >> 8, yy >> 8, combOp);
+ }
+ xx += stepX;
+ yy -= stepY;
+ ++i;
+ }
+ }
+
+ gfree(grayImg);
+
+ // combine the region bitmap into the page bitmap
+ if (imm) {
+ if (pageH == 0xffffffff && y + h > curPageH) {
+ pageBitmap->expand(y + h, pageDefPixel);
+ }
+ pageBitmap->combine(bitmap, x, y, extCombOp);
+ delete bitmap;
+
+ // store the region bitmap
+ } else {
+ segments->append(bitmap);
+ }
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readGenericRegionSeg(Guint segNum, GBool imm,
+ GBool /*lossless*/, Guint length) {
+ JBIG2Bitmap *bitmap;
+ Guint w, h, x, y, segInfoFlags, extCombOp;
+ Guint flags, mmr, templ, tpgdOn;
+ int atx[4], aty[4];
+
+ // region segment info field
+ if (!readULong(&w) || !readULong(&h) ||
+ !readULong(&x) || !readULong(&y) ||
+ !readUByte(&segInfoFlags)) {
+ goto eofError;
+ }
+ extCombOp = segInfoFlags & 7;
+
+ // rest of the generic region segment header
+ if (!readUByte(&flags)) {
+ goto eofError;
+ }
+ mmr = flags & 1;
+ templ = (flags >> 1) & 3;
+ tpgdOn = (flags >> 3) & 1;
+
+ // AT flags
+ if (!mmr) {
+ if (templ == 0) {
+ if (!readByte(&atx[0]) ||
+ !readByte(&aty[0]) ||
+ !readByte(&atx[1]) ||
+ !readByte(&aty[1]) ||
+ !readByte(&atx[2]) ||
+ !readByte(&aty[2]) ||
+ !readByte(&atx[3]) ||
+ !readByte(&aty[3])) {
+ goto eofError;
+ }
+ } else {
+ if (!readByte(&atx[0]) ||
+ !readByte(&aty[0])) {
+ goto eofError;
+ }
+ }
+ }
+
+ // set up the arithmetic decoder
+ if (!mmr) {
+ resetGenericStats(templ, NULL);
+ arithDecoder->start();
+ }
+
+ // read the bitmap
+ bitmap = readGenericBitmap(mmr, w, h, templ, tpgdOn, gFalse,
+ NULL, atx, aty, mmr ? 0 : length - 18);
+
+ // combine the region bitmap into the page bitmap
+ if (imm) {
+ if (pageH == 0xffffffff && y + h > curPageH) {
+ pageBitmap->expand(y + h, pageDefPixel);
+ }
+ pageBitmap->combine(bitmap, x, y, extCombOp);
+ delete bitmap;
+
+ // store the region bitmap
+ } else {
+ bitmap->setSegNum(segNum);
+ segments->append(bitmap);
+ }
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+JBIG2Bitmap *JBIG2Stream::readGenericBitmap(GBool mmr, int w, int h,
+ int templ, GBool tpgdOn,
+ GBool useSkip, JBIG2Bitmap *skip,
+ int *atx, int *aty,
+ int mmrDataLength) {
+ JBIG2Bitmap *bitmap;
+ GBool ltp;
+ Guint ltpCX, cx, cx0, cx1, cx2;
+ int *refLine, *codingLine;
+ int code1, code2, code3;
+ int x, y, a0, pix, i, refI, codingI;
+
+ bitmap = new JBIG2Bitmap(0, w, h);
+ bitmap->clearToZero();
+
+ //----- MMR decode
+
+ if (mmr) {
+
+ mmrDecoder->reset();
+ refLine = (int *)gmalloc((w + 2) * sizeof(int));
+ codingLine = (int *)gmalloc((w + 2) * sizeof(int));
+ codingLine[0] = codingLine[1] = w;
+
+ for (y = 0; y < h; ++y) {
+
+ // copy coding line to ref line
+ for (i = 0; codingLine[i] < w; ++i) {
+ refLine[i] = codingLine[i];
+ }
+ refLine[i] = refLine[i + 1] = w;
+
+ // decode a line
+ refI = 0; // b1 = refLine[refI]
+ codingI = 0; // a1 = codingLine[codingI]
+ a0 = 0;
+ do {
+ code1 = mmrDecoder->get2DCode();
+ switch (code1) {
+ case twoDimPass:
+ if (refLine[refI] < w) {
+ a0 = refLine[refI + 1];
+ refI += 2;
+ }
+ break;
+ case twoDimHoriz:
+ if (codingI & 1) {
+ code1 = 0;
+ do {
+ code1 += code3 = mmrDecoder->getBlackCode();
+ } while (code3 >= 64);
+ code2 = 0;
+ do {
+ code2 += code3 = mmrDecoder->getWhiteCode();
+ } while (code3 >= 64);
+ } else {
+ code1 = 0;
+ do {
+ code1 += code3 = mmrDecoder->getWhiteCode();
+ } while (code3 >= 64);
+ code2 = 0;
+ do {
+ code2 += code3 = mmrDecoder->getBlackCode();
+ } while (code3 >= 64);
+ }
+ a0 = codingLine[codingI++] = a0 + code1;
+ a0 = codingLine[codingI++] = a0 + code2;
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ break;
+ case twoDimVert0:
+ a0 = codingLine[codingI++] = refLine[refI];
+ if (refLine[refI] < w) {
+ ++refI;
+ }
+ break;
+ case twoDimVertR1:
+ a0 = codingLine[codingI++] = refLine[refI] + 1;
+ if (refLine[refI] < w) {
+ ++refI;
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ }
+ break;
+ case twoDimVertR2:
+ a0 = codingLine[codingI++] = refLine[refI] + 2;
+ if (refLine[refI] < w) {
+ ++refI;
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ }
+ break;
+ case twoDimVertR3:
+ a0 = codingLine[codingI++] = refLine[refI] + 3;
+ if (refLine[refI] < w) {
+ ++refI;
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ }
+ break;
+ case twoDimVertL1:
+ a0 = codingLine[codingI++] = refLine[refI] - 1;
+ if (refI > 0) {
+ --refI;
+ } else {
+ ++refI;
+ }
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ break;
+ case twoDimVertL2:
+ a0 = codingLine[codingI++] = refLine[refI] - 2;
+ if (refI > 0) {
+ --refI;
+ } else {
+ ++refI;
+ }
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ break;
+ case twoDimVertL3:
+ a0 = codingLine[codingI++] = refLine[refI] - 3;
+ if (refI > 0) {
+ --refI;
+ } else {
+ ++refI;
+ }
+ while (refLine[refI] <= a0 && refLine[refI] < w) {
+ refI += 2;
+ }
+ break;
+ default:
+ error(getPos(), "Illegal code in JBIG2 MMR bitmap data");
+ break;
+ }
+ } while (a0 < w);
+ codingLine[codingI++] = w;
+
+ // convert the run lengths to a bitmap line
+ i = 0;
+ while (codingLine[i] < w) {
+ for (x = codingLine[i]; x < codingLine[i+1]; ++x) {
+ bitmap->setPixel(x, y);
+ }
+ i += 2;
+ }
+ }
+
+ if (mmrDataLength >= 0) {
+ mmrDecoder->skipTo(mmrDataLength);
+ } else {
+ if (mmrDecoder->get24Bits() != 0x001001) {
+ error(getPos(), "Missing EOFB in JBIG2 MMR bitmap data");
+ }
+ }
+
+ gfree(refLine);
+ gfree(codingLine);
+
+ //----- arithmetic decode
+
+ } else {
+ // set up the typical row context
+ ltpCX = 0; // make gcc happy
+ if (tpgdOn) {
+ switch (templ) {
+ case 0:
+ ltpCX = 0x3953; // 001 11001 0101 0011
+ break;
+ case 1:
+ ltpCX = 0x079a; // 0011 11001 101 0
+ break;
+ case 2:
+ ltpCX = 0x0e3; // 001 1100 01 1
+ break;
+ case 3:
+ ltpCX = 0x18a; // 01100 0101 1
+ break;
+ }
+ }
+
+ ltp = 0;
+ cx = cx0 = cx1 = cx2 = 0; // make gcc happy
+ for (y = 0; y < h; ++y) {
+
+ // check for a "typical" (duplicate) row
+ if (tpgdOn) {
+ if (arithDecoder->decodeBit(ltpCX, genericRegionStats)) {
+ ltp = !ltp;
+ }
+ if (ltp) {
+ bitmap->duplicateRow(y, y-1);
+ continue;
+ }
+ }
+
+ // set up the context
+ switch (templ) {
+ case 0:
+ cx0 = (bitmap->getPixel(0, y-2) << 1) |
+ bitmap->getPixel(1, y-2);
+ cx1 = (bitmap->getPixel(0, y-1) << 2) |
+ (bitmap->getPixel(1, y-1) << 1) |
+ bitmap->getPixel(2, y-1);
+ cx2 = 0;
+ break;
+ case 1:
+ cx0 = (bitmap->getPixel(0, y-2) << 2) |
+ (bitmap->getPixel(1, y-2) << 1) |
+ bitmap->getPixel(2, y-2);
+ cx1 = (bitmap->getPixel(0, y-1) << 2) |
+ (bitmap->getPixel(1, y-1) << 1) |
+ bitmap->getPixel(2, y-1);
+ cx2 = 0;
+ break;
+ case 2:
+ cx0 = (bitmap->getPixel(0, y-2) << 1) |
+ bitmap->getPixel(1, y-2);
+ cx1 = (bitmap->getPixel(0, y-1) << 1) |
+ bitmap->getPixel(1, y-1);
+ cx2 = 0;
+ break;
+ case 3:
+ cx1 = (bitmap->getPixel(0, y-1) << 1) |
+ bitmap->getPixel(1, y-1);
+ cx2 = 0;
+ break;
+ }
+
+ // decode the row
+ for (x = 0; x < w; ++x) {
+
+ // check for a skipped pixel
+ if (useSkip && skip->getPixel(x, y)) {
+ pix = 0;
+
+ } else {
+
+ // build the context
+ switch (templ) {
+ case 0:
+ cx = (cx0 << 13) | (cx1 << 8) | (cx2 << 4) |
+ (bitmap->getPixel(x + atx[0], y + aty[0]) << 3) |
+ (bitmap->getPixel(x + atx[1], y + aty[1]) << 2) |
+ (bitmap->getPixel(x + atx[2], y + aty[2]) << 1) |
+ bitmap->getPixel(x + atx[3], y + aty[3]);
+ break;
+ case 1:
+ cx = (cx0 << 9) | (cx1 << 4) | (cx2 << 1) |
+ bitmap->getPixel(x + atx[0], y + aty[0]);
+ break;
+ case 2:
+ cx = (cx0 << 7) | (cx1 << 3) | (cx2 << 1) |
+ bitmap->getPixel(x + atx[0], y + aty[0]);
+ break;
+ case 3:
+ cx = (cx1 << 5) | (cx2 << 1) |
+ bitmap->getPixel(x + atx[0], y + aty[0]);
+ break;
+ }
+
+ // decode the pixel
+ if ((pix = arithDecoder->decodeBit(cx, genericRegionStats))) {
+ bitmap->setPixel(x, y);
+ }
+ }
+
+ // update the context
+ switch (templ) {
+ case 0:
+ cx0 = ((cx0 << 1) | bitmap->getPixel(x+2, y-2)) & 0x07;
+ cx1 = ((cx1 << 1) | bitmap->getPixel(x+3, y-1)) & 0x1f;
+ cx2 = ((cx2 << 1) | pix) & 0x0f;
+ break;
+ case 1:
+ cx0 = ((cx0 << 1) | bitmap->getPixel(x+3, y-2)) & 0x0f;
+ cx1 = ((cx1 << 1) | bitmap->getPixel(x+3, y-1)) & 0x1f;
+ cx2 = ((cx2 << 1) | pix) & 0x07;
+ break;
+ case 2:
+ cx0 = ((cx0 << 1) | bitmap->getPixel(x+2, y-2)) & 0x07;
+ cx1 = ((cx1 << 1) | bitmap->getPixel(x+2, y-1)) & 0x0f;
+ cx2 = ((cx2 << 1) | pix) & 0x03;
+ break;
+ case 3:
+ cx1 = ((cx1 << 1) | bitmap->getPixel(x+2, y-1)) & 0x1f;
+ cx2 = ((cx2 << 1) | pix) & 0x0f;
+ break;
+ }
+ }
+ }
+ }
+
+ return bitmap;
+}
+
+void JBIG2Stream::readGenericRefinementRegionSeg(Guint segNum, GBool imm,
+ GBool /*lossless*/, Guint /*length*/,
+ Guint *refSegs,
+ Guint nRefSegs) {
+ JBIG2Bitmap *bitmap, *refBitmap;
+ Guint w, h, x, y, segInfoFlags, extCombOp;
+ Guint flags, templ, tpgrOn;
+ int atx[2], aty[2];
+ JBIG2Segment *seg;
+
+ // region segment info field
+ if (!readULong(&w) || !readULong(&h) ||
+ !readULong(&x) || !readULong(&y) ||
+ !readUByte(&segInfoFlags)) {
+ goto eofError;
+ }
+ extCombOp = segInfoFlags & 7;
+
+ // rest of the generic refinement region segment header
+ if (!readUByte(&flags)) {
+ goto eofError;
+ }
+ templ = flags & 1;
+ tpgrOn = (flags >> 1) & 1;
+
+ // AT flags
+ if (!templ) {
+ if (!readByte(&atx[0]) || !readByte(&aty[0]) ||
+ !readByte(&atx[1]) || !readByte(&aty[1])) {
+ goto eofError;
+ }
+ }
+
+ // resize the page bitmap if needed
+ if (nRefSegs == 0 || imm) {
+ if (pageH == 0xffffffff && y + h > curPageH) {
+ pageBitmap->expand(y + h, pageDefPixel);
+ }
+ }
+
+ // get referenced bitmap
+ if (nRefSegs > 1) {
+ error(getPos(), "Bad reference in JBIG2 generic refinement segment");
+ return;
+ }
+ if (nRefSegs == 1) {
+ seg = findSegment(refSegs[0]);
+ if (seg->getType() != jbig2SegBitmap) {
+ error(getPos(), "Bad bitmap reference in JBIG2 generic refinement segment");
+ return;
+ }
+ refBitmap = (JBIG2Bitmap *)seg;
+ } else {
+ refBitmap = pageBitmap->getSlice(x, y, w, h);
+ }
+
+ // set up the arithmetic decoder
+ resetRefinementStats(templ, NULL);
+ arithDecoder->start();
+
+ // read
+ bitmap = readGenericRefinementRegion(w, h, templ, tpgrOn,
+ refBitmap, 0, 0, atx, aty);
+
+ // combine the region bitmap into the page bitmap
+ if (imm) {
+ pageBitmap->combine(bitmap, x, y, extCombOp);
+ delete bitmap;
+
+ // store the region bitmap
+ } else {
+ bitmap->setSegNum(segNum);
+ segments->append(bitmap);
+ }
+
+ // delete the referenced bitmap
+ if (nRefSegs == 1) {
+ discardSegment(refSegs[0]);
+ } else {
+ delete refBitmap;
+ }
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+JBIG2Bitmap *JBIG2Stream::readGenericRefinementRegion(int w, int h,
+ int templ, GBool tpgrOn,
+ JBIG2Bitmap *refBitmap,
+ int refDX, int refDY,
+ int *atx, int *aty) {
+ JBIG2Bitmap *bitmap;
+ GBool ltp;
+ Guint ltpCX, cx, cx0, cx2, cx3, cx4, tpgrCX0, tpgrCX1, tpgrCX2;
+ int x, y, pix;
+
+ if (w < 0 || h <= 0 || w >= INT_MAX / h) {
+ error(-1, "invalid width/height");
+ return NULL;
+ }
+
+ bitmap = new JBIG2Bitmap(0, w, h);
+ bitmap->clearToZero();
+
+ // set up the typical row context
+ if (templ) {
+ ltpCX = 0x008;
+ } else {
+ ltpCX = 0x0010;
+ }
+
+ ltp = 0;
+ for (y = 0; y < h; ++y) {
+
+ // set up the context
+ if (templ) {
+ cx0 = bitmap->getPixel(0, y-1);
+ cx2 = 0; // unused
+ cx3 = (refBitmap->getPixel(-1-refDX, y-refDY) << 1) |
+ refBitmap->getPixel(-refDX, y-refDY);
+ cx4 = refBitmap->getPixel(-refDX, y+1-refDY);
+ } else {
+ cx0 = bitmap->getPixel(0, y-1);
+ cx2 = refBitmap->getPixel(-refDX, y-1-refDY);
+ cx3 = (refBitmap->getPixel(-1-refDX, y-refDY) << 1) |
+ refBitmap->getPixel(-refDX, y-refDY);
+ cx4 = (refBitmap->getPixel(-1-refDX, y+1-refDY) << 1) |
+ refBitmap->getPixel(-refDX, y+1-refDY);
+ }
+
+ // set up the typical prediction context
+ tpgrCX0 = tpgrCX1 = tpgrCX2 = 0; // make gcc happy
+ if (tpgrOn) {
+ tpgrCX0 = (refBitmap->getPixel(-1-refDX, y-1-refDY) << 2) |
+ (refBitmap->getPixel(-refDX, y-1-refDY) << 1) |
+ refBitmap->getPixel(1-refDX, y-1-refDY);
+ tpgrCX1 = (refBitmap->getPixel(-1-refDX, y-refDY) << 2) |
+ (refBitmap->getPixel(-refDX, y-refDY) << 1) |
+ refBitmap->getPixel(1-refDX, y-refDY);
+ tpgrCX2 = (refBitmap->getPixel(-1-refDX, y+1-refDY) << 2) |
+ (refBitmap->getPixel(-refDX, y+1-refDY) << 1) |
+ refBitmap->getPixel(1-refDX, y+1-refDY);
+ }
+
+ for (x = 0; x < w; ++x) {
+
+ // update the context
+ if (templ) {
+ cx0 = ((cx0 << 1) | bitmap->getPixel(x+1, y-1)) & 7;
+ cx3 = ((cx3 << 1) | refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
+ cx4 = ((cx4 << 1) | refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 3;
+ } else {
+ cx0 = ((cx0 << 1) | bitmap->getPixel(x+1, y-1)) & 3;
+ cx2 = ((cx2 << 1) | refBitmap->getPixel(x+1-refDX, y-1-refDY)) & 3;
+ cx3 = ((cx3 << 1) | refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
+ cx4 = ((cx4 << 1) | refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 7;
+ }
+
+ if (tpgrOn) {
+ // update the typical predictor context
+ tpgrCX0 = ((tpgrCX0 << 1) |
+ refBitmap->getPixel(x+1-refDX, y-1-refDY)) & 7;
+ tpgrCX1 = ((tpgrCX1 << 1) |
+ refBitmap->getPixel(x+1-refDX, y-refDY)) & 7;
+ tpgrCX2 = ((tpgrCX2 << 1) |
+ refBitmap->getPixel(x+1-refDX, y+1-refDY)) & 7;
+
+ // check for a "typical" pixel
+ if (arithDecoder->decodeBit(ltpCX, refinementRegionStats)) {
+ ltp = !ltp;
+ }
+ if (tpgrCX0 == 0 && tpgrCX1 == 0 && tpgrCX2 == 0) {
+ bitmap->clearPixel(x, y);
+ continue;
+ } else if (tpgrCX0 == 7 && tpgrCX1 == 7 && tpgrCX2 == 7) {
+ bitmap->setPixel(x, y);
+ continue;
+ }
+ }
+
+ // build the context
+ if (templ) {
+ cx = (cx0 << 7) | (bitmap->getPixel(x-1, y) << 6) |
+ (refBitmap->getPixel(x-refDX, y-1-refDY) << 5) |
+ (cx3 << 2) | cx4;
+ } else {
+ cx = (cx0 << 11) | (bitmap->getPixel(x-1, y) << 10) |
+ (cx2 << 8) | (cx3 << 5) | (cx4 << 2) |
+ (bitmap->getPixel(x+atx[0], y+aty[0]) << 1) |
+ refBitmap->getPixel(x+atx[1]-refDX, y+aty[1]-refDY);
+ }
+
+ // decode the pixel
+ if ((pix = arithDecoder->decodeBit(cx, refinementRegionStats))) {
+ bitmap->setPixel(x, y);
+ }
+ }
+ }
+
+ return bitmap;
+}
+
+void JBIG2Stream::readPageInfoSeg(Guint /*length*/) {
+ Guint xRes, yRes, flags, striping;
+
+ if (!readULong(&pageW) || !readULong(&pageH) ||
+ !readULong(&xRes) || !readULong(&yRes) ||
+ !readUByte(&flags) || !readUWord(&striping)) {
+ goto eofError;
+ }
+ pageDefPixel = (flags >> 2) & 1;
+ defCombOp = (flags >> 3) & 3;
+
+ // allocate the page bitmap
+ if (pageH == 0xffffffff) {
+ curPageH = striping & 0x7fff;
+ } else {
+ curPageH = pageH;
+ }
+ pageBitmap = new JBIG2Bitmap(0, pageW, curPageH);
+
+ // default pixel value
+ if (pageDefPixel) {
+ pageBitmap->clearToOne();
+ } else {
+ pageBitmap->clearToZero();
+ }
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readEndOfStripeSeg(Guint length) {
+ Guint i;
+
+ // skip the segment
+ for (i = 0; i < length; ++i) {
+ curStr->getChar();
+ }
+}
+
+void JBIG2Stream::readProfilesSeg(Guint length) {
+ Guint i;
+
+ // skip the segment
+ for (i = 0; i < length; ++i) {
+ curStr->getChar();
+ }
+}
+
+void JBIG2Stream::readCodeTableSeg(Guint segNum, Guint /*length*/) {
+ JBIG2HuffmanTable *huffTab;
+ Guint flags, oob, prefixBits, rangeBits;
+ int lowVal, highVal, val;
+ Guint huffTabSize, i;
+
+ if (!readUByte(&flags) || !readLong(&lowVal) || !readLong(&highVal)) {
+ goto eofError;
+ }
+ oob = flags & 1;
+ prefixBits = (flags >> 1) & 7;
+ rangeBits = (flags >> 4) & 7;
+
+ huffDecoder->reset();
+ huffTabSize = 8;
+ huffTab = (JBIG2HuffmanTable *)
+ gmalloc(huffTabSize * sizeof(JBIG2HuffmanTable));
+ i = 0;
+ val = lowVal;
+ while (val < highVal) {
+ if (i == huffTabSize) {
+ huffTabSize *= 2;
+ huffTab = (JBIG2HuffmanTable *)
+ grealloc(huffTab, huffTabSize * sizeof(JBIG2HuffmanTable));
+ }
+ huffTab[i].val = val;
+ huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
+ huffTab[i].rangeLen = huffDecoder->readBits(rangeBits);
+ val += 1 << huffTab[i].rangeLen;
+ ++i;
+ }
+ if (i + oob + 3 > huffTabSize) {
+ huffTabSize = i + oob + 3;
+ huffTab = (JBIG2HuffmanTable *)
+ grealloc(huffTab, huffTabSize * sizeof(JBIG2HuffmanTable));
+ }
+ huffTab[i].val = lowVal - 1;
+ huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
+ huffTab[i].rangeLen = jbig2HuffmanLOW;
+ ++i;
+ huffTab[i].val = highVal;
+ huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
+ huffTab[i].rangeLen = 32;
+ ++i;
+ if (oob) {
+ huffTab[i].val = 0;
+ huffTab[i].prefixLen = huffDecoder->readBits(prefixBits);
+ huffTab[i].rangeLen = jbig2HuffmanOOB;
+ ++i;
+ }
+ huffTab[i].val = 0;
+ huffTab[i].prefixLen = 0;
+ huffTab[i].rangeLen = jbig2HuffmanEOT;
+ ++i;
+ huffDecoder->buildTable(huffTab, i);
+
+ // create and store the new table segment
+ segments->append(new JBIG2CodeTable(segNum, huffTab));
+
+ return;
+
+ eofError:
+ error(getPos(), "Unexpected EOF in JBIG2 stream");
+}
+
+void JBIG2Stream::readExtensionSeg(Guint length) {
+ Guint i;
+
+ // skip the segment
+ for (i = 0; i < length; ++i) {
+ curStr->getChar();
+ }
+}
+
+JBIG2Segment *JBIG2Stream::findSegment(Guint segNum) {
+ JBIG2Segment *seg;
+ int i;
+
+ for (i = 0; i < globalSegments->getLength(); ++i) {
+ seg = (JBIG2Segment *)globalSegments->get(i);
+ if (seg->getSegNum() == segNum) {
+ return seg;
+ }
+ }
+ for (i = 0; i < segments->getLength(); ++i) {
+ seg = (JBIG2Segment *)segments->get(i);
+ if (seg->getSegNum() == segNum) {
+ return seg;
+ }
+ }
+ return NULL;
+}
+
+void JBIG2Stream::discardSegment(Guint segNum) {
+ JBIG2Segment *seg;
+ int i;
+
+ for (i = 0; i < globalSegments->getLength(); ++i) {
+ seg = (JBIG2Segment *)globalSegments->get(i);
+ if (seg->getSegNum() == segNum) {
+ globalSegments->del(i);
+ return;
+ }
+ }
+ for (i = 0; i < segments->getLength(); ++i) {
+ seg = (JBIG2Segment *)segments->get(i);
+ if (seg->getSegNum() == segNum) {
+ globalSegments->del(i);
+ return;
+ }
+ }
+}
+
+void JBIG2Stream::resetGenericStats(Guint templ,
+ JBIG2ArithmeticDecoderStats *prevStats) {
+ int size;
+
+ size = contextSize[templ];
+ if (prevStats && prevStats->getContextSize() == size) {
+ if (genericRegionStats->getContextSize() == size) {
+ genericRegionStats->copyFrom(prevStats);
+ } else {
+ delete genericRegionStats;
+ genericRegionStats = prevStats->copy();
+ }
+ } else {
+ if (genericRegionStats->getContextSize() == size) {
+ genericRegionStats->reset();
+ } else {
+ delete genericRegionStats;
+ genericRegionStats = new JBIG2ArithmeticDecoderStats(size);
+ }
+ }
+}
+
+void JBIG2Stream::resetRefinementStats(
+ Guint templ,
+ JBIG2ArithmeticDecoderStats *prevStats) {
+ int size;
+
+ size = refContextSize[templ];
+ if (prevStats && prevStats->getContextSize() == size) {
+ if (refinementRegionStats->getContextSize() == size) {
+ refinementRegionStats->copyFrom(prevStats);
+ } else {
+ delete refinementRegionStats;
+ refinementRegionStats = prevStats->copy();
+ }
+ } else {
+ if (refinementRegionStats->getContextSize() == size) {
+ refinementRegionStats->reset();
+ } else {
+ delete refinementRegionStats;
+ refinementRegionStats = new JBIG2ArithmeticDecoderStats(size);
+ }
+ }
+}
+
+void JBIG2Stream::resetIntStats(int symCodeLen) {
+ iadhStats->reset();
+ iadwStats->reset();
+ iaexStats->reset();
+ iaaiStats->reset();
+ iadtStats->reset();
+ iaitStats->reset();
+ iafsStats->reset();
+ iadsStats->reset();
+ iardxStats->reset();
+ iardyStats->reset();
+ iardwStats->reset();
+ iardhStats->reset();
+ iariStats->reset();
+ if (iaidStats->getContextSize() == symCodeLen + 1) {
+ iaidStats->reset();
+ } else {
+ delete iaidStats;
+ iaidStats = new JBIG2ArithmeticDecoderStats(symCodeLen + 1);
+ }
+}
+
+GBool JBIG2Stream::readUByte(Guint *x) {
+ int c0;
+
+ if ((c0 = curStr->getChar()) == EOF) {
+ return gFalse;
+ }
+ *x = (Guint)c0;
+ return gTrue;
+}
+
+GBool JBIG2Stream::readByte(int *x) {
+ int c0;
+
+ if ((c0 = curStr->getChar()) == EOF) {
+ return gFalse;
+ }
+ *x = c0;
+ if (c0 & 0x80) {
+ *x |= -1 - 0xff;
+ }
+ return gTrue;
+}
+
+GBool JBIG2Stream::readUWord(Guint *x) {
+ int c0, c1;
+
+ if ((c0 = curStr->getChar()) == EOF ||
+ (c1 = curStr->getChar()) == EOF) {
+ return gFalse;
+ }
+ *x = (Guint)((c0 << 8) | c1);
+ return gTrue;
+}
+
+GBool JBIG2Stream::readULong(Guint *x) {
+ int c0, c1, c2, c3;
+
+ if ((c0 = curStr->getChar()) == EOF ||
+ (c1 = curStr->getChar()) == EOF ||
+ (c2 = curStr->getChar()) == EOF ||
+ (c3 = curStr->getChar()) == EOF) {
+ return gFalse;
+ }
+ *x = (Guint)((c0 << 24) | (c1 << 16) | (c2 << 8) | c3);
+ return gTrue;
+}
+
+GBool JBIG2Stream::readLong(int *x) {
+ int c0, c1, c2, c3;
+
+ if ((c0 = curStr->getChar()) == EOF ||
+ (c1 = curStr->getChar()) == EOF ||
+ (c2 = curStr->getChar()) == EOF ||
+ (c3 = curStr->getChar()) == EOF) {
+ return gFalse;
+ }
+ *x = ((c0 << 24) | (c1 << 16) | (c2 << 8) | c3);
+ if (c0 & 0x80) {
+ *x |= -1 - 0xffffffff;
+ }
+ return gTrue;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Lexer.cc b/filters/kword/pdf/xpdf/xpdf/Lexer.cc
deleted file mode 100644
index 982295ee3..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Lexer.cc
+++ /dev/null
@@ -1,474 +0,0 @@
-//========================================================================
-//
-// Lexer.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <ctype.h>
-#include "Lexer.h"
-#include "Error.h"
-
-//------------------------------------------------------------------------
-
-// A '1' in this array means the character is white space. A '1' or
-// '2' means the character ends a name or command.
-static char specialChars[256] = {
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
- 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
-};
-
-//------------------------------------------------------------------------
-// Lexer
-//------------------------------------------------------------------------
-
-Lexer::Lexer(XRef *xref, Stream *str) {
- Object obj;
-
- curStr.initStream(str);
- streams = new Array(xref);
- streams->add(curStr.copy(&obj));
- strPtr = 0;
- freeArray = gTrue;
- curStr.streamReset();
-}
-
-Lexer::Lexer(XRef *xref, Object *obj) {
- Object obj2;
-
- if (obj->isStream()) {
- streams = new Array(xref);
- freeArray = gTrue;
- streams->add(obj->copy(&obj2));
- } else {
- streams = obj->getArray();
- freeArray = gFalse;
- }
- strPtr = 0;
- if (streams->getLength() > 0) {
- streams->get(strPtr, &curStr);
- curStr.streamReset();
- }
-}
-
-Lexer::~Lexer() {
- if (!curStr.isNone()) {
- curStr.streamClose();
- curStr.free();
- }
- if (freeArray) {
- delete streams;
- }
-}
-
-int Lexer::getChar() {
- int c;
-
- c = EOF;
- while (!curStr.isNone() && (c = curStr.streamGetChar()) == EOF) {
- curStr.streamClose();
- curStr.free();
- ++strPtr;
- if (strPtr < streams->getLength()) {
- streams->get(strPtr, &curStr);
- curStr.streamReset();
- }
- }
- return c;
-}
-
-int Lexer::lookChar() {
- if (curStr.isNone()) {
- return EOF;
- }
- return curStr.streamLookChar();
-}
-
-Object *Lexer::getObj(Object *obj) {
- char *p;
- int c, c2;
- GBool comment, neg, done;
- int numParen;
- int xi;
- double xf, scale;
- GString *s;
- int n, m;
-
- // skip whitespace and comments
- comment = gFalse;
- while (1) {
- if ((c = getChar()) == EOF) {
- return obj->initEOF();
- }
- if (comment) {
- if (c == '\r' || c == '\n')
- comment = gFalse;
- } else if (c == '%') {
- comment = gTrue;
- } else if (specialChars[c] != 1) {
- break;
- }
- }
-
- // start reading token
- switch (c) {
-
- // number
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- case '-': case '.':
- neg = gFalse;
- xi = 0;
- if (c == '-') {
- neg = gTrue;
- } else if (c == '.') {
- goto doReal;
- } else {
- xi = c - '0';
- }
- while (1) {
- c = lookChar();
- if (isdigit(c)) {
- getChar();
- xi = xi * 10 + (c - '0');
- } else if (c == '.') {
- getChar();
- goto doReal;
- } else {
- break;
- }
- }
- if (neg)
- xi = -xi;
- obj->initInt(xi);
- break;
- doReal:
- xf = xi;
- scale = 0.1;
- while (1) {
- c = lookChar();
- if (!isdigit(c)) {
- break;
- }
- getChar();
- xf = xf + scale * (c - '0');
- scale *= 0.1;
- }
- if (neg)
- xf = -xf;
- obj->initReal(xf);
- break;
-
- // string
- case '(':
- p = tokBuf;
- n = 0;
- numParen = 1;
- done = gFalse;
- s = NULL;
- do {
- c2 = EOF;
- switch (c = getChar()) {
-
- case EOF:
-#if 0
- // This breaks some PDF files, e.g., ones from Photoshop.
- case '\r':
- case '\n':
-#endif
- error(getPos(), "Unterminated string");
- done = gTrue;
- break;
-
- case '(':
- ++numParen;
- c2 = c;
- break;
-
- case ')':
- if (--numParen == 0) {
- done = gTrue;
- } else {
- c2 = c;
- }
- break;
-
- case '\\':
- switch (c = getChar()) {
- case 'n':
- c2 = '\n';
- break;
- case 'r':
- c2 = '\r';
- break;
- case 't':
- c2 = '\t';
- break;
- case 'b':
- c2 = '\b';
- break;
- case 'f':
- c2 = '\f';
- break;
- case '\\':
- case '(':
- case ')':
- c2 = c;
- break;
- case '0': case '1': case '2': case '3':
- case '4': case '5': case '6': case '7':
- c2 = c - '0';
- c = lookChar();
- if (c >= '0' && c <= '7') {
- getChar();
- c2 = (c2 << 3) + (c - '0');
- c = lookChar();
- if (c >= '0' && c <= '7') {
- getChar();
- c2 = (c2 << 3) + (c - '0');
- }
- }
- break;
- case '\r':
- c = lookChar();
- if (c == '\n') {
- getChar();
- }
- break;
- case '\n':
- break;
- case EOF:
- error(getPos(), "Unterminated string");
- done = gTrue;
- break;
- default:
- c2 = c;
- break;
- }
- break;
-
- default:
- c2 = c;
- break;
- }
-
- if (c2 != EOF) {
- if (n == tokBufSize) {
- if (!s)
- s = new GString(tokBuf, tokBufSize);
- else
- s->append(tokBuf, tokBufSize);
- p = tokBuf;
- n = 0;
- }
- *p++ = (char)c2;
- ++n;
- }
- } while (!done);
- if (!s)
- s = new GString(tokBuf, n);
- else
- s->append(tokBuf, n);
- obj->initString(s);
- break;
-
- // name
- case '/':
- p = tokBuf;
- n = 0;
- while ((c = lookChar()) != EOF && !specialChars[c]) {
- getChar();
- if (c == '#') {
- c2 = lookChar();
- if (c2 >= '0' && c2 <= '9') {
- c = c2 - '0';
- } else if (c2 >= 'A' && c2 <= 'F') {
- c = c2 - 'A' + 10;
- } else if (c2 >= 'a' && c2 <= 'f') {
- c = c2 - 'a' + 10;
- } else {
- goto notEscChar;
- }
- getChar();
- c <<= 4;
- c2 = getChar();
- if (c2 >= '0' && c2 <= '9') {
- c += c2 - '0';
- } else if (c2 >= 'A' && c2 <= 'F') {
- c += c2 - 'A' + 10;
- } else if (c2 >= 'a' && c2 <= 'f') {
- c += c2 - 'a' + 10;
- } else {
- error(getPos(), "Illegal digit in hex char in name");
- }
- }
- notEscChar:
- if (++n == tokBufSize) {
- error(getPos(), "Name token too long");
- break;
- }
- *p++ = c;
- }
- *p = '\0';
- obj->initName(tokBuf);
- break;
-
- // array punctuation
- case '[':
- case ']':
- tokBuf[0] = c;
- tokBuf[1] = '\0';
- obj->initCmd(tokBuf);
- break;
-
- // hex string or dict punctuation
- case '<':
- c = lookChar();
-
- // dict punctuation
- if (c == '<') {
- getChar();
- tokBuf[0] = tokBuf[1] = '<';
- tokBuf[2] = '\0';
- obj->initCmd(tokBuf);
-
- // hex string
- } else {
- p = tokBuf;
- m = n = 0;
- c2 = 0;
- s = NULL;
- while (1) {
- c = getChar();
- if (c == '>') {
- break;
- } else if (c == EOF) {
- error(getPos(), "Unterminated hex string");
- break;
- } else if (specialChars[c] != 1) {
- c2 = c2 << 4;
- if (c >= '0' && c <= '9')
- c2 += c - '0';
- else if (c >= 'A' && c <= 'F')
- c2 += c - 'A' + 10;
- else if (c >= 'a' && c <= 'f')
- c2 += c - 'a' + 10;
- else
- error(getPos(), "Illegal character <%02x> in hex string", c);
- if (++m == 2) {
- if (n == tokBufSize) {
- if (!s)
- s = new GString(tokBuf, tokBufSize);
- else
- s->append(tokBuf, tokBufSize);
- p = tokBuf;
- n = 0;
- }
- *p++ = (char)c2;
- ++n;
- c2 = 0;
- m = 0;
- }
- }
- }
- if (!s)
- s = new GString(tokBuf, n);
- else
- s->append(tokBuf, n);
- if (m == 1)
- s->append((char)(c2 << 4));
- obj->initString(s);
- }
- break;
-
- // dict punctuation
- case '>':
- c = lookChar();
- if (c == '>') {
- getChar();
- tokBuf[0] = tokBuf[1] = '>';
- tokBuf[2] = '\0';
- obj->initCmd(tokBuf);
- } else {
- error(getPos(), "Illegal character '>'");
- obj->initError();
- }
- break;
-
- // error
- case ')':
- case '{':
- case '}':
- error(getPos(), "Illegal character '%c'", c);
- obj->initError();
- break;
-
- // command
- default:
- p = tokBuf;
- *p++ = c;
- n = 1;
- while ((c = lookChar()) != EOF && !specialChars[c]) {
- getChar();
- if (++n == tokBufSize) {
- error(getPos(), "Command token too long");
- break;
- }
- *p++ = c;
- }
- *p = '\0';
- if (tokBuf[0] == 't' && !strcmp(tokBuf, "true")) {
- obj->initBool(gTrue);
- } else if (tokBuf[0] == 'f' && !strcmp(tokBuf, "false")) {
- obj->initBool(gFalse);
- } else if (tokBuf[0] == 'n' && !strcmp(tokBuf, "null")) {
- obj->initNull();
- } else {
- obj->initCmd(tokBuf);
- }
- break;
- }
-
- return obj;
-}
-
-void Lexer::skipToNextLine() {
- int c;
-
- while (1) {
- c = getChar();
- if (c == EOF || c == '\n') {
- return;
- }
- if (c == '\r') {
- if ((c = lookChar()) == '\n') {
- getChar();
- }
- return;
- }
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Lexer.cpp b/filters/kword/pdf/xpdf/xpdf/Lexer.cpp
new file mode 100644
index 000000000..2d588814c
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Lexer.cpp
@@ -0,0 +1,474 @@
+//========================================================================
+//
+// Lexer.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <ctype.h>
+#include "Lexer.h"
+#include "Error.h"
+
+//------------------------------------------------------------------------
+
+// A '1' in this array means the character is white space. A '1' or
+// '2' means the character ends a name or command.
+static char specialChars[256] = {
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
+ 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
+};
+
+//------------------------------------------------------------------------
+// Lexer
+//------------------------------------------------------------------------
+
+Lexer::Lexer(XRef *xref, Stream *str) {
+ Object obj;
+
+ curStr.initStream(str);
+ streams = new Array(xref);
+ streams->add(curStr.copy(&obj));
+ strPtr = 0;
+ freeArray = gTrue;
+ curStr.streamReset();
+}
+
+Lexer::Lexer(XRef *xref, Object *obj) {
+ Object obj2;
+
+ if (obj->isStream()) {
+ streams = new Array(xref);
+ freeArray = gTrue;
+ streams->add(obj->copy(&obj2));
+ } else {
+ streams = obj->getArray();
+ freeArray = gFalse;
+ }
+ strPtr = 0;
+ if (streams->getLength() > 0) {
+ streams->get(strPtr, &curStr);
+ curStr.streamReset();
+ }
+}
+
+Lexer::~Lexer() {
+ if (!curStr.isNone()) {
+ curStr.streamClose();
+ curStr.free();
+ }
+ if (freeArray) {
+ delete streams;
+ }
+}
+
+int Lexer::getChar() {
+ int c;
+
+ c = EOF;
+ while (!curStr.isNone() && (c = curStr.streamGetChar()) == EOF) {
+ curStr.streamClose();
+ curStr.free();
+ ++strPtr;
+ if (strPtr < streams->getLength()) {
+ streams->get(strPtr, &curStr);
+ curStr.streamReset();
+ }
+ }
+ return c;
+}
+
+int Lexer::lookChar() {
+ if (curStr.isNone()) {
+ return EOF;
+ }
+ return curStr.streamLookChar();
+}
+
+Object *Lexer::getObj(Object *obj) {
+ char *p;
+ int c, c2;
+ GBool comment, neg, done;
+ int numParen;
+ int xi;
+ double xf, scale;
+ GString *s;
+ int n, m;
+
+ // skip whitespace and comments
+ comment = gFalse;
+ while (1) {
+ if ((c = getChar()) == EOF) {
+ return obj->initEOF();
+ }
+ if (comment) {
+ if (c == '\r' || c == '\n')
+ comment = gFalse;
+ } else if (c == '%') {
+ comment = gTrue;
+ } else if (specialChars[c] != 1) {
+ break;
+ }
+ }
+
+ // start reading token
+ switch (c) {
+
+ // number
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ case '-': case '.':
+ neg = gFalse;
+ xi = 0;
+ if (c == '-') {
+ neg = gTrue;
+ } else if (c == '.') {
+ goto doReal;
+ } else {
+ xi = c - '0';
+ }
+ while (1) {
+ c = lookChar();
+ if (isdigit(c)) {
+ getChar();
+ xi = xi * 10 + (c - '0');
+ } else if (c == '.') {
+ getChar();
+ goto doReal;
+ } else {
+ break;
+ }
+ }
+ if (neg)
+ xi = -xi;
+ obj->initInt(xi);
+ break;
+ doReal:
+ xf = xi;
+ scale = 0.1;
+ while (1) {
+ c = lookChar();
+ if (!isdigit(c)) {
+ break;
+ }
+ getChar();
+ xf = xf + scale * (c - '0');
+ scale *= 0.1;
+ }
+ if (neg)
+ xf = -xf;
+ obj->initReal(xf);
+ break;
+
+ // string
+ case '(':
+ p = tokBuf;
+ n = 0;
+ numParen = 1;
+ done = gFalse;
+ s = NULL;
+ do {
+ c2 = EOF;
+ switch (c = getChar()) {
+
+ case EOF:
+#if 0
+ // This breaks some PDF files, e.g., ones from Photoshop.
+ case '\r':
+ case '\n':
+#endif
+ error(getPos(), "Unterminated string");
+ done = gTrue;
+ break;
+
+ case '(':
+ ++numParen;
+ c2 = c;
+ break;
+
+ case ')':
+ if (--numParen == 0) {
+ done = gTrue;
+ } else {
+ c2 = c;
+ }
+ break;
+
+ case '\\':
+ switch (c = getChar()) {
+ case 'n':
+ c2 = '\n';
+ break;
+ case 'r':
+ c2 = '\r';
+ break;
+ case 't':
+ c2 = '\t';
+ break;
+ case 'b':
+ c2 = '\b';
+ break;
+ case 'f':
+ c2 = '\f';
+ break;
+ case '\\':
+ case '(':
+ case ')':
+ c2 = c;
+ break;
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ c2 = c - '0';
+ c = lookChar();
+ if (c >= '0' && c <= '7') {
+ getChar();
+ c2 = (c2 << 3) + (c - '0');
+ c = lookChar();
+ if (c >= '0' && c <= '7') {
+ getChar();
+ c2 = (c2 << 3) + (c - '0');
+ }
+ }
+ break;
+ case '\r':
+ c = lookChar();
+ if (c == '\n') {
+ getChar();
+ }
+ break;
+ case '\n':
+ break;
+ case EOF:
+ error(getPos(), "Unterminated string");
+ done = gTrue;
+ break;
+ default:
+ c2 = c;
+ break;
+ }
+ break;
+
+ default:
+ c2 = c;
+ break;
+ }
+
+ if (c2 != EOF) {
+ if (n == tokBufSize) {
+ if (!s)
+ s = new GString(tokBuf, tokBufSize);
+ else
+ s->append(tokBuf, tokBufSize);
+ p = tokBuf;
+ n = 0;
+ }
+ *p++ = (char)c2;
+ ++n;
+ }
+ } while (!done);
+ if (!s)
+ s = new GString(tokBuf, n);
+ else
+ s->append(tokBuf, n);
+ obj->initString(s);
+ break;
+
+ // name
+ case '/':
+ p = tokBuf;
+ n = 0;
+ while ((c = lookChar()) != EOF && !specialChars[c]) {
+ getChar();
+ if (c == '#') {
+ c2 = lookChar();
+ if (c2 >= '0' && c2 <= '9') {
+ c = c2 - '0';
+ } else if (c2 >= 'A' && c2 <= 'F') {
+ c = c2 - 'A' + 10;
+ } else if (c2 >= 'a' && c2 <= 'f') {
+ c = c2 - 'a' + 10;
+ } else {
+ goto notEscChar;
+ }
+ getChar();
+ c <<= 4;
+ c2 = getChar();
+ if (c2 >= '0' && c2 <= '9') {
+ c += c2 - '0';
+ } else if (c2 >= 'A' && c2 <= 'F') {
+ c += c2 - 'A' + 10;
+ } else if (c2 >= 'a' && c2 <= 'f') {
+ c += c2 - 'a' + 10;
+ } else {
+ error(getPos(), "Illegal digit in hex char in name");
+ }
+ }
+ notEscChar:
+ if (++n == tokBufSize) {
+ error(getPos(), "Name token too long");
+ break;
+ }
+ *p++ = c;
+ }
+ *p = '\0';
+ obj->initName(tokBuf);
+ break;
+
+ // array punctuation
+ case '[':
+ case ']':
+ tokBuf[0] = c;
+ tokBuf[1] = '\0';
+ obj->initCmd(tokBuf);
+ break;
+
+ // hex string or dict punctuation
+ case '<':
+ c = lookChar();
+
+ // dict punctuation
+ if (c == '<') {
+ getChar();
+ tokBuf[0] = tokBuf[1] = '<';
+ tokBuf[2] = '\0';
+ obj->initCmd(tokBuf);
+
+ // hex string
+ } else {
+ p = tokBuf;
+ m = n = 0;
+ c2 = 0;
+ s = NULL;
+ while (1) {
+ c = getChar();
+ if (c == '>') {
+ break;
+ } else if (c == EOF) {
+ error(getPos(), "Unterminated hex string");
+ break;
+ } else if (specialChars[c] != 1) {
+ c2 = c2 << 4;
+ if (c >= '0' && c <= '9')
+ c2 += c - '0';
+ else if (c >= 'A' && c <= 'F')
+ c2 += c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ c2 += c - 'a' + 10;
+ else
+ error(getPos(), "Illegal character <%02x> in hex string", c);
+ if (++m == 2) {
+ if (n == tokBufSize) {
+ if (!s)
+ s = new GString(tokBuf, tokBufSize);
+ else
+ s->append(tokBuf, tokBufSize);
+ p = tokBuf;
+ n = 0;
+ }
+ *p++ = (char)c2;
+ ++n;
+ c2 = 0;
+ m = 0;
+ }
+ }
+ }
+ if (!s)
+ s = new GString(tokBuf, n);
+ else
+ s->append(tokBuf, n);
+ if (m == 1)
+ s->append((char)(c2 << 4));
+ obj->initString(s);
+ }
+ break;
+
+ // dict punctuation
+ case '>':
+ c = lookChar();
+ if (c == '>') {
+ getChar();
+ tokBuf[0] = tokBuf[1] = '>';
+ tokBuf[2] = '\0';
+ obj->initCmd(tokBuf);
+ } else {
+ error(getPos(), "Illegal character '>'");
+ obj->initError();
+ }
+ break;
+
+ // error
+ case ')':
+ case '{':
+ case '}':
+ error(getPos(), "Illegal character '%c'", c);
+ obj->initError();
+ break;
+
+ // command
+ default:
+ p = tokBuf;
+ *p++ = c;
+ n = 1;
+ while ((c = lookChar()) != EOF && !specialChars[c]) {
+ getChar();
+ if (++n == tokBufSize) {
+ error(getPos(), "Command token too long");
+ break;
+ }
+ *p++ = c;
+ }
+ *p = '\0';
+ if (tokBuf[0] == 't' && !strcmp(tokBuf, "true")) {
+ obj->initBool(gTrue);
+ } else if (tokBuf[0] == 'f' && !strcmp(tokBuf, "false")) {
+ obj->initBool(gFalse);
+ } else if (tokBuf[0] == 'n' && !strcmp(tokBuf, "null")) {
+ obj->initNull();
+ } else {
+ obj->initCmd(tokBuf);
+ }
+ break;
+ }
+
+ return obj;
+}
+
+void Lexer::skipToNextLine() {
+ int c;
+
+ while (1) {
+ c = getChar();
+ if (c == EOF || c == '\n') {
+ return;
+ }
+ if (c == '\r') {
+ if ((c = lookChar()) == '\n') {
+ getChar();
+ }
+ return;
+ }
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Link.cc b/filters/kword/pdf/xpdf/xpdf/Link.cc
deleted file mode 100644
index 345e7296a..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Link.cc
+++ /dev/null
@@ -1,735 +0,0 @@
-//========================================================================
-//
-// Link.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include <string.h>
-#include "gmem.h"
-#include "GString.h"
-#include "Error.h"
-#include "Object.h"
-#include "Array.h"
-#include "Dict.h"
-#include "Link.h"
-
-//------------------------------------------------------------------------
-// LinkAction
-//------------------------------------------------------------------------
-
-LinkAction *LinkAction::parseDest(Object *obj) {
- LinkAction *action;
-
- action = new LinkGoTo(obj);
- if (!action->isOk()) {
- delete action;
- return NULL;
- }
- return action;
-}
-
-LinkAction *LinkAction::parseAction(Object *obj, GString *baseURI) {
- LinkAction *action;
- Object obj2, obj3, obj4;
-
- if (!obj->isDict()) {
- error(-1, "Bad annotation action");
- return NULL;
- }
-
- obj->dictLookup("S", &obj2);
-
- // GoTo action
- if (obj2.isName("GoTo")) {
- obj->dictLookup("D", &obj3);
- action = new LinkGoTo(&obj3);
- obj3.free();
-
- // GoToR action
- } else if (obj2.isName("GoToR")) {
- obj->dictLookup("F", &obj3);
- obj->dictLookup("D", &obj4);
- action = new LinkGoToR(&obj3, &obj4);
- obj3.free();
- obj4.free();
-
- // Launch action
- } else if (obj2.isName("Launch")) {
- action = new LinkLaunch(obj);
-
- // URI action
- } else if (obj2.isName("URI")) {
- obj->dictLookup("URI", &obj3);
- action = new LinkURI(&obj3, baseURI);
- obj3.free();
-
- // Named action
- } else if (obj2.isName("Named")) {
- obj->dictLookup("N", &obj3);
- action = new LinkNamed(&obj3);
- obj3.free();
-
- // Movie action
- } else if (obj2.isName("Movie")) {
- obj->dictLookupNF("Annot", &obj3);
- obj->dictLookup("T", &obj4);
- action = new LinkMovie(&obj3, &obj4);
- obj3.free();
- obj4.free();
-
- // unknown action
- } else if (obj2.isName()) {
- action = new LinkUnknown(obj2.getName());
-
- // action is missing or wrong type
- } else {
- error(-1, "Bad annotation action");
- action = NULL;
- }
-
- obj2.free();
-
- if (action && !action->isOk()) {
- delete action;
- return NULL;
- }
- return action;
-}
-
-GString *LinkAction::getFileSpecName(Object *fileSpecObj) {
- GString *name;
- Object obj1;
-
- name = NULL;
-
- // string
- if (fileSpecObj->isString()) {
- name = fileSpecObj->getString()->copy();
-
- // dictionary
- } else if (fileSpecObj->isDict()) {
- if (!fileSpecObj->dictLookup("Unix", &obj1)->isString()) {
- obj1.free();
- fileSpecObj->dictLookup("F", &obj1);
- }
- if (obj1.isString())
- name = obj1.getString()->copy();
- else
- error(-1, "Illegal file spec in link");
- obj1.free();
-
- // error
- } else {
- error(-1, "Illegal file spec in link");
- }
-
- return name;
-}
-
-//------------------------------------------------------------------------
-// LinkDest
-//------------------------------------------------------------------------
-
-LinkDest::LinkDest(Array *a) {
- Object obj1, obj2;
-
- // initialize fields
- left = bottom = right = top = zoom = 0;
- ok = gFalse;
-
- // get page
- if (a->getLength() < 2) {
- error(-1, "Annotation destination array has wrong length");
- return;
- }
- a->getNF(0, &obj1);
- if (obj1.isInt()) {
- pageNum = obj1.getInt() + 1;
- pageIsRef = gFalse;
- } else if (obj1.isRef()) {
- pageRef.num = obj1.getRefNum();
- pageRef.gen = obj1.getRefGen();
- pageIsRef = gTrue;
- } else {
- error(-1, "Bad annotation destination");
- goto err2;
- }
- obj1.free();
-
- // get destination type
- a->get(1, &obj1);
-
- // XYZ link
- if (obj1.isName("XYZ")) {
- if (a->getLength() != 5) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destXYZ;
- a->get(2, &obj2);
- if (obj2.isNull()) {
- changeLeft = gFalse;
- } else if (obj2.isNum()) {
- changeLeft = gTrue;
- left = obj2.getNum();
- } else {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- obj2.free();
- a->get(3, &obj2);
- if (obj2.isNull()) {
- changeTop = gFalse;
- } else if (obj2.isNum()) {
- changeTop = gTrue;
- top = obj2.getNum();
- } else {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- obj2.free();
- a->get(4, &obj2);
- if (obj2.isNull()) {
- changeZoom = gFalse;
- } else if (obj2.isNum()) {
- changeZoom = gTrue;
- zoom = obj2.getNum();
- } else {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- obj2.free();
-
- // Fit link
- } else if (obj1.isName("Fit")) {
- if (a->getLength() != 2) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFit;
-
- // FitH link
- } else if (obj1.isName("FitH")) {
- if (a->getLength() != 3) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitH;
- if (!a->get(2, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- top = obj2.getNum();
- obj2.free();
-
- // FitV link
- } else if (obj1.isName("FitV")) {
- if (a->getLength() != 3) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitV;
- if (!a->get(2, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- left = obj2.getNum();
- obj2.free();
-
- // FitR link
- } else if (obj1.isName("FitR")) {
- if (a->getLength() != 6) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitR;
- if (!a->get(2, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- left = obj2.getNum();
- obj2.free();
- if (!a->get(3, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- bottom = obj2.getNum();
- obj2.free();
- if (!a->get(4, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- right = obj2.getNum();
- obj2.free();
- if (!a->get(5, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- top = obj2.getNum();
- obj2.free();
-
- // FitB link
- } else if (obj1.isName("FitB")) {
- if (a->getLength() != 2) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitB;
-
- // FitBH link
- } else if (obj1.isName("FitBH")) {
- if (a->getLength() != 3) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitBH;
- if (!a->get(2, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- top = obj2.getNum();
- obj2.free();
-
- // FitBV link
- } else if (obj1.isName("FitBV")) {
- if (a->getLength() != 3) {
- error(-1, "Annotation destination array has wrong length");
- goto err2;
- }
- kind = destFitBV;
- if (!a->get(2, &obj2)->isNum()) {
- error(-1, "Bad annotation destination position");
- goto err1;
- }
- left = obj2.getNum();
- obj2.free();
-
- // unknown link kind
- } else {
- error(-1, "Unknown annotation destination type");
- goto err2;
- }
-
- obj1.free();
- ok = gTrue;
- return;
-
- err1:
- obj2.free();
- err2:
- obj1.free();
-}
-
-LinkDest::LinkDest(LinkDest *dest) {
- kind = dest->kind;
- pageIsRef = dest->pageIsRef;
- if (pageIsRef)
- pageRef = dest->pageRef;
- else
- pageNum = dest->pageNum;
- left = dest->left;
- bottom = dest->bottom;
- right = dest->right;
- top = dest->top;
- zoom = dest->zoom;
- changeLeft = dest->changeLeft;
- changeTop = dest->changeTop;
- changeZoom = dest->changeZoom;
- ok = gTrue;
-}
-
-//------------------------------------------------------------------------
-// LinkGoTo
-//------------------------------------------------------------------------
-
-LinkGoTo::LinkGoTo(Object *destObj) {
- dest = NULL;
- namedDest = NULL;
-
- // named destination
- if (destObj->isName()) {
- namedDest = new GString(destObj->getName());
- } else if (destObj->isString()) {
- namedDest = destObj->getString()->copy();
-
- // destination dictionary
- } else if (destObj->isArray()) {
- dest = new LinkDest(destObj->getArray());
- if (!dest->isOk()) {
- delete dest;
- dest = NULL;
- }
-
- // error
- } else {
- error(-1, "Illegal annotation destination");
- }
-}
-
-LinkGoTo::~LinkGoTo() {
- if (dest)
- delete dest;
- if (namedDest)
- delete namedDest;
-}
-
-//------------------------------------------------------------------------
-// LinkGoToR
-//------------------------------------------------------------------------
-
-LinkGoToR::LinkGoToR(Object *fileSpecObj, Object *destObj) {
- dest = NULL;
- namedDest = NULL;
-
- // get file name
- fileName = getFileSpecName(fileSpecObj);
-
- // named destination
- if (destObj->isName()) {
- namedDest = new GString(destObj->getName());
- } else if (destObj->isString()) {
- namedDest = destObj->getString()->copy();
-
- // destination dictionary
- } else if (destObj->isArray()) {
- dest = new LinkDest(destObj->getArray());
- if (!dest->isOk()) {
- delete dest;
- dest = NULL;
- }
-
- // error
- } else {
- error(-1, "Illegal annotation destination");
- }
-}
-
-LinkGoToR::~LinkGoToR() {
- if (fileName)
- delete fileName;
- if (dest)
- delete dest;
- if (namedDest)
- delete namedDest;
-}
-
-
-//------------------------------------------------------------------------
-// LinkLaunch
-//------------------------------------------------------------------------
-
-LinkLaunch::LinkLaunch(Object *actionObj) {
- Object obj1, obj2;
-
- fileName = NULL;
- params = NULL;
-
- if (actionObj->isDict()) {
- if (!actionObj->dictLookup("F", &obj1)->isNull()) {
- fileName = getFileSpecName(&obj1);
- } else {
- obj1.free();
-#ifdef WIN32
- if (actionObj->dictLookup("Win", &obj1)->isDict()) {
- obj1.dictLookup("F", &obj2);
- fileName = getFileSpecName(&obj2);
- obj2.free();
- if (obj1.dictLookup("P", &obj2)->isString()) {
- params = obj2.getString()->copy();
- }
- obj2.free();
- } else {
- error(-1, "Bad launch-type link action");
- }
-#else
- //~ This hasn't been defined by Adobe yet, so assume it looks
- //~ just like the Win dictionary until they say otherwise.
- if (actionObj->dictLookup("Unix", &obj1)->isDict()) {
- obj1.dictLookup("F", &obj2);
- fileName = getFileSpecName(&obj2);
- obj2.free();
- if (obj1.dictLookup("P", &obj2)->isString()) {
- params = obj2.getString()->copy();
- }
- obj2.free();
- } else {
- error(-1, "Bad launch-type link action");
- }
-#endif
- }
- obj1.free();
- }
-}
-
-LinkLaunch::~LinkLaunch() {
- if (fileName)
- delete fileName;
- if (params)
- delete params;
-}
-
-//------------------------------------------------------------------------
-// LinkURI
-//------------------------------------------------------------------------
-
-LinkURI::LinkURI(Object *uriObj, GString *baseURI) {
- GString *uri2;
- int n;
- char c;
-
- uri = NULL;
- if (uriObj->isString()) {
- uri2 = uriObj->getString()->copy();
- if (baseURI) {
- n = strcspn(uri2->getCString(), "/:");
- if (n == uri2->getLength() || uri2->getChar(n) == '/') {
- uri = baseURI->copy();
- c = uri->getChar(uri->getLength() - 1);
- if (c == '/' || c == '?') {
- if (uri2->getChar(0) == '/') {
- uri2->del(0);
- }
- } else {
- if (uri2->getChar(0) != '/') {
- uri->append('/');
- }
- }
- uri->append(uri2);
- delete uri2;
- } else {
- uri = uri2;
- }
- } else {
- uri = uri2;
- }
- } else {
- error(-1, "Illegal URI-type link");
- }
-}
-
-LinkURI::~LinkURI() {
- if (uri)
- delete uri;
-}
-
-//------------------------------------------------------------------------
-// LinkNamed
-//------------------------------------------------------------------------
-
-LinkNamed::LinkNamed(Object *nameObj) {
- name = NULL;
- if (nameObj->isName()) {
- name = new GString(nameObj->getName());
- }
-}
-
-LinkNamed::~LinkNamed() {
- if (name) {
- delete name;
- }
-}
-
-//------------------------------------------------------------------------
-// LinkMovie
-//------------------------------------------------------------------------
-
-LinkMovie::LinkMovie(Object *annotObj, Object *titleObj) {
- annotRef.num = -1;
- title = NULL;
- if (annotObj->isRef()) {
- annotRef = annotObj->getRef();
- } else if (titleObj->isString()) {
- title = titleObj->getString()->copy();
- } else {
- error(-1, "Movie action is missing both the Annot and T keys");
- }
-}
-
-LinkMovie::~LinkMovie() {
- if (title) {
- delete title;
- }
-}
-
-//------------------------------------------------------------------------
-// LinkUnknown
-//------------------------------------------------------------------------
-
-LinkUnknown::LinkUnknown(char *actionA) {
- action = new GString(actionA);
-}
-
-LinkUnknown::~LinkUnknown() {
- delete action;
-}
-
-//------------------------------------------------------------------------
-// Link
-//------------------------------------------------------------------------
-
-Link::Link(Dict *dict, GString *baseURI) {
- Object obj1, obj2;
- double t;
-
- action = NULL;
- ok = gFalse;
-
- // get rectangle
- if (!dict->lookup("Rect", &obj1)->isArray()) {
- error(-1, "Annotation rectangle is wrong type");
- goto err2;
- }
- if (!obj1.arrayGet(0, &obj2)->isNum()) {
- error(-1, "Bad annotation rectangle");
- goto err1;
- }
- x1 = obj2.getNum();
- obj2.free();
- if (!obj1.arrayGet(1, &obj2)->isNum()) {
- error(-1, "Bad annotation rectangle");
- goto err1;
- }
- y1 = obj2.getNum();
- obj2.free();
- if (!obj1.arrayGet(2, &obj2)->isNum()) {
- error(-1, "Bad annotation rectangle");
- goto err1;
- }
- x2 = obj2.getNum();
- obj2.free();
- if (!obj1.arrayGet(3, &obj2)->isNum()) {
- error(-1, "Bad annotation rectangle");
- goto err1;
- }
- y2 = obj2.getNum();
- obj2.free();
- obj1.free();
- if (x1 > x2) {
- t = x1;
- x1 = x2;
- x2 = t;
- }
- if (y1 > y2) {
- t = y1;
- y1 = y2;
- y2 = t;
- }
-
- // get border
- borderW = 1;
- if (!dict->lookup("Border", &obj1)->isNull()) {
- if (obj1.isArray() && obj1.arrayGetLength() >= 3) {
- if (obj1.arrayGet(2, &obj2)->isNum()) {
- borderW = obj2.getNum();
- } else {
- error(-1, "Bad annotation border");
- }
- obj2.free();
- }
- }
- obj1.free();
-
- // look for destination
- if (!dict->lookup("Dest", &obj1)->isNull()) {
- action = LinkAction::parseDest(&obj1);
-
- // look for action
- } else {
- obj1.free();
- if (dict->lookup("A", &obj1)->isDict()) {
- action = LinkAction::parseAction(&obj1, baseURI);
- }
- }
- obj1.free();
-
- // check for bad action
- if (action) {
- ok = gTrue;
- }
-
- return;
-
- err1:
- obj2.free();
- err2:
- obj1.free();
-}
-
-Link::~Link() {
- if (action)
- delete action;
-}
-
-//------------------------------------------------------------------------
-// Links
-//------------------------------------------------------------------------
-
-Links::Links(Object *annots, GString *baseURI) {
- Link *link;
- Object obj1, obj2;
- int size;
- int i;
-
- links = NULL;
- size = 0;
- numLinks = 0;
-
- if (annots->isArray()) {
- for (i = 0; i < annots->arrayGetLength(); ++i) {
- if (annots->arrayGet(i, &obj1)->isDict()) {
- if (obj1.dictLookup("Subtype", &obj2)->isName("Link")) {
- link = new Link(obj1.getDict(), baseURI);
- if (link->isOk()) {
- if (numLinks >= size) {
- size += 16;
- links = (Link **)grealloc(links, size * sizeof(Link *));
- }
- links[numLinks++] = link;
- } else {
- delete link;
- }
- }
- obj2.free();
- }
- obj1.free();
- }
- }
-}
-
-Links::~Links() {
- int i;
-
- for (i = 0; i < numLinks; ++i)
- delete links[i];
- gfree(links);
-}
-
-LinkAction *Links::find(double x, double y) {
- int i;
-
- for (i = numLinks - 1; i >= 0; --i) {
- if (links[i]->inRect(x, y)) {
- return links[i]->getAction();
- }
- }
- return NULL;
-}
-
-GBool Links::onLink(double x, double y) {
- int i;
-
- for (i = 0; i < numLinks; ++i) {
- if (links[i]->inRect(x, y))
- return gTrue;
- }
- return gFalse;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Link.cpp b/filters/kword/pdf/xpdf/xpdf/Link.cpp
new file mode 100644
index 000000000..45805d20d
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Link.cpp
@@ -0,0 +1,735 @@
+//========================================================================
+//
+// Link.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include <string.h>
+#include "gmem.h"
+#include "GString.h"
+#include "Error.h"
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Link.h"
+
+//------------------------------------------------------------------------
+// LinkAction
+//------------------------------------------------------------------------
+
+LinkAction *LinkAction::parseDest(Object *obj) {
+ LinkAction *action;
+
+ action = new LinkGoTo(obj);
+ if (!action->isOk()) {
+ delete action;
+ return NULL;
+ }
+ return action;
+}
+
+LinkAction *LinkAction::parseAction(Object *obj, GString *baseURI) {
+ LinkAction *action;
+ Object obj2, obj3, obj4;
+
+ if (!obj->isDict()) {
+ error(-1, "Bad annotation action");
+ return NULL;
+ }
+
+ obj->dictLookup("S", &obj2);
+
+ // GoTo action
+ if (obj2.isName("GoTo")) {
+ obj->dictLookup("D", &obj3);
+ action = new LinkGoTo(&obj3);
+ obj3.free();
+
+ // GoToR action
+ } else if (obj2.isName("GoToR")) {
+ obj->dictLookup("F", &obj3);
+ obj->dictLookup("D", &obj4);
+ action = new LinkGoToR(&obj3, &obj4);
+ obj3.free();
+ obj4.free();
+
+ // Launch action
+ } else if (obj2.isName("Launch")) {
+ action = new LinkLaunch(obj);
+
+ // URI action
+ } else if (obj2.isName("URI")) {
+ obj->dictLookup("URI", &obj3);
+ action = new LinkURI(&obj3, baseURI);
+ obj3.free();
+
+ // Named action
+ } else if (obj2.isName("Named")) {
+ obj->dictLookup("N", &obj3);
+ action = new LinkNamed(&obj3);
+ obj3.free();
+
+ // Movie action
+ } else if (obj2.isName("Movie")) {
+ obj->dictLookupNF("Annot", &obj3);
+ obj->dictLookup("T", &obj4);
+ action = new LinkMovie(&obj3, &obj4);
+ obj3.free();
+ obj4.free();
+
+ // unknown action
+ } else if (obj2.isName()) {
+ action = new LinkUnknown(obj2.getName());
+
+ // action is missing or wrong type
+ } else {
+ error(-1, "Bad annotation action");
+ action = NULL;
+ }
+
+ obj2.free();
+
+ if (action && !action->isOk()) {
+ delete action;
+ return NULL;
+ }
+ return action;
+}
+
+GString *LinkAction::getFileSpecName(Object *fileSpecObj) {
+ GString *name;
+ Object obj1;
+
+ name = NULL;
+
+ // string
+ if (fileSpecObj->isString()) {
+ name = fileSpecObj->getString()->copy();
+
+ // dictionary
+ } else if (fileSpecObj->isDict()) {
+ if (!fileSpecObj->dictLookup("Unix", &obj1)->isString()) {
+ obj1.free();
+ fileSpecObj->dictLookup("F", &obj1);
+ }
+ if (obj1.isString())
+ name = obj1.getString()->copy();
+ else
+ error(-1, "Illegal file spec in link");
+ obj1.free();
+
+ // error
+ } else {
+ error(-1, "Illegal file spec in link");
+ }
+
+ return name;
+}
+
+//------------------------------------------------------------------------
+// LinkDest
+//------------------------------------------------------------------------
+
+LinkDest::LinkDest(Array *a) {
+ Object obj1, obj2;
+
+ // initialize fields
+ left = bottom = right = top = zoom = 0;
+ ok = gFalse;
+
+ // get page
+ if (a->getLength() < 2) {
+ error(-1, "Annotation destination array has wrong length");
+ return;
+ }
+ a->getNF(0, &obj1);
+ if (obj1.isInt()) {
+ pageNum = obj1.getInt() + 1;
+ pageIsRef = gFalse;
+ } else if (obj1.isRef()) {
+ pageRef.num = obj1.getRefNum();
+ pageRef.gen = obj1.getRefGen();
+ pageIsRef = gTrue;
+ } else {
+ error(-1, "Bad annotation destination");
+ goto err2;
+ }
+ obj1.free();
+
+ // get destination type
+ a->get(1, &obj1);
+
+ // XYZ link
+ if (obj1.isName("XYZ")) {
+ if (a->getLength() != 5) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destXYZ;
+ a->get(2, &obj2);
+ if (obj2.isNull()) {
+ changeLeft = gFalse;
+ } else if (obj2.isNum()) {
+ changeLeft = gTrue;
+ left = obj2.getNum();
+ } else {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ obj2.free();
+ a->get(3, &obj2);
+ if (obj2.isNull()) {
+ changeTop = gFalse;
+ } else if (obj2.isNum()) {
+ changeTop = gTrue;
+ top = obj2.getNum();
+ } else {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ obj2.free();
+ a->get(4, &obj2);
+ if (obj2.isNull()) {
+ changeZoom = gFalse;
+ } else if (obj2.isNum()) {
+ changeZoom = gTrue;
+ zoom = obj2.getNum();
+ } else {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ obj2.free();
+
+ // Fit link
+ } else if (obj1.isName("Fit")) {
+ if (a->getLength() != 2) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFit;
+
+ // FitH link
+ } else if (obj1.isName("FitH")) {
+ if (a->getLength() != 3) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitH;
+ if (!a->get(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ top = obj2.getNum();
+ obj2.free();
+
+ // FitV link
+ } else if (obj1.isName("FitV")) {
+ if (a->getLength() != 3) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitV;
+ if (!a->get(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ left = obj2.getNum();
+ obj2.free();
+
+ // FitR link
+ } else if (obj1.isName("FitR")) {
+ if (a->getLength() != 6) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitR;
+ if (!a->get(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ left = obj2.getNum();
+ obj2.free();
+ if (!a->get(3, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ bottom = obj2.getNum();
+ obj2.free();
+ if (!a->get(4, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ right = obj2.getNum();
+ obj2.free();
+ if (!a->get(5, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ top = obj2.getNum();
+ obj2.free();
+
+ // FitB link
+ } else if (obj1.isName("FitB")) {
+ if (a->getLength() != 2) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitB;
+
+ // FitBH link
+ } else if (obj1.isName("FitBH")) {
+ if (a->getLength() != 3) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitBH;
+ if (!a->get(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ top = obj2.getNum();
+ obj2.free();
+
+ // FitBV link
+ } else if (obj1.isName("FitBV")) {
+ if (a->getLength() != 3) {
+ error(-1, "Annotation destination array has wrong length");
+ goto err2;
+ }
+ kind = destFitBV;
+ if (!a->get(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation destination position");
+ goto err1;
+ }
+ left = obj2.getNum();
+ obj2.free();
+
+ // unknown link kind
+ } else {
+ error(-1, "Unknown annotation destination type");
+ goto err2;
+ }
+
+ obj1.free();
+ ok = gTrue;
+ return;
+
+ err1:
+ obj2.free();
+ err2:
+ obj1.free();
+}
+
+LinkDest::LinkDest(LinkDest *dest) {
+ kind = dest->kind;
+ pageIsRef = dest->pageIsRef;
+ if (pageIsRef)
+ pageRef = dest->pageRef;
+ else
+ pageNum = dest->pageNum;
+ left = dest->left;
+ bottom = dest->bottom;
+ right = dest->right;
+ top = dest->top;
+ zoom = dest->zoom;
+ changeLeft = dest->changeLeft;
+ changeTop = dest->changeTop;
+ changeZoom = dest->changeZoom;
+ ok = gTrue;
+}
+
+//------------------------------------------------------------------------
+// LinkGoTo
+//------------------------------------------------------------------------
+
+LinkGoTo::LinkGoTo(Object *destObj) {
+ dest = NULL;
+ namedDest = NULL;
+
+ // named destination
+ if (destObj->isName()) {
+ namedDest = new GString(destObj->getName());
+ } else if (destObj->isString()) {
+ namedDest = destObj->getString()->copy();
+
+ // destination dictionary
+ } else if (destObj->isArray()) {
+ dest = new LinkDest(destObj->getArray());
+ if (!dest->isOk()) {
+ delete dest;
+ dest = NULL;
+ }
+
+ // error
+ } else {
+ error(-1, "Illegal annotation destination");
+ }
+}
+
+LinkGoTo::~LinkGoTo() {
+ if (dest)
+ delete dest;
+ if (namedDest)
+ delete namedDest;
+}
+
+//------------------------------------------------------------------------
+// LinkGoToR
+//------------------------------------------------------------------------
+
+LinkGoToR::LinkGoToR(Object *fileSpecObj, Object *destObj) {
+ dest = NULL;
+ namedDest = NULL;
+
+ // get file name
+ fileName = getFileSpecName(fileSpecObj);
+
+ // named destination
+ if (destObj->isName()) {
+ namedDest = new GString(destObj->getName());
+ } else if (destObj->isString()) {
+ namedDest = destObj->getString()->copy();
+
+ // destination dictionary
+ } else if (destObj->isArray()) {
+ dest = new LinkDest(destObj->getArray());
+ if (!dest->isOk()) {
+ delete dest;
+ dest = NULL;
+ }
+
+ // error
+ } else {
+ error(-1, "Illegal annotation destination");
+ }
+}
+
+LinkGoToR::~LinkGoToR() {
+ if (fileName)
+ delete fileName;
+ if (dest)
+ delete dest;
+ if (namedDest)
+ delete namedDest;
+}
+
+
+//------------------------------------------------------------------------
+// LinkLaunch
+//------------------------------------------------------------------------
+
+LinkLaunch::LinkLaunch(Object *actionObj) {
+ Object obj1, obj2;
+
+ fileName = NULL;
+ params = NULL;
+
+ if (actionObj->isDict()) {
+ if (!actionObj->dictLookup("F", &obj1)->isNull()) {
+ fileName = getFileSpecName(&obj1);
+ } else {
+ obj1.free();
+#ifdef WIN32
+ if (actionObj->dictLookup("Win", &obj1)->isDict()) {
+ obj1.dictLookup("F", &obj2);
+ fileName = getFileSpecName(&obj2);
+ obj2.free();
+ if (obj1.dictLookup("P", &obj2)->isString()) {
+ params = obj2.getString()->copy();
+ }
+ obj2.free();
+ } else {
+ error(-1, "Bad launch-type link action");
+ }
+#else
+ //~ This hasn't been defined by Adobe yet, so assume it looks
+ //~ just like the Win dictionary until they say otherwise.
+ if (actionObj->dictLookup("Unix", &obj1)->isDict()) {
+ obj1.dictLookup("F", &obj2);
+ fileName = getFileSpecName(&obj2);
+ obj2.free();
+ if (obj1.dictLookup("P", &obj2)->isString()) {
+ params = obj2.getString()->copy();
+ }
+ obj2.free();
+ } else {
+ error(-1, "Bad launch-type link action");
+ }
+#endif
+ }
+ obj1.free();
+ }
+}
+
+LinkLaunch::~LinkLaunch() {
+ if (fileName)
+ delete fileName;
+ if (params)
+ delete params;
+}
+
+//------------------------------------------------------------------------
+// LinkURI
+//------------------------------------------------------------------------
+
+LinkURI::LinkURI(Object *uriObj, GString *baseURI) {
+ GString *uri2;
+ int n;
+ char c;
+
+ uri = NULL;
+ if (uriObj->isString()) {
+ uri2 = uriObj->getString()->copy();
+ if (baseURI) {
+ n = strcspn(uri2->getCString(), "/:");
+ if (n == uri2->getLength() || uri2->getChar(n) == '/') {
+ uri = baseURI->copy();
+ c = uri->getChar(uri->getLength() - 1);
+ if (c == '/' || c == '?') {
+ if (uri2->getChar(0) == '/') {
+ uri2->del(0);
+ }
+ } else {
+ if (uri2->getChar(0) != '/') {
+ uri->append('/');
+ }
+ }
+ uri->append(uri2);
+ delete uri2;
+ } else {
+ uri = uri2;
+ }
+ } else {
+ uri = uri2;
+ }
+ } else {
+ error(-1, "Illegal URI-type link");
+ }
+}
+
+LinkURI::~LinkURI() {
+ if (uri)
+ delete uri;
+}
+
+//------------------------------------------------------------------------
+// LinkNamed
+//------------------------------------------------------------------------
+
+LinkNamed::LinkNamed(Object *nameObj) {
+ name = NULL;
+ if (nameObj->isName()) {
+ name = new GString(nameObj->getName());
+ }
+}
+
+LinkNamed::~LinkNamed() {
+ if (name) {
+ delete name;
+ }
+}
+
+//------------------------------------------------------------------------
+// LinkMovie
+//------------------------------------------------------------------------
+
+LinkMovie::LinkMovie(Object *annotObj, Object *titleObj) {
+ annotRef.num = -1;
+ title = NULL;
+ if (annotObj->isRef()) {
+ annotRef = annotObj->getRef();
+ } else if (titleObj->isString()) {
+ title = titleObj->getString()->copy();
+ } else {
+ error(-1, "Movie action is missing both the Annot and T keys");
+ }
+}
+
+LinkMovie::~LinkMovie() {
+ if (title) {
+ delete title;
+ }
+}
+
+//------------------------------------------------------------------------
+// LinkUnknown
+//------------------------------------------------------------------------
+
+LinkUnknown::LinkUnknown(char *actionA) {
+ action = new GString(actionA);
+}
+
+LinkUnknown::~LinkUnknown() {
+ delete action;
+}
+
+//------------------------------------------------------------------------
+// Link
+//------------------------------------------------------------------------
+
+Link::Link(Dict *dict, GString *baseURI) {
+ Object obj1, obj2;
+ double t;
+
+ action = NULL;
+ ok = gFalse;
+
+ // get rectangle
+ if (!dict->lookup("Rect", &obj1)->isArray()) {
+ error(-1, "Annotation rectangle is wrong type");
+ goto err2;
+ }
+ if (!obj1.arrayGet(0, &obj2)->isNum()) {
+ error(-1, "Bad annotation rectangle");
+ goto err1;
+ }
+ x1 = obj2.getNum();
+ obj2.free();
+ if (!obj1.arrayGet(1, &obj2)->isNum()) {
+ error(-1, "Bad annotation rectangle");
+ goto err1;
+ }
+ y1 = obj2.getNum();
+ obj2.free();
+ if (!obj1.arrayGet(2, &obj2)->isNum()) {
+ error(-1, "Bad annotation rectangle");
+ goto err1;
+ }
+ x2 = obj2.getNum();
+ obj2.free();
+ if (!obj1.arrayGet(3, &obj2)->isNum()) {
+ error(-1, "Bad annotation rectangle");
+ goto err1;
+ }
+ y2 = obj2.getNum();
+ obj2.free();
+ obj1.free();
+ if (x1 > x2) {
+ t = x1;
+ x1 = x2;
+ x2 = t;
+ }
+ if (y1 > y2) {
+ t = y1;
+ y1 = y2;
+ y2 = t;
+ }
+
+ // get border
+ borderW = 1;
+ if (!dict->lookup("Border", &obj1)->isNull()) {
+ if (obj1.isArray() && obj1.arrayGetLength() >= 3) {
+ if (obj1.arrayGet(2, &obj2)->isNum()) {
+ borderW = obj2.getNum();
+ } else {
+ error(-1, "Bad annotation border");
+ }
+ obj2.free();
+ }
+ }
+ obj1.free();
+
+ // look for destination
+ if (!dict->lookup("Dest", &obj1)->isNull()) {
+ action = LinkAction::parseDest(&obj1);
+
+ // look for action
+ } else {
+ obj1.free();
+ if (dict->lookup("A", &obj1)->isDict()) {
+ action = LinkAction::parseAction(&obj1, baseURI);
+ }
+ }
+ obj1.free();
+
+ // check for bad action
+ if (action) {
+ ok = gTrue;
+ }
+
+ return;
+
+ err1:
+ obj2.free();
+ err2:
+ obj1.free();
+}
+
+Link::~Link() {
+ if (action)
+ delete action;
+}
+
+//------------------------------------------------------------------------
+// Links
+//------------------------------------------------------------------------
+
+Links::Links(Object *annots, GString *baseURI) {
+ Link *link;
+ Object obj1, obj2;
+ int size;
+ int i;
+
+ links = NULL;
+ size = 0;
+ numLinks = 0;
+
+ if (annots->isArray()) {
+ for (i = 0; i < annots->arrayGetLength(); ++i) {
+ if (annots->arrayGet(i, &obj1)->isDict()) {
+ if (obj1.dictLookup("Subtype", &obj2)->isName("Link")) {
+ link = new Link(obj1.getDict(), baseURI);
+ if (link->isOk()) {
+ if (numLinks >= size) {
+ size += 16;
+ links = (Link **)grealloc(links, size * sizeof(Link *));
+ }
+ links[numLinks++] = link;
+ } else {
+ delete link;
+ }
+ }
+ obj2.free();
+ }
+ obj1.free();
+ }
+ }
+}
+
+Links::~Links() {
+ int i;
+
+ for (i = 0; i < numLinks; ++i)
+ delete links[i];
+ gfree(links);
+}
+
+LinkAction *Links::find(double x, double y) {
+ int i;
+
+ for (i = numLinks - 1; i >= 0; --i) {
+ if (links[i]->inRect(x, y)) {
+ return links[i]->getAction();
+ }
+ }
+ return NULL;
+}
+
+GBool Links::onLink(double x, double y) {
+ int i;
+
+ for (i = 0; i < numLinks; ++i) {
+ if (links[i]->inRect(x, y))
+ return gTrue;
+ }
+ return gFalse;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Makefile.am b/filters/kword/pdf/xpdf/xpdf/Makefile.am
index 2ad61b24f..001e9ea00 100644
--- a/filters/kword/pdf/xpdf/xpdf/Makefile.am
+++ b/filters/kword/pdf/xpdf/xpdf/Makefile.am
@@ -4,11 +4,11 @@ INCLUDES= -I$(srcdir) -I$(srcdir)/../goo $(all_includes)
noinst_LTLIBRARIES = libxpdf.la
-libxpdf_la_SOURCES = Array.cc BuiltinFont.cc BuiltinFontTables.cc Catalog.cc \
- CharCodeToUnicode.cc CMap.cc Decrypt.cc Dict.cc Error.cc \
- FontEncodingTables.cc FontFile.cc Function.cc Gfx.cc \
- GfxFont.cc GfxState.cc GlobalParams.cc Lexer.cc Link.cc \
- NameToCharCode.cc Object.cc OutputDev.cc Page.cc Parser.cc PDFDoc.cc \
- PSTokenizer.cc Stream.cc UnicodeMap.cc XRef.cc Annot.cc \
- Outline.cc JBIG2Stream.cc PDFDocEncoding.cc \
- TextOutputDev.cc
+libxpdf_la_SOURCES = Array.cpp BuiltinFont.cpp BuiltinFontTables.cpp Catalog.cpp \
+ CharCodeToUnicode.cpp CMap.cpp Decrypt.cpp Dict.cpp Error.cpp \
+ FontEncodingTables.cpp FontFile.cpp Function.cpp Gfx.cpp \
+ GfxFont.cpp GfxState.cpp GlobalParams.cpp Lexer.cpp Link.cpp \
+ NameToCharCode.cpp Object.cpp OutputDev.cpp Page.cpp Parser.cpp PDFDoc.cpp \
+ PSTokenizer.cpp Stream.cpp UnicodeMap.cpp XRef.cpp Annot.cpp \
+ Outline.cpp JBIG2Stream.cpp PDFDocEncoding.cpp \
+ TextOutputDev.cpp
diff --git a/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cc b/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cc
deleted file mode 100644
index bc5165335..000000000
--- a/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cc
+++ /dev/null
@@ -1,116 +0,0 @@
-//========================================================================
-//
-// NameToCharCode.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <string.h>
-#include "gmem.h"
-#include "NameToCharCode.h"
-
-//------------------------------------------------------------------------
-
-struct NameToCharCodeEntry {
- char *name;
- CharCode c;
-};
-
-//------------------------------------------------------------------------
-
-NameToCharCode::NameToCharCode() {
- int i;
-
- size = 31;
- len = 0;
- tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
- for (i = 0; i < size; ++i) {
- tab[i].name = NULL;
- }
-}
-
-NameToCharCode::~NameToCharCode() {
- int i;
-
- for (i = 0; i < size; ++i) {
- if (tab[i].name) {
- gfree(tab[i].name);
- }
- }
- gfree(tab);
-}
-
-void NameToCharCode::add(const char *name, CharCode c) {
- NameToCharCodeEntry *oldTab;
- int h, i, oldSize;
-
- // expand the table if necessary
- if (len >= size / 2) {
- oldSize = size;
- oldTab = tab;
- size = 2*size + 1;
- tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
- for (h = 0; h < size; ++h) {
- tab[h].name = NULL;
- }
- for (i = 0; i < oldSize; ++i) {
- if (oldTab[i].name) {
- h = hash(oldTab[i].name);
- while (tab[h].name) {
- if (++h == size) {
- h = 0;
- }
- }
- tab[h] = oldTab[i];
- }
- }
- gfree(oldTab);
- }
-
- // add the new name
- h = hash(name);
- while (tab[h].name && strcmp(tab[h].name, name)) {
- if (++h == size) {
- h = 0;
- }
- }
- if (!tab[h].name) {
- tab[h].name = copyString(name);
- }
- tab[h].c = c;
-
- ++len;
-}
-
-CharCode NameToCharCode::lookup(const char *name) {
- int h;
-
- h = hash(name);
- while (tab[h].name) {
- if (!strcmp(tab[h].name, name)) {
- return tab[h].c;
- }
- if (++h == size) {
- h = 0;
- }
- }
- return 0;
-}
-
-int NameToCharCode::hash(const char *name) {
- const char *p;
- unsigned int h;
-
- h = 0;
- for (p = name; *p; ++p) {
- h = 17 * h + (int)(*p & 0xff);
- }
- return (int)(h % size);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cpp b/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cpp
new file mode 100644
index 000000000..81739488a
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/NameToCharCode.cpp
@@ -0,0 +1,116 @@
+//========================================================================
+//
+// NameToCharCode.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <string.h>
+#include "gmem.h"
+#include "NameToCharCode.h"
+
+//------------------------------------------------------------------------
+
+struct NameToCharCodeEntry {
+ char *name;
+ CharCode c;
+};
+
+//------------------------------------------------------------------------
+
+NameToCharCode::NameToCharCode() {
+ int i;
+
+ size = 31;
+ len = 0;
+ tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
+ for (i = 0; i < size; ++i) {
+ tab[i].name = NULL;
+ }
+}
+
+NameToCharCode::~NameToCharCode() {
+ int i;
+
+ for (i = 0; i < size; ++i) {
+ if (tab[i].name) {
+ gfree(tab[i].name);
+ }
+ }
+ gfree(tab);
+}
+
+void NameToCharCode::add(const char *name, CharCode c) {
+ NameToCharCodeEntry *oldTab;
+ int h, i, oldSize;
+
+ // expand the table if necessary
+ if (len >= size / 2) {
+ oldSize = size;
+ oldTab = tab;
+ size = 2*size + 1;
+ tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry));
+ for (h = 0; h < size; ++h) {
+ tab[h].name = NULL;
+ }
+ for (i = 0; i < oldSize; ++i) {
+ if (oldTab[i].name) {
+ h = hash(oldTab[i].name);
+ while (tab[h].name) {
+ if (++h == size) {
+ h = 0;
+ }
+ }
+ tab[h] = oldTab[i];
+ }
+ }
+ gfree(oldTab);
+ }
+
+ // add the new name
+ h = hash(name);
+ while (tab[h].name && strcmp(tab[h].name, name)) {
+ if (++h == size) {
+ h = 0;
+ }
+ }
+ if (!tab[h].name) {
+ tab[h].name = copyString(name);
+ }
+ tab[h].c = c;
+
+ ++len;
+}
+
+CharCode NameToCharCode::lookup(const char *name) {
+ int h;
+
+ h = hash(name);
+ while (tab[h].name) {
+ if (!strcmp(tab[h].name, name)) {
+ return tab[h].c;
+ }
+ if (++h == size) {
+ h = 0;
+ }
+ }
+ return 0;
+}
+
+int NameToCharCode::hash(const char *name) {
+ const char *p;
+ unsigned int h;
+
+ h = 0;
+ for (p = name; *p; ++p) {
+ h = 17 * h + (int)(*p & 0xff);
+ }
+ return (int)(h % size);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Object.cc b/filters/kword/pdf/xpdf/xpdf/Object.cc
deleted file mode 100644
index 296522ce4..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Object.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-//========================================================================
-//
-// Object.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include "Object.h"
-#include "Array.h"
-#include "Dict.h"
-#include "Error.h"
-#include "Stream.h"
-#include "XRef.h"
-
-//------------------------------------------------------------------------
-// Object
-//------------------------------------------------------------------------
-
-const char *objTypeNames[numObjTypes] = {
- "boolean",
- "integer",
- "real",
- "string",
- "name",
- "null",
- "array",
- "dictionary",
- "stream",
- "ref",
- "cmd",
- "error",
- "eof",
- "none"
-};
-
-#ifdef DEBUG_MEM
-int Object::numAlloc[numObjTypes] =
- {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-#endif
-
-Object *Object::initArray(XRef *xref) {
- initObj(objArray);
- array = new Array(xref);
- return this;
-}
-
-Object *Object::initDict(XRef *xref) {
- initObj(objDict);
- dict = new Dict(xref);
- return this;
-}
-
-Object *Object::initStream(Stream *streamA) {
- initObj(objStream);
- stream = streamA;
- return this;
-}
-
-Object *Object::copy(Object *obj) {
- *obj = *this;
- switch (type) {
- case objString:
- obj->string = string->copy();
- break;
- case objName:
- obj->name = copyString(name);
- break;
- case objArray:
- array->incRef();
- break;
- case objDict:
- dict->incRef();
- break;
- case objStream:
- stream->incRef();
- break;
- case objCmd:
- obj->cmd = copyString(cmd);
- break;
- default:
- break;
- }
-#ifdef DEBUG_MEM
- ++numAlloc[type];
-#endif
- return obj;
-}
-
-Object *Object::fetch(XRef *xref, Object *obj) {
- return (type == objRef && xref) ?
- xref->fetch(ref.num, ref.gen, obj) : copy(obj);
-}
-
-void Object::free() {
- switch (type) {
- case objString:
- delete string;
- break;
- case objName:
- gfree(name);
- break;
- case objArray:
- if (!array->decRef()) {
- delete array;
- }
- break;
- case objDict:
- if (!dict->decRef()) {
- delete dict;
- }
- break;
- case objStream:
- if (!stream->decRef()) {
- delete stream;
- }
- break;
- case objCmd:
- gfree(cmd);
- break;
- default:
- break;
- }
-#ifdef DEBUG_MEM
- --numAlloc[type];
-#endif
- type = objNone;
-}
-
-const char *Object::getTypeName() {
- return objTypeNames[type];
-}
-
-void Object::print(FILE *f) {
- Object obj;
- int i;
-
- switch (type) {
- case objBool:
- fprintf(f, "%s", booln ? "true" : "false");
- break;
- case objInt:
- fprintf(f, "%d", intg);
- break;
- case objReal:
- fprintf(f, "%g", real);
- break;
- case objString:
- fprintf(f, "(");
- fwrite(string->getCString(), 1, string->getLength(), stdout);
- fprintf(f, ")");
- break;
- case objName:
- fprintf(f, "/%s", name);
- break;
- case objNull:
- fprintf(f, "null");
- break;
- case objArray:
- fprintf(f, "[");
- for (i = 0; i < arrayGetLength(); ++i) {
- if (i > 0)
- fprintf(f, " ");
- arrayGetNF(i, &obj);
- obj.print(f);
- obj.free();
- }
- fprintf(f, "]");
- break;
- case objDict:
- fprintf(f, "<<");
- for (i = 0; i < dictGetLength(); ++i) {
- fprintf(f, " /%s ", dictGetKey(i));
- dictGetValNF(i, &obj);
- obj.print(f);
- obj.free();
- }
- fprintf(f, " >>");
- break;
- case objStream:
- fprintf(f, "<stream>");
- break;
- case objRef:
- fprintf(f, "%d %d R", ref.num, ref.gen);
- break;
- case objCmd:
- fprintf(f, "%s", cmd);
- break;
- case objError:
- fprintf(f, "<error>");
- break;
- case objEOF:
- fprintf(f, "<EOF>");
- break;
- case objNone:
- fprintf(f, "<none>");
- break;
- }
-}
-
-void Object::memCheck(FILE *f) {
-#ifdef DEBUG_MEM
- int i;
- int t;
-
- t = 0;
- for (i = 0; i < numObjTypes; ++i)
- t += numAlloc[i];
- if (t > 0) {
- fprintf(f, "Allocated objects:\n");
- for (i = 0; i < numObjTypes; ++i) {
- if (numAlloc[i] > 0)
- fprintf(f, " %-20s: %6d\n", objTypeNames[i], numAlloc[i]);
- }
- }
-#endif
- (void)f;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Object.cpp b/filters/kword/pdf/xpdf/xpdf/Object.cpp
new file mode 100644
index 000000000..2a251536f
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Object.cpp
@@ -0,0 +1,225 @@
+//========================================================================
+//
+// Object.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Error.h"
+#include "Stream.h"
+#include "XRef.h"
+
+//------------------------------------------------------------------------
+// Object
+//------------------------------------------------------------------------
+
+const char *objTypeNames[numObjTypes] = {
+ "boolean",
+ "integer",
+ "real",
+ "string",
+ "name",
+ "null",
+ "array",
+ "dictionary",
+ "stream",
+ "ref",
+ "cmd",
+ "error",
+ "eof",
+ "none"
+};
+
+#ifdef DEBUG_MEM
+int Object::numAlloc[numObjTypes] =
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+#endif
+
+Object *Object::initArray(XRef *xref) {
+ initObj(objArray);
+ array = new Array(xref);
+ return this;
+}
+
+Object *Object::initDict(XRef *xref) {
+ initObj(objDict);
+ dict = new Dict(xref);
+ return this;
+}
+
+Object *Object::initStream(Stream *streamA) {
+ initObj(objStream);
+ stream = streamA;
+ return this;
+}
+
+Object *Object::copy(Object *obj) {
+ *obj = *this;
+ switch (type) {
+ case objString:
+ obj->string = string->copy();
+ break;
+ case objName:
+ obj->name = copyString(name);
+ break;
+ case objArray:
+ array->incRef();
+ break;
+ case objDict:
+ dict->incRef();
+ break;
+ case objStream:
+ stream->incRef();
+ break;
+ case objCmd:
+ obj->cmd = copyString(cmd);
+ break;
+ default:
+ break;
+ }
+#ifdef DEBUG_MEM
+ ++numAlloc[type];
+#endif
+ return obj;
+}
+
+Object *Object::fetch(XRef *xref, Object *obj) {
+ return (type == objRef && xref) ?
+ xref->fetch(ref.num, ref.gen, obj) : copy(obj);
+}
+
+void Object::free() {
+ switch (type) {
+ case objString:
+ delete string;
+ break;
+ case objName:
+ gfree(name);
+ break;
+ case objArray:
+ if (!array->decRef()) {
+ delete array;
+ }
+ break;
+ case objDict:
+ if (!dict->decRef()) {
+ delete dict;
+ }
+ break;
+ case objStream:
+ if (!stream->decRef()) {
+ delete stream;
+ }
+ break;
+ case objCmd:
+ gfree(cmd);
+ break;
+ default:
+ break;
+ }
+#ifdef DEBUG_MEM
+ --numAlloc[type];
+#endif
+ type = objNone;
+}
+
+const char *Object::getTypeName() {
+ return objTypeNames[type];
+}
+
+void Object::print(FILE *f) {
+ Object obj;
+ int i;
+
+ switch (type) {
+ case objBool:
+ fprintf(f, "%s", booln ? "true" : "false");
+ break;
+ case objInt:
+ fprintf(f, "%d", intg);
+ break;
+ case objReal:
+ fprintf(f, "%g", real);
+ break;
+ case objString:
+ fprintf(f, "(");
+ fwrite(string->getCString(), 1, string->getLength(), stdout);
+ fprintf(f, ")");
+ break;
+ case objName:
+ fprintf(f, "/%s", name);
+ break;
+ case objNull:
+ fprintf(f, "null");
+ break;
+ case objArray:
+ fprintf(f, "[");
+ for (i = 0; i < arrayGetLength(); ++i) {
+ if (i > 0)
+ fprintf(f, " ");
+ arrayGetNF(i, &obj);
+ obj.print(f);
+ obj.free();
+ }
+ fprintf(f, "]");
+ break;
+ case objDict:
+ fprintf(f, "<<");
+ for (i = 0; i < dictGetLength(); ++i) {
+ fprintf(f, " /%s ", dictGetKey(i));
+ dictGetValNF(i, &obj);
+ obj.print(f);
+ obj.free();
+ }
+ fprintf(f, " >>");
+ break;
+ case objStream:
+ fprintf(f, "<stream>");
+ break;
+ case objRef:
+ fprintf(f, "%d %d R", ref.num, ref.gen);
+ break;
+ case objCmd:
+ fprintf(f, "%s", cmd);
+ break;
+ case objError:
+ fprintf(f, "<error>");
+ break;
+ case objEOF:
+ fprintf(f, "<EOF>");
+ break;
+ case objNone:
+ fprintf(f, "<none>");
+ break;
+ }
+}
+
+void Object::memCheck(FILE *f) {
+#ifdef DEBUG_MEM
+ int i;
+ int t;
+
+ t = 0;
+ for (i = 0; i < numObjTypes; ++i)
+ t += numAlloc[i];
+ if (t > 0) {
+ fprintf(f, "Allocated objects:\n");
+ for (i = 0; i < numObjTypes; ++i) {
+ if (numAlloc[i] > 0)
+ fprintf(f, " %-20s: %6d\n", objTypeNames[i], numAlloc[i]);
+ }
+ }
+#endif
+ (void)f;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Outline.cc b/filters/kword/pdf/xpdf/xpdf/Outline.cc
deleted file mode 100644
index 256d38d4b..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Outline.cc
+++ /dev/null
@@ -1,140 +0,0 @@
-//========================================================================
-//
-// Outline.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "gmem.h"
-#include "GString.h"
-#include "GList.h"
-#include "Link.h"
-#include "PDFDocEncoding.h"
-#include "Outline.h"
-
-//------------------------------------------------------------------------
-
-Outline::Outline(Object *outlineObj, XRef *xref) {
- Object first;
-
- items = NULL;
- if (!outlineObj->isDict()) {
- return;
- }
- items = OutlineItem::readItemList(outlineObj->dictLookupNF("First", &first),
- xref);
- first.free();
-}
-
-Outline::~Outline() {
- if (items) {
- deleteGList(items, OutlineItem);
- }
-}
-
-//------------------------------------------------------------------------
-
-OutlineItem::OutlineItem(Dict *dict, XRef *xrefA) {
- Object obj1;
- GString *s;
- int i;
-
- xref = xrefA;
- title = NULL;
- action = NULL;
- kids = NULL;
-
- if (dict->lookup("Title", &obj1)->isString()) {
- s = obj1.getString();
- if ((s->getChar(0) & 0xff) == 0xfe &&
- (s->getChar(1) & 0xff) == 0xff) {
- titleLen = (s->getLength() - 2) / 2;
- title = (Unicode *)gmalloc(titleLen * sizeof(Unicode));
- for (i = 0; i < titleLen; ++i) {
- title[i] = ((s->getChar(2 + 2*i) & 0xff) << 8) |
- (s->getChar(3 + 2*i) & 0xff);
- }
- } else {
- titleLen = s->getLength();
- title = (Unicode *)gmalloc(titleLen * sizeof(Unicode));
- for (i = 0; i < titleLen; ++i) {
- title[i] = pdfDocEncoding[s->getChar(i) & 0xff];
- }
- }
- }
- obj1.free();
-
- if (!dict->lookup("Dest", &obj1)->isNull()) {
- action = LinkAction::parseDest(&obj1);
- } else {
- obj1.free();
- if (dict->lookup("A", &obj1)) {
- action = LinkAction::parseAction(&obj1);
- }
- }
- obj1.free();
-
- dict->lookupNF("First", &firstRef);
- dict->lookupNF("Next", &nextRef);
-
- startsOpen = gFalse;
- if (dict->lookup("Count", &obj1)->isInt()) {
- if (obj1.getInt() > 0) {
- startsOpen = gTrue;
- }
- }
- obj1.free();
-}
-
-OutlineItem::~OutlineItem() {
- close();
- if (title) {
- delete title;
- }
- if (action) {
- delete action;
- }
- firstRef.free();
- nextRef.free();
-}
-
-GList *OutlineItem::readItemList(Object *itemRef, XRef *xrefA) {
- GList *items;
- OutlineItem *item;
- Object obj;
- Object *p;
-
- items = new GList();
- p = itemRef;
- while (p->isRef()) {
- if (!p->fetch(xrefA, &obj)->isDict()) {
- obj.free();
- break;
- }
- item = new OutlineItem(obj.getDict(), xrefA);
- obj.free();
- items->append(item);
- p = &item->nextRef;
- }
- return items;
-}
-
-void OutlineItem::open() {
- if (!kids) {
- kids = readItemList(&firstRef, xref);
- }
-}
-
-void OutlineItem::close() {
- if (kids) {
- deleteGList(kids, OutlineItem);
- kids = NULL;
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Outline.cpp b/filters/kword/pdf/xpdf/xpdf/Outline.cpp
new file mode 100644
index 000000000..b0753fda2
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Outline.cpp
@@ -0,0 +1,140 @@
+//========================================================================
+//
+// Outline.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "gmem.h"
+#include "GString.h"
+#include "GList.h"
+#include "Link.h"
+#include "PDFDocEncoding.h"
+#include "Outline.h"
+
+//------------------------------------------------------------------------
+
+Outline::Outline(Object *outlineObj, XRef *xref) {
+ Object first;
+
+ items = NULL;
+ if (!outlineObj->isDict()) {
+ return;
+ }
+ items = OutlineItem::readItemList(outlineObj->dictLookupNF("First", &first),
+ xref);
+ first.free();
+}
+
+Outline::~Outline() {
+ if (items) {
+ deleteGList(items, OutlineItem);
+ }
+}
+
+//------------------------------------------------------------------------
+
+OutlineItem::OutlineItem(Dict *dict, XRef *xrefA) {
+ Object obj1;
+ GString *s;
+ int i;
+
+ xref = xrefA;
+ title = NULL;
+ action = NULL;
+ kids = NULL;
+
+ if (dict->lookup("Title", &obj1)->isString()) {
+ s = obj1.getString();
+ if ((s->getChar(0) & 0xff) == 0xfe &&
+ (s->getChar(1) & 0xff) == 0xff) {
+ titleLen = (s->getLength() - 2) / 2;
+ title = (Unicode *)gmalloc(titleLen * sizeof(Unicode));
+ for (i = 0; i < titleLen; ++i) {
+ title[i] = ((s->getChar(2 + 2*i) & 0xff) << 8) |
+ (s->getChar(3 + 2*i) & 0xff);
+ }
+ } else {
+ titleLen = s->getLength();
+ title = (Unicode *)gmalloc(titleLen * sizeof(Unicode));
+ for (i = 0; i < titleLen; ++i) {
+ title[i] = pdfDocEncoding[s->getChar(i) & 0xff];
+ }
+ }
+ }
+ obj1.free();
+
+ if (!dict->lookup("Dest", &obj1)->isNull()) {
+ action = LinkAction::parseDest(&obj1);
+ } else {
+ obj1.free();
+ if (dict->lookup("A", &obj1)) {
+ action = LinkAction::parseAction(&obj1);
+ }
+ }
+ obj1.free();
+
+ dict->lookupNF("First", &firstRef);
+ dict->lookupNF("Next", &nextRef);
+
+ startsOpen = gFalse;
+ if (dict->lookup("Count", &obj1)->isInt()) {
+ if (obj1.getInt() > 0) {
+ startsOpen = gTrue;
+ }
+ }
+ obj1.free();
+}
+
+OutlineItem::~OutlineItem() {
+ close();
+ if (title) {
+ delete title;
+ }
+ if (action) {
+ delete action;
+ }
+ firstRef.free();
+ nextRef.free();
+}
+
+GList *OutlineItem::readItemList(Object *itemRef, XRef *xrefA) {
+ GList *items;
+ OutlineItem *item;
+ Object obj;
+ Object *p;
+
+ items = new GList();
+ p = itemRef;
+ while (p->isRef()) {
+ if (!p->fetch(xrefA, &obj)->isDict()) {
+ obj.free();
+ break;
+ }
+ item = new OutlineItem(obj.getDict(), xrefA);
+ obj.free();
+ items->append(item);
+ p = &item->nextRef;
+ }
+ return items;
+}
+
+void OutlineItem::open() {
+ if (!kids) {
+ kids = readItemList(&firstRef, xref);
+ }
+}
+
+void OutlineItem::close() {
+ if (kids) {
+ deleteGList(kids, OutlineItem);
+ kids = NULL;
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/OutputDev.cc b/filters/kword/pdf/xpdf/xpdf/OutputDev.cc
deleted file mode 100644
index 34ec56836..000000000
--- a/filters/kword/pdf/xpdf/xpdf/OutputDev.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-//========================================================================
-//
-// OutputDev.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include "Object.h"
-#include "Stream.h"
-#include "GfxState.h"
-#include "OutputDev.h"
-
-//------------------------------------------------------------------------
-// OutputDev
-//------------------------------------------------------------------------
-
-void OutputDev::setDefaultCTM(const double *ctm) {
- int i;
- double det;
-
- for (i = 0; i < 6; ++i) {
- defCTM[i] = ctm[i];
- }
- det = 1 / (defCTM[0] * defCTM[3] - defCTM[1] * defCTM[2]);
- defICTM[0] = defCTM[3] * det;
- defICTM[1] = -defCTM[1] * det;
- defICTM[2] = -defCTM[2] * det;
- defICTM[3] = defCTM[0] * det;
- defICTM[4] = (defCTM[2] * defCTM[5] - defCTM[3] * defCTM[4]) * det;
- defICTM[5] = (defCTM[1] * defCTM[4] - defCTM[0] * defCTM[5]) * det;
-}
-
-void OutputDev::cvtDevToUser(int dx, int dy, double *ux, double *uy) {
- *ux = defICTM[0] * dx + defICTM[2] * dy + defICTM[4];
- *uy = defICTM[1] * dx + defICTM[3] * dy + defICTM[5];
-}
-
-void OutputDev::cvtUserToDev(double ux, double uy, int *dx, int *dy) {
- *dx = (int)(defCTM[0] * ux + defCTM[2] * uy + defCTM[4] + 0.5);
- *dy = (int)(defCTM[1] * ux + defCTM[3] * uy + defCTM[5] + 0.5);
-}
-
-void OutputDev::updateAll(GfxState *state) {
- updateLineDash(state);
- updateFlatness(state);
- updateLineJoin(state);
- updateLineCap(state);
- updateMiterLimit(state);
- updateLineWidth(state);
- updateFillColor(state);
- updateStrokeColor(state);
- updateFont(state);
-}
-
-GBool OutputDev::beginType3Char(GfxState */*state*/,
- CharCode /*code*/, Unicode */*u*/, int /*uLen*/) {
- return gFalse;
-}
-
-void OutputDev::drawImageMask(GfxState */*state*/, Object */*ref*/,
- Stream *str, int width, int height, GBool /*invert*/,
- GBool inlineImg) {
- int i, j;
-
- if (inlineImg) {
- str->reset();
- j = height * ((width + 7) / 8);
- for (i = 0; i < j; ++i)
- str->getChar();
- str->close();
- }
-}
-
-void OutputDev::drawImage(GfxState */*state*/, Object */*ref*/, Stream *str,
- int width, int height, GfxImageColorMap *colorMap,
- int */*maskColors*/, GBool inlineImg) {
- int i, j;
-
- if (inlineImg) {
- str->reset();
- j = height * ((width * colorMap->getNumPixelComps() *
- colorMap->getBits() + 7) / 8);
- for (i = 0; i < j; ++i)
- str->getChar();
- str->close();
- }
-}
-
-#ifdef OPI_SUPPORT
-void OutputDev::opiBegin(GfxState */*state*/, Dict */*opiDict*/) {
-}
-
-void OutputDev::opiEnd(GfxState */*state*/, Dict */*opiDict*/) {
-}
-#endif
diff --git a/filters/kword/pdf/xpdf/xpdf/OutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/OutputDev.cpp
new file mode 100644
index 000000000..84f7a2ac9
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/OutputDev.cpp
@@ -0,0 +1,103 @@
+//========================================================================
+//
+// OutputDev.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include "Object.h"
+#include "Stream.h"
+#include "GfxState.h"
+#include "OutputDev.h"
+
+//------------------------------------------------------------------------
+// OutputDev
+//------------------------------------------------------------------------
+
+void OutputDev::setDefaultCTM(const double *ctm) {
+ int i;
+ double det;
+
+ for (i = 0; i < 6; ++i) {
+ defCTM[i] = ctm[i];
+ }
+ det = 1 / (defCTM[0] * defCTM[3] - defCTM[1] * defCTM[2]);
+ defICTM[0] = defCTM[3] * det;
+ defICTM[1] = -defCTM[1] * det;
+ defICTM[2] = -defCTM[2] * det;
+ defICTM[3] = defCTM[0] * det;
+ defICTM[4] = (defCTM[2] * defCTM[5] - defCTM[3] * defCTM[4]) * det;
+ defICTM[5] = (defCTM[1] * defCTM[4] - defCTM[0] * defCTM[5]) * det;
+}
+
+void OutputDev::cvtDevToUser(int dx, int dy, double *ux, double *uy) {
+ *ux = defICTM[0] * dx + defICTM[2] * dy + defICTM[4];
+ *uy = defICTM[1] * dx + defICTM[3] * dy + defICTM[5];
+}
+
+void OutputDev::cvtUserToDev(double ux, double uy, int *dx, int *dy) {
+ *dx = (int)(defCTM[0] * ux + defCTM[2] * uy + defCTM[4] + 0.5);
+ *dy = (int)(defCTM[1] * ux + defCTM[3] * uy + defCTM[5] + 0.5);
+}
+
+void OutputDev::updateAll(GfxState *state) {
+ updateLineDash(state);
+ updateFlatness(state);
+ updateLineJoin(state);
+ updateLineCap(state);
+ updateMiterLimit(state);
+ updateLineWidth(state);
+ updateFillColor(state);
+ updateStrokeColor(state);
+ updateFont(state);
+}
+
+GBool OutputDev::beginType3Char(GfxState */*state*/,
+ CharCode /*code*/, Unicode */*u*/, int /*uLen*/) {
+ return gFalse;
+}
+
+void OutputDev::drawImageMask(GfxState */*state*/, Object */*ref*/,
+ Stream *str, int width, int height, GBool /*invert*/,
+ GBool inlineImg) {
+ int i, j;
+
+ if (inlineImg) {
+ str->reset();
+ j = height * ((width + 7) / 8);
+ for (i = 0; i < j; ++i)
+ str->getChar();
+ str->close();
+ }
+}
+
+void OutputDev::drawImage(GfxState */*state*/, Object */*ref*/, Stream *str,
+ int width, int height, GfxImageColorMap *colorMap,
+ int */*maskColors*/, GBool inlineImg) {
+ int i, j;
+
+ if (inlineImg) {
+ str->reset();
+ j = height * ((width * colorMap->getNumPixelComps() *
+ colorMap->getBits() + 7) / 8);
+ for (i = 0; i < j; ++i)
+ str->getChar();
+ str->close();
+ }
+}
+
+#ifdef OPI_SUPPORT
+void OutputDev::opiBegin(GfxState */*state*/, Dict */*opiDict*/) {
+}
+
+void OutputDev::opiEnd(GfxState */*state*/, Dict */*opiDict*/) {
+}
+#endif
diff --git a/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cc
deleted file mode 100644
index 34432991d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cc
+++ /dev/null
@@ -1,162 +0,0 @@
-//========================================================================
-//
-// PBMOutputDev.cc
-//
-// Copyright 1998-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "gmem.h"
-#include "GString.h"
-#include "Object.h"
-#include "Stream.h"
-#include "GfxState.h"
-#include "GfxFont.h"
-#include "Error.h"
-#include "PBMOutputDev.h"
-
-//------------------------------------------------------------------------
-
-PBMOutputDev *PBMOutputDev::makePBMOutputDev(char *displayName,
- char *fileRootA) {
- Display *displayA;
- Pixmap pixmapA;
- Window dummyWinA;
- int screenA;
- int invertA;
- unsigned long black, white;
- PBMOutputDev *out;
-
- if (!(displayA = XOpenDisplay(displayName))) {
- fprintf(stderr, "Couldn't open display '%s'\n", displayName);
- exit(1);
- }
- screenA = DefaultScreen(displayA);
-
- black = BlackPixel(displayA, screenA);
- white = WhitePixel(displayA, screenA);
- if ((black & 1) == (white & 1)) {
- fprintf(stderr, "Weird black/white pixel colors\n");
- XCloseDisplay(displayA);
- return NULL;
- }
- invertA = (white & 1) == 1 ? 0xff : 0x00;
-
- dummyWinA = XCreateSimpleWindow(displayA, RootWindow(displayA, screenA),
- 0, 0, 1, 1, 0,
- black, white);
- pixmapA = XCreatePixmap(displayA, dummyWinA, 1, 1, 1);
- out = new PBMOutputDev(displayA, screenA, pixmapA, dummyWinA,
- invertA, fileRootA);
- return out;
-}
-
-void PBMOutputDev::killPBMOutputDev(PBMOutputDev *out) {
- Display *displayA;
- Pixmap pixmapA;
- Window dummyWinA;
-
- displayA = out->display;
- pixmapA = out->pixmap;
- dummyWinA = out->dummyWin;
-
- delete out;
-
- // these have to be done *after* the XOutputDev (parent of the
- // PBMOutputDev) is deleted, since XOutputDev::~XOutputDev() needs
- // them
- XFreePixmap(displayA, pixmapA);
- XDestroyWindow(displayA, dummyWinA);
- XCloseDisplay(displayA);
-}
-
-PBMOutputDev::PBMOutputDev(Display *displayA, int screenA,
- Pixmap pixmapA, Window dummyWinA,
- int invertA, char *fileRootA):
- XOutputDev(displayA, screenA,
- DefaultVisual(displayA, screenA),
- DefaultColormap(displayA, screenA),
- gFalse,
- WhitePixel(displayA, DefaultScreen(displayA)),
- gFalse, 1, 1)
-{
- display = displayA;
- screen = screenA;
- pixmap = pixmapA;
- dummyWin = dummyWinA;
- invert = invertA;
- fileRoot = fileRootA;
- fileName = (char *)gmalloc(strlen(fileRoot) + 20);
-}
-
-PBMOutputDev::~PBMOutputDev() {
- gfree(fileName);
-}
-
-void PBMOutputDev::startPage(int pageNum, GfxState *state) {
- curPage = pageNum;
- width = (int)(state->getPageWidth() + 0.5);
- height = (int)(state->getPageHeight() + 0.5);
- XFreePixmap(display, pixmap);
- pixmap = XCreatePixmap(display, dummyWin, width, height, 1);
- setPixmap(pixmap, width, height);
- XOutputDev::startPage(pageNum, state);
-}
-
-void PBMOutputDev::endPage() {
- XImage *image;
- FILE *f;
- int p;
- int x, y, i;
-
- image = XCreateImage(display, DefaultVisual(display, screen),
- 1, ZPixmap, 0, NULL, width, height, 8, 0);
- image->data = (char *)gmalloc(height * image->bytes_per_line);
- XGetSubImage(display, pixmap, 0, 0, width, height, 1, ZPixmap,
- image, 0, 0);
-
- sprintf(fileName, "%s-%06d.pbm", fileRoot, curPage);
- if (!(f = fopen(fileName, "wb"))) {
- fprintf(stderr, "Couldn't open output file '%s'\n", fileName);
- goto err;
- }
- fprintf(f, "P4\n");
- fprintf(f, "%d %d\n", width, height);
-
- for (y = 0; y < height; ++y) {
- for (x = 0; x+8 <= width; x += 8) {
- p = 0;
- for (i = 0; i < 8; ++i)
- p = (p << 1) + (XGetPixel(image, x+i, y) & 1);
- p ^= invert;
- fputc((char)p, f);
- }
- if (width & 7) {
- p = 0;
- for (i = 0; i < (width & 7); ++i)
- p = (p << 1) + (XGetPixel(image, x+i, y) & 1);
- p <<= 8 - (width & 7);
- p ^= invert;
- fputc((char)p, f);
- }
- }
-
- fclose(f);
-
- err:
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
-
- XOutputDev::endPage();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cpp
new file mode 100644
index 000000000..4a65ac041
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/PBMOutputDev.cpp
@@ -0,0 +1,162 @@
+//========================================================================
+//
+// PBMOutputDev.cpp
+//
+// Copyright 1998-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "gmem.h"
+#include "GString.h"
+#include "Object.h"
+#include "Stream.h"
+#include "GfxState.h"
+#include "GfxFont.h"
+#include "Error.h"
+#include "PBMOutputDev.h"
+
+//------------------------------------------------------------------------
+
+PBMOutputDev *PBMOutputDev::makePBMOutputDev(char *displayName,
+ char *fileRootA) {
+ Display *displayA;
+ Pixmap pixmapA;
+ Window dummyWinA;
+ int screenA;
+ int invertA;
+ unsigned long black, white;
+ PBMOutputDev *out;
+
+ if (!(displayA = XOpenDisplay(displayName))) {
+ fprintf(stderr, "Couldn't open display '%s'\n", displayName);
+ exit(1);
+ }
+ screenA = DefaultScreen(displayA);
+
+ black = BlackPixel(displayA, screenA);
+ white = WhitePixel(displayA, screenA);
+ if ((black & 1) == (white & 1)) {
+ fprintf(stderr, "Weird black/white pixel colors\n");
+ XCloseDisplay(displayA);
+ return NULL;
+ }
+ invertA = (white & 1) == 1 ? 0xff : 0x00;
+
+ dummyWinA = XCreateSimpleWindow(displayA, RootWindow(displayA, screenA),
+ 0, 0, 1, 1, 0,
+ black, white);
+ pixmapA = XCreatePixmap(displayA, dummyWinA, 1, 1, 1);
+ out = new PBMOutputDev(displayA, screenA, pixmapA, dummyWinA,
+ invertA, fileRootA);
+ return out;
+}
+
+void PBMOutputDev::killPBMOutputDev(PBMOutputDev *out) {
+ Display *displayA;
+ Pixmap pixmapA;
+ Window dummyWinA;
+
+ displayA = out->display;
+ pixmapA = out->pixmap;
+ dummyWinA = out->dummyWin;
+
+ delete out;
+
+ // these have to be done *after* the XOutputDev (parent of the
+ // PBMOutputDev) is deleted, since XOutputDev::~XOutputDev() needs
+ // them
+ XFreePixmap(displayA, pixmapA);
+ XDestroyWindow(displayA, dummyWinA);
+ XCloseDisplay(displayA);
+}
+
+PBMOutputDev::PBMOutputDev(Display *displayA, int screenA,
+ Pixmap pixmapA, Window dummyWinA,
+ int invertA, char *fileRootA):
+ XOutputDev(displayA, screenA,
+ DefaultVisual(displayA, screenA),
+ DefaultColormap(displayA, screenA),
+ gFalse,
+ WhitePixel(displayA, DefaultScreen(displayA)),
+ gFalse, 1, 1)
+{
+ display = displayA;
+ screen = screenA;
+ pixmap = pixmapA;
+ dummyWin = dummyWinA;
+ invert = invertA;
+ fileRoot = fileRootA;
+ fileName = (char *)gmalloc(strlen(fileRoot) + 20);
+}
+
+PBMOutputDev::~PBMOutputDev() {
+ gfree(fileName);
+}
+
+void PBMOutputDev::startPage(int pageNum, GfxState *state) {
+ curPage = pageNum;
+ width = (int)(state->getPageWidth() + 0.5);
+ height = (int)(state->getPageHeight() + 0.5);
+ XFreePixmap(display, pixmap);
+ pixmap = XCreatePixmap(display, dummyWin, width, height, 1);
+ setPixmap(pixmap, width, height);
+ XOutputDev::startPage(pageNum, state);
+}
+
+void PBMOutputDev::endPage() {
+ XImage *image;
+ FILE *f;
+ int p;
+ int x, y, i;
+
+ image = XCreateImage(display, DefaultVisual(display, screen),
+ 1, ZPixmap, 0, NULL, width, height, 8, 0);
+ image->data = (char *)gmalloc(height * image->bytes_per_line);
+ XGetSubImage(display, pixmap, 0, 0, width, height, 1, ZPixmap,
+ image, 0, 0);
+
+ sprintf(fileName, "%s-%06d.pbm", fileRoot, curPage);
+ if (!(f = fopen(fileName, "wb"))) {
+ fprintf(stderr, "Couldn't open output file '%s'\n", fileName);
+ goto err;
+ }
+ fprintf(f, "P4\n");
+ fprintf(f, "%d %d\n", width, height);
+
+ for (y = 0; y < height; ++y) {
+ for (x = 0; x+8 <= width; x += 8) {
+ p = 0;
+ for (i = 0; i < 8; ++i)
+ p = (p << 1) + (XGetPixel(image, x+i, y) & 1);
+ p ^= invert;
+ fputc((char)p, f);
+ }
+ if (width & 7) {
+ p = 0;
+ for (i = 0; i < (width & 7); ++i)
+ p = (p << 1) + (XGetPixel(image, x+i, y) & 1);
+ p <<= 8 - (width & 7);
+ p ^= invert;
+ fputc((char)p, f);
+ }
+ }
+
+ fclose(f);
+
+ err:
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+
+ XOutputDev::endPage();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/PDFDoc.cc b/filters/kword/pdf/xpdf/xpdf/PDFDoc.cc
deleted file mode 100644
index 19efc1aa6..000000000
--- a/filters/kword/pdf/xpdf/xpdf/PDFDoc.cc
+++ /dev/null
@@ -1,288 +0,0 @@
-//========================================================================
-//
-// PDFDoc.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "GString.h"
-#include "xpdf_config.h"
-#include "GlobalParams.h"
-#include "Page.h"
-#include "Catalog.h"
-#include "Stream.h"
-#include "XRef.h"
-#include "Link.h"
-#include "OutputDev.h"
-#include "Error.h"
-#include "ErrorCodes.h"
-#include "Lexer.h"
-#include "Parser.h"
-#ifndef DISABLE_OUTLINE
-#include "Outline.h"
-#endif
-#include "PDFDoc.h"
-
-//------------------------------------------------------------------------
-
-#define headerSearchSize 1024 // read this many bytes at beginning of
- // file to look for '%PDF'
-
-//------------------------------------------------------------------------
-// PDFDoc
-//------------------------------------------------------------------------
-
-PDFDoc::PDFDoc(GString *fileNameA, GString *ownerPassword,
- GString *userPassword) {
- Object obj;
- GString *fileName1, *fileName2;
-
- ok = gFalse;
- errCode = errNone;
-
- file = NULL;
- str = NULL;
- xref = NULL;
- catalog = NULL;
- links = NULL;
-#ifndef DISABLE_OUTLINE
- outline = NULL;
-#endif
-
- fileName = fileNameA;
- fileName1 = fileName;
-
-
- // try to open file
- fileName2 = NULL;
-#ifdef VMS
- if (!(file = fopen(fileName1->getCString(), "rb", "ctx=stm"))) {
- error(-1, "Couldn't open file '%s'", fileName1->getCString());
- errCode = errOpenFile;
- return;
- }
-#else
- if (!(file = fopen(fileName1->getCString(), "rb"))) {
- fileName2 = fileName->copy();
- fileName2->lowerCase();
- if (!(file = fopen(fileName2->getCString(), "rb"))) {
- fileName2->upperCase();
- if (!(file = fopen(fileName2->getCString(), "rb"))) {
- error(-1, "Couldn't open file '%s'", fileName->getCString());
- delete fileName2;
- errCode = errOpenFile;
- return;
- }
- }
- delete fileName2;
- }
-#endif
-
- // create stream
- obj.initNull();
- str = new FileStream(file, 0, gFalse, 0, &obj);
-
- ok = setup(ownerPassword, userPassword);
-}
-
-PDFDoc::PDFDoc(BaseStream *strA, GString *ownerPassword,
- GString *userPassword) {
- ok = gFalse;
- errCode = errNone;
- fileName = NULL;
- file = NULL;
- str = strA;
- xref = NULL;
- catalog = NULL;
- links = NULL;
-#ifndef DISABLE_OUTLINE
- outline = NULL;
-#endif
- ok = setup(ownerPassword, userPassword);
-}
-
-GBool PDFDoc::setup(GString *ownerPassword, GString *userPassword) {
- // check header
- checkHeader();
-
- // read xref table
- xref = new XRef(str, ownerPassword, userPassword);
- if (!xref->isOk()) {
- error(-1, "Couldn't read xref table");
- errCode = xref->getErrorCode();
- return gFalse;
- }
-
- // read catalog
- catalog = new Catalog(xref);
- if (!catalog->isOk()) {
- error(-1, "Couldn't read page catalog");
- errCode = errBadCatalog;
- return gFalse;
- }
-
-#ifndef DISABLE_OUTLINE
- // read outline
- outline = new Outline(catalog->getOutline(), xref);
-#endif
-
- // done
- return gTrue;
-}
-
-PDFDoc::~PDFDoc() {
-#ifndef DISABLE_OUTLINE
- delete outline;
-#endif
- delete catalog;
- delete xref;
- delete str;
- if (file) {
- fclose(file);
- }
- delete fileName;
- delete links;
-}
-
-// Check for a PDF header on this stream. Skip past some garbage
-// if necessary.
-void PDFDoc::checkHeader() {
- char hdrBuf[headerSearchSize+1];
- char *p;
- int i;
-
- pdfVersion = 0;
- for (i = 0; i < headerSearchSize; ++i) {
- hdrBuf[i] = str->getChar();
- }
- hdrBuf[headerSearchSize] = '\0';
- for (i = 0; i < headerSearchSize - 5; ++i) {
- if (!strncmp(&hdrBuf[i], "%PDF-", 5)) {
- break;
- }
- }
- if (i >= headerSearchSize - 5) {
- error(-1, "May not be a PDF file (continuing anyway)");
- return;
- }
- str->moveStart(i);
- p = strtok(&hdrBuf[i+5], " \t\n\r");
- pdfVersion = atof(p);
- if (!(hdrBuf[i+5] >= '0' && hdrBuf[i+5] <= '9') ||
- pdfVersion > supportedPDFVersionNum + 0.0001) {
- error(-1, "PDF version %s -- xpdf supports version %s"
- " (continuing anyway)", p, supportedPDFVersionStr);
- }
-}
-
-void PDFDoc::displayPage(OutputDev *out, int page, double zoom,
- int rotate, GBool doLinks,
- GBool (*abortCheckCbk)(void *data),
- void *abortCheckCbkData) {
- Page *p;
-
- if (globalParams->getPrintCommands()) {
- printf("***** page %d *****\n", page);
- }
- p = catalog->getPage(page);
- if (doLinks) {
- if (links) {
- delete links;
- }
- getLinks(p);
- p->display(out, zoom, rotate, links, catalog,
- abortCheckCbk, abortCheckCbkData);
- } else {
- p->display(out, zoom, rotate, NULL, catalog,
- abortCheckCbk, abortCheckCbkData);
- }
-}
-
-void PDFDoc::displayPages(OutputDev *out, int firstPage, int lastPage,
- int zoom, int rotate, GBool doLinks,
- GBool (*abortCheckCbk)(void *data),
- void *abortCheckCbkData) {
- int page;
-
- for (page = firstPage; page <= lastPage; ++page) {
- displayPage(out, page, zoom, rotate, doLinks,
- abortCheckCbk, abortCheckCbkData);
- }
-}
-
-void PDFDoc::displayPageSlice(OutputDev *out, int page, double zoom,
- int rotate, int sliceX, int sliceY,
- int sliceW, int sliceH,
- GBool (*abortCheckCbk)(void *data),
- void *abortCheckCbkData) {
- Page *p;
-
- p = catalog->getPage(page);
- p->displaySlice(out, zoom, rotate, sliceX, sliceY, sliceW, sliceH,
- NULL, catalog, abortCheckCbk, abortCheckCbkData);
-}
-
-GBool PDFDoc::isLinearized() {
- Parser *parser;
- Object obj1, obj2, obj3, obj4, obj5;
- GBool lin;
-
- lin = gFalse;
- obj1.initNull();
- parser = new Parser(xref,
- new Lexer(xref,
- str->makeSubStream(str->getStart(), gFalse, 0, &obj1)));
- parser->getObj(&obj1);
- parser->getObj(&obj2);
- parser->getObj(&obj3);
- parser->getObj(&obj4);
- if (obj1.isInt() && obj2.isInt() && obj3.isCmd("obj") &&
- obj4.isDict()) {
- obj4.dictLookup("Linearized", &obj5);
- if (obj5.isNum() && obj5.getNum() > 0) {
- lin = gTrue;
- }
- obj5.free();
- }
- obj4.free();
- obj3.free();
- obj2.free();
- obj1.free();
- delete parser;
- return lin;
-}
-
-GBool PDFDoc::saveAs(GString *name) {
- FILE *f;
- int c;
-
- if (!(f = fopen(name->getCString(), "wb"))) {
- error(-1, "Couldn't open file '%s'", name->getCString());
- return gFalse;
- }
- str->reset();
- while ((c = str->getChar()) != EOF) {
- fputc(c, f);
- }
- str->close();
- fclose(f);
- return gTrue;
-}
-
-void PDFDoc::getLinks(Page *page) {
- Object obj;
-
- links = new Links(page->getAnnots(&obj), catalog->getBaseURI());
- obj.free();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/PDFDoc.cpp b/filters/kword/pdf/xpdf/xpdf/PDFDoc.cpp
new file mode 100644
index 000000000..63f5d2da4
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/PDFDoc.cpp
@@ -0,0 +1,288 @@
+//========================================================================
+//
+// PDFDoc.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "GString.h"
+#include "xpdf_config.h"
+#include "GlobalParams.h"
+#include "Page.h"
+#include "Catalog.h"
+#include "Stream.h"
+#include "XRef.h"
+#include "Link.h"
+#include "OutputDev.h"
+#include "Error.h"
+#include "ErrorCodes.h"
+#include "Lexer.h"
+#include "Parser.h"
+#ifndef DISABLE_OUTLINE
+#include "Outline.h"
+#endif
+#include "PDFDoc.h"
+
+//------------------------------------------------------------------------
+
+#define headerSearchSize 1024 // read this many bytes at beginning of
+ // file to look for '%PDF'
+
+//------------------------------------------------------------------------
+// PDFDoc
+//------------------------------------------------------------------------
+
+PDFDoc::PDFDoc(GString *fileNameA, GString *ownerPassword,
+ GString *userPassword) {
+ Object obj;
+ GString *fileName1, *fileName2;
+
+ ok = gFalse;
+ errCode = errNone;
+
+ file = NULL;
+ str = NULL;
+ xref = NULL;
+ catalog = NULL;
+ links = NULL;
+#ifndef DISABLE_OUTLINE
+ outline = NULL;
+#endif
+
+ fileName = fileNameA;
+ fileName1 = fileName;
+
+
+ // try to open file
+ fileName2 = NULL;
+#ifdef VMS
+ if (!(file = fopen(fileName1->getCString(), "rb", "ctx=stm"))) {
+ error(-1, "Couldn't open file '%s'", fileName1->getCString());
+ errCode = errOpenFile;
+ return;
+ }
+#else
+ if (!(file = fopen(fileName1->getCString(), "rb"))) {
+ fileName2 = fileName->copy();
+ fileName2->lowerCase();
+ if (!(file = fopen(fileName2->getCString(), "rb"))) {
+ fileName2->upperCase();
+ if (!(file = fopen(fileName2->getCString(), "rb"))) {
+ error(-1, "Couldn't open file '%s'", fileName->getCString());
+ delete fileName2;
+ errCode = errOpenFile;
+ return;
+ }
+ }
+ delete fileName2;
+ }
+#endif
+
+ // create stream
+ obj.initNull();
+ str = new FileStream(file, 0, gFalse, 0, &obj);
+
+ ok = setup(ownerPassword, userPassword);
+}
+
+PDFDoc::PDFDoc(BaseStream *strA, GString *ownerPassword,
+ GString *userPassword) {
+ ok = gFalse;
+ errCode = errNone;
+ fileName = NULL;
+ file = NULL;
+ str = strA;
+ xref = NULL;
+ catalog = NULL;
+ links = NULL;
+#ifndef DISABLE_OUTLINE
+ outline = NULL;
+#endif
+ ok = setup(ownerPassword, userPassword);
+}
+
+GBool PDFDoc::setup(GString *ownerPassword, GString *userPassword) {
+ // check header
+ checkHeader();
+
+ // read xref table
+ xref = new XRef(str, ownerPassword, userPassword);
+ if (!xref->isOk()) {
+ error(-1, "Couldn't read xref table");
+ errCode = xref->getErrorCode();
+ return gFalse;
+ }
+
+ // read catalog
+ catalog = new Catalog(xref);
+ if (!catalog->isOk()) {
+ error(-1, "Couldn't read page catalog");
+ errCode = errBadCatalog;
+ return gFalse;
+ }
+
+#ifndef DISABLE_OUTLINE
+ // read outline
+ outline = new Outline(catalog->getOutline(), xref);
+#endif
+
+ // done
+ return gTrue;
+}
+
+PDFDoc::~PDFDoc() {
+#ifndef DISABLE_OUTLINE
+ delete outline;
+#endif
+ delete catalog;
+ delete xref;
+ delete str;
+ if (file) {
+ fclose(file);
+ }
+ delete fileName;
+ delete links;
+}
+
+// Check for a PDF header on this stream. Skip past some garbage
+// if necessary.
+void PDFDoc::checkHeader() {
+ char hdrBuf[headerSearchSize+1];
+ char *p;
+ int i;
+
+ pdfVersion = 0;
+ for (i = 0; i < headerSearchSize; ++i) {
+ hdrBuf[i] = str->getChar();
+ }
+ hdrBuf[headerSearchSize] = '\0';
+ for (i = 0; i < headerSearchSize - 5; ++i) {
+ if (!strncmp(&hdrBuf[i], "%PDF-", 5)) {
+ break;
+ }
+ }
+ if (i >= headerSearchSize - 5) {
+ error(-1, "May not be a PDF file (continuing anyway)");
+ return;
+ }
+ str->moveStart(i);
+ p = strtok(&hdrBuf[i+5], " \t\n\r");
+ pdfVersion = atof(p);
+ if (!(hdrBuf[i+5] >= '0' && hdrBuf[i+5] <= '9') ||
+ pdfVersion > supportedPDFVersionNum + 0.0001) {
+ error(-1, "PDF version %s -- xpdf supports version %s"
+ " (continuing anyway)", p, supportedPDFVersionStr);
+ }
+}
+
+void PDFDoc::displayPage(OutputDev *out, int page, double zoom,
+ int rotate, GBool doLinks,
+ GBool (*abortCheckCbk)(void *data),
+ void *abortCheckCbkData) {
+ Page *p;
+
+ if (globalParams->getPrintCommands()) {
+ printf("***** page %d *****\n", page);
+ }
+ p = catalog->getPage(page);
+ if (doLinks) {
+ if (links) {
+ delete links;
+ }
+ getLinks(p);
+ p->display(out, zoom, rotate, links, catalog,
+ abortCheckCbk, abortCheckCbkData);
+ } else {
+ p->display(out, zoom, rotate, NULL, catalog,
+ abortCheckCbk, abortCheckCbkData);
+ }
+}
+
+void PDFDoc::displayPages(OutputDev *out, int firstPage, int lastPage,
+ int zoom, int rotate, GBool doLinks,
+ GBool (*abortCheckCbk)(void *data),
+ void *abortCheckCbkData) {
+ int page;
+
+ for (page = firstPage; page <= lastPage; ++page) {
+ displayPage(out, page, zoom, rotate, doLinks,
+ abortCheckCbk, abortCheckCbkData);
+ }
+}
+
+void PDFDoc::displayPageSlice(OutputDev *out, int page, double zoom,
+ int rotate, int sliceX, int sliceY,
+ int sliceW, int sliceH,
+ GBool (*abortCheckCbk)(void *data),
+ void *abortCheckCbkData) {
+ Page *p;
+
+ p = catalog->getPage(page);
+ p->displaySlice(out, zoom, rotate, sliceX, sliceY, sliceW, sliceH,
+ NULL, catalog, abortCheckCbk, abortCheckCbkData);
+}
+
+GBool PDFDoc::isLinearized() {
+ Parser *parser;
+ Object obj1, obj2, obj3, obj4, obj5;
+ GBool lin;
+
+ lin = gFalse;
+ obj1.initNull();
+ parser = new Parser(xref,
+ new Lexer(xref,
+ str->makeSubStream(str->getStart(), gFalse, 0, &obj1)));
+ parser->getObj(&obj1);
+ parser->getObj(&obj2);
+ parser->getObj(&obj3);
+ parser->getObj(&obj4);
+ if (obj1.isInt() && obj2.isInt() && obj3.isCmd("obj") &&
+ obj4.isDict()) {
+ obj4.dictLookup("Linearized", &obj5);
+ if (obj5.isNum() && obj5.getNum() > 0) {
+ lin = gTrue;
+ }
+ obj5.free();
+ }
+ obj4.free();
+ obj3.free();
+ obj2.free();
+ obj1.free();
+ delete parser;
+ return lin;
+}
+
+GBool PDFDoc::saveAs(GString *name) {
+ FILE *f;
+ int c;
+
+ if (!(f = fopen(name->getCString(), "wb"))) {
+ error(-1, "Couldn't open file '%s'", name->getCString());
+ return gFalse;
+ }
+ str->reset();
+ while ((c = str->getChar()) != EOF) {
+ fputc(c, f);
+ }
+ str->close();
+ fclose(f);
+ return gTrue;
+}
+
+void PDFDoc::getLinks(Page *page) {
+ Object obj;
+
+ links = new Links(page->getAnnots(&obj), catalog->getBaseURI());
+ obj.free();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cc b/filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cpp
index 4f1e20132..4f1e20132 100644
--- a/filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cc
+++ b/filters/kword/pdf/xpdf/xpdf/PDFDocEncoding.cpp
diff --git a/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cc
deleted file mode 100644
index 111d8717b..000000000
--- a/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cc
+++ /dev/null
@@ -1,3325 +0,0 @@
-//========================================================================
-//
-// PSOutputDev.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stddef.h>
-#include <stdarg.h>
-#include <signal.h>
-#include <math.h>
-#include "GString.h"
-#include "config.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Error.h"
-#include "Function.h"
-#include "Gfx.h"
-#include "GfxState.h"
-#include "GfxFont.h"
-#include "CharCodeToUnicode.h"
-#include "UnicodeMap.h"
-#include "FontFile.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "Stream.h"
-#include "Annot.h"
-#include "PSOutputDev.h"
-
-#ifdef MACOS
-// needed for setting type/creator of MacOS files
-#include "ICSupport.h"
-#endif
-
-//------------------------------------------------------------------------
-// PostScript prolog and setup
-//------------------------------------------------------------------------
-
-static char *prolog[] = {
- "/xpdf 75 dict def xpdf begin",
- "% PDF special state",
- "/pdfDictSize 14 def",
- "/pdfSetup {",
- " 3 1 roll 2 array astore",
- " /setpagedevice where {",
- " pop 3 dict begin",
- " /PageSize exch def",
- " /ImagingBBox null def",
- " /Policies 1 dict dup begin /PageSize 3 def end def",
- " { /Duplex true def } if",
- " currentdict end setpagedevice",
- " } {",
- " pop pop",
- " } ifelse",
- "} def",
- "/pdfStartPage {",
- " pdfDictSize dict begin",
- " /pdfFill [0] def",
- " /pdfStroke [0] def",
- " /pdfLastFill false def",
- " /pdfLastStroke false def",
- " /pdfTextMat [1 0 0 1 0 0] def",
- " /pdfFontSize 0 def",
- " /pdfCharSpacing 0 def",
- " /pdfTextRender 0 def",
- " /pdfTextRise 0 def",
- " /pdfWordSpacing 0 def",
- " /pdfHorizScaling 1 def",
- "} def",
- "/pdfEndPage { end } def",
- "% separation convention operators",
- "/findcmykcustomcolor where {",
- " pop",
- "}{",
- " /findcmykcustomcolor { 5 array astore } def",
- "} ifelse",
- "/setcustomcolor where {",
- " pop",
- "}{",
- " /setcustomcolor {",
- " exch",
- " [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
- " 0 4 getinterval cvx",
- " [ exch /dup load exch { mul exch dup } /forall load",
- " /pop load dup ] cvx",
- " ] setcolorspace setcolor",
- " } def",
- "} ifelse",
- "/customcolorimage where {",
- " pop",
- "}{",
- " /customcolorimage {",
- " gsave",
- " [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
- " 0 4 getinterval cvx",
- " [ exch /dup load exch { mul exch dup } /forall load",
- " /pop load dup ] cvx",
- " ] setcolorspace",
- " 10 dict begin",
- " /ImageType 1 def",
- " /DataSource exch def",
- " /ImageMatrix exch def",
- " /BitsPerComponent exch def",
- " /Height exch def",
- " /Width exch def",
- " /Decode [1 0] def",
- " currentdict end",
- " image",
- " grestore",
- " } def",
- "} ifelse",
- "% PDF color state",
- "/sCol {",
- " pdfLastStroke not {",
- " pdfStroke aload length",
- " dup 1 eq {",
- " pop setgray",
- " }{",
- " dup 3 eq {",
- " pop setrgbcolor",
- " }{",
- " 4 eq {",
- " setcmykcolor",
- " }{",
- " findcmykcustomcolor exch setcustomcolor",
- " } ifelse",
- " } ifelse",
- " } ifelse",
- " /pdfLastStroke true def /pdfLastFill false def",
- " } if",
- "} def",
- "/fCol {",
- " pdfLastFill not {",
- " pdfFill aload length",
- " dup 1 eq {",
- " pop setgray",
- " }{",
- " dup 3 eq {",
- " pop setrgbcolor",
- " }{",
- " 4 eq {",
- " setcmykcolor",
- " }{",
- " findcmykcustomcolor exch setcustomcolor",
- " } ifelse",
- " } ifelse",
- " } ifelse",
- " /pdfLastFill true def /pdfLastStroke false def",
- " } if",
- "} def",
- "% build a font",
- "/pdfMakeFont {",
- " 4 3 roll findfont",
- " 4 2 roll matrix scale makefont",
- " dup length dict begin",
- " { 1 index /FID ne { def } { pop pop } ifelse } forall",
- " /Encoding exch def",
- " currentdict",
- " end",
- " definefont pop",
- "} def",
- "/pdfMakeFont16 {",
- " exch findfont",
- " dup length dict begin",
- " { 1 index /FID ne { def } { pop pop } ifelse } forall",
- " /WMode exch def",
- " currentdict",
- " end",
- " definefont pop",
- "} def",
- "/pdfMakeFont16L3 {",
- " 1 index /CIDFont resourcestatus {",
- " pop pop 1 index /CIDFont findresource /CIDFontType known",
- " } {",
- " false",
- " } ifelse",
- " {",
- " 0 eq { /Identity-H } { /Identity-V } ifelse",
- " exch 1 array astore composefont pop",
- " } {",
- " pdfMakeFont16",
- " } ifelse",
- "} def",
- "% graphics state operators",
- "/q { gsave pdfDictSize dict begin } def",
- "/Q { end grestore } def",
- "/cm { concat } def",
- "/d { setdash } def",
- "/i { setflat } def",
- "/j { setlinejoin } def",
- "/J { setlinecap } def",
- "/M { setmiterlimit } def",
- "/w { setlinewidth } def",
- "% color operators",
- "/g { dup 1 array astore /pdfFill exch def setgray",
- " /pdfLastFill true def /pdfLastStroke false def } def",
- "/G { dup 1 array astore /pdfStroke exch def setgray",
- " /pdfLastStroke true def /pdfLastFill false def } def",
- "/rg { 3 copy 3 array astore /pdfFill exch def setrgbcolor",
- " /pdfLastFill true def /pdfLastStroke false def } def",
- "/RG { 3 copy 3 array astore /pdfStroke exch def setrgbcolor",
- " /pdfLastStroke true def /pdfLastFill false def } def",
- "/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
- " /pdfLastFill true def /pdfLastStroke false def } def",
- "/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
- " /pdfLastStroke true def /pdfLastFill false def } def",
- "/ck { 6 copy 6 array astore /pdfFill exch def",
- " findcmykcustomcolor exch setcustomcolor",
- " /pdfLastFill true def /pdfLastStroke false def } def",
- "/CK { 6 copy 6 array astore /pdfStroke exch def",
- " findcmykcustomcolor exch setcustomcolor",
- " /pdfLastStroke true def /pdfLastFill false def } def",
- "% path segment operators",
- "/m { moveto } def",
- "/l { lineto } def",
- "/c { curveto } def",
- "/re { 4 2 roll moveto 1 index 0 rlineto 0 exch rlineto",
- " neg 0 rlineto closepath } def",
- "/h { closepath } def",
- "% path painting operators",
- "/S { sCol stroke } def",
- "/Sf { fCol stroke } def",
- "/f { fCol fill } def",
- "/f* { fCol eofill } def",
- "% clipping operators",
- "/W { clip newpath } def",
- "/W* { eoclip newpath } def",
- "% text state operators",
- "/Tc { /pdfCharSpacing exch def } def",
- "/Tf { dup /pdfFontSize exch def",
- " dup pdfHorizScaling mul exch matrix scale",
- " pdfTextMat matrix concatmatrix dup 4 0 put dup 5 0 put",
- " exch findfont exch makefont setfont } def",
- "/Tr { /pdfTextRender exch def } def",
- "/Ts { /pdfTextRise exch def } def",
- "/Tw { /pdfWordSpacing exch def } def",
- "/Tz { /pdfHorizScaling exch def } def",
- "% text positioning operators",
- "/Td { pdfTextMat transform moveto } def",
- "/Tm { /pdfTextMat exch def } def",
- "% text string operators",
- "/awcp { % awidthcharpath",
- " exch {",
- " 1 string dup 0 3 index put 2 index charpath",
- " 3 index 3 index rmoveto",
- " 4 index eq { 5 index 5 index rmoveto } if",
- " } forall",
- " 6 {pop} repeat",
- "} def",
- "/Tj { fCol", // because stringwidth has to draw Type 3 chars
- " 0 pdfTextRise pdfTextMat dtransform rmoveto",
- " 1 index stringwidth pdfTextMat idtransform pop",
- " sub 1 index length dup 0 ne { div } { pop pop 0 } ifelse",
- " pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
- " 4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
- " pdfTextMat dtransform",
- " 6 5 roll",
- " currentpoint 8 2 roll",
- " pdfTextRender 1 and 0 eq {",
- " 6 copy awidthshow",
- " } if",
- " pdfTextRender 3 and dup 1 eq exch 2 eq or {",
- " 8 6 roll moveto",
- " currentfont /FontType get 3 eq { fCol } { sCol } ifelse",
- " false awcp currentpoint stroke moveto",
- " } {",
- " 8 {pop} repeat",
- " } ifelse",
- " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
- "/Tj16 { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
- " 0 pdfTextRise pdfTextMat dtransform rmoveto",
- " 2 index stringwidth pdfTextMat idtransform pop",
- " sub exch div",
- " pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
- " 4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
- " pdfTextMat dtransform",
- " 6 5 roll awidthshow",
- " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
- "/Tj16V { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
- " 0 pdfTextRise pdfTextMat dtransform rmoveto",
- " 2 index stringwidth pdfTextMat idtransform exch pop",
- " sub exch div",
- " 0 pdfWordSpacing pdfTextMat dtransform 32",
- " 4 3 roll pdfCharSpacing add 0 exch",
- " pdfTextMat dtransform",
- " 6 5 roll awidthshow",
- " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
- "/TJm { pdfFontSize 0.001 mul mul neg 0",
- " pdfTextMat dtransform rmoveto } def",
- "/TJmV { pdfFontSize 0.001 mul mul neg 0 exch",
- " pdfTextMat dtransform rmoveto } def",
- "% Level 1 image operators",
- "/pdfIm1 {",
- " /pdfImBuf1 4 index string def",
- " { currentfile pdfImBuf1 readhexstring pop } image",
- "} def",
- "/pdfIm1Sep {",
- " /pdfImBuf1 4 index string def",
- " /pdfImBuf2 4 index string def",
- " /pdfImBuf3 4 index string def",
- " /pdfImBuf4 4 index string def",
- " { currentfile pdfImBuf1 readhexstring pop }",
- " { currentfile pdfImBuf2 readhexstring pop }",
- " { currentfile pdfImBuf3 readhexstring pop }",
- " { currentfile pdfImBuf4 readhexstring pop }",
- " true 4 colorimage",
- "} def",
- "/pdfImM1 {",
- " /pdfImBuf1 4 index 7 add 8 idiv string def",
- " { currentfile pdfImBuf1 readhexstring pop } imagemask",
- "} def",
- "% Level 2 image operators",
- "/pdfImBuf 100 string def",
- "/pdfIm {",
- " image",
- " { currentfile pdfImBuf readline",
- " not { pop exit } if",
- " (%-EOD-) eq { exit } if } loop",
- "} def",
- "/pdfImSep {",
- " findcmykcustomcolor exch",
- " dup /Width get /pdfImBuf1 exch string def",
- " begin Width Height BitsPerComponent ImageMatrix DataSource end",
- " /pdfImData exch def",
- " { pdfImData pdfImBuf1 readstring pop",
- " 0 1 2 index length 1 sub {",
- " 1 index exch 2 copy get 255 exch sub put",
- " } for }",
- " 6 5 roll customcolorimage",
- " { currentfile pdfImBuf readline",
- " not { pop exit } if",
- " (%-EOD-) eq { exit } if } loop",
- "} def",
- "/pdfImM {",
- " fCol imagemask",
- " { currentfile pdfImBuf readline",
- " not { pop exit } if",
- " (%-EOD-) eq { exit } if } loop",
- "} def",
- "end",
- NULL
-};
-
-static char *cmapProlog[] = {
- "/CIDInit /ProcSet findresource begin",
- "10 dict begin",
- " begincmap",
- " /CMapType 1 def",
- " /CMapName /Identity-H def",
- " /CIDSystemInfo 3 dict dup begin",
- " /Registry (Adobe) def",
- " /Ordering (Identity) def",
- " /Supplement 0 def",
- " end def",
- " 1 begincodespacerange",
- " <0000> <ffff>",
- " endcodespacerange",
- " 0 usefont",
- " 1 begincidrange",
- " <0000> <ffff> 0",
- " endcidrange",
- " endcmap",
- " currentdict CMapName exch /CMap defineresource pop",
- "end",
- "10 dict begin",
- " begincmap",
- " /CMapType 1 def",
- " /CMapName /Identity-V def",
- " /CIDSystemInfo 3 dict dup begin",
- " /Registry (Adobe) def",
- " /Ordering (Identity) def",
- " /Supplement 0 def",
- " end def",
- " /WMode 1 def",
- " 1 begincodespacerange",
- " <0000> <ffff>",
- " endcodespacerange",
- " 0 usefont",
- " 1 begincidrange",
- " <0000> <ffff> 0",
- " endcidrange",
- " endcmap",
- " currentdict CMapName exch /CMap defineresource pop",
- "end",
- "end",
- NULL
-};
-
-//------------------------------------------------------------------------
-// Fonts
-//------------------------------------------------------------------------
-
-struct PSSubstFont {
- char *psName; // PostScript name
- double mWidth; // width of 'm' character
-};
-
-static char *psFonts[] = {
- "Courier",
- "Courier-Bold",
- "Courier-Oblique",
- "Courier-BoldOblique",
- "Helvetica",
- "Helvetica-Bold",
- "Helvetica-Oblique",
- "Helvetica-BoldOblique",
- "Symbol",
- "Times-Roman",
- "Times-Bold",
- "Times-Italic",
- "Times-BoldItalic",
- "ZapfDingbats",
- NULL
-};
-
-static PSSubstFont psSubstFonts[] = {
- {"Helvetica", 0.833},
- {"Helvetica-Oblique", 0.833},
- {"Helvetica-Bold", 0.889},
- {"Helvetica-BoldOblique", 0.889},
- {"Times-Roman", 0.788},
- {"Times-Italic", 0.722},
- {"Times-Bold", 0.833},
- {"Times-BoldItalic", 0.778},
- {"Courier", 0.600},
- {"Courier-Oblique", 0.600},
- {"Courier-Bold", 0.600},
- {"Courier-BoldOblique", 0.600}
-};
-
-// Encoding info for substitute 16-bit font
-struct PSFont16Enc {
- Ref fontID;
- GString *enc;
-};
-
-//------------------------------------------------------------------------
-// process colors
-//------------------------------------------------------------------------
-
-#define psProcessCyan 1
-#define psProcessMagenta 2
-#define psProcessYellow 4
-#define psProcessBlack 8
-#define psProcessCMYK 15
-
-//------------------------------------------------------------------------
-// PSOutCustomColor
-//------------------------------------------------------------------------
-
-class PSOutCustomColor {
-public:
-
- PSOutCustomColor(double cA, double mA,
- double yA, double kA, GString *nameA);
- ~PSOutCustomColor();
-
- double c, m, y, k;
- GString *name;
- PSOutCustomColor *next;
-};
-
-PSOutCustomColor::PSOutCustomColor(double cA, double mA,
- double yA, double kA, GString *nameA) {
- c = cA;
- m = mA;
- y = yA;
- k = kA;
- name = nameA;
- next = NULL;
-}
-
-PSOutCustomColor::~PSOutCustomColor() {
- delete name;
-}
-
-//------------------------------------------------------------------------
-// PSOutputDev
-//------------------------------------------------------------------------
-
-extern "C" {
-typedef void (*SignalFunc)(int);
-}
-
-static void outputToFile(void *stream, char *data, int len) {
- fwrite(data, 1, len, (FILE *)stream);
-}
-
-PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
- int firstPage, int lastPage, PSOutMode modeA) {
- FILE *f;
- PSFileType fileTypeA;
-
- fontIDs = NULL;
- fontFileIDs = NULL;
- fontFileNames = NULL;
- font16Enc = NULL;
- embFontList = NULL;
- customColors = NULL;
- t3String = NULL;
-
- // open file or pipe
- if (!strcmp(fileName, "-")) {
- fileTypeA = psStdout;
- f = stdout;
- } else if (fileName[0] == '|') {
- fileTypeA = psPipe;
-#ifdef HAVE_POPEN
-#ifndef WIN32
- signal(SIGPIPE, (SignalFunc)SIG_IGN);
-#endif
- if (!(f = popen(fileName + 1, "w"))) {
- error(-1, "Couldn't run print command '%s'", fileName);
- ok = gFalse;
- return;
- }
-#else
- error(-1, "Print commands are not supported ('%s')", fileName);
- ok = gFalse;
- return;
-#endif
- } else {
- fileTypeA = psFile;
- if (!(f = fopen(fileName, "w"))) {
- error(-1, "Couldn't open PostScript file '%s'", fileName);
- ok = gFalse;
- return;
- }
- }
-
- init(outputToFile, f, fileTypeA,
- xrefA, catalog, firstPage, lastPage, modeA);
-}
-
-PSOutputDev::PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
- XRef *xrefA, Catalog *catalog,
- int firstPage, int lastPage, PSOutMode modeA) {
- fontIDs = NULL;
- fontFileIDs = NULL;
- fontFileNames = NULL;
- font16Enc = NULL;
- embFontList = NULL;
- customColors = NULL;
- t3String = NULL;
-
- init(outputFuncA, outputStreamA, psGeneric,
- xrefA, catalog, firstPage, lastPage, modeA);
-}
-
-void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
- PSFileType fileTypeA, XRef *xrefA, Catalog *catalog,
- int firstPage, int lastPage, PSOutMode modeA) {
- Page *page;
- PDFRectangle *box;
- Dict *resDict;
- Annots *annots;
- char **p;
- int pg;
- Object obj1, obj2;
- int i;
-
- // initialize
- ok = gTrue;
- outputFunc = outputFuncA;
- outputStream = outputStreamA;
- fileType = fileTypeA;
- xref = xrefA;
- level = globalParams->getPSLevel();
- mode = modeA;
- paperWidth = globalParams->getPSPaperWidth();
- paperHeight = globalParams->getPSPaperHeight();
- if (mode == psModeForm) {
- lastPage = firstPage;
- }
- processColors = 0;
- inType3Char = gFalse;
-
-#if OPI_SUPPORT
- // initialize OPI nesting levels
- opi13Nest = 0;
- opi20Nest = 0;
-#endif
-
- // initialize fontIDs, fontFileIDs, and fontFileNames lists
- fontIDSize = 64;
- fontIDLen = 0;
- fontIDs = (Ref *)gmalloc(fontIDSize * sizeof(Ref));
- fontFileIDSize = 64;
- fontFileIDLen = 0;
- fontFileIDs = (Ref *)gmalloc(fontFileIDSize * sizeof(Ref));
- fontFileNameSize = 64;
- fontFileNameLen = 0;
- fontFileNames = (GString **)gmalloc(fontFileNameSize * sizeof(GString *));
- font16EncLen = 0;
- font16EncSize = 0;
-
- // initialize embedded font resource comment list
- embFontList = new GString();
-
- // write header
- switch (mode) {
- case psModePS:
- writePS("%!PS-Adobe-3.0\n");
- writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
- writePSFmt("%%%%LanguageLevel: %d\n",
- (level == psLevel1 || level == psLevel1Sep) ? 1 :
- (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
- if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
- writePS("%%DocumentProcessColors: (atend)\n");
- writePS("%%DocumentCustomColors: (atend)\n");
- }
- writePS("%%DocumentSuppliedResources: (atend)\n");
- writePSFmt("%%%%DocumentMedia: plain %d %d 0 () ()\n",
- paperWidth, paperHeight);
- writePSFmt("%%%%Pages: %d\n", lastPage - firstPage + 1);
- writePS("%%EndComments\n");
- writePS("%%BeginDefaults\n");
- writePS("%%PageMedia: plain\n");
- writePS("%%EndDefaults\n");
- break;
- case psModeEPS:
- writePS("%!PS-Adobe-3.0 EPSF-3.0\n");
- writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
- writePSFmt("%%%%LanguageLevel: %d\n",
- (level == psLevel1 || level == psLevel1Sep) ? 1 :
- (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
- if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
- writePS("%%DocumentProcessColors: (atend)\n");
- writePS("%%DocumentCustomColors: (atend)\n");
- }
- page = catalog->getPage(firstPage);
- box = page->getBox();
- writePSFmt("%%%%BoundingBox: %d %d %d %d\n",
- (int)floor(box->x1), (int)floor(box->y1),
- (int)ceil(box->x2), (int)ceil(box->y2));
- if (floor(box->x1) != ceil(box->x1) ||
- floor(box->y1) != ceil(box->y1) ||
- floor(box->x2) != ceil(box->x2) ||
- floor(box->y2) != ceil(box->y2)) {
- writePSFmt("%%%%HiResBoundingBox: %g %g %g %g\n",
- box->x1, box->y1, box->x2, box->y2);
- }
- writePS("%%DocumentSuppliedResources: (atend)\n");
- writePS("%%EndComments\n");
- break;
- case psModeForm:
- writePS("%!PS-Adobe-3.0 Resource-Form\n");
- writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
- writePSFmt("%%%%LanguageLevel: %d\n",
- (level == psLevel1 || level == psLevel1Sep) ? 1 :
- (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
- if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
- writePS("%%DocumentProcessColors: (atend)\n");
- writePS("%%DocumentCustomColors: (atend)\n");
- }
- writePS("%%DocumentSuppliedResources: (atend)\n");
- writePS("%%EndComments\n");
- page = catalog->getPage(firstPage);
- box = page->getBox();
- writePS("32 dict dup begin\n");
- writePSFmt("/BBox [%d %d %d %d] def\n",
- (int)box->x1, (int)box->y1, (int)box->x2, (int)box->y2);
- writePS("/FormType 1 def\n");
- writePS("/Matrix [1 0 0 1 0 0] def\n");
- break;
- }
-
- // write prolog
- if (mode != psModeForm) {
- writePS("%%BeginProlog\n");
- }
- writePSFmt("%%%%BeginResource: procset xpdf %s 0\n", xpdfVersion);
- for (p = prolog; *p; ++p) {
- writePSFmt("%s\n", *p);
- }
- writePS("%%EndResource\n");
- if (level >= psLevel3) {
- for (p = cmapProlog; *p; ++p) {
- writePSFmt("%s\n", *p);
- }
- }
- if (mode != psModeForm) {
- writePS("%%EndProlog\n");
- }
-
- // set up fonts and images
- if (mode == psModeForm) {
- // swap the form and xpdf dicts
- writePS("xpdf end begin dup begin\n");
- } else {
- writePS("%%BeginSetup\n");
- writePS("xpdf begin\n");
- }
- for (pg = firstPage; pg <= lastPage; ++pg) {
- page = catalog->getPage(pg);
- if ((resDict = page->getResourceDict())) {
- setupResources(resDict);
- }
- annots = new Annots(xref, page->getAnnots(&obj1));
- obj1.free();
- for (i = 0; i < annots->getNumAnnots(); ++i) {
- if (annots->getAnnot(i)->getAppearance(&obj1)->isStream()) {
- obj1.streamGetDict()->lookup("Resources", &obj2);
- if (obj2.isDict()) {
- setupResources(obj2.getDict());
- }
- obj2.free();
- }
- obj1.free();
- }
- delete annots;
- }
- if (mode != psModeForm) {
- if (mode != psModeEPS) {
- writePSFmt("%d %d %s pdfSetup\n",
- paperWidth, paperHeight,
- globalParams->getPSDuplex() ? "true" : "false");
- }
-#if OPI_SUPPORT
- if (globalParams->getPSOPI()) {
- writePS("/opiMatrix matrix currentmatrix def\n");
- }
-#endif
- writePS("%%EndSetup\n");
- }
-
- // initialize sequential page number
- seqPage = 1;
-}
-
-PSOutputDev::~PSOutputDev() {
- PSOutCustomColor *cc;
- int i;
-
- if (ok) {
- if (mode == psModeForm) {
- writePS("/Foo exch /Form defineresource pop\n");
- } else {
- writePS("%%Trailer\n");
- writePS("end\n");
- writePS("%%DocumentSuppliedResources:\n");
- writePS(embFontList->getCString());
- if (level == psLevel1Sep || level == psLevel2Sep ||
- level == psLevel3Sep) {
- writePS("%%DocumentProcessColors:");
- if (processColors & psProcessCyan) {
- writePS(" Cyan");
- }
- if (processColors & psProcessMagenta) {
- writePS(" Magenta");
- }
- if (processColors & psProcessYellow) {
- writePS(" Yellow");
- }
- if (processColors & psProcessBlack) {
- writePS(" Black");
- }
- writePS("\n");
- writePS("%%DocumentCustomColors:");
- for (cc = customColors; cc; cc = cc->next) {
- writePSFmt(" (%s)", cc->name->getCString());
- }
- writePS("\n");
- writePS("%%CMYKCustomColor:\n");
- for (cc = customColors; cc; cc = cc->next) {
- writePSFmt("%%%%+ %g %g %g %g (%s)\n",
- cc->c, cc->m, cc->y, cc->k, cc->name->getCString());
- }
- }
- writePS("%%EOF\n");
- }
- if (fileType == psFile) {
-#ifdef MACOS
- ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
-#endif
- fclose((FILE *)outputStream);
- }
-#ifdef HAVE_POPEN
- else if (fileType == psPipe) {
- pclose((FILE *)outputStream);
-#ifndef WIN32
- signal(SIGPIPE, (SignalFunc)SIG_DFL);
-#endif
- }
-#endif
- }
- if (embFontList) {
- delete embFontList;
- }
- if (fontIDs) {
- gfree(fontIDs);
- }
- if (fontFileIDs) {
- gfree(fontFileIDs);
- }
- if (fontFileNames) {
- for (i = 0; i < fontFileNameLen; ++i) {
- delete fontFileNames[i];
- }
- gfree(fontFileNames);
- }
- if (font16Enc) {
- for (i = 0; i < font16EncLen; ++i) {
- delete font16Enc[i].enc;
- }
- gfree(font16Enc);
- }
- while (customColors) {
- cc = customColors;
- customColors = cc->next;
- delete cc;
- }
-}
-
-void PSOutputDev::setupResources(Dict *resDict) {
- Object xObjDict, xObj, resObj;
- int i;
-
- setupFonts(resDict);
- setupImages(resDict);
-
- resDict->lookup("XObject", &xObjDict);
- if (xObjDict.isDict()) {
- for (i = 0; i < xObjDict.dictGetLength(); ++i) {
- xObjDict.dictGetVal(i, &xObj);
- if (xObj.isStream()) {
- xObj.streamGetDict()->lookup("Resources", &resObj);
- if (resObj.isDict()) {
- setupResources(resObj.getDict());
- }
- resObj.free();
- }
- xObj.free();
- }
- }
- xObjDict.free();
-}
-
-void PSOutputDev::setupFonts(Dict *resDict) {
- Object fontDict;
- GfxFontDict *gfxFontDict;
- GfxFont *font;
- int i;
-
- resDict->lookup("Font", &fontDict);
- if (fontDict.isDict()) {
- gfxFontDict = new GfxFontDict(xref, fontDict.getDict());
- for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
- font = gfxFontDict->getFont(i);
- setupFont(font, resDict);
- }
- delete gfxFontDict;
- }
- fontDict.free();
-}
-
-void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
- Ref fontFileID;
- GString *name;
- PSFontParam *fontParam;
- GString *psNameStr;
- char *psName;
- char type3Name[64], buf[16];
- UnicodeMap *uMap;
- char *charName;
- double xs, ys;
- int code;
- double w1, w2;
- double *fm;
- int i, j;
-
- // check if font is already set up
- for (i = 0; i < fontIDLen; ++i) {
- if (fontIDs[i].num == font->getID()->num &&
- fontIDs[i].gen == font->getID()->gen) {
- return;
- }
- }
-
- // add entry to fontIDs list
- if (fontIDLen >= fontIDSize) {
- fontIDSize += 64;
- fontIDs = (Ref *)grealloc(fontIDs, fontIDSize * sizeof(Ref));
- }
- fontIDs[fontIDLen++] = *font->getID();
-
- xs = ys = 1;
- psNameStr = NULL;
-
- // check for resident 8-bit font
- if (font->getName() &&
- (fontParam = globalParams->getPSFont(font->getName()))) {
- psName = fontParam->psFontName->getCString();
-
- // check for embedded Type 1 font
- } else if (globalParams->getPSEmbedType1() &&
- font->getType() == fontType1 &&
- font->getEmbeddedFontID(&fontFileID)) {
- psNameStr = filterPSName(font->getEmbeddedFontName());
- psName = psNameStr->getCString();
- setupEmbeddedType1Font(&fontFileID, psName);
-
- // check for embedded Type 1C font
- } else if (globalParams->getPSEmbedType1() &&
- font->getType() == fontType1C &&
- font->getEmbeddedFontID(&fontFileID)) {
- psNameStr = filterPSName(font->getEmbeddedFontName());
- psName = psNameStr->getCString();
- setupEmbeddedType1CFont(font, &fontFileID, psName);
-
- // check for external Type 1 font file
- } else if (globalParams->getPSEmbedType1() &&
- font->getType() == fontType1 &&
- font->getExtFontFile()) {
- // this assumes that the PS font name matches the PDF font name
- psName = font->getName()->getCString();
- setupExternalType1Font(font->getExtFontFile(), psName);
-
- // check for embedded TrueType font
- } else if (globalParams->getPSEmbedTrueType() &&
- font->getType() == fontTrueType &&
- font->getEmbeddedFontID(&fontFileID)) {
- psNameStr = filterPSName(font->getEmbeddedFontName());
- psName = psNameStr->getCString();
- setupEmbeddedTrueTypeFont(font, &fontFileID, psName);
-
- // check for external TrueType font file
- } else if (globalParams->getPSEmbedTrueType() &&
- font->getType() == fontTrueType &&
- font->getExtFontFile()) {
- psNameStr = filterPSName(font->getName());
- psName = psNameStr->getCString();
- setupExternalTrueTypeFont(font, psName);
-
- // check for embedded CID PostScript font
- } else if (globalParams->getPSEmbedCIDPostScript() &&
- font->getType() == fontCIDType0C &&
- font->getEmbeddedFontID(&fontFileID)) {
- psNameStr = filterPSName(font->getEmbeddedFontName());
- psName = psNameStr->getCString();
- setupEmbeddedCIDType0Font(font, &fontFileID, psName);
-
- // check for embedded CID TrueType font
- } else if (globalParams->getPSEmbedCIDTrueType() &&
- font->getType() == fontCIDType2 &&
- font->getEmbeddedFontID(&fontFileID)) {
- psNameStr = filterPSName(font->getEmbeddedFontName());
- psName = psNameStr->getCString();
- setupEmbeddedCIDTrueTypeFont(font, &fontFileID, psName);
-
- } else if (font->getType() == fontType3) {
- sprintf(type3Name, "T3_%d_%d",
- font->getID()->num, font->getID()->gen);
- psName = type3Name;
- setupType3Font(font, psName, parentResDict);
-
- // do 8-bit font substitution
- } else if (!font->isCIDFont()) {
- name = font->getName();
- psName = NULL;
- if (name) {
- for (i = 0; psFonts[i]; ++i) {
- if (name->cmp(psFonts[i]) == 0) {
- psName = psFonts[i];
- break;
- }
- }
- }
- if (!psName) {
- if (font->isFixedWidth()) {
- i = 8;
- } else if (font->isSerif()) {
- i = 4;
- } else {
- i = 0;
- }
- if (font->isBold()) {
- i += 2;
- }
- if (font->isItalic()) {
- i += 1;
- }
- psName = psSubstFonts[i].psName;
- for (code = 0; code < 256; ++code) {
- if ((charName = ((Gfx8BitFont *)font)->getCharName(code)) &&
- charName[0] == 'm' && charName[1] == '\0') {
- break;
- }
- }
- if (code < 256) {
- w1 = ((Gfx8BitFont *)font)->getWidth(code);
- } else {
- w1 = 0;
- }
- w2 = psSubstFonts[i].mWidth;
- xs = w1 / w2;
- if (xs < 0.1) {
- xs = 1;
- }
- if (font->getType() == fontType3) {
- // This is a hack which makes it possible to substitute for some
- // Type 3 fonts. The problem is that it's impossible to know what
- // the base coordinate system used in the font is without actually
- // rendering the font.
- ys = xs;
- fm = font->getFontMatrix();
- if (fm[0] != 0) {
- ys *= fm[3] / fm[0];
- }
- } else {
- ys = 1;
- }
- }
-
- // do 16-bit font substitution
- } else if ((fontParam = globalParams->
- getPSFont16(font->getName(),
- ((GfxCIDFont *)font)->getCollection(),
- font->getWMode()))) {
- psName = fontParam->psFontName->getCString();
- if (font16EncLen >= font16EncSize) {
- font16EncSize += 16;
- font16Enc = (PSFont16Enc *)grealloc(font16Enc,
- font16EncSize * sizeof(PSFont16Enc));
- }
- font16Enc[font16EncLen].fontID = *font->getID();
- font16Enc[font16EncLen].enc = fontParam->encoding->copy();
- if ((uMap = globalParams->getUnicodeMap(font16Enc[font16EncLen].enc))) {
- uMap->decRefCnt();
- ++font16EncLen;
- } else {
- error(-1, "Couldn't find Unicode map for 16-bit font encoding '%s'",
- font16Enc[font16EncLen].enc->getCString());
- }
-
- // give up - can't do anything with this font
- } else {
- error(-1, "Couldn't find a font to substitute for '%s' ('%s' character collection)",
- font->getName() ? font->getName()->getCString() : "(unnamed)",
- ((GfxCIDFont *)font)->getCollection()
- ? ((GfxCIDFont *)font)->getCollection()->getCString()
- : "(unknown)");
- return;
- }
-
- // generate PostScript code to set up the font
- if (font->isCIDFont()) {
- if (level == psLevel3 || level == psLevel3Sep) {
- writePSFmt("/F%d_%d /%s %d pdfMakeFont16L3\n",
- font->getID()->num, font->getID()->gen, psName,
- font->getWMode());
- } else {
- writePSFmt("/F%d_%d /%s %d pdfMakeFont16\n",
- font->getID()->num, font->getID()->gen, psName,
- font->getWMode());
- }
- } else {
- writePSFmt("/F%d_%d /%s %g %g\n",
- font->getID()->num, font->getID()->gen, psName, xs, ys);
- for (i = 0; i < 256; i += 8) {
- writePSFmt((i == 0) ? "[ " : " ");
- for (j = 0; j < 8; ++j) {
- if (font->getType() == fontTrueType &&
- !((Gfx8BitFont *)font)->getHasEncoding()) {
- sprintf(buf, "c%02x", i+j);
- charName = buf;
- } else {
- charName = ((Gfx8BitFont *)font)->getCharName(i+j);
- // this is a kludge for broken PDF files that encode char 32
- // as .notdef
- if (i+j == 32 && charName && !strcmp(charName, ".notdef")) {
- charName = "space";
- }
- }
- writePS("/");
- writePSName(charName ? charName : (char *)".notdef");
- }
- writePS((i == 256-8) ? (char *)"]\n" : (char *)"\n");
- }
- writePS("pdfMakeFont\n");
- }
-
- if (psNameStr) {
- delete psNameStr;
- }
-}
-
-void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
- static char hexChar[17] = "0123456789abcdef";
- Object refObj, strObj, obj1, obj2;
- Dict *dict;
- int length1, length2;
- int c;
- int start[4];
- GBool binMode;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileIDLen; ++i) {
- if (fontFileIDs[i].num == id->num &&
- fontFileIDs[i].gen == id->gen)
- return;
- }
-
- // add entry to fontFileIDs list
- if (fontFileIDLen >= fontFileIDSize) {
- fontFileIDSize += 64;
- fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
- }
- fontFileIDs[fontFileIDLen++] = *id;
-
- // get the font stream and info
- refObj.initRef(id->num, id->gen);
- refObj.fetch(xref, &strObj);
- refObj.free();
- if (!strObj.isStream()) {
- error(-1, "Embedded font file object is not a stream");
- goto err1;
- }
- if (!(dict = strObj.streamGetDict())) {
- error(-1, "Embedded font stream is missing its dictionary");
- goto err1;
- }
- dict->lookup("Length1", &obj1);
- dict->lookup("Length2", &obj2);
- if (!obj1.isInt() || !obj2.isInt()) {
- error(-1, "Missing length fields in embedded font stream dictionary");
- obj1.free();
- obj2.free();
- goto err1;
- }
- length1 = obj1.getInt();
- length2 = obj2.getInt();
- obj1.free();
- obj2.free();
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // copy ASCII portion of font
- strObj.streamReset();
- for (i = 0; i < length1 && (c = strObj.streamGetChar()) != EOF; ++i) {
- writePSChar(c);
- }
-
- // figure out if encrypted portion is binary or ASCII
- binMode = gFalse;
- for (i = 0; i < 4; ++i) {
- start[i] = strObj.streamGetChar();
- if (start[i] == EOF) {
- error(-1, "Unexpected end of file in embedded font stream");
- goto err1;
- }
- if (!((start[i] >= '0' && start[i] <= '9') ||
- (start[i] >= 'A' && start[i] <= 'F') ||
- (start[i] >= 'a' && start[i] <= 'f')))
- binMode = gTrue;
- }
-
- // convert binary data to ASCII
- if (binMode) {
- for (i = 0; i < 4; ++i) {
- writePSChar(hexChar[(start[i] >> 4) & 0x0f]);
- writePSChar(hexChar[start[i] & 0x0f]);
- }
- while (i < length2) {
- if ((c = strObj.streamGetChar()) == EOF) {
- break;
- }
- writePSChar(hexChar[(c >> 4) & 0x0f]);
- writePSChar(hexChar[c & 0x0f]);
- if (++i % 32 == 0) {
- writePSChar('\n');
- }
- }
- if (i % 32 > 0) {
- writePSChar('\n');
- }
-
- // already in ASCII format -- just copy it
- } else {
- for (i = 0; i < 4; ++i) {
- writePSChar(start[i]);
- }
- for (i = 4; i < length2; ++i) {
- if ((c = strObj.streamGetChar()) == EOF) {
- break;
- }
- writePSChar(c);
- }
- }
-
- // write padding and "cleartomark"
- for (i = 0; i < 8; ++i) {
- writePS("00000000000000000000000000000000"
- "00000000000000000000000000000000\n");
- }
- writePS("cleartomark\n");
-
- // ending comment
- writePS("%%EndResource\n");
-
- err1:
- strObj.streamClose();
- strObj.free();
-}
-
-//~ This doesn't handle .pfb files or binary eexec data (which only
-//~ happens in pfb files?).
-void PSOutputDev::setupExternalType1Font(GString *fileName, char *psName) {
- FILE *fontFile;
- int c;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileNameLen; ++i) {
- if (!fontFileNames[i]->cmp(fileName)) {
- return;
- }
- }
-
- // add entry to fontFileNames list
- if (fontFileNameLen >= fontFileNameSize) {
- fontFileNameSize += 64;
- fontFileNames = (GString **)grealloc(fontFileNames,
- fontFileNameSize * sizeof(GString *));
- }
- fontFileNames[fontFileNameLen++] = fileName->copy();
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // copy the font file
- if (!(fontFile = fopen(fileName->getCString(), "rb"))) {
- error(-1, "Couldn't open external font file");
- return;
- }
- while ((c = fgetc(fontFile)) != EOF) {
- writePSChar(c);
- }
- fclose(fontFile);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
- char *psName) {
- char *fontBuf;
- int fontLen;
- Type1CFontFile *t1cFile;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileIDLen; ++i) {
- if (fontFileIDs[i].num == id->num &&
- fontFileIDs[i].gen == id->gen)
- return;
- }
-
- // add entry to fontFileIDs list
- if (fontFileIDLen >= fontFileIDSize) {
- fontFileIDSize += 64;
- fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
- }
- fontFileIDs[fontFileIDLen++] = *id;
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // convert it to a Type 1 font
- fontBuf = font->readEmbFontFile(xref, &fontLen);
- t1cFile = new Type1CFontFile(fontBuf, fontLen);
- t1cFile->convertToType1(outputFunc, outputStream);
- delete t1cFile;
- gfree(fontBuf);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id,
- char *psName) {
- char *fontBuf;
- int fontLen;
- TrueTypeFontFile *ttFile;
- CharCodeToUnicode *ctu;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileIDLen; ++i) {
- if (fontFileIDs[i].num == id->num &&
- fontFileIDs[i].gen == id->gen)
- return;
- }
-
- // add entry to fontFileIDs list
- if (fontFileIDLen >= fontFileIDSize) {
- fontFileIDSize += 64;
- fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
- }
- fontFileIDs[fontFileIDLen++] = *id;
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // convert it to a Type 42 font
- fontBuf = font->readEmbFontFile(xref, &fontLen);
- ttFile = new TrueTypeFontFile(fontBuf, fontLen);
- ctu = ((Gfx8BitFont *)font)->getToUnicode();
- ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
- ctu, ((Gfx8BitFont *)font)->getHasEncoding(),
- outputFunc, outputStream);
- ctu->decRefCnt();
- delete ttFile;
- gfree(fontBuf);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupExternalTrueTypeFont(GfxFont *font, char *psName) {
- GString *fileName;
- char *fontBuf;
- int fontLen;
- TrueTypeFontFile *ttFile;
- CharCodeToUnicode *ctu;
- int i;
-
- // check if font is already embedded
- fileName = font->getExtFontFile();
- for (i = 0; i < fontFileNameLen; ++i) {
- if (!fontFileNames[i]->cmp(fileName)) {
- return;
- }
- }
-
- // add entry to fontFileNames list
- if (fontFileNameLen >= fontFileNameSize) {
- fontFileNameSize += 64;
- fontFileNames = (GString **)grealloc(fontFileNames,
- fontFileNameSize * sizeof(GString *));
- }
- fontFileNames[fontFileNameLen++] = fileName->copy();
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // convert it to a Type 42 font
- fontBuf = font->readExtFontFile(&fontLen);
- ttFile = new TrueTypeFontFile(fontBuf, fontLen);
- ctu = ((Gfx8BitFont *)font)->getToUnicode();
- ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
- ctu, ((Gfx8BitFont *)font)->getHasEncoding(),
- outputFunc, outputStream);
- ctu->decRefCnt();
- delete ttFile;
- gfree(fontBuf);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
- char *psName) {
- char *fontBuf;
- int fontLen;
- Type1CFontFile *t1cFile;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileIDLen; ++i) {
- if (fontFileIDs[i].num == id->num &&
- fontFileIDs[i].gen == id->gen)
- return;
- }
-
- // add entry to fontFileIDs list
- if (fontFileIDLen >= fontFileIDSize) {
- fontFileIDSize += 64;
- fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
- }
- fontFileIDs[fontFileIDLen++] = *id;
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // convert it to a Type 0 font
- fontBuf = font->readEmbFontFile(xref, &fontLen);
- t1cFile = new Type1CFontFile(fontBuf, fontLen);
- if (globalParams->getPSLevel() >= psLevel3) {
- // Level 3: use a CID font
- t1cFile->convertToCIDType0(psName, outputFunc, outputStream);
- } else {
- // otherwise: use a non-CID composite font
- t1cFile->convertToType0(psName, outputFunc, outputStream);
- }
- delete t1cFile;
- gfree(fontBuf);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
- char *psName) {
- char *fontBuf;
- int fontLen;
- TrueTypeFontFile *ttFile;
- int i;
-
- // check if font is already embedded
- for (i = 0; i < fontFileIDLen; ++i) {
- if (fontFileIDs[i].num == id->num &&
- fontFileIDs[i].gen == id->gen)
- return;
- }
-
- // add entry to fontFileIDs list
- if (fontFileIDLen >= fontFileIDSize) {
- fontFileIDSize += 64;
- fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
- }
- fontFileIDs[fontFileIDLen++] = *id;
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // convert it to a Type 0 font
- fontBuf = font->readEmbFontFile(xref, &fontLen);
- ttFile = new TrueTypeFontFile(fontBuf, fontLen);
- if (globalParams->getPSLevel() >= psLevel3) {
- ttFile->convertToCIDType2(psName,
- ((GfxCIDFont *)font)->getCIDToGID(),
- ((GfxCIDFont *)font)->getCIDToGIDLen(),
- outputFunc, outputStream);
- } else {
- // otherwise: use a non-CID composite font
- ttFile->convertToType0(psName, ((GfxCIDFont *)font)->getCIDToGID(),
- ((GfxCIDFont *)font)->getCIDToGIDLen(),
- outputFunc, outputStream);
- }
- delete ttFile;
- gfree(fontBuf);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
- Dict *parentResDict) {
- Dict *resDict;
- Dict *charProcs;
- Object charProc;
- Gfx *gfx;
- PDFRectangle box;
- double *m;
- char buf[256];
- int i;
-
- // set up resources used by font
- if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
- setupResources(resDict);
- } else {
- resDict = parentResDict;
- }
-
- // beginning comment
- writePSFmt("%%%%BeginResource: font %s\n", psName);
- embFontList->append("%%+ font ");
- embFontList->append(psName);
- embFontList->append("\n");
-
- // font dictionary
- writePS("7 dict begin\n");
- writePS("/FontType 3 def\n");
- m = font->getFontMatrix();
- writePSFmt("/FontMatrix [%g %g %g %g %g %g] def\n",
- m[0], m[1], m[2], m[3], m[4], m[5]);
- m = font->getFontBBox();
- writePSFmt("/FontBBox [%g %g %g %g] def\n",
- m[0], m[1], m[2], m[3]);
- writePS("/Encoding 256 array def\n");
- writePS(" 0 1 255 { Encoding exch /.notdef put } for\n");
- writePS("/BuildGlyph {\n");
- writePS(" exch /CharProcs get exch\n");
- writePS(" 2 copy known not { pop /.notdef } if\n");
- writePS(" get exec\n");
- writePS("} bind def\n");
- writePS("/BuildChar {\n");
- writePS(" 1 index /Encoding get exch get\n");
- writePS(" 1 index /BuildGlyph get exec\n");
- writePS("} bind def\n");
- if ((charProcs = ((Gfx8BitFont *)font)->getCharProcs())) {
- writePSFmt("/CharProcs %d dict def\n", charProcs->getLength());
- writePS("CharProcs begin\n");
- box.x1 = m[0];
- box.y1 = m[1];
- box.x2 = m[2];
- box.y2 = m[3];
- gfx = new Gfx(xref, this, resDict, &box, gFalse, NULL);
- inType3Char = gTrue;
- t3Cacheable = gFalse;
- for (i = 0; i < charProcs->getLength(); ++i) {
- writePS("/");
- writePSName(charProcs->getKey(i));
- writePS(" {\n");
- gfx->display(charProcs->getVal(i, &charProc));
- charProc.free();
- if (t3String) {
- if (t3Cacheable) {
- sprintf(buf, "%g %g %g %g %g %g setcachedevice\n",
- t3WX, t3WY, t3LLX, t3LLY, t3URX, t3URY);
- } else {
- sprintf(buf, "%g %g setcharwidth\n", t3WX, t3WY);
- }
- (*outputFunc)(outputStream, buf, strlen(buf));
- (*outputFunc)(outputStream, t3String->getCString(),
- t3String->getLength());
- delete t3String;
- t3String = NULL;
- }
- (*outputFunc)(outputStream, "Q\n", 2);
- writePS("} def\n");
- }
- inType3Char = gFalse;
- delete gfx;
- writePS("end\n");
- }
- writePS("currentdict end\n");
- writePSFmt("/%s exch definefont pop\n", psName);
-
- // ending comment
- writePS("%%EndResource\n");
-}
-
-void PSOutputDev::setupImages(Dict *resDict) {
- Object xObjDict, xObj, xObjRef, subtypeObj;
- int i;
-
- if (mode != psModeForm) {
- return;
- }
-
- resDict->lookup("XObject", &xObjDict);
- if (xObjDict.isDict()) {
- for (i = 0; i < xObjDict.dictGetLength(); ++i) {
- xObjDict.dictGetValNF(i, &xObjRef);
- xObjDict.dictGetVal(i, &xObj);
- if (xObj.isStream()) {
- xObj.streamGetDict()->lookup("Subtype", &subtypeObj);
- if (subtypeObj.isName("Image")) {
- if (xObjRef.isRef()) {
- setupImage(xObjRef.getRef(), xObj.getStream());
- } else {
- error(-1, "Image in resource dict is not an indirect reference");
- }
- }
- subtypeObj.free();
- }
- xObj.free();
- xObjRef.free();
- }
- }
- xObjDict.free();
-}
-
-void PSOutputDev::setupImage(Ref id, Stream *str) {
- int c;
- int size, line, col, i;
-
- // construct an encoder stream
- if (globalParams->getPSASCIIHex()) {
- str = new ASCIIHexEncoder(str);
- } else {
- str = new ASCII85Encoder(str);
- }
-
- // compute image data size
- str->reset();
- col = size = 0;
- do {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- if (c == 'z') {
- ++col;
- } else {
- ++col;
- for (i = 1; i <= 4; ++i) {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- ++col;
- }
- }
- if (col > 225) {
- ++size;
- col = 0;
- }
- } while (c != '~' && c != EOF);
- ++size;
- writePSFmt("%d array dup /ImData_%d_%d exch def\n", size, id.num, id.gen);
-
- // write the data into the array
- str->reset();
- line = col = 0;
- writePS("dup 0 <~");
- do {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- if (c == 'z') {
- writePSChar(c);
- ++col;
- } else {
- writePSChar(c);
- ++col;
- for (i = 1; i <= 4; ++i) {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- writePSChar(c);
- ++col;
- }
- }
- // each line is: "dup nnnnn <~...data...~> put<eol>"
- // so max data length = 255 - 20 = 235
- // chunks are 1 or 4 bytes each, so we have to stop at 232
- // but make it 225 just to be safe
- if (col > 225) {
- writePS("~> put\n");
- ++line;
- writePSFmt("dup %d <~", line);
- col = 0;
- }
- } while (c != '~' && c != EOF);
- writePS("~> put\n");
- writePS("pop\n");
-
- delete str;
-}
-
-void PSOutputDev::startPage(int pageNum, GfxState *state) {
- int x1, y1, x2, y2, width, height, t;
-
-
- switch (mode) {
-
- case psModePS:
- writePSFmt("%%%%Page: %d %d\n", pageNum, seqPage);
- writePS("%%BeginPageSetup\n");
-
- // rotate, translate, and scale page
- x1 = (int)(state->getX1() + 0.5);
- y1 = (int)(state->getY1() + 0.5);
- x2 = (int)(state->getX2() + 0.5);
- y2 = (int)(state->getY2() + 0.5);
- width = x2 - x1;
- height = y2 - y1;
- if (width > height && width > paperWidth) {
- landscape = gTrue;
- writePSFmt("%%%%PageQt::Orientation: %s\n",
- state->getCTM()[0] ? "Landscape" : "Portrait");
- writePS("pdfStartPage\n");
- writePS("90 rotate\n");
- tx = -x1;
- ty = -(y1 + paperWidth);
- t = width;
- width = height;
- height = t;
- } else {
- landscape = gFalse;
- writePSFmt("%%%%PageQt::Orientation: %s\n",
- state->getCTM()[0] ? "Portrait" : "Landscape");
- writePS("pdfStartPage\n");
- tx = -x1;
- ty = -y1;
- }
- if (width < paperWidth) {
- tx += (paperWidth - width) / 2;
- }
- if (height < paperHeight) {
- ty += (paperHeight - height) / 2;
- }
- if (tx != 0 || ty != 0) {
- writePSFmt("%g %g translate\n", tx, ty);
- }
- if (width > paperWidth || height > paperHeight) {
- xScale = (double)paperWidth / (double)width;
- yScale = (double)paperHeight / (double)height;
- if (yScale < xScale) {
- xScale = yScale;
- } else {
- yScale = xScale;
- }
- writePSFmt("%0.4f %0.4f scale\n", xScale, xScale);
- } else {
- xScale = yScale = 1;
- }
-
- writePS("%%EndPageSetup\n");
- ++seqPage;
- break;
-
- case psModeEPS:
- writePS("pdfStartPage\n");
- tx = ty = 0;
- xScale = yScale = 1;
- landscape = gFalse;
- break;
-
- case psModeForm:
- writePS("/PaintProc {\n");
- writePS("begin xpdf begin\n");
- writePS("pdfStartPage\n");
- tx = ty = 0;
- xScale = yScale = 1;
- landscape = gFalse;
- break;
- }
-}
-
-void PSOutputDev::endPage() {
-
- if (mode == psModeForm) {
- writePS("pdfEndPage\n");
- writePS("end end\n");
- writePS("} def\n");
- writePS("end end\n");
- } else {
- writePS("showpage\n");
- writePS("%%PageTrailer\n");
- writePS("pdfEndPage\n");
- }
-}
-
-void PSOutputDev::saveState(GfxState *state) {
- writePS("q\n");
-}
-
-void PSOutputDev::restoreState(GfxState *state) {
- writePS("Q\n");
-}
-
-void PSOutputDev::updateCTM(GfxState *state, double m11, double m12,
- double m21, double m22, double m31, double m32) {
- writePSFmt("[%g %g %g %g %g %g] cm\n", m11, m12, m21, m22, m31, m32);
-}
-
-void PSOutputDev::updateLineDash(GfxState *state) {
- double *dash;
- double start;
- int length, i;
-
- state->getLineDash(&dash, &length, &start);
- writePS("[");
- for (i = 0; i < length; ++i)
- writePSFmt("%g%s", dash[i], (i == length-1) ? "" : " ");
- writePSFmt("] %g d\n", start);
-}
-
-void PSOutputDev::updateFlatness(GfxState *state) {
- writePSFmt("%d i\n", state->getFlatness());
-}
-
-void PSOutputDev::updateLineJoin(GfxState *state) {
- writePSFmt("%d j\n", state->getLineJoin());
-}
-
-void PSOutputDev::updateLineCap(GfxState *state) {
- writePSFmt("%d J\n", state->getLineCap());
-}
-
-void PSOutputDev::updateMiterLimit(GfxState *state) {
- writePSFmt("%g M\n", state->getMiterLimit());
-}
-
-void PSOutputDev::updateLineWidth(GfxState *state) {
- writePSFmt("%g w\n", state->getLineWidth());
-}
-
-void PSOutputDev::updateFillColor(GfxState *state) {
- GfxColor color;
- double gray;
- GfxRGB rgb;
- GfxCMYK cmyk;
- GfxSeparationColorSpace *sepCS;
-
- switch (level) {
- case psLevel1:
- state->getFillGray(&gray);
- writePSFmt("%g g\n", gray);
- break;
- case psLevel1Sep:
- state->getFillCMYK(&cmyk);
- writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- break;
- case psLevel2:
- case psLevel3:
- if (state->getFillColorSpace()->getMode() == csDeviceCMYK) {
- state->getFillCMYK(&cmyk);
- writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- } else {
- state->getFillRGB(&rgb);
- if (rgb.r == rgb.g && rgb.g == rgb.b) {
- writePSFmt("%g g\n", rgb.r);
- } else {
- writePSFmt("%g %g %g rg\n", rgb.r, rgb.g, rgb.b);
- }
- }
- break;
- case psLevel2Sep:
- case psLevel3Sep:
- if (state->getFillColorSpace()->getMode() == csSeparation) {
- sepCS = (GfxSeparationColorSpace *)state->getFillColorSpace();
- color.c[0] = 1;
- sepCS->getCMYK(&color, &cmyk);
- writePSFmt("%g %g %g %g %g (%s) ck\n",
- state->getFillColor()->c[0],
- cmyk.c, cmyk.m, cmyk.y, cmyk.k,
- sepCS->getName()->getCString());
- addCustomColor(sepCS);
- } else {
- state->getFillCMYK(&cmyk);
- writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- }
- break;
- }
- t3Cacheable = gFalse;
-}
-
-void PSOutputDev::updateStrokeColor(GfxState *state) {
- GfxColor color;
- double gray;
- GfxRGB rgb;
- GfxCMYK cmyk;
- GfxSeparationColorSpace *sepCS;
-
- switch (level) {
- case psLevel1:
- state->getStrokeGray(&gray);
- writePSFmt("%g G\n", gray);
- break;
- case psLevel1Sep:
- state->getStrokeCMYK(&cmyk);
- writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- break;
- case psLevel2:
- case psLevel3:
- if (state->getStrokeColorSpace()->getMode() == csDeviceCMYK) {
- state->getStrokeCMYK(&cmyk);
- writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- } else {
- state->getStrokeRGB(&rgb);
- if (rgb.r == rgb.g && rgb.g == rgb.b) {
- writePSFmt("%g G\n", rgb.r);
- } else {
- writePSFmt("%g %g %g RG\n", rgb.r, rgb.g, rgb.b);
- }
- }
- break;
- case psLevel2Sep:
- case psLevel3Sep:
- if (state->getStrokeColorSpace()->getMode() == csSeparation) {
- sepCS = (GfxSeparationColorSpace *)state->getStrokeColorSpace();
- color.c[0] = 1;
- sepCS->getCMYK(&color, &cmyk);
- writePSFmt("%g %g %g %g %g (%s) CK\n",
- state->getStrokeColor()->c[0],
- cmyk.c, cmyk.m, cmyk.y, cmyk.k,
- sepCS->getName()->getCString());
- addCustomColor(sepCS);
- } else {
- state->getStrokeCMYK(&cmyk);
- writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- }
- break;
- }
- t3Cacheable = gFalse;
-}
-
-void PSOutputDev::addProcessColor(double c, double m, double y, double k) {
- if (c > 0) {
- processColors |= psProcessCyan;
- }
- if (m > 0) {
- processColors |= psProcessMagenta;
- }
- if (y > 0) {
- processColors |= psProcessYellow;
- }
- if (k > 0) {
- processColors |= psProcessBlack;
- }
-}
-
-void PSOutputDev::addCustomColor(GfxSeparationColorSpace *sepCS) {
- PSOutCustomColor *cc;
- GfxColor color;
- GfxCMYK cmyk;
-
- for (cc = customColors; cc; cc = cc->next) {
- if (!cc->name->cmp(sepCS->getName())) {
- return;
- }
- }
- color.c[0] = 1;
- sepCS->getCMYK(&color, &cmyk);
- cc = new PSOutCustomColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k,
- sepCS->getName()->copy());
- cc->next = customColors;
- customColors = cc;
-}
-
-void PSOutputDev::updateFont(GfxState *state) {
- if (state->getFont()) {
- writePSFmt("/F%d_%d %g Tf\n",
- state->getFont()->getID()->num, state->getFont()->getID()->gen,
- state->getFontSize());
- }
-}
-
-void PSOutputDev::updateTextMat(GfxState *state) {
- double *mat;
-
- mat = state->getTextMat();
- writePSFmt("[%g %g %g %g %g %g] Tm\n",
- mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
-}
-
-void PSOutputDev::updateCharSpace(GfxState *state) {
- writePSFmt("%g Tc\n", state->getCharSpace());
-}
-
-void PSOutputDev::updateRender(GfxState *state) {
- int rm;
-
- rm = state->getRender();
- writePSFmt("%d Tr\n", rm);
- rm &= 3;
- if (rm != 0 && rm != 3) {
- t3Cacheable = gFalse;
- }
-}
-
-void PSOutputDev::updateRise(GfxState *state) {
- writePSFmt("%g Ts\n", state->getRise());
-}
-
-void PSOutputDev::updateWordSpace(GfxState *state) {
- writePSFmt("%g Tw\n", state->getWordSpace());
-}
-
-void PSOutputDev::updateHorizScaling(GfxState *state) {
- writePSFmt("%g Tz\n", state->getHorizScaling());
-}
-
-void PSOutputDev::updateTextPos(GfxState *state) {
- writePSFmt("%g %g Td\n", state->getLineX(), state->getLineY());
-}
-
-void PSOutputDev::updateTextShift(GfxState *state, double shift) {
- if (state->getFont()->getWMode()) {
- writePSFmt("%g TJmV\n", shift);
- } else {
- writePSFmt("%g TJm\n", shift);
- }
-}
-
-void PSOutputDev::stroke(GfxState *state) {
- doPath(state->getPath());
- if (t3String) {
- // if we're construct a cacheable Type 3 glyph, we need to do
- // everything in the fill color
- writePS("Sf\n");
- } else {
- writePS("S\n");
- }
-}
-
-void PSOutputDev::fill(GfxState *state) {
- doPath(state->getPath());
- writePS("f\n");
-}
-
-void PSOutputDev::eoFill(GfxState *state) {
- doPath(state->getPath());
- writePS("f*\n");
-}
-
-void PSOutputDev::clip(GfxState *state) {
- doPath(state->getPath());
- writePS("W\n");
-}
-
-void PSOutputDev::eoClip(GfxState *state) {
- doPath(state->getPath());
- writePS("W*\n");
-}
-
-void PSOutputDev::doPath(GfxPath *path) {
- GfxSubpath *subpath;
- double x0, y0, x1, y1, x2, y2, x3, y3, x4, y4;
- int n, m, i, j;
-
- n = path->getNumSubpaths();
-
- if (n == 1 && path->getSubpath(0)->getNumPoints() == 5) {
- subpath = path->getSubpath(0);
- x0 = subpath->getX(0);
- y0 = subpath->getY(0);
- x4 = subpath->getX(4);
- y4 = subpath->getY(4);
- if (x4 == x0 && y4 == y0) {
- x1 = subpath->getX(1);
- y1 = subpath->getY(1);
- x2 = subpath->getX(2);
- y2 = subpath->getY(2);
- x3 = subpath->getX(3);
- y3 = subpath->getY(3);
- if (x0 == x1 && x2 == x3 && y0 == y3 && y1 == y2) {
- writePSFmt("%g %g %g %g re\n",
- x0 < x2 ? x0 : x2, y0 < y1 ? y0 : y1,
- fabs(x2 - x0), fabs(y1 - y0));
- return;
- } else if (x0 == x3 && x1 == x2 && y0 == y1 && y2 == y3) {
- writePSFmt("%g %g %g %g re\n",
- x0 < x1 ? x0 : x1, y0 < y2 ? y0 : y2,
- fabs(x1 - x0), fabs(y2 - y0));
- return;
- }
- }
- }
-
- for (i = 0; i < n; ++i) {
- subpath = path->getSubpath(i);
- m = subpath->getNumPoints();
- writePSFmt("%g %g m\n", subpath->getX(0), subpath->getY(0));
- j = 1;
- while (j < m) {
- if (subpath->getCurve(j)) {
- writePSFmt("%g %g %g %g %g %g c\n", subpath->getX(j), subpath->getY(j),
- subpath->getX(j+1), subpath->getY(j+1),
- subpath->getX(j+2), subpath->getY(j+2));
- j += 3;
- } else {
- writePSFmt("%g %g l\n", subpath->getX(j), subpath->getY(j));
- ++j;
- }
- }
- if (subpath->isClosed()) {
- writePS("h\n");
- }
- }
-}
-
-void PSOutputDev::drawString(GfxState *state, GString *s) {
- GfxFont *font;
- int wMode;
- GString *s2;
- double dx, dy, dx2, dy2, originX, originY;
- char *p;
- UnicodeMap *uMap;
- CharCode code;
- Unicode u[8];
- char buf[8];
- int len, nChars, uLen, n, m, i, j;
-
- // check for invisible text -- this is used by Acrobat Capture
- if ((state->getRender() & 3) == 3) {
- return;
- }
-
- // ignore empty strings
- if (s->getLength() == 0) {
- return;
- }
-
- // get the font
- if (!(font = state->getFont())) {
- return;
- }
- wMode = font->getWMode();
-
- // check for a subtitute 16-bit font
- uMap = NULL;
- if (font->isCIDFont()) {
- for (i = 0; i < font16EncLen; ++i) {
- if (font->getID()->num == font16Enc[i].fontID.num &&
- font->getID()->gen == font16Enc[i].fontID.gen) {
- uMap = globalParams->getUnicodeMap(font16Enc[i].enc);
- break;
- }
- }
- }
-
- // compute width of chars in string, ignoring char spacing and word
- // spacing -- the Tj operator will adjust for the metrics of the
- // font that's actually used
- dx = dy = 0;
- nChars = 0;
- p = s->getCString();
- len = s->getLength();
- if (font->isCIDFont()) {
- s2 = new GString();
- } else {
- s2 = s;
- }
- while (len > 0) {
- n = font->getNextChar(p, len, &code,
- u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
- &dx2, &dy2, &originX, &originY);
- if (font->isCIDFont()) {
- if (uMap) {
- for (i = 0; i < uLen; ++i) {
- m = uMap->mapUnicode(u[i], buf, (int)sizeof(buf));
- for (j = 0; j < m; ++j) {
- s2->append(buf[j]);
- }
- }
- //~ this really needs to get the number of chars in the target
- //~ encoding - which may be more than the number of Unicode
- //~ chars
- nChars += uLen;
- } else {
- s2->append((char)((code >> 8) & 0xff));
- s2->append((char)(code & 0xff));
- ++nChars;
- }
- }
- dx += dx2;
- dy += dy2;
- p += n;
- len -= n;
- }
- dx *= state->getFontSize() * state->getHorizScaling();
- dy *= state->getFontSize();
- if (uMap) {
- uMap->decRefCnt();
- }
-
- if (s2->getLength() > 0) {
- writePSString(s2);
- if (font->isCIDFont()) {
- if (wMode) {
- writePSFmt(" %d %g Tj16V\n", nChars, dy);
- } else {
- writePSFmt(" %d %g Tj16\n", nChars, dx);
- }
- } else {
- writePSFmt(" %g Tj\n", dx);
- }
- }
- if (font->isCIDFont()) {
- delete s2;
- }
-}
-
-void PSOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
- int width, int height, GBool invert,
- GBool inlineImg) {
- int len;
-
- len = height * ((width + 7) / 8);
- if (level == psLevel1 || level == psLevel1Sep) {
- doImageL1(NULL, invert, inlineImg, str, width, height, len);
- } else {
- doImageL2(ref, NULL, invert, inlineImg, str, width, height, len);
- }
-}
-
-void PSOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
- int width, int height, GfxImageColorMap *colorMap,
- int *maskColors, GBool inlineImg) {
- int len;
-
- len = height * ((width * colorMap->getNumPixelComps() *
- colorMap->getBits() + 7) / 8);
- switch (level) {
- case psLevel1:
- doImageL1(colorMap, gFalse, inlineImg, str, width, height, len);
- break;
- case psLevel1Sep:
- //~ handle indexed, separation, ... color spaces
- doImageL1Sep(colorMap, gFalse, inlineImg, str, width, height, len);
- break;
- case psLevel2:
- case psLevel2Sep:
- case psLevel3:
- case psLevel3Sep:
- doImageL2(ref, colorMap, gFalse, inlineImg, str, width, height, len);
- break;
- }
- t3Cacheable = gFalse;
-}
-
-void PSOutputDev::doImageL1(GfxImageColorMap *colorMap,
- GBool invert, GBool inlineImg,
- Stream *str, int width, int height, int len) {
- ImageStream *imgStr;
- Guchar pixBuf[gfxColorMaxComps];
- double gray;
- int x, y, i;
-
- // width, height, matrix, bits per component
- if (colorMap) {
- writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1\n",
- width, height,
- width, -height, height);
- } else {
- writePSFmt("%d %d %s [%d 0 0 %d 0 %d] pdfImM1\n",
- width, height, invert ? "true" : "false",
- width, -height, height);
- }
-
- // image
- if (colorMap) {
-
- // set up to process the data stream
- imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
- colorMap->getBits());
- imgStr->reset();
-
- // process the data stream
- i = 0;
- for (y = 0; y < height; ++y) {
-
- // write the line
- for (x = 0; x < width; ++x) {
- imgStr->getPixel(pixBuf);
- colorMap->getGray(pixBuf, &gray);
- writePSFmt("%02x", (int)(gray * 255 + 0.5));
- if (++i == 32) {
- writePSChar('\n');
- i = 0;
- }
- }
- }
- if (i != 0) {
- writePSChar('\n');
- }
- delete imgStr;
-
- // imagemask
- } else {
- str->reset();
- i = 0;
- for (y = 0; y < height; ++y) {
- for (x = 0; x < width; x += 8) {
- writePSFmt("%02x", str->getChar() & 0xff);
- if (++i == 32) {
- writePSChar('\n');
- i = 0;
- }
- }
- }
- if (i != 0) {
- writePSChar('\n');
- }
- str->close();
- }
-}
-
-void PSOutputDev::doImageL1Sep(GfxImageColorMap *colorMap,
- GBool invert, GBool inlineImg,
- Stream *str, int width, int height, int len) {
- ImageStream *imgStr;
- Guchar *lineBuf;
- Guchar pixBuf[gfxColorMaxComps];
- GfxCMYK cmyk;
- int x, y, i, comp;
-
- // width, height, matrix, bits per component
- writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1Sep\n",
- width, height,
- width, -height, height);
-
- // allocate a line buffer
- lineBuf = (Guchar *)gmalloc(4 * width);
-
- // set up to process the data stream
- imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
- colorMap->getBits());
- imgStr->reset();
-
- // process the data stream
- i = 0;
- for (y = 0; y < height; ++y) {
-
- // read the line
- for (x = 0; x < width; ++x) {
- imgStr->getPixel(pixBuf);
- colorMap->getCMYK(pixBuf, &cmyk);
- lineBuf[4*x+0] = (int)(255 * cmyk.c + 0.5);
- lineBuf[4*x+1] = (int)(255 * cmyk.m + 0.5);
- lineBuf[4*x+2] = (int)(255 * cmyk.y + 0.5);
- lineBuf[4*x+3] = (int)(255 * cmyk.k + 0.5);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- }
-
- // write one line of each color component
- for (comp = 0; comp < 4; ++comp) {
- for (x = 0; x < width; ++x) {
- writePSFmt("%02x", lineBuf[4*x + comp]);
- if (++i == 32) {
- writePSChar('\n');
- i = 0;
- }
- }
- }
- }
-
- if (i != 0) {
- writePSChar('\n');
- }
-
- delete imgStr;
- gfree(lineBuf);
-}
-
-void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
- GBool invert, GBool inlineImg,
- Stream *str, int width, int height, int len) {
- GString *s;
- int n, numComps;
- GBool useRLE, useASCII, useCompressed;
- GfxSeparationColorSpace *sepCS;
- GfxColor color;
- GfxCMYK cmyk;
- int c;
- int line, col, i;
-
- // color space
- if (colorMap) {
- dumpColorSpaceL2(colorMap->getColorSpace());
- writePS(" setcolorspace\n");
- }
-
- // set up the image data
- if (mode == psModeForm || inType3Char) {
- if (inlineImg) {
- // create an array
- str = new FixedLengthEncoder(str, len);
- if (globalParams->getPSASCIIHex()) {
- str = new ASCIIHexEncoder(str);
- } else {
- str = new ASCII85Encoder(str);
- }
- str->reset();
- line = col = 0;
- writePS("[<~");
- do {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- if (c == 'z') {
- writePSChar(c);
- ++col;
- } else {
- writePSChar(c);
- ++col;
- for (i = 1; i <= 4; ++i) {
- do {
- c = str->getChar();
- } while (c == '\n' || c == '\r');
- if (c == '~' || c == EOF) {
- break;
- }
- writePSChar(c);
- ++col;
- }
- }
- // each line is: "dup nnnnn <~...data...~> put<eol>"
- // so max data length = 255 - 20 = 235
- // chunks are 1 or 4 bytes each, so we have to stop at 232
- // but make it 225 just to be safe
- if (col > 225) {
- writePS("~>\n");
- ++line;
- writePSFmt("<~", line);
- col = 0;
- }
- } while (c != '~' && c != EOF);
- writePS("~>]\n");
- writePS("0\n");
- delete str;
- } else {
- // set up to use the array already created by setupImages()
- writePSFmt("ImData_%d_%d 0\n", ref->getRefNum(), ref->getRefGen());
- }
- }
-
- // image dictionary
- writePS("<<\n /ImageType 1\n");
-
- // width, height, matrix, bits per component
- writePSFmt(" /Width %d\n", width);
- writePSFmt(" /Height %d\n", height);
- writePSFmt(" /ImageMatrix [%d 0 0 %d 0 %d]\n", width, -height, height);
- writePSFmt(" /BitsPerComponent %d\n",
- colorMap ? colorMap->getBits() : 1);
-
- // decode
- if (colorMap) {
- writePS(" /Decode [");
- if (colorMap->getColorSpace()->getMode() == csSeparation) {
- //~ this is a kludge -- see comment in dumpColorSpaceL2
- n = (1 << colorMap->getBits()) - 1;
- writePSFmt("%g %g", colorMap->getDecodeLow(0) * n,
- colorMap->getDecodeHigh(0) * n);
- } else {
- numComps = colorMap->getNumPixelComps();
- for (i = 0; i < numComps; ++i) {
- if (i > 0) {
- writePS(" ");
- }
- writePSFmt("%g %g", colorMap->getDecodeLow(i),
- colorMap->getDecodeHigh(i));
- }
- }
- writePS("]\n");
- } else {
- writePSFmt(" /Decode [%d %d]\n", invert ? 1 : 0, invert ? 0 : 1);
- }
-
- if (mode == psModeForm || inType3Char) {
-
- // data source
- writePS(" /DataSource { 2 copy get exch 1 add exch }\n");
-
- // end of image dictionary
- writePSFmt(">>\n%s\n", colorMap ? "image" : "imagemask");
-
- // get rid of the array and index
- writePS("pop pop\n");
-
- } else {
-
- // data source
- writePS(" /DataSource currentfile\n");
- s = str->getPSFilter(" ");
- if (inlineImg || !s) {
- useRLE = gTrue;
- useASCII = gTrue;
- useCompressed = gFalse;
- } else {
- useRLE = gFalse;
- useASCII = str->isBinary();
- useCompressed = gTrue;
- }
- if (useASCII) {
- writePSFmt(" /ASCII%sDecode filter\n",
- globalParams->getPSASCIIHex() ? "Hex" : "85");
- }
- if (useRLE) {
- writePS(" /RunLengthDecode filter\n");
- }
- if (useCompressed) {
- writePS(s->getCString());
- }
- if (s) {
- delete s;
- }
-
- // cut off inline image streams at appropriate length
- if (inlineImg) {
- str = new FixedLengthEncoder(str, len);
- } else if (useCompressed) {
- str = str->getBaseStream();
- }
-
- // add RunLengthEncode and ASCIIHex/85 encode filters
- if (useRLE) {
- str = new RunLengthEncoder(str);
- }
- if (useASCII) {
- if (globalParams->getPSASCIIHex()) {
- str = new ASCIIHexEncoder(str);
- } else {
- str = new ASCII85Encoder(str);
- }
- }
-
- // end of image dictionary
- writePS(">>\n");
-#if OPI_SUPPORT
- if (opi13Nest) {
- if (inlineImg) {
- // this can't happen -- OPI dictionaries are in XObjects
- error(-1, "Internal: OPI in inline image");
- n = 0;
- } else {
- // need to read the stream to count characters -- the length
- // is data-dependent (because of ASCII and RLE filters)
- str->reset();
- n = 0;
- while ((c = str->getChar()) != EOF) {
- ++n;
- }
- str->close();
- }
- // +6/7 for "pdfIm\n" / "pdfImM\n"
- // +8 for newline + trailer
- n += colorMap ? 14 : 15;
- writePSFmt("%%%%BeginData: %d Hex Bytes\n", n);
- }
-#endif
- if ((level == psLevel2Sep || level == psLevel3Sep) && colorMap &&
- colorMap->getColorSpace()->getMode() == csSeparation) {
- color.c[0] = 1;
- sepCS = (GfxSeparationColorSpace *)colorMap->getColorSpace();
- sepCS->getCMYK(&color, &cmyk);
- writePSFmt("%g %g %g %g (%s) pdfImSep\n",
- cmyk.c, cmyk.m, cmyk.y, cmyk.k,
- sepCS->getName()->getCString());
- } else {
- writePSFmt("%s\n", colorMap ? "pdfIm" : "pdfImM");
- }
-
- // copy the stream data
- str->reset();
- while ((c = str->getChar()) != EOF) {
- writePSChar(c);
- }
- str->close();
-
- // add newline and trailer to the end
- writePSChar('\n');
- writePS("%-EOD-\n");
-#if OPI_SUPPORT
- if (opi13Nest) {
- writePS("%%EndData\n");
- }
-#endif
-
- // delete encoders
- if (useRLE || useASCII || inlineImg) {
- delete str;
- }
- }
-}
-
-void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
- GfxCalGrayColorSpace *calGrayCS;
- GfxCalRGBColorSpace *calRGBCS;
- GfxLabColorSpace *labCS;
- GfxIndexedColorSpace *indexedCS;
- GfxSeparationColorSpace *separationCS;
- GfxColorSpace *baseCS;
- Guchar *lookup, *p;
- double x[gfxColorMaxComps], y[gfxColorMaxComps];
- GfxColor color;
- GfxCMYK cmyk;
- Function *func;
- int n, numComps, numAltComps;
- int byte;
- int i, j, k;
-
- switch (colorSpace->getMode()) {
-
- case csDeviceGray:
- writePS("/DeviceGray");
- processColors |= psProcessBlack;
- break;
-
- case csCalGray:
- calGrayCS = (GfxCalGrayColorSpace *)colorSpace;
- writePS("[/CIEBasedA <<\n");
- writePSFmt(" /DecodeA {%g exp} bind\n", calGrayCS->getGamma());
- writePSFmt(" /MatrixA [%g %g %g]\n",
- calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
- calGrayCS->getWhiteZ());
- writePSFmt(" /WhitePoint [%g %g %g]\n",
- calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
- calGrayCS->getWhiteZ());
- writePSFmt(" /BlackPoint [%g %g %g]\n",
- calGrayCS->getBlackX(), calGrayCS->getBlackY(),
- calGrayCS->getBlackZ());
- writePS(">>]");
- processColors |= psProcessBlack;
- break;
-
- case csDeviceRGB:
- writePS("/DeviceRGB");
- processColors |= psProcessCMYK;
- break;
-
- case csCalRGB:
- calRGBCS = (GfxCalRGBColorSpace *)colorSpace;
- writePS("[/CIEBasedABC <<\n");
- writePSFmt(" /DecodeABC [{%g exp} bind {%g exp} bind {%g exp} bind]\n",
- calRGBCS->getGammaR(), calRGBCS->getGammaG(),
- calRGBCS->getGammaB());
- writePSFmt(" /MatrixABC [%g %g %g %g %g %g %g %g %g]\n",
- calRGBCS->getMatrix()[0], calRGBCS->getMatrix()[1],
- calRGBCS->getMatrix()[2], calRGBCS->getMatrix()[3],
- calRGBCS->getMatrix()[4], calRGBCS->getMatrix()[5],
- calRGBCS->getMatrix()[6], calRGBCS->getMatrix()[7],
- calRGBCS->getMatrix()[8]);
- writePSFmt(" /WhitePoint [%g %g %g]\n",
- calRGBCS->getWhiteX(), calRGBCS->getWhiteY(),
- calRGBCS->getWhiteZ());
- writePSFmt(" /BlackPoint [%g %g %g]\n",
- calRGBCS->getBlackX(), calRGBCS->getBlackY(),
- calRGBCS->getBlackZ());
- writePS(">>]");
- processColors |= psProcessCMYK;
- break;
-
- case csDeviceCMYK:
- writePS("/DeviceCMYK");
- processColors |= psProcessCMYK;
- break;
-
- case csLab:
- labCS = (GfxLabColorSpace *)colorSpace;
- writePS("[/CIEBasedABC <<\n");
- writePSFmt(" /RangeABC [0 100 %g %g %g %g]\n",
- labCS->getAMin(), labCS->getAMax(),
- labCS->getBMin(), labCS->getBMax());
- writePS(" /DecodeABC [{16 add 116 div} bind {500 div} bind {200 div} bind]\n");
- writePS(" /MatrixABC [1 1 1 1 0 0 0 0 -1]\n");
- writePS(" /DecodeLMN\n");
- writePS(" [{dup 6 29 div ge {dup dup mul mul}\n");
- writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
- labCS->getWhiteX());
- writePS(" {dup 6 29 div ge {dup dup mul mul}\n");
- writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
- labCS->getWhiteY());
- writePS(" {dup 6 29 div ge {dup dup mul mul}\n");
- writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind]\n",
- labCS->getWhiteZ());
- writePSFmt(" /WhitePoint [%g %g %g]\n",
- labCS->getWhiteX(), labCS->getWhiteY(), labCS->getWhiteZ());
- writePSFmt(" /BlackPoint [%g %g %g]\n",
- labCS->getBlackX(), labCS->getBlackY(), labCS->getBlackZ());
- writePS(">>]");
- processColors |= psProcessCMYK;
- break;
-
- case csICCBased:
- dumpColorSpaceL2(((GfxICCBasedColorSpace *)colorSpace)->getAlt());
- break;
-
- case csIndexed:
- indexedCS = (GfxIndexedColorSpace *)colorSpace;
- baseCS = indexedCS->getBase();
- writePS("[/Indexed ");
- dumpColorSpaceL2(baseCS);
- n = indexedCS->getIndexHigh();
- numComps = baseCS->getNComps();
- lookup = indexedCS->getLookup();
- writePSFmt(" %d <\n", n);
- if (baseCS->getMode() == csDeviceN) {
- func = ((GfxDeviceNColorSpace *)baseCS)->getTintTransformFunc();
- numAltComps = ((GfxDeviceNColorSpace *)baseCS)->getAlt()->getNComps();
- p = lookup;
- for (i = 0; i <= n; i += 8) {
- writePS(" ");
- for (j = i; j < i+8 && j <= n; ++j) {
- for (k = 0; k < numComps; ++k) {
- x[k] = *p++ / 255.0;
- }
- func->transform(x, y);
- for (k = 0; k < numAltComps; ++k) {
- byte = (int)(y[k] * 255 + 0.5);
- if (byte < 0) {
- byte = 0;
- } else if (byte > 255) {
- byte = 255;
- }
- writePSFmt("%02x", byte);
- }
- color.c[0] = j;
- indexedCS->getCMYK(&color, &cmyk);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- }
- writePS("\n");
- }
- } else {
- for (i = 0; i <= n; i += 8) {
- writePS(" ");
- for (j = i; j < i+8 && j <= n; ++j) {
- for (k = 0; k < numComps; ++k) {
- writePSFmt("%02x", lookup[j * numComps + k]);
- }
- color.c[0] = j;
- indexedCS->getCMYK(&color, &cmyk);
- addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
- }
- writePS("\n");
- }
- }
- writePS(">]");
- break;
-
- case csSeparation:
- //~ this is a kludge -- the correct thing would to output a
- //~ separation color space, with the specified alternate color
- //~ space and tint transform
- separationCS = (GfxSeparationColorSpace *)colorSpace;
- writePS("[/Indexed ");
- dumpColorSpaceL2(separationCS->getAlt());
- writePS(" 255 <\n");
- numComps = separationCS->getAlt()->getNComps();
- for (i = 0; i <= 255; i += 8) {
- writePS(" ");
- for (j = i; j < i+8 && j <= 255; ++j) {
- x[0] = (double)j / 255.0;
- separationCS->getFunc()->transform(x, y);
- for (k = 0; k < numComps; ++k) {
- writePSFmt("%02x", (int)(255 * y[k] + 0.5));
- }
- }
- writePS("\n");
- }
- writePS(">]");
- addCustomColor(separationCS);
- break;
-
- case csDeviceN:
- // DeviceN color spaces are a Level 3 PostScript feature.
- dumpColorSpaceL2(((GfxDeviceNColorSpace *)colorSpace)->getAlt());
- break;
-
- case csPattern:
- //~ unimplemented
- break;
-
- }
-}
-
-#if OPI_SUPPORT
-void PSOutputDev::opiBegin(GfxState *state, Dict *opiDict) {
- Object dict;
-
- if (globalParams->getPSOPI()) {
- opiDict->lookup("2.0", &dict);
- if (dict.isDict()) {
- opiBegin20(state, dict.getDict());
- dict.free();
- } else {
- dict.free();
- opiDict->lookup("1.3", &dict);
- if (dict.isDict()) {
- opiBegin13(state, dict.getDict());
- }
- dict.free();
- }
- }
-}
-
-void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
- Object obj1, obj2, obj3, obj4;
- double width, height, left, right, top, bottom;
- int w, h;
- int i;
-
- writePS("%%BeginOPI: 2.0\n");
- writePS("%%Distilled\n");
-
- dict->lookup("F", &obj1);
- if (getFileSpec(&obj1, &obj2)) {
- writePSFmt("%%%%ImageFileName: %s\n",
- obj2.getString()->getCString());
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("MainImage", &obj1);
- if (obj1.isString()) {
- writePSFmt("%%%%MainImage: %s\n", obj1.getString()->getCString());
- }
- obj1.free();
-
- //~ ignoring 'Tags' entry
- //~ need to use writePSString() and deal with >255-char lines
-
- dict->lookup("Size", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 2) {
- obj1.arrayGet(0, &obj2);
- width = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- height = obj2.getNum();
- obj2.free();
- writePSFmt("%%%%ImageDimensions: %g %g\n", width, height);
- }
- obj1.free();
-
- dict->lookup("CropRect", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 4) {
- obj1.arrayGet(0, &obj2);
- left = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- top = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- right = obj2.getNum();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- bottom = obj2.getNum();
- obj2.free();
- writePSFmt("%%%%ImageCropRect: %g %g %g %g\n", left, top, right, bottom);
- }
- obj1.free();
-
- dict->lookup("Overprint", &obj1);
- if (obj1.isBool()) {
- writePSFmt("%%%%ImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
- }
- obj1.free();
-
- dict->lookup("Inks", &obj1);
- if (obj1.isName()) {
- writePSFmt("%%%%ImageInks: %s\n", obj1.getName());
- } else if (obj1.isArray() && obj1.arrayGetLength() >= 1) {
- obj1.arrayGet(0, &obj2);
- if (obj2.isName()) {
- writePSFmt("%%%%ImageInks: %s %d",
- obj2.getName(), (obj1.arrayGetLength() - 1) / 2);
- for (i = 1; i+1 < obj1.arrayGetLength(); i += 2) {
- obj1.arrayGet(i, &obj3);
- obj1.arrayGet(i+1, &obj4);
- if (obj3.isString() && obj4.isNum()) {
- writePS(" ");
- writePSString(obj3.getString());
- writePSFmt(" %g", obj4.getNum());
- }
- obj3.free();
- obj4.free();
- }
- writePS("\n");
- }
- obj2.free();
- }
- obj1.free();
-
- writePS("gsave\n");
-
- writePS("%%BeginIncludedImage\n");
-
- dict->lookup("IncludedImageDimensions", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 2) {
- obj1.arrayGet(0, &obj2);
- w = obj2.getInt();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- h = obj2.getInt();
- obj2.free();
- writePSFmt("%%%%IncludedImageDimensions: %d %d\n", w, h);
- }
- obj1.free();
-
- dict->lookup("IncludedImageQuality", &obj1);
- if (obj1.isNum()) {
- writePSFmt("%%%%IncludedImageQuality: %g\n", obj1.getNum());
- }
- obj1.free();
-
- ++opi20Nest;
-}
-
-void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
- Object obj1, obj2;
- int left, right, top, bottom, samples, bits, width, height;
- double c, m, y, k;
- double llx, lly, ulx, uly, urx, ury, lrx, lry;
- double tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry;
- double horiz, vert;
- int i, j;
-
- writePS("save\n");
- writePS("/opiMatrix2 matrix currentmatrix def\n");
- writePS("opiMatrix setmatrix\n");
-
- dict->lookup("F", &obj1);
- if (getFileSpec(&obj1, &obj2)) {
- writePSFmt("%%ALDImageFileName: %s\n",
- obj2.getString()->getCString());
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("CropRect", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 4) {
- obj1.arrayGet(0, &obj2);
- left = obj2.getInt();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- top = obj2.getInt();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- right = obj2.getInt();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- bottom = obj2.getInt();
- obj2.free();
- writePSFmt("%%ALDImageCropRect: %d %d %d %d\n", left, top, right, bottom);
- }
- obj1.free();
-
- dict->lookup("Color", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 5) {
- obj1.arrayGet(0, &obj2);
- c = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- m = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- y = obj2.getNum();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- k = obj2.getNum();
- obj2.free();
- obj1.arrayGet(4, &obj2);
- if (obj2.isString()) {
- writePSFmt("%%ALDImageColor: %g %g %g %g ", c, m, y, k);
- writePSString(obj2.getString());
- writePS("\n");
- }
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("ColorType", &obj1);
- if (obj1.isName()) {
- writePSFmt("%%ALDImageColorType: %s\n", obj1.getName());
- }
- obj1.free();
-
- //~ ignores 'Comments' entry
- //~ need to handle multiple lines
-
- dict->lookup("CropFixed", &obj1);
- if (obj1.isArray()) {
- obj1.arrayGet(0, &obj2);
- ulx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- uly = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- lrx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- lry = obj2.getNum();
- obj2.free();
- writePSFmt("%%ALDImageCropFixed: %g %g %g %g\n", ulx, uly, lrx, lry);
- }
- obj1.free();
-
- dict->lookup("GrayMap", &obj1);
- if (obj1.isArray()) {
- writePS("%ALDImageGrayMap:");
- for (i = 0; i < obj1.arrayGetLength(); i += 16) {
- if (i > 0) {
- writePS("\n%%+");
- }
- for (j = 0; j < 16 && i+j < obj1.arrayGetLength(); ++j) {
- obj1.arrayGet(i+j, &obj2);
- writePSFmt(" %d", obj2.getInt());
- obj2.free();
- }
- }
- writePS("\n");
- }
- obj1.free();
-
- dict->lookup("ID", &obj1);
- if (obj1.isString()) {
- writePSFmt("%%ALDImageID: %s\n", obj1.getString()->getCString());
- }
- obj1.free();
-
- dict->lookup("ImageType", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 2) {
- obj1.arrayGet(0, &obj2);
- samples = obj2.getInt();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- bits = obj2.getInt();
- obj2.free();
- writePSFmt("%%ALDImageType: %d %d\n", samples, bits);
- }
- obj1.free();
-
- dict->lookup("Overprint", &obj1);
- if (obj1.isBool()) {
- writePSFmt("%%ALDImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
- }
- obj1.free();
-
- dict->lookup("Position", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 8) {
- obj1.arrayGet(0, &obj2);
- llx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- lly = obj2.getNum();
- obj2.free();
- obj1.arrayGet(2, &obj2);
- ulx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(3, &obj2);
- uly = obj2.getNum();
- obj2.free();
- obj1.arrayGet(4, &obj2);
- urx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(5, &obj2);
- ury = obj2.getNum();
- obj2.free();
- obj1.arrayGet(6, &obj2);
- lrx = obj2.getNum();
- obj2.free();
- obj1.arrayGet(7, &obj2);
- lry = obj2.getNum();
- obj2.free();
- opiTransform(state, llx, lly, &tllx, &tlly);
- opiTransform(state, ulx, uly, &tulx, &tuly);
- opiTransform(state, urx, ury, &turx, &tury);
- opiTransform(state, lrx, lry, &tlrx, &tlry);
- writePSFmt("%%ALDImagePosition: %g %g %g %g %g %g %g %g\n",
- tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry);
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("Resolution", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 2) {
- obj1.arrayGet(0, &obj2);
- horiz = obj2.getNum();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- vert = obj2.getNum();
- obj2.free();
- writePSFmt("%%ALDImageResoution: %g %g\n", horiz, vert);
- obj2.free();
- }
- obj1.free();
-
- dict->lookup("Size", &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 2) {
- obj1.arrayGet(0, &obj2);
- width = obj2.getInt();
- obj2.free();
- obj1.arrayGet(1, &obj2);
- height = obj2.getInt();
- obj2.free();
- writePSFmt("%%ALDImageDimensions: %d %d\n", width, height);
- }
- obj1.free();
-
- //~ ignoring 'Tags' entry
- //~ need to use writePSString() and deal with >255-char lines
-
- dict->lookup("Tint", &obj1);
- if (obj1.isNum()) {
- writePSFmt("%%ALDImageTint: %g\n", obj1.getNum());
- }
- obj1.free();
-
- dict->lookup("Transparency", &obj1);
- if (obj1.isBool()) {
- writePSFmt("%%ALDImageTransparency: %s\n", obj1.getBool() ? "true" : "false");
- }
- obj1.free();
-
- writePS("%%BeginObject: image\n");
- writePS("opiMatrix2 setmatrix\n");
- ++opi13Nest;
-}
-
-// Convert PDF user space coordinates to PostScript default user space
-// coordinates. This has to account for both the PDF CTM and the
-// PSOutputDev page-fitting transform.
-void PSOutputDev::opiTransform(GfxState *state, double x0, double y0,
- double *x1, double *y1) {
- double t;
-
- state->transform(x0, y0, x1, y1);
- *x1 += tx;
- *y1 += ty;
- if (landscape) {
- t = *x1;
- *x1 = -*y1;
- *y1 = t;
- }
- *x1 *= xScale;
- *y1 *= yScale;
-}
-
-void PSOutputDev::opiEnd(GfxState *state, Dict *opiDict) {
- Object dict;
-
- if (globalParams->getPSOPI()) {
- opiDict->lookup("2.0", &dict);
- if (dict.isDict()) {
- writePS("%%EndIncludedImage\n");
- writePS("%%EndOPI\n");
- writePS("grestore\n");
- --opi20Nest;
- dict.free();
- } else {
- dict.free();
- opiDict->lookup("1.3", &dict);
- if (dict.isDict()) {
- writePS("%%EndObject\n");
- writePS("restore\n");
- --opi13Nest;
- }
- dict.free();
- }
- }
-}
-
-GBool PSOutputDev::getFileSpec(Object *fileSpec, Object *fileName) {
- if (fileSpec->isString()) {
- fileSpec->copy(fileName);
- return gTrue;
- }
- if (fileSpec->isDict()) {
- fileSpec->dictLookup("DOS", fileName);
- if (fileName->isString()) {
- return gTrue;
- }
- fileName->free();
- fileSpec->dictLookup("Mac", fileName);
- if (fileName->isString()) {
- return gTrue;
- }
- fileName->free();
- fileSpec->dictLookup("Unix", fileName);
- if (fileName->isString()) {
- return gTrue;
- }
- fileName->free();
- fileSpec->dictLookup("F", fileName);
- if (fileName->isString()) {
- return gTrue;
- }
- fileName->free();
- }
- return gFalse;
-}
-#endif // OPI_SUPPORT
-
-void PSOutputDev::type3D0(GfxState *state, double wx, double wy) {
- writePSFmt("%g %g setcharwidth\n", wx, wy);
- writePS("q\n");
-}
-
-void PSOutputDev::type3D1(GfxState *state, double wx, double wy,
- double llx, double lly, double urx, double ury) {
- t3WX = wx;
- t3WY = wy;
- t3LLX = llx;
- t3LLY = lly;
- t3URX = urx;
- t3URY = ury;
- t3String = new GString();
- writePS("q\n");
- t3Cacheable = gTrue;
-}
-
-void PSOutputDev::psXObject(Stream *psStream, Stream *level1Stream) {
- Stream *str;
- int c;
-
- if ((level == psLevel1 || level == psLevel1Sep) && level1Stream) {
- str = level1Stream;
- } else {
- str = psStream;
- }
- str->reset();
- while ((c = str->getChar()) != EOF) {
- writePSChar(c);
- }
- str->close();
-}
-
-void PSOutputDev::writePSChar(char c) {
- if (t3String) {
- t3String->append(c);
- } else {
- (*outputFunc)(outputStream, &c, 1);
- }
-}
-
-void PSOutputDev::writePS(char *s) {
- if (t3String) {
- t3String->append(s);
- } else {
- (*outputFunc)(outputStream, s, strlen(s));
- }
-}
-
-void PSOutputDev::writePSFmt(const char *fmt, ...) {
- va_list args;
- char buf[512];
-
- va_start(args, fmt);
- vsprintf(buf, fmt, args);
- va_end(args);
- if (t3String) {
- t3String->append(buf);
- } else {
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
-}
-
-void PSOutputDev::writePSString(GString *s) {
- Guchar *p;
- int n;
- char buf[8];
-
- writePSChar('(');
- for (p = (Guchar *)s->getCString(), n = s->getLength(); n; ++p, --n) {
- if (*p == '(' || *p == ')' || *p == '\\') {
- writePSChar('\\');
- writePSChar((char)*p);
- } else if (*p < 0x20 || *p >= 0x80) {
- sprintf(buf, "\\%03o", *p);
- if (t3String) {
- t3String->append(buf);
- } else {
- (*outputFunc)(outputStream, buf, strlen(buf));
- }
- } else {
- writePSChar((char)*p);
- }
- }
- writePSChar(')');
-}
-
-void PSOutputDev::writePSName(char *s) {
- char *p;
- char c;
-
- p = s;
- while ((c = *p++)) {
- if (c <= (char)0x20 || c >= (char)0x7f ||
- c == '(' || c == ')' || c == '<' || c == '>' ||
- c == '[' || c == ']' || c == '{' || c == '}' ||
- c == '/' || c == '%') {
- writePSFmt("#%02x", c & 0xff);
- } else {
- writePSChar(c);
- }
- }
-}
-
-GString *PSOutputDev::filterPSName(GString *name) {
- GString *name2;
- char buf[8];
- int i;
- char c;
-
- name2 = new GString();
- for (i = 0; i < name->getLength(); ++i) {
- c = name->getChar(i);
- if (c <= (char)0x20 || c >= (char)0x7f ||
- c == '(' || c == ')' || c == '<' || c == '>' ||
- c == '[' || c == ']' || c == '{' || c == '}' ||
- c == '/' || c == '%') {
- sprintf(buf, "#%02x", c & 0xff);
- name2->append(buf);
- } else {
- name2->append(c);
- }
- }
- return name2;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cpp
new file mode 100644
index 000000000..66fd3fa6a
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/PSOutputDev.cpp
@@ -0,0 +1,3325 @@
+//========================================================================
+//
+// PSOutputDev.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <signal.h>
+#include <math.h>
+#include "GString.h"
+#include "config.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Error.h"
+#include "Function.h"
+#include "Gfx.h"
+#include "GfxState.h"
+#include "GfxFont.h"
+#include "CharCodeToUnicode.h"
+#include "UnicodeMap.h"
+#include "FontFile.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "Stream.h"
+#include "Annot.h"
+#include "PSOutputDev.h"
+
+#ifdef MACOS
+// needed for setting type/creator of MacOS files
+#include "ICSupport.h"
+#endif
+
+//------------------------------------------------------------------------
+// PostScript prolog and setup
+//------------------------------------------------------------------------
+
+static char *prolog[] = {
+ "/xpdf 75 dict def xpdf begin",
+ "% PDF special state",
+ "/pdfDictSize 14 def",
+ "/pdfSetup {",
+ " 3 1 roll 2 array astore",
+ " /setpagedevice where {",
+ " pop 3 dict begin",
+ " /PageSize exch def",
+ " /ImagingBBox null def",
+ " /Policies 1 dict dup begin /PageSize 3 def end def",
+ " { /Duplex true def } if",
+ " currentdict end setpagedevice",
+ " } {",
+ " pop pop",
+ " } ifelse",
+ "} def",
+ "/pdfStartPage {",
+ " pdfDictSize dict begin",
+ " /pdfFill [0] def",
+ " /pdfStroke [0] def",
+ " /pdfLastFill false def",
+ " /pdfLastStroke false def",
+ " /pdfTextMat [1 0 0 1 0 0] def",
+ " /pdfFontSize 0 def",
+ " /pdfCharSpacing 0 def",
+ " /pdfTextRender 0 def",
+ " /pdfTextRise 0 def",
+ " /pdfWordSpacing 0 def",
+ " /pdfHorizScaling 1 def",
+ "} def",
+ "/pdfEndPage { end } def",
+ "% separation convention operators",
+ "/findcmykcustomcolor where {",
+ " pop",
+ "}{",
+ " /findcmykcustomcolor { 5 array astore } def",
+ "} ifelse",
+ "/setcustomcolor where {",
+ " pop",
+ "}{",
+ " /setcustomcolor {",
+ " exch",
+ " [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
+ " 0 4 getinterval cvx",
+ " [ exch /dup load exch { mul exch dup } /forall load",
+ " /pop load dup ] cvx",
+ " ] setcolorspace setcolor",
+ " } def",
+ "} ifelse",
+ "/customcolorimage where {",
+ " pop",
+ "}{",
+ " /customcolorimage {",
+ " gsave",
+ " [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
+ " 0 4 getinterval cvx",
+ " [ exch /dup load exch { mul exch dup } /forall load",
+ " /pop load dup ] cvx",
+ " ] setcolorspace",
+ " 10 dict begin",
+ " /ImageType 1 def",
+ " /DataSource exch def",
+ " /ImageMatrix exch def",
+ " /BitsPerComponent exch def",
+ " /Height exch def",
+ " /Width exch def",
+ " /Decode [1 0] def",
+ " currentdict end",
+ " image",
+ " grestore",
+ " } def",
+ "} ifelse",
+ "% PDF color state",
+ "/sCol {",
+ " pdfLastStroke not {",
+ " pdfStroke aload length",
+ " dup 1 eq {",
+ " pop setgray",
+ " }{",
+ " dup 3 eq {",
+ " pop setrgbcolor",
+ " }{",
+ " 4 eq {",
+ " setcmykcolor",
+ " }{",
+ " findcmykcustomcolor exch setcustomcolor",
+ " } ifelse",
+ " } ifelse",
+ " } ifelse",
+ " /pdfLastStroke true def /pdfLastFill false def",
+ " } if",
+ "} def",
+ "/fCol {",
+ " pdfLastFill not {",
+ " pdfFill aload length",
+ " dup 1 eq {",
+ " pop setgray",
+ " }{",
+ " dup 3 eq {",
+ " pop setrgbcolor",
+ " }{",
+ " 4 eq {",
+ " setcmykcolor",
+ " }{",
+ " findcmykcustomcolor exch setcustomcolor",
+ " } ifelse",
+ " } ifelse",
+ " } ifelse",
+ " /pdfLastFill true def /pdfLastStroke false def",
+ " } if",
+ "} def",
+ "% build a font",
+ "/pdfMakeFont {",
+ " 4 3 roll findfont",
+ " 4 2 roll matrix scale makefont",
+ " dup length dict begin",
+ " { 1 index /FID ne { def } { pop pop } ifelse } forall",
+ " /Encoding exch def",
+ " currentdict",
+ " end",
+ " definefont pop",
+ "} def",
+ "/pdfMakeFont16 {",
+ " exch findfont",
+ " dup length dict begin",
+ " { 1 index /FID ne { def } { pop pop } ifelse } forall",
+ " /WMode exch def",
+ " currentdict",
+ " end",
+ " definefont pop",
+ "} def",
+ "/pdfMakeFont16L3 {",
+ " 1 index /CIDFont resourcestatus {",
+ " pop pop 1 index /CIDFont findresource /CIDFontType known",
+ " } {",
+ " false",
+ " } ifelse",
+ " {",
+ " 0 eq { /Identity-H } { /Identity-V } ifelse",
+ " exch 1 array astore composefont pop",
+ " } {",
+ " pdfMakeFont16",
+ " } ifelse",
+ "} def",
+ "% graphics state operators",
+ "/q { gsave pdfDictSize dict begin } def",
+ "/Q { end grestore } def",
+ "/cm { concat } def",
+ "/d { setdash } def",
+ "/i { setflat } def",
+ "/j { setlinejoin } def",
+ "/J { setlinecap } def",
+ "/M { setmiterlimit } def",
+ "/w { setlinewidth } def",
+ "% color operators",
+ "/g { dup 1 array astore /pdfFill exch def setgray",
+ " /pdfLastFill true def /pdfLastStroke false def } def",
+ "/G { dup 1 array astore /pdfStroke exch def setgray",
+ " /pdfLastStroke true def /pdfLastFill false def } def",
+ "/rg { 3 copy 3 array astore /pdfFill exch def setrgbcolor",
+ " /pdfLastFill true def /pdfLastStroke false def } def",
+ "/RG { 3 copy 3 array astore /pdfStroke exch def setrgbcolor",
+ " /pdfLastStroke true def /pdfLastFill false def } def",
+ "/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
+ " /pdfLastFill true def /pdfLastStroke false def } def",
+ "/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
+ " /pdfLastStroke true def /pdfLastFill false def } def",
+ "/ck { 6 copy 6 array astore /pdfFill exch def",
+ " findcmykcustomcolor exch setcustomcolor",
+ " /pdfLastFill true def /pdfLastStroke false def } def",
+ "/CK { 6 copy 6 array astore /pdfStroke exch def",
+ " findcmykcustomcolor exch setcustomcolor",
+ " /pdfLastStroke true def /pdfLastFill false def } def",
+ "% path segment operators",
+ "/m { moveto } def",
+ "/l { lineto } def",
+ "/c { curveto } def",
+ "/re { 4 2 roll moveto 1 index 0 rlineto 0 exch rlineto",
+ " neg 0 rlineto closepath } def",
+ "/h { closepath } def",
+ "% path painting operators",
+ "/S { sCol stroke } def",
+ "/Sf { fCol stroke } def",
+ "/f { fCol fill } def",
+ "/f* { fCol eofill } def",
+ "% clipping operators",
+ "/W { clip newpath } def",
+ "/W* { eoclip newpath } def",
+ "% text state operators",
+ "/Tc { /pdfCharSpacing exch def } def",
+ "/Tf { dup /pdfFontSize exch def",
+ " dup pdfHorizScaling mul exch matrix scale",
+ " pdfTextMat matrix concatmatrix dup 4 0 put dup 5 0 put",
+ " exch findfont exch makefont setfont } def",
+ "/Tr { /pdfTextRender exch def } def",
+ "/Ts { /pdfTextRise exch def } def",
+ "/Tw { /pdfWordSpacing exch def } def",
+ "/Tz { /pdfHorizScaling exch def } def",
+ "% text positioning operators",
+ "/Td { pdfTextMat transform moveto } def",
+ "/Tm { /pdfTextMat exch def } def",
+ "% text string operators",
+ "/awcp { % awidthcharpath",
+ " exch {",
+ " 1 string dup 0 3 index put 2 index charpath",
+ " 3 index 3 index rmoveto",
+ " 4 index eq { 5 index 5 index rmoveto } if",
+ " } forall",
+ " 6 {pop} repeat",
+ "} def",
+ "/Tj { fCol", // because stringwidth has to draw Type 3 chars
+ " 0 pdfTextRise pdfTextMat dtransform rmoveto",
+ " 1 index stringwidth pdfTextMat idtransform pop",
+ " sub 1 index length dup 0 ne { div } { pop pop 0 } ifelse",
+ " pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
+ " 4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
+ " pdfTextMat dtransform",
+ " 6 5 roll",
+ " currentpoint 8 2 roll",
+ " pdfTextRender 1 and 0 eq {",
+ " 6 copy awidthshow",
+ " } if",
+ " pdfTextRender 3 and dup 1 eq exch 2 eq or {",
+ " 8 6 roll moveto",
+ " currentfont /FontType get 3 eq { fCol } { sCol } ifelse",
+ " false awcp currentpoint stroke moveto",
+ " } {",
+ " 8 {pop} repeat",
+ " } ifelse",
+ " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
+ "/Tj16 { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
+ " 0 pdfTextRise pdfTextMat dtransform rmoveto",
+ " 2 index stringwidth pdfTextMat idtransform pop",
+ " sub exch div",
+ " pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
+ " 4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
+ " pdfTextMat dtransform",
+ " 6 5 roll awidthshow",
+ " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
+ "/Tj16V { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
+ " 0 pdfTextRise pdfTextMat dtransform rmoveto",
+ " 2 index stringwidth pdfTextMat idtransform exch pop",
+ " sub exch div",
+ " 0 pdfWordSpacing pdfTextMat dtransform 32",
+ " 4 3 roll pdfCharSpacing add 0 exch",
+ " pdfTextMat dtransform",
+ " 6 5 roll awidthshow",
+ " 0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
+ "/TJm { pdfFontSize 0.001 mul mul neg 0",
+ " pdfTextMat dtransform rmoveto } def",
+ "/TJmV { pdfFontSize 0.001 mul mul neg 0 exch",
+ " pdfTextMat dtransform rmoveto } def",
+ "% Level 1 image operators",
+ "/pdfIm1 {",
+ " /pdfImBuf1 4 index string def",
+ " { currentfile pdfImBuf1 readhexstring pop } image",
+ "} def",
+ "/pdfIm1Sep {",
+ " /pdfImBuf1 4 index string def",
+ " /pdfImBuf2 4 index string def",
+ " /pdfImBuf3 4 index string def",
+ " /pdfImBuf4 4 index string def",
+ " { currentfile pdfImBuf1 readhexstring pop }",
+ " { currentfile pdfImBuf2 readhexstring pop }",
+ " { currentfile pdfImBuf3 readhexstring pop }",
+ " { currentfile pdfImBuf4 readhexstring pop }",
+ " true 4 colorimage",
+ "} def",
+ "/pdfImM1 {",
+ " /pdfImBuf1 4 index 7 add 8 idiv string def",
+ " { currentfile pdfImBuf1 readhexstring pop } imagemask",
+ "} def",
+ "% Level 2 image operators",
+ "/pdfImBuf 100 string def",
+ "/pdfIm {",
+ " image",
+ " { currentfile pdfImBuf readline",
+ " not { pop exit } if",
+ " (%-EOD-) eq { exit } if } loop",
+ "} def",
+ "/pdfImSep {",
+ " findcmykcustomcolor exch",
+ " dup /Width get /pdfImBuf1 exch string def",
+ " begin Width Height BitsPerComponent ImageMatrix DataSource end",
+ " /pdfImData exch def",
+ " { pdfImData pdfImBuf1 readstring pop",
+ " 0 1 2 index length 1 sub {",
+ " 1 index exch 2 copy get 255 exch sub put",
+ " } for }",
+ " 6 5 roll customcolorimage",
+ " { currentfile pdfImBuf readline",
+ " not { pop exit } if",
+ " (%-EOD-) eq { exit } if } loop",
+ "} def",
+ "/pdfImM {",
+ " fCol imagemask",
+ " { currentfile pdfImBuf readline",
+ " not { pop exit } if",
+ " (%-EOD-) eq { exit } if } loop",
+ "} def",
+ "end",
+ NULL
+};
+
+static char *cmapProlog[] = {
+ "/CIDInit /ProcSet findresource begin",
+ "10 dict begin",
+ " begincmap",
+ " /CMapType 1 def",
+ " /CMapName /Identity-H def",
+ " /CIDSystemInfo 3 dict dup begin",
+ " /Registry (Adobe) def",
+ " /Ordering (Identity) def",
+ " /Supplement 0 def",
+ " end def",
+ " 1 begincodespacerange",
+ " <0000> <ffff>",
+ " endcodespacerange",
+ " 0 usefont",
+ " 1 begincidrange",
+ " <0000> <ffff> 0",
+ " endcidrange",
+ " endcmap",
+ " currentdict CMapName exch /CMap defineresource pop",
+ "end",
+ "10 dict begin",
+ " begincmap",
+ " /CMapType 1 def",
+ " /CMapName /Identity-V def",
+ " /CIDSystemInfo 3 dict dup begin",
+ " /Registry (Adobe) def",
+ " /Ordering (Identity) def",
+ " /Supplement 0 def",
+ " end def",
+ " /WMode 1 def",
+ " 1 begincodespacerange",
+ " <0000> <ffff>",
+ " endcodespacerange",
+ " 0 usefont",
+ " 1 begincidrange",
+ " <0000> <ffff> 0",
+ " endcidrange",
+ " endcmap",
+ " currentdict CMapName exch /CMap defineresource pop",
+ "end",
+ "end",
+ NULL
+};
+
+//------------------------------------------------------------------------
+// Fonts
+//------------------------------------------------------------------------
+
+struct PSSubstFont {
+ char *psName; // PostScript name
+ double mWidth; // width of 'm' character
+};
+
+static char *psFonts[] = {
+ "Courier",
+ "Courier-Bold",
+ "Courier-Oblique",
+ "Courier-BoldOblique",
+ "Helvetica",
+ "Helvetica-Bold",
+ "Helvetica-Oblique",
+ "Helvetica-BoldOblique",
+ "Symbol",
+ "Times-Roman",
+ "Times-Bold",
+ "Times-Italic",
+ "Times-BoldItalic",
+ "ZapfDingbats",
+ NULL
+};
+
+static PSSubstFont psSubstFonts[] = {
+ {"Helvetica", 0.833},
+ {"Helvetica-Oblique", 0.833},
+ {"Helvetica-Bold", 0.889},
+ {"Helvetica-BoldOblique", 0.889},
+ {"Times-Roman", 0.788},
+ {"Times-Italic", 0.722},
+ {"Times-Bold", 0.833},
+ {"Times-BoldItalic", 0.778},
+ {"Courier", 0.600},
+ {"Courier-Oblique", 0.600},
+ {"Courier-Bold", 0.600},
+ {"Courier-BoldOblique", 0.600}
+};
+
+// Encoding info for substitute 16-bit font
+struct PSFont16Enc {
+ Ref fontID;
+ GString *enc;
+};
+
+//------------------------------------------------------------------------
+// process colors
+//------------------------------------------------------------------------
+
+#define psProcessCyan 1
+#define psProcessMagenta 2
+#define psProcessYellow 4
+#define psProcessBlack 8
+#define psProcessCMYK 15
+
+//------------------------------------------------------------------------
+// PSOutCustomColor
+//------------------------------------------------------------------------
+
+class PSOutCustomColor {
+public:
+
+ PSOutCustomColor(double cA, double mA,
+ double yA, double kA, GString *nameA);
+ ~PSOutCustomColor();
+
+ double c, m, y, k;
+ GString *name;
+ PSOutCustomColor *next;
+};
+
+PSOutCustomColor::PSOutCustomColor(double cA, double mA,
+ double yA, double kA, GString *nameA) {
+ c = cA;
+ m = mA;
+ y = yA;
+ k = kA;
+ name = nameA;
+ next = NULL;
+}
+
+PSOutCustomColor::~PSOutCustomColor() {
+ delete name;
+}
+
+//------------------------------------------------------------------------
+// PSOutputDev
+//------------------------------------------------------------------------
+
+extern "C" {
+typedef void (*SignalFunc)(int);
+}
+
+static void outputToFile(void *stream, char *data, int len) {
+ fwrite(data, 1, len, (FILE *)stream);
+}
+
+PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
+ int firstPage, int lastPage, PSOutMode modeA) {
+ FILE *f;
+ PSFileType fileTypeA;
+
+ fontIDs = NULL;
+ fontFileIDs = NULL;
+ fontFileNames = NULL;
+ font16Enc = NULL;
+ embFontList = NULL;
+ customColors = NULL;
+ t3String = NULL;
+
+ // open file or pipe
+ if (!strcmp(fileName, "-")) {
+ fileTypeA = psStdout;
+ f = stdout;
+ } else if (fileName[0] == '|') {
+ fileTypeA = psPipe;
+#ifdef HAVE_POPEN
+#ifndef WIN32
+ signal(SIGPIPE, (SignalFunc)SIG_IGN);
+#endif
+ if (!(f = popen(fileName + 1, "w"))) {
+ error(-1, "Couldn't run print command '%s'", fileName);
+ ok = gFalse;
+ return;
+ }
+#else
+ error(-1, "Print commands are not supported ('%s')", fileName);
+ ok = gFalse;
+ return;
+#endif
+ } else {
+ fileTypeA = psFile;
+ if (!(f = fopen(fileName, "w"))) {
+ error(-1, "Couldn't open PostScript file '%s'", fileName);
+ ok = gFalse;
+ return;
+ }
+ }
+
+ init(outputToFile, f, fileTypeA,
+ xrefA, catalog, firstPage, lastPage, modeA);
+}
+
+PSOutputDev::PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
+ XRef *xrefA, Catalog *catalog,
+ int firstPage, int lastPage, PSOutMode modeA) {
+ fontIDs = NULL;
+ fontFileIDs = NULL;
+ fontFileNames = NULL;
+ font16Enc = NULL;
+ embFontList = NULL;
+ customColors = NULL;
+ t3String = NULL;
+
+ init(outputFuncA, outputStreamA, psGeneric,
+ xrefA, catalog, firstPage, lastPage, modeA);
+}
+
+void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
+ PSFileType fileTypeA, XRef *xrefA, Catalog *catalog,
+ int firstPage, int lastPage, PSOutMode modeA) {
+ Page *page;
+ PDFRectangle *box;
+ Dict *resDict;
+ Annots *annots;
+ char **p;
+ int pg;
+ Object obj1, obj2;
+ int i;
+
+ // initialize
+ ok = gTrue;
+ outputFunc = outputFuncA;
+ outputStream = outputStreamA;
+ fileType = fileTypeA;
+ xref = xrefA;
+ level = globalParams->getPSLevel();
+ mode = modeA;
+ paperWidth = globalParams->getPSPaperWidth();
+ paperHeight = globalParams->getPSPaperHeight();
+ if (mode == psModeForm) {
+ lastPage = firstPage;
+ }
+ processColors = 0;
+ inType3Char = gFalse;
+
+#if OPI_SUPPORT
+ // initialize OPI nesting levels
+ opi13Nest = 0;
+ opi20Nest = 0;
+#endif
+
+ // initialize fontIDs, fontFileIDs, and fontFileNames lists
+ fontIDSize = 64;
+ fontIDLen = 0;
+ fontIDs = (Ref *)gmalloc(fontIDSize * sizeof(Ref));
+ fontFileIDSize = 64;
+ fontFileIDLen = 0;
+ fontFileIDs = (Ref *)gmalloc(fontFileIDSize * sizeof(Ref));
+ fontFileNameSize = 64;
+ fontFileNameLen = 0;
+ fontFileNames = (GString **)gmalloc(fontFileNameSize * sizeof(GString *));
+ font16EncLen = 0;
+ font16EncSize = 0;
+
+ // initialize embedded font resource comment list
+ embFontList = new GString();
+
+ // write header
+ switch (mode) {
+ case psModePS:
+ writePS("%!PS-Adobe-3.0\n");
+ writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+ writePSFmt("%%%%LanguageLevel: %d\n",
+ (level == psLevel1 || level == psLevel1Sep) ? 1 :
+ (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+ if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
+ writePS("%%DocumentProcessColors: (atend)\n");
+ writePS("%%DocumentCustomColors: (atend)\n");
+ }
+ writePS("%%DocumentSuppliedResources: (atend)\n");
+ writePSFmt("%%%%DocumentMedia: plain %d %d 0 () ()\n",
+ paperWidth, paperHeight);
+ writePSFmt("%%%%Pages: %d\n", lastPage - firstPage + 1);
+ writePS("%%EndComments\n");
+ writePS("%%BeginDefaults\n");
+ writePS("%%PageMedia: plain\n");
+ writePS("%%EndDefaults\n");
+ break;
+ case psModeEPS:
+ writePS("%!PS-Adobe-3.0 EPSF-3.0\n");
+ writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+ writePSFmt("%%%%LanguageLevel: %d\n",
+ (level == psLevel1 || level == psLevel1Sep) ? 1 :
+ (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+ if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
+ writePS("%%DocumentProcessColors: (atend)\n");
+ writePS("%%DocumentCustomColors: (atend)\n");
+ }
+ page = catalog->getPage(firstPage);
+ box = page->getBox();
+ writePSFmt("%%%%BoundingBox: %d %d %d %d\n",
+ (int)floor(box->x1), (int)floor(box->y1),
+ (int)ceil(box->x2), (int)ceil(box->y2));
+ if (floor(box->x1) != ceil(box->x1) ||
+ floor(box->y1) != ceil(box->y1) ||
+ floor(box->x2) != ceil(box->x2) ||
+ floor(box->y2) != ceil(box->y2)) {
+ writePSFmt("%%%%HiResBoundingBox: %g %g %g %g\n",
+ box->x1, box->y1, box->x2, box->y2);
+ }
+ writePS("%%DocumentSuppliedResources: (atend)\n");
+ writePS("%%EndComments\n");
+ break;
+ case psModeForm:
+ writePS("%!PS-Adobe-3.0 Resource-Form\n");
+ writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+ writePSFmt("%%%%LanguageLevel: %d\n",
+ (level == psLevel1 || level == psLevel1Sep) ? 1 :
+ (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+ if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
+ writePS("%%DocumentProcessColors: (atend)\n");
+ writePS("%%DocumentCustomColors: (atend)\n");
+ }
+ writePS("%%DocumentSuppliedResources: (atend)\n");
+ writePS("%%EndComments\n");
+ page = catalog->getPage(firstPage);
+ box = page->getBox();
+ writePS("32 dict dup begin\n");
+ writePSFmt("/BBox [%d %d %d %d] def\n",
+ (int)box->x1, (int)box->y1, (int)box->x2, (int)box->y2);
+ writePS("/FormType 1 def\n");
+ writePS("/Matrix [1 0 0 1 0 0] def\n");
+ break;
+ }
+
+ // write prolog
+ if (mode != psModeForm) {
+ writePS("%%BeginProlog\n");
+ }
+ writePSFmt("%%%%BeginResource: procset xpdf %s 0\n", xpdfVersion);
+ for (p = prolog; *p; ++p) {
+ writePSFmt("%s\n", *p);
+ }
+ writePS("%%EndResource\n");
+ if (level >= psLevel3) {
+ for (p = cmapProlog; *p; ++p) {
+ writePSFmt("%s\n", *p);
+ }
+ }
+ if (mode != psModeForm) {
+ writePS("%%EndProlog\n");
+ }
+
+ // set up fonts and images
+ if (mode == psModeForm) {
+ // swap the form and xpdf dicts
+ writePS("xpdf end begin dup begin\n");
+ } else {
+ writePS("%%BeginSetup\n");
+ writePS("xpdf begin\n");
+ }
+ for (pg = firstPage; pg <= lastPage; ++pg) {
+ page = catalog->getPage(pg);
+ if ((resDict = page->getResourceDict())) {
+ setupResources(resDict);
+ }
+ annots = new Annots(xref, page->getAnnots(&obj1));
+ obj1.free();
+ for (i = 0; i < annots->getNumAnnots(); ++i) {
+ if (annots->getAnnot(i)->getAppearance(&obj1)->isStream()) {
+ obj1.streamGetDict()->lookup("Resources", &obj2);
+ if (obj2.isDict()) {
+ setupResources(obj2.getDict());
+ }
+ obj2.free();
+ }
+ obj1.free();
+ }
+ delete annots;
+ }
+ if (mode != psModeForm) {
+ if (mode != psModeEPS) {
+ writePSFmt("%d %d %s pdfSetup\n",
+ paperWidth, paperHeight,
+ globalParams->getPSDuplex() ? "true" : "false");
+ }
+#if OPI_SUPPORT
+ if (globalParams->getPSOPI()) {
+ writePS("/opiMatrix matrix currentmatrix def\n");
+ }
+#endif
+ writePS("%%EndSetup\n");
+ }
+
+ // initialize sequential page number
+ seqPage = 1;
+}
+
+PSOutputDev::~PSOutputDev() {
+ PSOutCustomColor *cc;
+ int i;
+
+ if (ok) {
+ if (mode == psModeForm) {
+ writePS("/Foo exch /Form defineresource pop\n");
+ } else {
+ writePS("%%Trailer\n");
+ writePS("end\n");
+ writePS("%%DocumentSuppliedResources:\n");
+ writePS(embFontList->getCString());
+ if (level == psLevel1Sep || level == psLevel2Sep ||
+ level == psLevel3Sep) {
+ writePS("%%DocumentProcessColors:");
+ if (processColors & psProcessCyan) {
+ writePS(" Cyan");
+ }
+ if (processColors & psProcessMagenta) {
+ writePS(" Magenta");
+ }
+ if (processColors & psProcessYellow) {
+ writePS(" Yellow");
+ }
+ if (processColors & psProcessBlack) {
+ writePS(" Black");
+ }
+ writePS("\n");
+ writePS("%%DocumentCustomColors:");
+ for (cc = customColors; cc; cc = cc->next) {
+ writePSFmt(" (%s)", cc->name->getCString());
+ }
+ writePS("\n");
+ writePS("%%CMYKCustomColor:\n");
+ for (cc = customColors; cc; cc = cc->next) {
+ writePSFmt("%%%%+ %g %g %g %g (%s)\n",
+ cc->c, cc->m, cc->y, cc->k, cc->name->getCString());
+ }
+ }
+ writePS("%%EOF\n");
+ }
+ if (fileType == psFile) {
+#ifdef MACOS
+ ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
+#endif
+ fclose((FILE *)outputStream);
+ }
+#ifdef HAVE_POPEN
+ else if (fileType == psPipe) {
+ pclose((FILE *)outputStream);
+#ifndef WIN32
+ signal(SIGPIPE, (SignalFunc)SIG_DFL);
+#endif
+ }
+#endif
+ }
+ if (embFontList) {
+ delete embFontList;
+ }
+ if (fontIDs) {
+ gfree(fontIDs);
+ }
+ if (fontFileIDs) {
+ gfree(fontFileIDs);
+ }
+ if (fontFileNames) {
+ for (i = 0; i < fontFileNameLen; ++i) {
+ delete fontFileNames[i];
+ }
+ gfree(fontFileNames);
+ }
+ if (font16Enc) {
+ for (i = 0; i < font16EncLen; ++i) {
+ delete font16Enc[i].enc;
+ }
+ gfree(font16Enc);
+ }
+ while (customColors) {
+ cc = customColors;
+ customColors = cc->next;
+ delete cc;
+ }
+}
+
+void PSOutputDev::setupResources(Dict *resDict) {
+ Object xObjDict, xObj, resObj;
+ int i;
+
+ setupFonts(resDict);
+ setupImages(resDict);
+
+ resDict->lookup("XObject", &xObjDict);
+ if (xObjDict.isDict()) {
+ for (i = 0; i < xObjDict.dictGetLength(); ++i) {
+ xObjDict.dictGetVal(i, &xObj);
+ if (xObj.isStream()) {
+ xObj.streamGetDict()->lookup("Resources", &resObj);
+ if (resObj.isDict()) {
+ setupResources(resObj.getDict());
+ }
+ resObj.free();
+ }
+ xObj.free();
+ }
+ }
+ xObjDict.free();
+}
+
+void PSOutputDev::setupFonts(Dict *resDict) {
+ Object fontDict;
+ GfxFontDict *gfxFontDict;
+ GfxFont *font;
+ int i;
+
+ resDict->lookup("Font", &fontDict);
+ if (fontDict.isDict()) {
+ gfxFontDict = new GfxFontDict(xref, fontDict.getDict());
+ for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
+ font = gfxFontDict->getFont(i);
+ setupFont(font, resDict);
+ }
+ delete gfxFontDict;
+ }
+ fontDict.free();
+}
+
+void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
+ Ref fontFileID;
+ GString *name;
+ PSFontParam *fontParam;
+ GString *psNameStr;
+ char *psName;
+ char type3Name[64], buf[16];
+ UnicodeMap *uMap;
+ char *charName;
+ double xs, ys;
+ int code;
+ double w1, w2;
+ double *fm;
+ int i, j;
+
+ // check if font is already set up
+ for (i = 0; i < fontIDLen; ++i) {
+ if (fontIDs[i].num == font->getID()->num &&
+ fontIDs[i].gen == font->getID()->gen) {
+ return;
+ }
+ }
+
+ // add entry to fontIDs list
+ if (fontIDLen >= fontIDSize) {
+ fontIDSize += 64;
+ fontIDs = (Ref *)grealloc(fontIDs, fontIDSize * sizeof(Ref));
+ }
+ fontIDs[fontIDLen++] = *font->getID();
+
+ xs = ys = 1;
+ psNameStr = NULL;
+
+ // check for resident 8-bit font
+ if (font->getName() &&
+ (fontParam = globalParams->getPSFont(font->getName()))) {
+ psName = fontParam->psFontName->getCString();
+
+ // check for embedded Type 1 font
+ } else if (globalParams->getPSEmbedType1() &&
+ font->getType() == fontType1 &&
+ font->getEmbeddedFontID(&fontFileID)) {
+ psNameStr = filterPSName(font->getEmbeddedFontName());
+ psName = psNameStr->getCString();
+ setupEmbeddedType1Font(&fontFileID, psName);
+
+ // check for embedded Type 1C font
+ } else if (globalParams->getPSEmbedType1() &&
+ font->getType() == fontType1C &&
+ font->getEmbeddedFontID(&fontFileID)) {
+ psNameStr = filterPSName(font->getEmbeddedFontName());
+ psName = psNameStr->getCString();
+ setupEmbeddedType1CFont(font, &fontFileID, psName);
+
+ // check for external Type 1 font file
+ } else if (globalParams->getPSEmbedType1() &&
+ font->getType() == fontType1 &&
+ font->getExtFontFile()) {
+ // this assumes that the PS font name matches the PDF font name
+ psName = font->getName()->getCString();
+ setupExternalType1Font(font->getExtFontFile(), psName);
+
+ // check for embedded TrueType font
+ } else if (globalParams->getPSEmbedTrueType() &&
+ font->getType() == fontTrueType &&
+ font->getEmbeddedFontID(&fontFileID)) {
+ psNameStr = filterPSName(font->getEmbeddedFontName());
+ psName = psNameStr->getCString();
+ setupEmbeddedTrueTypeFont(font, &fontFileID, psName);
+
+ // check for external TrueType font file
+ } else if (globalParams->getPSEmbedTrueType() &&
+ font->getType() == fontTrueType &&
+ font->getExtFontFile()) {
+ psNameStr = filterPSName(font->getName());
+ psName = psNameStr->getCString();
+ setupExternalTrueTypeFont(font, psName);
+
+ // check for embedded CID PostScript font
+ } else if (globalParams->getPSEmbedCIDPostScript() &&
+ font->getType() == fontCIDType0C &&
+ font->getEmbeddedFontID(&fontFileID)) {
+ psNameStr = filterPSName(font->getEmbeddedFontName());
+ psName = psNameStr->getCString();
+ setupEmbeddedCIDType0Font(font, &fontFileID, psName);
+
+ // check for embedded CID TrueType font
+ } else if (globalParams->getPSEmbedCIDTrueType() &&
+ font->getType() == fontCIDType2 &&
+ font->getEmbeddedFontID(&fontFileID)) {
+ psNameStr = filterPSName(font->getEmbeddedFontName());
+ psName = psNameStr->getCString();
+ setupEmbeddedCIDTrueTypeFont(font, &fontFileID, psName);
+
+ } else if (font->getType() == fontType3) {
+ sprintf(type3Name, "T3_%d_%d",
+ font->getID()->num, font->getID()->gen);
+ psName = type3Name;
+ setupType3Font(font, psName, parentResDict);
+
+ // do 8-bit font substitution
+ } else if (!font->isCIDFont()) {
+ name = font->getName();
+ psName = NULL;
+ if (name) {
+ for (i = 0; psFonts[i]; ++i) {
+ if (name->cmp(psFonts[i]) == 0) {
+ psName = psFonts[i];
+ break;
+ }
+ }
+ }
+ if (!psName) {
+ if (font->isFixedWidth()) {
+ i = 8;
+ } else if (font->isSerif()) {
+ i = 4;
+ } else {
+ i = 0;
+ }
+ if (font->isBold()) {
+ i += 2;
+ }
+ if (font->isItalic()) {
+ i += 1;
+ }
+ psName = psSubstFonts[i].psName;
+ for (code = 0; code < 256; ++code) {
+ if ((charName = ((Gfx8BitFont *)font)->getCharName(code)) &&
+ charName[0] == 'm' && charName[1] == '\0') {
+ break;
+ }
+ }
+ if (code < 256) {
+ w1 = ((Gfx8BitFont *)font)->getWidth(code);
+ } else {
+ w1 = 0;
+ }
+ w2 = psSubstFonts[i].mWidth;
+ xs = w1 / w2;
+ if (xs < 0.1) {
+ xs = 1;
+ }
+ if (font->getType() == fontType3) {
+ // This is a hack which makes it possible to substitute for some
+ // Type 3 fonts. The problem is that it's impossible to know what
+ // the base coordinate system used in the font is without actually
+ // rendering the font.
+ ys = xs;
+ fm = font->getFontMatrix();
+ if (fm[0] != 0) {
+ ys *= fm[3] / fm[0];
+ }
+ } else {
+ ys = 1;
+ }
+ }
+
+ // do 16-bit font substitution
+ } else if ((fontParam = globalParams->
+ getPSFont16(font->getName(),
+ ((GfxCIDFont *)font)->getCollection(),
+ font->getWMode()))) {
+ psName = fontParam->psFontName->getCString();
+ if (font16EncLen >= font16EncSize) {
+ font16EncSize += 16;
+ font16Enc = (PSFont16Enc *)grealloc(font16Enc,
+ font16EncSize * sizeof(PSFont16Enc));
+ }
+ font16Enc[font16EncLen].fontID = *font->getID();
+ font16Enc[font16EncLen].enc = fontParam->encoding->copy();
+ if ((uMap = globalParams->getUnicodeMap(font16Enc[font16EncLen].enc))) {
+ uMap->decRefCnt();
+ ++font16EncLen;
+ } else {
+ error(-1, "Couldn't find Unicode map for 16-bit font encoding '%s'",
+ font16Enc[font16EncLen].enc->getCString());
+ }
+
+ // give up - can't do anything with this font
+ } else {
+ error(-1, "Couldn't find a font to substitute for '%s' ('%s' character collection)",
+ font->getName() ? font->getName()->getCString() : "(unnamed)",
+ ((GfxCIDFont *)font)->getCollection()
+ ? ((GfxCIDFont *)font)->getCollection()->getCString()
+ : "(unknown)");
+ return;
+ }
+
+ // generate PostScript code to set up the font
+ if (font->isCIDFont()) {
+ if (level == psLevel3 || level == psLevel3Sep) {
+ writePSFmt("/F%d_%d /%s %d pdfMakeFont16L3\n",
+ font->getID()->num, font->getID()->gen, psName,
+ font->getWMode());
+ } else {
+ writePSFmt("/F%d_%d /%s %d pdfMakeFont16\n",
+ font->getID()->num, font->getID()->gen, psName,
+ font->getWMode());
+ }
+ } else {
+ writePSFmt("/F%d_%d /%s %g %g\n",
+ font->getID()->num, font->getID()->gen, psName, xs, ys);
+ for (i = 0; i < 256; i += 8) {
+ writePSFmt((i == 0) ? "[ " : " ");
+ for (j = 0; j < 8; ++j) {
+ if (font->getType() == fontTrueType &&
+ !((Gfx8BitFont *)font)->getHasEncoding()) {
+ sprintf(buf, "c%02x", i+j);
+ charName = buf;
+ } else {
+ charName = ((Gfx8BitFont *)font)->getCharName(i+j);
+ // this is a kludge for broken PDF files that encode char 32
+ // as .notdef
+ if (i+j == 32 && charName && !strcmp(charName, ".notdef")) {
+ charName = "space";
+ }
+ }
+ writePS("/");
+ writePSName(charName ? charName : (char *)".notdef");
+ }
+ writePS((i == 256-8) ? (char *)"]\n" : (char *)"\n");
+ }
+ writePS("pdfMakeFont\n");
+ }
+
+ if (psNameStr) {
+ delete psNameStr;
+ }
+}
+
+void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
+ static char hexChar[17] = "0123456789abcdef";
+ Object refObj, strObj, obj1, obj2;
+ Dict *dict;
+ int length1, length2;
+ int c;
+ int start[4];
+ GBool binMode;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileIDLen; ++i) {
+ if (fontFileIDs[i].num == id->num &&
+ fontFileIDs[i].gen == id->gen)
+ return;
+ }
+
+ // add entry to fontFileIDs list
+ if (fontFileIDLen >= fontFileIDSize) {
+ fontFileIDSize += 64;
+ fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+ }
+ fontFileIDs[fontFileIDLen++] = *id;
+
+ // get the font stream and info
+ refObj.initRef(id->num, id->gen);
+ refObj.fetch(xref, &strObj);
+ refObj.free();
+ if (!strObj.isStream()) {
+ error(-1, "Embedded font file object is not a stream");
+ goto err1;
+ }
+ if (!(dict = strObj.streamGetDict())) {
+ error(-1, "Embedded font stream is missing its dictionary");
+ goto err1;
+ }
+ dict->lookup("Length1", &obj1);
+ dict->lookup("Length2", &obj2);
+ if (!obj1.isInt() || !obj2.isInt()) {
+ error(-1, "Missing length fields in embedded font stream dictionary");
+ obj1.free();
+ obj2.free();
+ goto err1;
+ }
+ length1 = obj1.getInt();
+ length2 = obj2.getInt();
+ obj1.free();
+ obj2.free();
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // copy ASCII portion of font
+ strObj.streamReset();
+ for (i = 0; i < length1 && (c = strObj.streamGetChar()) != EOF; ++i) {
+ writePSChar(c);
+ }
+
+ // figure out if encrypted portion is binary or ASCII
+ binMode = gFalse;
+ for (i = 0; i < 4; ++i) {
+ start[i] = strObj.streamGetChar();
+ if (start[i] == EOF) {
+ error(-1, "Unexpected end of file in embedded font stream");
+ goto err1;
+ }
+ if (!((start[i] >= '0' && start[i] <= '9') ||
+ (start[i] >= 'A' && start[i] <= 'F') ||
+ (start[i] >= 'a' && start[i] <= 'f')))
+ binMode = gTrue;
+ }
+
+ // convert binary data to ASCII
+ if (binMode) {
+ for (i = 0; i < 4; ++i) {
+ writePSChar(hexChar[(start[i] >> 4) & 0x0f]);
+ writePSChar(hexChar[start[i] & 0x0f]);
+ }
+ while (i < length2) {
+ if ((c = strObj.streamGetChar()) == EOF) {
+ break;
+ }
+ writePSChar(hexChar[(c >> 4) & 0x0f]);
+ writePSChar(hexChar[c & 0x0f]);
+ if (++i % 32 == 0) {
+ writePSChar('\n');
+ }
+ }
+ if (i % 32 > 0) {
+ writePSChar('\n');
+ }
+
+ // already in ASCII format -- just copy it
+ } else {
+ for (i = 0; i < 4; ++i) {
+ writePSChar(start[i]);
+ }
+ for (i = 4; i < length2; ++i) {
+ if ((c = strObj.streamGetChar()) == EOF) {
+ break;
+ }
+ writePSChar(c);
+ }
+ }
+
+ // write padding and "cleartomark"
+ for (i = 0; i < 8; ++i) {
+ writePS("00000000000000000000000000000000"
+ "00000000000000000000000000000000\n");
+ }
+ writePS("cleartomark\n");
+
+ // ending comment
+ writePS("%%EndResource\n");
+
+ err1:
+ strObj.streamClose();
+ strObj.free();
+}
+
+//~ This doesn't handle .pfb files or binary eexec data (which only
+//~ happens in pfb files?).
+void PSOutputDev::setupExternalType1Font(GString *fileName, char *psName) {
+ FILE *fontFile;
+ int c;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileNameLen; ++i) {
+ if (!fontFileNames[i]->cmp(fileName)) {
+ return;
+ }
+ }
+
+ // add entry to fontFileNames list
+ if (fontFileNameLen >= fontFileNameSize) {
+ fontFileNameSize += 64;
+ fontFileNames = (GString **)grealloc(fontFileNames,
+ fontFileNameSize * sizeof(GString *));
+ }
+ fontFileNames[fontFileNameLen++] = fileName->copy();
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // copy the font file
+ if (!(fontFile = fopen(fileName->getCString(), "rb"))) {
+ error(-1, "Couldn't open external font file");
+ return;
+ }
+ while ((c = fgetc(fontFile)) != EOF) {
+ writePSChar(c);
+ }
+ fclose(fontFile);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
+ char *psName) {
+ char *fontBuf;
+ int fontLen;
+ Type1CFontFile *t1cFile;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileIDLen; ++i) {
+ if (fontFileIDs[i].num == id->num &&
+ fontFileIDs[i].gen == id->gen)
+ return;
+ }
+
+ // add entry to fontFileIDs list
+ if (fontFileIDLen >= fontFileIDSize) {
+ fontFileIDSize += 64;
+ fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+ }
+ fontFileIDs[fontFileIDLen++] = *id;
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // convert it to a Type 1 font
+ fontBuf = font->readEmbFontFile(xref, &fontLen);
+ t1cFile = new Type1CFontFile(fontBuf, fontLen);
+ t1cFile->convertToType1(outputFunc, outputStream);
+ delete t1cFile;
+ gfree(fontBuf);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id,
+ char *psName) {
+ char *fontBuf;
+ int fontLen;
+ TrueTypeFontFile *ttFile;
+ CharCodeToUnicode *ctu;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileIDLen; ++i) {
+ if (fontFileIDs[i].num == id->num &&
+ fontFileIDs[i].gen == id->gen)
+ return;
+ }
+
+ // add entry to fontFileIDs list
+ if (fontFileIDLen >= fontFileIDSize) {
+ fontFileIDSize += 64;
+ fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+ }
+ fontFileIDs[fontFileIDLen++] = *id;
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // convert it to a Type 42 font
+ fontBuf = font->readEmbFontFile(xref, &fontLen);
+ ttFile = new TrueTypeFontFile(fontBuf, fontLen);
+ ctu = ((Gfx8BitFont *)font)->getToUnicode();
+ ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
+ ctu, ((Gfx8BitFont *)font)->getHasEncoding(),
+ outputFunc, outputStream);
+ ctu->decRefCnt();
+ delete ttFile;
+ gfree(fontBuf);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupExternalTrueTypeFont(GfxFont *font, char *psName) {
+ GString *fileName;
+ char *fontBuf;
+ int fontLen;
+ TrueTypeFontFile *ttFile;
+ CharCodeToUnicode *ctu;
+ int i;
+
+ // check if font is already embedded
+ fileName = font->getExtFontFile();
+ for (i = 0; i < fontFileNameLen; ++i) {
+ if (!fontFileNames[i]->cmp(fileName)) {
+ return;
+ }
+ }
+
+ // add entry to fontFileNames list
+ if (fontFileNameLen >= fontFileNameSize) {
+ fontFileNameSize += 64;
+ fontFileNames = (GString **)grealloc(fontFileNames,
+ fontFileNameSize * sizeof(GString *));
+ }
+ fontFileNames[fontFileNameLen++] = fileName->copy();
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // convert it to a Type 42 font
+ fontBuf = font->readExtFontFile(&fontLen);
+ ttFile = new TrueTypeFontFile(fontBuf, fontLen);
+ ctu = ((Gfx8BitFont *)font)->getToUnicode();
+ ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
+ ctu, ((Gfx8BitFont *)font)->getHasEncoding(),
+ outputFunc, outputStream);
+ ctu->decRefCnt();
+ delete ttFile;
+ gfree(fontBuf);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
+ char *psName) {
+ char *fontBuf;
+ int fontLen;
+ Type1CFontFile *t1cFile;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileIDLen; ++i) {
+ if (fontFileIDs[i].num == id->num &&
+ fontFileIDs[i].gen == id->gen)
+ return;
+ }
+
+ // add entry to fontFileIDs list
+ if (fontFileIDLen >= fontFileIDSize) {
+ fontFileIDSize += 64;
+ fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+ }
+ fontFileIDs[fontFileIDLen++] = *id;
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // convert it to a Type 0 font
+ fontBuf = font->readEmbFontFile(xref, &fontLen);
+ t1cFile = new Type1CFontFile(fontBuf, fontLen);
+ if (globalParams->getPSLevel() >= psLevel3) {
+ // Level 3: use a CID font
+ t1cFile->convertToCIDType0(psName, outputFunc, outputStream);
+ } else {
+ // otherwise: use a non-CID composite font
+ t1cFile->convertToType0(psName, outputFunc, outputStream);
+ }
+ delete t1cFile;
+ gfree(fontBuf);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
+ char *psName) {
+ char *fontBuf;
+ int fontLen;
+ TrueTypeFontFile *ttFile;
+ int i;
+
+ // check if font is already embedded
+ for (i = 0; i < fontFileIDLen; ++i) {
+ if (fontFileIDs[i].num == id->num &&
+ fontFileIDs[i].gen == id->gen)
+ return;
+ }
+
+ // add entry to fontFileIDs list
+ if (fontFileIDLen >= fontFileIDSize) {
+ fontFileIDSize += 64;
+ fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+ }
+ fontFileIDs[fontFileIDLen++] = *id;
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // convert it to a Type 0 font
+ fontBuf = font->readEmbFontFile(xref, &fontLen);
+ ttFile = new TrueTypeFontFile(fontBuf, fontLen);
+ if (globalParams->getPSLevel() >= psLevel3) {
+ ttFile->convertToCIDType2(psName,
+ ((GfxCIDFont *)font)->getCIDToGID(),
+ ((GfxCIDFont *)font)->getCIDToGIDLen(),
+ outputFunc, outputStream);
+ } else {
+ // otherwise: use a non-CID composite font
+ ttFile->convertToType0(psName, ((GfxCIDFont *)font)->getCIDToGID(),
+ ((GfxCIDFont *)font)->getCIDToGIDLen(),
+ outputFunc, outputStream);
+ }
+ delete ttFile;
+ gfree(fontBuf);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
+ Dict *parentResDict) {
+ Dict *resDict;
+ Dict *charProcs;
+ Object charProc;
+ Gfx *gfx;
+ PDFRectangle box;
+ double *m;
+ char buf[256];
+ int i;
+
+ // set up resources used by font
+ if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
+ setupResources(resDict);
+ } else {
+ resDict = parentResDict;
+ }
+
+ // beginning comment
+ writePSFmt("%%%%BeginResource: font %s\n", psName);
+ embFontList->append("%%+ font ");
+ embFontList->append(psName);
+ embFontList->append("\n");
+
+ // font dictionary
+ writePS("7 dict begin\n");
+ writePS("/FontType 3 def\n");
+ m = font->getFontMatrix();
+ writePSFmt("/FontMatrix [%g %g %g %g %g %g] def\n",
+ m[0], m[1], m[2], m[3], m[4], m[5]);
+ m = font->getFontBBox();
+ writePSFmt("/FontBBox [%g %g %g %g] def\n",
+ m[0], m[1], m[2], m[3]);
+ writePS("/Encoding 256 array def\n");
+ writePS(" 0 1 255 { Encoding exch /.notdef put } for\n");
+ writePS("/BuildGlyph {\n");
+ writePS(" exch /CharProcs get exch\n");
+ writePS(" 2 copy known not { pop /.notdef } if\n");
+ writePS(" get exec\n");
+ writePS("} bind def\n");
+ writePS("/BuildChar {\n");
+ writePS(" 1 index /Encoding get exch get\n");
+ writePS(" 1 index /BuildGlyph get exec\n");
+ writePS("} bind def\n");
+ if ((charProcs = ((Gfx8BitFont *)font)->getCharProcs())) {
+ writePSFmt("/CharProcs %d dict def\n", charProcs->getLength());
+ writePS("CharProcs begin\n");
+ box.x1 = m[0];
+ box.y1 = m[1];
+ box.x2 = m[2];
+ box.y2 = m[3];
+ gfx = new Gfx(xref, this, resDict, &box, gFalse, NULL);
+ inType3Char = gTrue;
+ t3Cacheable = gFalse;
+ for (i = 0; i < charProcs->getLength(); ++i) {
+ writePS("/");
+ writePSName(charProcs->getKey(i));
+ writePS(" {\n");
+ gfx->display(charProcs->getVal(i, &charProc));
+ charProc.free();
+ if (t3String) {
+ if (t3Cacheable) {
+ sprintf(buf, "%g %g %g %g %g %g setcachedevice\n",
+ t3WX, t3WY, t3LLX, t3LLY, t3URX, t3URY);
+ } else {
+ sprintf(buf, "%g %g setcharwidth\n", t3WX, t3WY);
+ }
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ (*outputFunc)(outputStream, t3String->getCString(),
+ t3String->getLength());
+ delete t3String;
+ t3String = NULL;
+ }
+ (*outputFunc)(outputStream, "Q\n", 2);
+ writePS("} def\n");
+ }
+ inType3Char = gFalse;
+ delete gfx;
+ writePS("end\n");
+ }
+ writePS("currentdict end\n");
+ writePSFmt("/%s exch definefont pop\n", psName);
+
+ // ending comment
+ writePS("%%EndResource\n");
+}
+
+void PSOutputDev::setupImages(Dict *resDict) {
+ Object xObjDict, xObj, xObjRef, subtypeObj;
+ int i;
+
+ if (mode != psModeForm) {
+ return;
+ }
+
+ resDict->lookup("XObject", &xObjDict);
+ if (xObjDict.isDict()) {
+ for (i = 0; i < xObjDict.dictGetLength(); ++i) {
+ xObjDict.dictGetValNF(i, &xObjRef);
+ xObjDict.dictGetVal(i, &xObj);
+ if (xObj.isStream()) {
+ xObj.streamGetDict()->lookup("Subtype", &subtypeObj);
+ if (subtypeObj.isName("Image")) {
+ if (xObjRef.isRef()) {
+ setupImage(xObjRef.getRef(), xObj.getStream());
+ } else {
+ error(-1, "Image in resource dict is not an indirect reference");
+ }
+ }
+ subtypeObj.free();
+ }
+ xObj.free();
+ xObjRef.free();
+ }
+ }
+ xObjDict.free();
+}
+
+void PSOutputDev::setupImage(Ref id, Stream *str) {
+ int c;
+ int size, line, col, i;
+
+ // construct an encoder stream
+ if (globalParams->getPSASCIIHex()) {
+ str = new ASCIIHexEncoder(str);
+ } else {
+ str = new ASCII85Encoder(str);
+ }
+
+ // compute image data size
+ str->reset();
+ col = size = 0;
+ do {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ if (c == 'z') {
+ ++col;
+ } else {
+ ++col;
+ for (i = 1; i <= 4; ++i) {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ ++col;
+ }
+ }
+ if (col > 225) {
+ ++size;
+ col = 0;
+ }
+ } while (c != '~' && c != EOF);
+ ++size;
+ writePSFmt("%d array dup /ImData_%d_%d exch def\n", size, id.num, id.gen);
+
+ // write the data into the array
+ str->reset();
+ line = col = 0;
+ writePS("dup 0 <~");
+ do {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ if (c == 'z') {
+ writePSChar(c);
+ ++col;
+ } else {
+ writePSChar(c);
+ ++col;
+ for (i = 1; i <= 4; ++i) {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ writePSChar(c);
+ ++col;
+ }
+ }
+ // each line is: "dup nnnnn <~...data...~> put<eol>"
+ // so max data length = 255 - 20 = 235
+ // chunks are 1 or 4 bytes each, so we have to stop at 232
+ // but make it 225 just to be safe
+ if (col > 225) {
+ writePS("~> put\n");
+ ++line;
+ writePSFmt("dup %d <~", line);
+ col = 0;
+ }
+ } while (c != '~' && c != EOF);
+ writePS("~> put\n");
+ writePS("pop\n");
+
+ delete str;
+}
+
+void PSOutputDev::startPage(int pageNum, GfxState *state) {
+ int x1, y1, x2, y2, width, height, t;
+
+
+ switch (mode) {
+
+ case psModePS:
+ writePSFmt("%%%%Page: %d %d\n", pageNum, seqPage);
+ writePS("%%BeginPageSetup\n");
+
+ // rotate, translate, and scale page
+ x1 = (int)(state->getX1() + 0.5);
+ y1 = (int)(state->getY1() + 0.5);
+ x2 = (int)(state->getX2() + 0.5);
+ y2 = (int)(state->getY2() + 0.5);
+ width = x2 - x1;
+ height = y2 - y1;
+ if (width > height && width > paperWidth) {
+ landscape = gTrue;
+ writePSFmt("%%%%PageQt::Orientation: %s\n",
+ state->getCTM()[0] ? "Landscape" : "Portrait");
+ writePS("pdfStartPage\n");
+ writePS("90 rotate\n");
+ tx = -x1;
+ ty = -(y1 + paperWidth);
+ t = width;
+ width = height;
+ height = t;
+ } else {
+ landscape = gFalse;
+ writePSFmt("%%%%PageQt::Orientation: %s\n",
+ state->getCTM()[0] ? "Portrait" : "Landscape");
+ writePS("pdfStartPage\n");
+ tx = -x1;
+ ty = -y1;
+ }
+ if (width < paperWidth) {
+ tx += (paperWidth - width) / 2;
+ }
+ if (height < paperHeight) {
+ ty += (paperHeight - height) / 2;
+ }
+ if (tx != 0 || ty != 0) {
+ writePSFmt("%g %g translate\n", tx, ty);
+ }
+ if (width > paperWidth || height > paperHeight) {
+ xScale = (double)paperWidth / (double)width;
+ yScale = (double)paperHeight / (double)height;
+ if (yScale < xScale) {
+ xScale = yScale;
+ } else {
+ yScale = xScale;
+ }
+ writePSFmt("%0.4f %0.4f scale\n", xScale, xScale);
+ } else {
+ xScale = yScale = 1;
+ }
+
+ writePS("%%EndPageSetup\n");
+ ++seqPage;
+ break;
+
+ case psModeEPS:
+ writePS("pdfStartPage\n");
+ tx = ty = 0;
+ xScale = yScale = 1;
+ landscape = gFalse;
+ break;
+
+ case psModeForm:
+ writePS("/PaintProc {\n");
+ writePS("begin xpdf begin\n");
+ writePS("pdfStartPage\n");
+ tx = ty = 0;
+ xScale = yScale = 1;
+ landscape = gFalse;
+ break;
+ }
+}
+
+void PSOutputDev::endPage() {
+
+ if (mode == psModeForm) {
+ writePS("pdfEndPage\n");
+ writePS("end end\n");
+ writePS("} def\n");
+ writePS("end end\n");
+ } else {
+ writePS("showpage\n");
+ writePS("%%PageTrailer\n");
+ writePS("pdfEndPage\n");
+ }
+}
+
+void PSOutputDev::saveState(GfxState *state) {
+ writePS("q\n");
+}
+
+void PSOutputDev::restoreState(GfxState *state) {
+ writePS("Q\n");
+}
+
+void PSOutputDev::updateCTM(GfxState *state, double m11, double m12,
+ double m21, double m22, double m31, double m32) {
+ writePSFmt("[%g %g %g %g %g %g] cm\n", m11, m12, m21, m22, m31, m32);
+}
+
+void PSOutputDev::updateLineDash(GfxState *state) {
+ double *dash;
+ double start;
+ int length, i;
+
+ state->getLineDash(&dash, &length, &start);
+ writePS("[");
+ for (i = 0; i < length; ++i)
+ writePSFmt("%g%s", dash[i], (i == length-1) ? "" : " ");
+ writePSFmt("] %g d\n", start);
+}
+
+void PSOutputDev::updateFlatness(GfxState *state) {
+ writePSFmt("%d i\n", state->getFlatness());
+}
+
+void PSOutputDev::updateLineJoin(GfxState *state) {
+ writePSFmt("%d j\n", state->getLineJoin());
+}
+
+void PSOutputDev::updateLineCap(GfxState *state) {
+ writePSFmt("%d J\n", state->getLineCap());
+}
+
+void PSOutputDev::updateMiterLimit(GfxState *state) {
+ writePSFmt("%g M\n", state->getMiterLimit());
+}
+
+void PSOutputDev::updateLineWidth(GfxState *state) {
+ writePSFmt("%g w\n", state->getLineWidth());
+}
+
+void PSOutputDev::updateFillColor(GfxState *state) {
+ GfxColor color;
+ double gray;
+ GfxRGB rgb;
+ GfxCMYK cmyk;
+ GfxSeparationColorSpace *sepCS;
+
+ switch (level) {
+ case psLevel1:
+ state->getFillGray(&gray);
+ writePSFmt("%g g\n", gray);
+ break;
+ case psLevel1Sep:
+ state->getFillCMYK(&cmyk);
+ writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ break;
+ case psLevel2:
+ case psLevel3:
+ if (state->getFillColorSpace()->getMode() == csDeviceCMYK) {
+ state->getFillCMYK(&cmyk);
+ writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ } else {
+ state->getFillRGB(&rgb);
+ if (rgb.r == rgb.g && rgb.g == rgb.b) {
+ writePSFmt("%g g\n", rgb.r);
+ } else {
+ writePSFmt("%g %g %g rg\n", rgb.r, rgb.g, rgb.b);
+ }
+ }
+ break;
+ case psLevel2Sep:
+ case psLevel3Sep:
+ if (state->getFillColorSpace()->getMode() == csSeparation) {
+ sepCS = (GfxSeparationColorSpace *)state->getFillColorSpace();
+ color.c[0] = 1;
+ sepCS->getCMYK(&color, &cmyk);
+ writePSFmt("%g %g %g %g %g (%s) ck\n",
+ state->getFillColor()->c[0],
+ cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+ sepCS->getName()->getCString());
+ addCustomColor(sepCS);
+ } else {
+ state->getFillCMYK(&cmyk);
+ writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ }
+ break;
+ }
+ t3Cacheable = gFalse;
+}
+
+void PSOutputDev::updateStrokeColor(GfxState *state) {
+ GfxColor color;
+ double gray;
+ GfxRGB rgb;
+ GfxCMYK cmyk;
+ GfxSeparationColorSpace *sepCS;
+
+ switch (level) {
+ case psLevel1:
+ state->getStrokeGray(&gray);
+ writePSFmt("%g G\n", gray);
+ break;
+ case psLevel1Sep:
+ state->getStrokeCMYK(&cmyk);
+ writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ break;
+ case psLevel2:
+ case psLevel3:
+ if (state->getStrokeColorSpace()->getMode() == csDeviceCMYK) {
+ state->getStrokeCMYK(&cmyk);
+ writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ } else {
+ state->getStrokeRGB(&rgb);
+ if (rgb.r == rgb.g && rgb.g == rgb.b) {
+ writePSFmt("%g G\n", rgb.r);
+ } else {
+ writePSFmt("%g %g %g RG\n", rgb.r, rgb.g, rgb.b);
+ }
+ }
+ break;
+ case psLevel2Sep:
+ case psLevel3Sep:
+ if (state->getStrokeColorSpace()->getMode() == csSeparation) {
+ sepCS = (GfxSeparationColorSpace *)state->getStrokeColorSpace();
+ color.c[0] = 1;
+ sepCS->getCMYK(&color, &cmyk);
+ writePSFmt("%g %g %g %g %g (%s) CK\n",
+ state->getStrokeColor()->c[0],
+ cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+ sepCS->getName()->getCString());
+ addCustomColor(sepCS);
+ } else {
+ state->getStrokeCMYK(&cmyk);
+ writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ }
+ break;
+ }
+ t3Cacheable = gFalse;
+}
+
+void PSOutputDev::addProcessColor(double c, double m, double y, double k) {
+ if (c > 0) {
+ processColors |= psProcessCyan;
+ }
+ if (m > 0) {
+ processColors |= psProcessMagenta;
+ }
+ if (y > 0) {
+ processColors |= psProcessYellow;
+ }
+ if (k > 0) {
+ processColors |= psProcessBlack;
+ }
+}
+
+void PSOutputDev::addCustomColor(GfxSeparationColorSpace *sepCS) {
+ PSOutCustomColor *cc;
+ GfxColor color;
+ GfxCMYK cmyk;
+
+ for (cc = customColors; cc; cc = cc->next) {
+ if (!cc->name->cmp(sepCS->getName())) {
+ return;
+ }
+ }
+ color.c[0] = 1;
+ sepCS->getCMYK(&color, &cmyk);
+ cc = new PSOutCustomColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+ sepCS->getName()->copy());
+ cc->next = customColors;
+ customColors = cc;
+}
+
+void PSOutputDev::updateFont(GfxState *state) {
+ if (state->getFont()) {
+ writePSFmt("/F%d_%d %g Tf\n",
+ state->getFont()->getID()->num, state->getFont()->getID()->gen,
+ state->getFontSize());
+ }
+}
+
+void PSOutputDev::updateTextMat(GfxState *state) {
+ double *mat;
+
+ mat = state->getTextMat();
+ writePSFmt("[%g %g %g %g %g %g] Tm\n",
+ mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
+}
+
+void PSOutputDev::updateCharSpace(GfxState *state) {
+ writePSFmt("%g Tc\n", state->getCharSpace());
+}
+
+void PSOutputDev::updateRender(GfxState *state) {
+ int rm;
+
+ rm = state->getRender();
+ writePSFmt("%d Tr\n", rm);
+ rm &= 3;
+ if (rm != 0 && rm != 3) {
+ t3Cacheable = gFalse;
+ }
+}
+
+void PSOutputDev::updateRise(GfxState *state) {
+ writePSFmt("%g Ts\n", state->getRise());
+}
+
+void PSOutputDev::updateWordSpace(GfxState *state) {
+ writePSFmt("%g Tw\n", state->getWordSpace());
+}
+
+void PSOutputDev::updateHorizScaling(GfxState *state) {
+ writePSFmt("%g Tz\n", state->getHorizScaling());
+}
+
+void PSOutputDev::updateTextPos(GfxState *state) {
+ writePSFmt("%g %g Td\n", state->getLineX(), state->getLineY());
+}
+
+void PSOutputDev::updateTextShift(GfxState *state, double shift) {
+ if (state->getFont()->getWMode()) {
+ writePSFmt("%g TJmV\n", shift);
+ } else {
+ writePSFmt("%g TJm\n", shift);
+ }
+}
+
+void PSOutputDev::stroke(GfxState *state) {
+ doPath(state->getPath());
+ if (t3String) {
+ // if we're construct a cacheable Type 3 glyph, we need to do
+ // everything in the fill color
+ writePS("Sf\n");
+ } else {
+ writePS("S\n");
+ }
+}
+
+void PSOutputDev::fill(GfxState *state) {
+ doPath(state->getPath());
+ writePS("f\n");
+}
+
+void PSOutputDev::eoFill(GfxState *state) {
+ doPath(state->getPath());
+ writePS("f*\n");
+}
+
+void PSOutputDev::clip(GfxState *state) {
+ doPath(state->getPath());
+ writePS("W\n");
+}
+
+void PSOutputDev::eoClip(GfxState *state) {
+ doPath(state->getPath());
+ writePS("W*\n");
+}
+
+void PSOutputDev::doPath(GfxPath *path) {
+ GfxSubpath *subpath;
+ double x0, y0, x1, y1, x2, y2, x3, y3, x4, y4;
+ int n, m, i, j;
+
+ n = path->getNumSubpaths();
+
+ if (n == 1 && path->getSubpath(0)->getNumPoints() == 5) {
+ subpath = path->getSubpath(0);
+ x0 = subpath->getX(0);
+ y0 = subpath->getY(0);
+ x4 = subpath->getX(4);
+ y4 = subpath->getY(4);
+ if (x4 == x0 && y4 == y0) {
+ x1 = subpath->getX(1);
+ y1 = subpath->getY(1);
+ x2 = subpath->getX(2);
+ y2 = subpath->getY(2);
+ x3 = subpath->getX(3);
+ y3 = subpath->getY(3);
+ if (x0 == x1 && x2 == x3 && y0 == y3 && y1 == y2) {
+ writePSFmt("%g %g %g %g re\n",
+ x0 < x2 ? x0 : x2, y0 < y1 ? y0 : y1,
+ fabs(x2 - x0), fabs(y1 - y0));
+ return;
+ } else if (x0 == x3 && x1 == x2 && y0 == y1 && y2 == y3) {
+ writePSFmt("%g %g %g %g re\n",
+ x0 < x1 ? x0 : x1, y0 < y2 ? y0 : y2,
+ fabs(x1 - x0), fabs(y2 - y0));
+ return;
+ }
+ }
+ }
+
+ for (i = 0; i < n; ++i) {
+ subpath = path->getSubpath(i);
+ m = subpath->getNumPoints();
+ writePSFmt("%g %g m\n", subpath->getX(0), subpath->getY(0));
+ j = 1;
+ while (j < m) {
+ if (subpath->getCurve(j)) {
+ writePSFmt("%g %g %g %g %g %g c\n", subpath->getX(j), subpath->getY(j),
+ subpath->getX(j+1), subpath->getY(j+1),
+ subpath->getX(j+2), subpath->getY(j+2));
+ j += 3;
+ } else {
+ writePSFmt("%g %g l\n", subpath->getX(j), subpath->getY(j));
+ ++j;
+ }
+ }
+ if (subpath->isClosed()) {
+ writePS("h\n");
+ }
+ }
+}
+
+void PSOutputDev::drawString(GfxState *state, GString *s) {
+ GfxFont *font;
+ int wMode;
+ GString *s2;
+ double dx, dy, dx2, dy2, originX, originY;
+ char *p;
+ UnicodeMap *uMap;
+ CharCode code;
+ Unicode u[8];
+ char buf[8];
+ int len, nChars, uLen, n, m, i, j;
+
+ // check for invisible text -- this is used by Acrobat Capture
+ if ((state->getRender() & 3) == 3) {
+ return;
+ }
+
+ // ignore empty strings
+ if (s->getLength() == 0) {
+ return;
+ }
+
+ // get the font
+ if (!(font = state->getFont())) {
+ return;
+ }
+ wMode = font->getWMode();
+
+ // check for a subtitute 16-bit font
+ uMap = NULL;
+ if (font->isCIDFont()) {
+ for (i = 0; i < font16EncLen; ++i) {
+ if (font->getID()->num == font16Enc[i].fontID.num &&
+ font->getID()->gen == font16Enc[i].fontID.gen) {
+ uMap = globalParams->getUnicodeMap(font16Enc[i].enc);
+ break;
+ }
+ }
+ }
+
+ // compute width of chars in string, ignoring char spacing and word
+ // spacing -- the Tj operator will adjust for the metrics of the
+ // font that's actually used
+ dx = dy = 0;
+ nChars = 0;
+ p = s->getCString();
+ len = s->getLength();
+ if (font->isCIDFont()) {
+ s2 = new GString();
+ } else {
+ s2 = s;
+ }
+ while (len > 0) {
+ n = font->getNextChar(p, len, &code,
+ u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
+ &dx2, &dy2, &originX, &originY);
+ if (font->isCIDFont()) {
+ if (uMap) {
+ for (i = 0; i < uLen; ++i) {
+ m = uMap->mapUnicode(u[i], buf, (int)sizeof(buf));
+ for (j = 0; j < m; ++j) {
+ s2->append(buf[j]);
+ }
+ }
+ //~ this really needs to get the number of chars in the target
+ //~ encoding - which may be more than the number of Unicode
+ //~ chars
+ nChars += uLen;
+ } else {
+ s2->append((char)((code >> 8) & 0xff));
+ s2->append((char)(code & 0xff));
+ ++nChars;
+ }
+ }
+ dx += dx2;
+ dy += dy2;
+ p += n;
+ len -= n;
+ }
+ dx *= state->getFontSize() * state->getHorizScaling();
+ dy *= state->getFontSize();
+ if (uMap) {
+ uMap->decRefCnt();
+ }
+
+ if (s2->getLength() > 0) {
+ writePSString(s2);
+ if (font->isCIDFont()) {
+ if (wMode) {
+ writePSFmt(" %d %g Tj16V\n", nChars, dy);
+ } else {
+ writePSFmt(" %d %g Tj16\n", nChars, dx);
+ }
+ } else {
+ writePSFmt(" %g Tj\n", dx);
+ }
+ }
+ if (font->isCIDFont()) {
+ delete s2;
+ }
+}
+
+void PSOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
+ int width, int height, GBool invert,
+ GBool inlineImg) {
+ int len;
+
+ len = height * ((width + 7) / 8);
+ if (level == psLevel1 || level == psLevel1Sep) {
+ doImageL1(NULL, invert, inlineImg, str, width, height, len);
+ } else {
+ doImageL2(ref, NULL, invert, inlineImg, str, width, height, len);
+ }
+}
+
+void PSOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
+ int width, int height, GfxImageColorMap *colorMap,
+ int *maskColors, GBool inlineImg) {
+ int len;
+
+ len = height * ((width * colorMap->getNumPixelComps() *
+ colorMap->getBits() + 7) / 8);
+ switch (level) {
+ case psLevel1:
+ doImageL1(colorMap, gFalse, inlineImg, str, width, height, len);
+ break;
+ case psLevel1Sep:
+ //~ handle indexed, separation, ... color spaces
+ doImageL1Sep(colorMap, gFalse, inlineImg, str, width, height, len);
+ break;
+ case psLevel2:
+ case psLevel2Sep:
+ case psLevel3:
+ case psLevel3Sep:
+ doImageL2(ref, colorMap, gFalse, inlineImg, str, width, height, len);
+ break;
+ }
+ t3Cacheable = gFalse;
+}
+
+void PSOutputDev::doImageL1(GfxImageColorMap *colorMap,
+ GBool invert, GBool inlineImg,
+ Stream *str, int width, int height, int len) {
+ ImageStream *imgStr;
+ Guchar pixBuf[gfxColorMaxComps];
+ double gray;
+ int x, y, i;
+
+ // width, height, matrix, bits per component
+ if (colorMap) {
+ writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1\n",
+ width, height,
+ width, -height, height);
+ } else {
+ writePSFmt("%d %d %s [%d 0 0 %d 0 %d] pdfImM1\n",
+ width, height, invert ? "true" : "false",
+ width, -height, height);
+ }
+
+ // image
+ if (colorMap) {
+
+ // set up to process the data stream
+ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+ colorMap->getBits());
+ imgStr->reset();
+
+ // process the data stream
+ i = 0;
+ for (y = 0; y < height; ++y) {
+
+ // write the line
+ for (x = 0; x < width; ++x) {
+ imgStr->getPixel(pixBuf);
+ colorMap->getGray(pixBuf, &gray);
+ writePSFmt("%02x", (int)(gray * 255 + 0.5));
+ if (++i == 32) {
+ writePSChar('\n');
+ i = 0;
+ }
+ }
+ }
+ if (i != 0) {
+ writePSChar('\n');
+ }
+ delete imgStr;
+
+ // imagemask
+ } else {
+ str->reset();
+ i = 0;
+ for (y = 0; y < height; ++y) {
+ for (x = 0; x < width; x += 8) {
+ writePSFmt("%02x", str->getChar() & 0xff);
+ if (++i == 32) {
+ writePSChar('\n');
+ i = 0;
+ }
+ }
+ }
+ if (i != 0) {
+ writePSChar('\n');
+ }
+ str->close();
+ }
+}
+
+void PSOutputDev::doImageL1Sep(GfxImageColorMap *colorMap,
+ GBool invert, GBool inlineImg,
+ Stream *str, int width, int height, int len) {
+ ImageStream *imgStr;
+ Guchar *lineBuf;
+ Guchar pixBuf[gfxColorMaxComps];
+ GfxCMYK cmyk;
+ int x, y, i, comp;
+
+ // width, height, matrix, bits per component
+ writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1Sep\n",
+ width, height,
+ width, -height, height);
+
+ // allocate a line buffer
+ lineBuf = (Guchar *)gmalloc(4 * width);
+
+ // set up to process the data stream
+ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+ colorMap->getBits());
+ imgStr->reset();
+
+ // process the data stream
+ i = 0;
+ for (y = 0; y < height; ++y) {
+
+ // read the line
+ for (x = 0; x < width; ++x) {
+ imgStr->getPixel(pixBuf);
+ colorMap->getCMYK(pixBuf, &cmyk);
+ lineBuf[4*x+0] = (int)(255 * cmyk.c + 0.5);
+ lineBuf[4*x+1] = (int)(255 * cmyk.m + 0.5);
+ lineBuf[4*x+2] = (int)(255 * cmyk.y + 0.5);
+ lineBuf[4*x+3] = (int)(255 * cmyk.k + 0.5);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ }
+
+ // write one line of each color component
+ for (comp = 0; comp < 4; ++comp) {
+ for (x = 0; x < width; ++x) {
+ writePSFmt("%02x", lineBuf[4*x + comp]);
+ if (++i == 32) {
+ writePSChar('\n');
+ i = 0;
+ }
+ }
+ }
+ }
+
+ if (i != 0) {
+ writePSChar('\n');
+ }
+
+ delete imgStr;
+ gfree(lineBuf);
+}
+
+void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
+ GBool invert, GBool inlineImg,
+ Stream *str, int width, int height, int len) {
+ GString *s;
+ int n, numComps;
+ GBool useRLE, useASCII, useCompressed;
+ GfxSeparationColorSpace *sepCS;
+ GfxColor color;
+ GfxCMYK cmyk;
+ int c;
+ int line, col, i;
+
+ // color space
+ if (colorMap) {
+ dumpColorSpaceL2(colorMap->getColorSpace());
+ writePS(" setcolorspace\n");
+ }
+
+ // set up the image data
+ if (mode == psModeForm || inType3Char) {
+ if (inlineImg) {
+ // create an array
+ str = new FixedLengthEncoder(str, len);
+ if (globalParams->getPSASCIIHex()) {
+ str = new ASCIIHexEncoder(str);
+ } else {
+ str = new ASCII85Encoder(str);
+ }
+ str->reset();
+ line = col = 0;
+ writePS("[<~");
+ do {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ if (c == 'z') {
+ writePSChar(c);
+ ++col;
+ } else {
+ writePSChar(c);
+ ++col;
+ for (i = 1; i <= 4; ++i) {
+ do {
+ c = str->getChar();
+ } while (c == '\n' || c == '\r');
+ if (c == '~' || c == EOF) {
+ break;
+ }
+ writePSChar(c);
+ ++col;
+ }
+ }
+ // each line is: "dup nnnnn <~...data...~> put<eol>"
+ // so max data length = 255 - 20 = 235
+ // chunks are 1 or 4 bytes each, so we have to stop at 232
+ // but make it 225 just to be safe
+ if (col > 225) {
+ writePS("~>\n");
+ ++line;
+ writePSFmt("<~", line);
+ col = 0;
+ }
+ } while (c != '~' && c != EOF);
+ writePS("~>]\n");
+ writePS("0\n");
+ delete str;
+ } else {
+ // set up to use the array already created by setupImages()
+ writePSFmt("ImData_%d_%d 0\n", ref->getRefNum(), ref->getRefGen());
+ }
+ }
+
+ // image dictionary
+ writePS("<<\n /ImageType 1\n");
+
+ // width, height, matrix, bits per component
+ writePSFmt(" /Width %d\n", width);
+ writePSFmt(" /Height %d\n", height);
+ writePSFmt(" /ImageMatrix [%d 0 0 %d 0 %d]\n", width, -height, height);
+ writePSFmt(" /BitsPerComponent %d\n",
+ colorMap ? colorMap->getBits() : 1);
+
+ // decode
+ if (colorMap) {
+ writePS(" /Decode [");
+ if (colorMap->getColorSpace()->getMode() == csSeparation) {
+ //~ this is a kludge -- see comment in dumpColorSpaceL2
+ n = (1 << colorMap->getBits()) - 1;
+ writePSFmt("%g %g", colorMap->getDecodeLow(0) * n,
+ colorMap->getDecodeHigh(0) * n);
+ } else {
+ numComps = colorMap->getNumPixelComps();
+ for (i = 0; i < numComps; ++i) {
+ if (i > 0) {
+ writePS(" ");
+ }
+ writePSFmt("%g %g", colorMap->getDecodeLow(i),
+ colorMap->getDecodeHigh(i));
+ }
+ }
+ writePS("]\n");
+ } else {
+ writePSFmt(" /Decode [%d %d]\n", invert ? 1 : 0, invert ? 0 : 1);
+ }
+
+ if (mode == psModeForm || inType3Char) {
+
+ // data source
+ writePS(" /DataSource { 2 copy get exch 1 add exch }\n");
+
+ // end of image dictionary
+ writePSFmt(">>\n%s\n", colorMap ? "image" : "imagemask");
+
+ // get rid of the array and index
+ writePS("pop pop\n");
+
+ } else {
+
+ // data source
+ writePS(" /DataSource currentfile\n");
+ s = str->getPSFilter(" ");
+ if (inlineImg || !s) {
+ useRLE = gTrue;
+ useASCII = gTrue;
+ useCompressed = gFalse;
+ } else {
+ useRLE = gFalse;
+ useASCII = str->isBinary();
+ useCompressed = gTrue;
+ }
+ if (useASCII) {
+ writePSFmt(" /ASCII%sDecode filter\n",
+ globalParams->getPSASCIIHex() ? "Hex" : "85");
+ }
+ if (useRLE) {
+ writePS(" /RunLengthDecode filter\n");
+ }
+ if (useCompressed) {
+ writePS(s->getCString());
+ }
+ if (s) {
+ delete s;
+ }
+
+ // cut off inline image streams at appropriate length
+ if (inlineImg) {
+ str = new FixedLengthEncoder(str, len);
+ } else if (useCompressed) {
+ str = str->getBaseStream();
+ }
+
+ // add RunLengthEncode and ASCIIHex/85 encode filters
+ if (useRLE) {
+ str = new RunLengthEncoder(str);
+ }
+ if (useASCII) {
+ if (globalParams->getPSASCIIHex()) {
+ str = new ASCIIHexEncoder(str);
+ } else {
+ str = new ASCII85Encoder(str);
+ }
+ }
+
+ // end of image dictionary
+ writePS(">>\n");
+#if OPI_SUPPORT
+ if (opi13Nest) {
+ if (inlineImg) {
+ // this can't happen -- OPI dictionaries are in XObjects
+ error(-1, "Internal: OPI in inline image");
+ n = 0;
+ } else {
+ // need to read the stream to count characters -- the length
+ // is data-dependent (because of ASCII and RLE filters)
+ str->reset();
+ n = 0;
+ while ((c = str->getChar()) != EOF) {
+ ++n;
+ }
+ str->close();
+ }
+ // +6/7 for "pdfIm\n" / "pdfImM\n"
+ // +8 for newline + trailer
+ n += colorMap ? 14 : 15;
+ writePSFmt("%%%%BeginData: %d Hex Bytes\n", n);
+ }
+#endif
+ if ((level == psLevel2Sep || level == psLevel3Sep) && colorMap &&
+ colorMap->getColorSpace()->getMode() == csSeparation) {
+ color.c[0] = 1;
+ sepCS = (GfxSeparationColorSpace *)colorMap->getColorSpace();
+ sepCS->getCMYK(&color, &cmyk);
+ writePSFmt("%g %g %g %g (%s) pdfImSep\n",
+ cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+ sepCS->getName()->getCString());
+ } else {
+ writePSFmt("%s\n", colorMap ? "pdfIm" : "pdfImM");
+ }
+
+ // copy the stream data
+ str->reset();
+ while ((c = str->getChar()) != EOF) {
+ writePSChar(c);
+ }
+ str->close();
+
+ // add newline and trailer to the end
+ writePSChar('\n');
+ writePS("%-EOD-\n");
+#if OPI_SUPPORT
+ if (opi13Nest) {
+ writePS("%%EndData\n");
+ }
+#endif
+
+ // delete encoders
+ if (useRLE || useASCII || inlineImg) {
+ delete str;
+ }
+ }
+}
+
+void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
+ GfxCalGrayColorSpace *calGrayCS;
+ GfxCalRGBColorSpace *calRGBCS;
+ GfxLabColorSpace *labCS;
+ GfxIndexedColorSpace *indexedCS;
+ GfxSeparationColorSpace *separationCS;
+ GfxColorSpace *baseCS;
+ Guchar *lookup, *p;
+ double x[gfxColorMaxComps], y[gfxColorMaxComps];
+ GfxColor color;
+ GfxCMYK cmyk;
+ Function *func;
+ int n, numComps, numAltComps;
+ int byte;
+ int i, j, k;
+
+ switch (colorSpace->getMode()) {
+
+ case csDeviceGray:
+ writePS("/DeviceGray");
+ processColors |= psProcessBlack;
+ break;
+
+ case csCalGray:
+ calGrayCS = (GfxCalGrayColorSpace *)colorSpace;
+ writePS("[/CIEBasedA <<\n");
+ writePSFmt(" /DecodeA {%g exp} bind\n", calGrayCS->getGamma());
+ writePSFmt(" /MatrixA [%g %g %g]\n",
+ calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
+ calGrayCS->getWhiteZ());
+ writePSFmt(" /WhitePoint [%g %g %g]\n",
+ calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
+ calGrayCS->getWhiteZ());
+ writePSFmt(" /BlackPoint [%g %g %g]\n",
+ calGrayCS->getBlackX(), calGrayCS->getBlackY(),
+ calGrayCS->getBlackZ());
+ writePS(">>]");
+ processColors |= psProcessBlack;
+ break;
+
+ case csDeviceRGB:
+ writePS("/DeviceRGB");
+ processColors |= psProcessCMYK;
+ break;
+
+ case csCalRGB:
+ calRGBCS = (GfxCalRGBColorSpace *)colorSpace;
+ writePS("[/CIEBasedABC <<\n");
+ writePSFmt(" /DecodeABC [{%g exp} bind {%g exp} bind {%g exp} bind]\n",
+ calRGBCS->getGammaR(), calRGBCS->getGammaG(),
+ calRGBCS->getGammaB());
+ writePSFmt(" /MatrixABC [%g %g %g %g %g %g %g %g %g]\n",
+ calRGBCS->getMatrix()[0], calRGBCS->getMatrix()[1],
+ calRGBCS->getMatrix()[2], calRGBCS->getMatrix()[3],
+ calRGBCS->getMatrix()[4], calRGBCS->getMatrix()[5],
+ calRGBCS->getMatrix()[6], calRGBCS->getMatrix()[7],
+ calRGBCS->getMatrix()[8]);
+ writePSFmt(" /WhitePoint [%g %g %g]\n",
+ calRGBCS->getWhiteX(), calRGBCS->getWhiteY(),
+ calRGBCS->getWhiteZ());
+ writePSFmt(" /BlackPoint [%g %g %g]\n",
+ calRGBCS->getBlackX(), calRGBCS->getBlackY(),
+ calRGBCS->getBlackZ());
+ writePS(">>]");
+ processColors |= psProcessCMYK;
+ break;
+
+ case csDeviceCMYK:
+ writePS("/DeviceCMYK");
+ processColors |= psProcessCMYK;
+ break;
+
+ case csLab:
+ labCS = (GfxLabColorSpace *)colorSpace;
+ writePS("[/CIEBasedABC <<\n");
+ writePSFmt(" /RangeABC [0 100 %g %g %g %g]\n",
+ labCS->getAMin(), labCS->getAMax(),
+ labCS->getBMin(), labCS->getBMax());
+ writePS(" /DecodeABC [{16 add 116 div} bind {500 div} bind {200 div} bind]\n");
+ writePS(" /MatrixABC [1 1 1 1 0 0 0 0 -1]\n");
+ writePS(" /DecodeLMN\n");
+ writePS(" [{dup 6 29 div ge {dup dup mul mul}\n");
+ writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
+ labCS->getWhiteX());
+ writePS(" {dup 6 29 div ge {dup dup mul mul}\n");
+ writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
+ labCS->getWhiteY());
+ writePS(" {dup 6 29 div ge {dup dup mul mul}\n");
+ writePSFmt(" {4 29 div sub 108 841 div mul } ifelse %g mul} bind]\n",
+ labCS->getWhiteZ());
+ writePSFmt(" /WhitePoint [%g %g %g]\n",
+ labCS->getWhiteX(), labCS->getWhiteY(), labCS->getWhiteZ());
+ writePSFmt(" /BlackPoint [%g %g %g]\n",
+ labCS->getBlackX(), labCS->getBlackY(), labCS->getBlackZ());
+ writePS(">>]");
+ processColors |= psProcessCMYK;
+ break;
+
+ case csICCBased:
+ dumpColorSpaceL2(((GfxICCBasedColorSpace *)colorSpace)->getAlt());
+ break;
+
+ case csIndexed:
+ indexedCS = (GfxIndexedColorSpace *)colorSpace;
+ baseCS = indexedCS->getBase();
+ writePS("[/Indexed ");
+ dumpColorSpaceL2(baseCS);
+ n = indexedCS->getIndexHigh();
+ numComps = baseCS->getNComps();
+ lookup = indexedCS->getLookup();
+ writePSFmt(" %d <\n", n);
+ if (baseCS->getMode() == csDeviceN) {
+ func = ((GfxDeviceNColorSpace *)baseCS)->getTintTransformFunc();
+ numAltComps = ((GfxDeviceNColorSpace *)baseCS)->getAlt()->getNComps();
+ p = lookup;
+ for (i = 0; i <= n; i += 8) {
+ writePS(" ");
+ for (j = i; j < i+8 && j <= n; ++j) {
+ for (k = 0; k < numComps; ++k) {
+ x[k] = *p++ / 255.0;
+ }
+ func->transform(x, y);
+ for (k = 0; k < numAltComps; ++k) {
+ byte = (int)(y[k] * 255 + 0.5);
+ if (byte < 0) {
+ byte = 0;
+ } else if (byte > 255) {
+ byte = 255;
+ }
+ writePSFmt("%02x", byte);
+ }
+ color.c[0] = j;
+ indexedCS->getCMYK(&color, &cmyk);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ }
+ writePS("\n");
+ }
+ } else {
+ for (i = 0; i <= n; i += 8) {
+ writePS(" ");
+ for (j = i; j < i+8 && j <= n; ++j) {
+ for (k = 0; k < numComps; ++k) {
+ writePSFmt("%02x", lookup[j * numComps + k]);
+ }
+ color.c[0] = j;
+ indexedCS->getCMYK(&color, &cmyk);
+ addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+ }
+ writePS("\n");
+ }
+ }
+ writePS(">]");
+ break;
+
+ case csSeparation:
+ //~ this is a kludge -- the correct thing would to output a
+ //~ separation color space, with the specified alternate color
+ //~ space and tint transform
+ separationCS = (GfxSeparationColorSpace *)colorSpace;
+ writePS("[/Indexed ");
+ dumpColorSpaceL2(separationCS->getAlt());
+ writePS(" 255 <\n");
+ numComps = separationCS->getAlt()->getNComps();
+ for (i = 0; i <= 255; i += 8) {
+ writePS(" ");
+ for (j = i; j < i+8 && j <= 255; ++j) {
+ x[0] = (double)j / 255.0;
+ separationCS->getFunc()->transform(x, y);
+ for (k = 0; k < numComps; ++k) {
+ writePSFmt("%02x", (int)(255 * y[k] + 0.5));
+ }
+ }
+ writePS("\n");
+ }
+ writePS(">]");
+ addCustomColor(separationCS);
+ break;
+
+ case csDeviceN:
+ // DeviceN color spaces are a Level 3 PostScript feature.
+ dumpColorSpaceL2(((GfxDeviceNColorSpace *)colorSpace)->getAlt());
+ break;
+
+ case csPattern:
+ //~ unimplemented
+ break;
+
+ }
+}
+
+#if OPI_SUPPORT
+void PSOutputDev::opiBegin(GfxState *state, Dict *opiDict) {
+ Object dict;
+
+ if (globalParams->getPSOPI()) {
+ opiDict->lookup("2.0", &dict);
+ if (dict.isDict()) {
+ opiBegin20(state, dict.getDict());
+ dict.free();
+ } else {
+ dict.free();
+ opiDict->lookup("1.3", &dict);
+ if (dict.isDict()) {
+ opiBegin13(state, dict.getDict());
+ }
+ dict.free();
+ }
+ }
+}
+
+void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
+ Object obj1, obj2, obj3, obj4;
+ double width, height, left, right, top, bottom;
+ int w, h;
+ int i;
+
+ writePS("%%BeginOPI: 2.0\n");
+ writePS("%%Distilled\n");
+
+ dict->lookup("F", &obj1);
+ if (getFileSpec(&obj1, &obj2)) {
+ writePSFmt("%%%%ImageFileName: %s\n",
+ obj2.getString()->getCString());
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("MainImage", &obj1);
+ if (obj1.isString()) {
+ writePSFmt("%%%%MainImage: %s\n", obj1.getString()->getCString());
+ }
+ obj1.free();
+
+ //~ ignoring 'Tags' entry
+ //~ need to use writePSString() and deal with >255-char lines
+
+ dict->lookup("Size", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 2) {
+ obj1.arrayGet(0, &obj2);
+ width = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ height = obj2.getNum();
+ obj2.free();
+ writePSFmt("%%%%ImageDimensions: %g %g\n", width, height);
+ }
+ obj1.free();
+
+ dict->lookup("CropRect", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 4) {
+ obj1.arrayGet(0, &obj2);
+ left = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ top = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ right = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ bottom = obj2.getNum();
+ obj2.free();
+ writePSFmt("%%%%ImageCropRect: %g %g %g %g\n", left, top, right, bottom);
+ }
+ obj1.free();
+
+ dict->lookup("Overprint", &obj1);
+ if (obj1.isBool()) {
+ writePSFmt("%%%%ImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
+ }
+ obj1.free();
+
+ dict->lookup("Inks", &obj1);
+ if (obj1.isName()) {
+ writePSFmt("%%%%ImageInks: %s\n", obj1.getName());
+ } else if (obj1.isArray() && obj1.arrayGetLength() >= 1) {
+ obj1.arrayGet(0, &obj2);
+ if (obj2.isName()) {
+ writePSFmt("%%%%ImageInks: %s %d",
+ obj2.getName(), (obj1.arrayGetLength() - 1) / 2);
+ for (i = 1; i+1 < obj1.arrayGetLength(); i += 2) {
+ obj1.arrayGet(i, &obj3);
+ obj1.arrayGet(i+1, &obj4);
+ if (obj3.isString() && obj4.isNum()) {
+ writePS(" ");
+ writePSString(obj3.getString());
+ writePSFmt(" %g", obj4.getNum());
+ }
+ obj3.free();
+ obj4.free();
+ }
+ writePS("\n");
+ }
+ obj2.free();
+ }
+ obj1.free();
+
+ writePS("gsave\n");
+
+ writePS("%%BeginIncludedImage\n");
+
+ dict->lookup("IncludedImageDimensions", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 2) {
+ obj1.arrayGet(0, &obj2);
+ w = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ h = obj2.getInt();
+ obj2.free();
+ writePSFmt("%%%%IncludedImageDimensions: %d %d\n", w, h);
+ }
+ obj1.free();
+
+ dict->lookup("IncludedImageQuality", &obj1);
+ if (obj1.isNum()) {
+ writePSFmt("%%%%IncludedImageQuality: %g\n", obj1.getNum());
+ }
+ obj1.free();
+
+ ++opi20Nest;
+}
+
+void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
+ Object obj1, obj2;
+ int left, right, top, bottom, samples, bits, width, height;
+ double c, m, y, k;
+ double llx, lly, ulx, uly, urx, ury, lrx, lry;
+ double tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry;
+ double horiz, vert;
+ int i, j;
+
+ writePS("save\n");
+ writePS("/opiMatrix2 matrix currentmatrix def\n");
+ writePS("opiMatrix setmatrix\n");
+
+ dict->lookup("F", &obj1);
+ if (getFileSpec(&obj1, &obj2)) {
+ writePSFmt("%%ALDImageFileName: %s\n",
+ obj2.getString()->getCString());
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("CropRect", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 4) {
+ obj1.arrayGet(0, &obj2);
+ left = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ top = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ right = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ bottom = obj2.getInt();
+ obj2.free();
+ writePSFmt("%%ALDImageCropRect: %d %d %d %d\n", left, top, right, bottom);
+ }
+ obj1.free();
+
+ dict->lookup("Color", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 5) {
+ obj1.arrayGet(0, &obj2);
+ c = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ m = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ y = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ k = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(4, &obj2);
+ if (obj2.isString()) {
+ writePSFmt("%%ALDImageColor: %g %g %g %g ", c, m, y, k);
+ writePSString(obj2.getString());
+ writePS("\n");
+ }
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("ColorType", &obj1);
+ if (obj1.isName()) {
+ writePSFmt("%%ALDImageColorType: %s\n", obj1.getName());
+ }
+ obj1.free();
+
+ //~ ignores 'Comments' entry
+ //~ need to handle multiple lines
+
+ dict->lookup("CropFixed", &obj1);
+ if (obj1.isArray()) {
+ obj1.arrayGet(0, &obj2);
+ ulx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ uly = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ lrx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ lry = obj2.getNum();
+ obj2.free();
+ writePSFmt("%%ALDImageCropFixed: %g %g %g %g\n", ulx, uly, lrx, lry);
+ }
+ obj1.free();
+
+ dict->lookup("GrayMap", &obj1);
+ if (obj1.isArray()) {
+ writePS("%ALDImageGrayMap:");
+ for (i = 0; i < obj1.arrayGetLength(); i += 16) {
+ if (i > 0) {
+ writePS("\n%%+");
+ }
+ for (j = 0; j < 16 && i+j < obj1.arrayGetLength(); ++j) {
+ obj1.arrayGet(i+j, &obj2);
+ writePSFmt(" %d", obj2.getInt());
+ obj2.free();
+ }
+ }
+ writePS("\n");
+ }
+ obj1.free();
+
+ dict->lookup("ID", &obj1);
+ if (obj1.isString()) {
+ writePSFmt("%%ALDImageID: %s\n", obj1.getString()->getCString());
+ }
+ obj1.free();
+
+ dict->lookup("ImageType", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 2) {
+ obj1.arrayGet(0, &obj2);
+ samples = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ bits = obj2.getInt();
+ obj2.free();
+ writePSFmt("%%ALDImageType: %d %d\n", samples, bits);
+ }
+ obj1.free();
+
+ dict->lookup("Overprint", &obj1);
+ if (obj1.isBool()) {
+ writePSFmt("%%ALDImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
+ }
+ obj1.free();
+
+ dict->lookup("Position", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 8) {
+ obj1.arrayGet(0, &obj2);
+ llx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ lly = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ ulx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ uly = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(4, &obj2);
+ urx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(5, &obj2);
+ ury = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(6, &obj2);
+ lrx = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(7, &obj2);
+ lry = obj2.getNum();
+ obj2.free();
+ opiTransform(state, llx, lly, &tllx, &tlly);
+ opiTransform(state, ulx, uly, &tulx, &tuly);
+ opiTransform(state, urx, ury, &turx, &tury);
+ opiTransform(state, lrx, lry, &tlrx, &tlry);
+ writePSFmt("%%ALDImagePosition: %g %g %g %g %g %g %g %g\n",
+ tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry);
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("Resolution", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 2) {
+ obj1.arrayGet(0, &obj2);
+ horiz = obj2.getNum();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ vert = obj2.getNum();
+ obj2.free();
+ writePSFmt("%%ALDImageResoution: %g %g\n", horiz, vert);
+ obj2.free();
+ }
+ obj1.free();
+
+ dict->lookup("Size", &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 2) {
+ obj1.arrayGet(0, &obj2);
+ width = obj2.getInt();
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ height = obj2.getInt();
+ obj2.free();
+ writePSFmt("%%ALDImageDimensions: %d %d\n", width, height);
+ }
+ obj1.free();
+
+ //~ ignoring 'Tags' entry
+ //~ need to use writePSString() and deal with >255-char lines
+
+ dict->lookup("Tint", &obj1);
+ if (obj1.isNum()) {
+ writePSFmt("%%ALDImageTint: %g\n", obj1.getNum());
+ }
+ obj1.free();
+
+ dict->lookup("Transparency", &obj1);
+ if (obj1.isBool()) {
+ writePSFmt("%%ALDImageTransparency: %s\n", obj1.getBool() ? "true" : "false");
+ }
+ obj1.free();
+
+ writePS("%%BeginObject: image\n");
+ writePS("opiMatrix2 setmatrix\n");
+ ++opi13Nest;
+}
+
+// Convert PDF user space coordinates to PostScript default user space
+// coordinates. This has to account for both the PDF CTM and the
+// PSOutputDev page-fitting transform.
+void PSOutputDev::opiTransform(GfxState *state, double x0, double y0,
+ double *x1, double *y1) {
+ double t;
+
+ state->transform(x0, y0, x1, y1);
+ *x1 += tx;
+ *y1 += ty;
+ if (landscape) {
+ t = *x1;
+ *x1 = -*y1;
+ *y1 = t;
+ }
+ *x1 *= xScale;
+ *y1 *= yScale;
+}
+
+void PSOutputDev::opiEnd(GfxState *state, Dict *opiDict) {
+ Object dict;
+
+ if (globalParams->getPSOPI()) {
+ opiDict->lookup("2.0", &dict);
+ if (dict.isDict()) {
+ writePS("%%EndIncludedImage\n");
+ writePS("%%EndOPI\n");
+ writePS("grestore\n");
+ --opi20Nest;
+ dict.free();
+ } else {
+ dict.free();
+ opiDict->lookup("1.3", &dict);
+ if (dict.isDict()) {
+ writePS("%%EndObject\n");
+ writePS("restore\n");
+ --opi13Nest;
+ }
+ dict.free();
+ }
+ }
+}
+
+GBool PSOutputDev::getFileSpec(Object *fileSpec, Object *fileName) {
+ if (fileSpec->isString()) {
+ fileSpec->copy(fileName);
+ return gTrue;
+ }
+ if (fileSpec->isDict()) {
+ fileSpec->dictLookup("DOS", fileName);
+ if (fileName->isString()) {
+ return gTrue;
+ }
+ fileName->free();
+ fileSpec->dictLookup("Mac", fileName);
+ if (fileName->isString()) {
+ return gTrue;
+ }
+ fileName->free();
+ fileSpec->dictLookup("Unix", fileName);
+ if (fileName->isString()) {
+ return gTrue;
+ }
+ fileName->free();
+ fileSpec->dictLookup("F", fileName);
+ if (fileName->isString()) {
+ return gTrue;
+ }
+ fileName->free();
+ }
+ return gFalse;
+}
+#endif // OPI_SUPPORT
+
+void PSOutputDev::type3D0(GfxState *state, double wx, double wy) {
+ writePSFmt("%g %g setcharwidth\n", wx, wy);
+ writePS("q\n");
+}
+
+void PSOutputDev::type3D1(GfxState *state, double wx, double wy,
+ double llx, double lly, double urx, double ury) {
+ t3WX = wx;
+ t3WY = wy;
+ t3LLX = llx;
+ t3LLY = lly;
+ t3URX = urx;
+ t3URY = ury;
+ t3String = new GString();
+ writePS("q\n");
+ t3Cacheable = gTrue;
+}
+
+void PSOutputDev::psXObject(Stream *psStream, Stream *level1Stream) {
+ Stream *str;
+ int c;
+
+ if ((level == psLevel1 || level == psLevel1Sep) && level1Stream) {
+ str = level1Stream;
+ } else {
+ str = psStream;
+ }
+ str->reset();
+ while ((c = str->getChar()) != EOF) {
+ writePSChar(c);
+ }
+ str->close();
+}
+
+void PSOutputDev::writePSChar(char c) {
+ if (t3String) {
+ t3String->append(c);
+ } else {
+ (*outputFunc)(outputStream, &c, 1);
+ }
+}
+
+void PSOutputDev::writePS(char *s) {
+ if (t3String) {
+ t3String->append(s);
+ } else {
+ (*outputFunc)(outputStream, s, strlen(s));
+ }
+}
+
+void PSOutputDev::writePSFmt(const char *fmt, ...) {
+ va_list args;
+ char buf[512];
+
+ va_start(args, fmt);
+ vsprintf(buf, fmt, args);
+ va_end(args);
+ if (t3String) {
+ t3String->append(buf);
+ } else {
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+}
+
+void PSOutputDev::writePSString(GString *s) {
+ Guchar *p;
+ int n;
+ char buf[8];
+
+ writePSChar('(');
+ for (p = (Guchar *)s->getCString(), n = s->getLength(); n; ++p, --n) {
+ if (*p == '(' || *p == ')' || *p == '\\') {
+ writePSChar('\\');
+ writePSChar((char)*p);
+ } else if (*p < 0x20 || *p >= 0x80) {
+ sprintf(buf, "\\%03o", *p);
+ if (t3String) {
+ t3String->append(buf);
+ } else {
+ (*outputFunc)(outputStream, buf, strlen(buf));
+ }
+ } else {
+ writePSChar((char)*p);
+ }
+ }
+ writePSChar(')');
+}
+
+void PSOutputDev::writePSName(char *s) {
+ char *p;
+ char c;
+
+ p = s;
+ while ((c = *p++)) {
+ if (c <= (char)0x20 || c >= (char)0x7f ||
+ c == '(' || c == ')' || c == '<' || c == '>' ||
+ c == '[' || c == ']' || c == '{' || c == '}' ||
+ c == '/' || c == '%') {
+ writePSFmt("#%02x", c & 0xff);
+ } else {
+ writePSChar(c);
+ }
+ }
+}
+
+GString *PSOutputDev::filterPSName(GString *name) {
+ GString *name2;
+ char buf[8];
+ int i;
+ char c;
+
+ name2 = new GString();
+ for (i = 0; i < name->getLength(); ++i) {
+ c = name->getChar(i);
+ if (c <= (char)0x20 || c >= (char)0x7f ||
+ c == '(' || c == ')' || c == '<' || c == '>' ||
+ c == '[' || c == ']' || c == '{' || c == '}' ||
+ c == '/' || c == '%') {
+ sprintf(buf, "#%02x", c & 0xff);
+ name2->append(buf);
+ } else {
+ name2->append(c);
+ }
+ }
+ return name2;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cc b/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cc
deleted file mode 100644
index 570a7bac7..000000000
--- a/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cc
+++ /dev/null
@@ -1,135 +0,0 @@
-//========================================================================
-//
-// PSTokenizer.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "PSTokenizer.h"
-
-//------------------------------------------------------------------------
-
-// A '1' in this array means the character is white space. A '1' or
-// '2' means the character ends a name or command.
-static char specialChars[256] = {
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
- 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
-};
-
-//------------------------------------------------------------------------
-
-PSTokenizer::PSTokenizer(int (*getCharFuncA)(void *), void *dataA) {
- getCharFunc = getCharFuncA;
- data = dataA;
- charBuf = -1;
-}
-
-PSTokenizer::~PSTokenizer() {
-}
-
-GBool PSTokenizer::getToken(char *buf, int size, int *length) {
- GBool comment, backslash;
- int c;
- int i;
-
- // skip whitespace and comments
- comment = gFalse;
- while (1) {
- if ((c = getChar()) == EOF) {
- buf[0] = '\0';
- *length = 0;
- return gFalse;
- }
- if (comment) {
- if (c == '\x0a' || c == '\x0d') {
- comment = gFalse;
- }
- } else if (c == '%') {
- comment = gTrue;
- } else if (specialChars[c] != 1) {
- break;
- }
- }
-
- // read a token
- i = 0;
- buf[i++] = c;
- if (c == '(') {
- backslash = gFalse;
- while ((c = lookChar()) != EOF) {
- if (i < size - 1) {
- buf[i++] = c;
- }
- getChar();
- if (c == '\\') {
- backslash = gTrue;
- } else if (!backslash && c == ')') {
- break;
- } else {
- backslash = gFalse;
- }
- }
- } else if (c == '<') {
- while ((c = lookChar()) != EOF) {
- getChar();
- if (i < size - 1) {
- buf[i++] = c;
- }
- if (c == '>') {
- break;
- }
- }
- } else if (c != '[' && c != ']') {
- while ((c = lookChar()) != EOF && !specialChars[c]) {
- getChar();
- if (i < size - 1) {
- buf[i++] = c;
- }
- }
- }
- buf[i] = '\0';
- *length = i;
-
- return gTrue;
-}
-
-int PSTokenizer::lookChar() {
- if (charBuf < 0) {
- charBuf = (*getCharFunc)(data);
- }
- return charBuf;
-}
-
-int PSTokenizer::getChar() {
- int c;
-
- if (charBuf < 0) {
- charBuf = (*getCharFunc)(data);
- }
- c = charBuf;
- charBuf = -1;
- return c;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cpp b/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cpp
new file mode 100644
index 000000000..73b04323e
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/PSTokenizer.cpp
@@ -0,0 +1,135 @@
+//========================================================================
+//
+// PSTokenizer.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "PSTokenizer.h"
+
+//------------------------------------------------------------------------
+
+// A '1' in this array means the character is white space. A '1' or
+// '2' means the character ends a name or command.
+static char specialChars[256] = {
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
+ 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
+};
+
+//------------------------------------------------------------------------
+
+PSTokenizer::PSTokenizer(int (*getCharFuncA)(void *), void *dataA) {
+ getCharFunc = getCharFuncA;
+ data = dataA;
+ charBuf = -1;
+}
+
+PSTokenizer::~PSTokenizer() {
+}
+
+GBool PSTokenizer::getToken(char *buf, int size, int *length) {
+ GBool comment, backslash;
+ int c;
+ int i;
+
+ // skip whitespace and comments
+ comment = gFalse;
+ while (1) {
+ if ((c = getChar()) == EOF) {
+ buf[0] = '\0';
+ *length = 0;
+ return gFalse;
+ }
+ if (comment) {
+ if (c == '\x0a' || c == '\x0d') {
+ comment = gFalse;
+ }
+ } else if (c == '%') {
+ comment = gTrue;
+ } else if (specialChars[c] != 1) {
+ break;
+ }
+ }
+
+ // read a token
+ i = 0;
+ buf[i++] = c;
+ if (c == '(') {
+ backslash = gFalse;
+ while ((c = lookChar()) != EOF) {
+ if (i < size - 1) {
+ buf[i++] = c;
+ }
+ getChar();
+ if (c == '\\') {
+ backslash = gTrue;
+ } else if (!backslash && c == ')') {
+ break;
+ } else {
+ backslash = gFalse;
+ }
+ }
+ } else if (c == '<') {
+ while ((c = lookChar()) != EOF) {
+ getChar();
+ if (i < size - 1) {
+ buf[i++] = c;
+ }
+ if (c == '>') {
+ break;
+ }
+ }
+ } else if (c != '[' && c != ']') {
+ while ((c = lookChar()) != EOF && !specialChars[c]) {
+ getChar();
+ if (i < size - 1) {
+ buf[i++] = c;
+ }
+ }
+ }
+ buf[i] = '\0';
+ *length = i;
+
+ return gTrue;
+}
+
+int PSTokenizer::lookChar() {
+ if (charBuf < 0) {
+ charBuf = (*getCharFunc)(data);
+ }
+ return charBuf;
+}
+
+int PSTokenizer::getChar() {
+ int c;
+
+ if (charBuf < 0) {
+ charBuf = (*getCharFunc)(data);
+ }
+ c = charBuf;
+ charBuf = -1;
+ return c;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Page.cc b/filters/kword/pdf/xpdf/xpdf/Page.cc
deleted file mode 100644
index 891ed82ee..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Page.cc
+++ /dev/null
@@ -1,341 +0,0 @@
-//========================================================================
-//
-// Page.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Link.h"
-#include "OutputDev.h"
-#ifndef PDF_PARSER_ONLY
-#include "Gfx.h"
-#include "Annot.h"
-#endif
-#include "Error.h"
-#include "Page.h"
-
-//------------------------------------------------------------------------
-// PageAttrs
-//------------------------------------------------------------------------
-
-PageAttrs::PageAttrs(PageAttrs *attrs, Dict *dict) {
- Object obj1;
- double w, h;
-
- // get old/default values
- if (attrs) {
- mediaBox = attrs->mediaBox;
- cropBox = attrs->cropBox;
- haveCropBox = attrs->haveCropBox;
- rotate = attrs->rotate;
- attrs->resources.copy(&resources);
- } else {
- // set default MediaBox to 8.5" x 11" -- this shouldn't be necessary
- // but some (non-compliant) PDF files don't specify a MediaBox
- mediaBox.x1 = 0;
- mediaBox.y1 = 0;
- mediaBox.x2 = 612;
- mediaBox.y2 = 792;
- cropBox.x1 = cropBox.y1 = cropBox.x2 = cropBox.y2 = 0;
- haveCropBox = gFalse;
- rotate = 0;
- resources.initNull();
- }
-
- // media box
- readBox(dict, "MediaBox", &mediaBox);
-
- // crop box
- cropBox = mediaBox;
- haveCropBox = readBox(dict, "CropBox", &cropBox);
-
- // if the MediaBox is excessively larger than the CropBox,
- // just use the CropBox
- limitToCropBox = gFalse;
- if (haveCropBox) {
- w = 0.25 * (cropBox.x2 - cropBox.x1);
- h = 0.25 * (cropBox.y2 - cropBox.y1);
- if ((cropBox.x1 - mediaBox.x1) + (mediaBox.x2 - cropBox.x2) > w ||
- (cropBox.y1 - mediaBox.y1) + (mediaBox.y2 - cropBox.y2) > h) {
- limitToCropBox = gTrue;
- }
- }
-
- // other boxes
- bleedBox = cropBox;
- readBox(dict, "BleedBox", &bleedBox);
- trimBox = cropBox;
- readBox(dict, "TrimBox", &trimBox);
- artBox = cropBox;
- readBox(dict, "ArtBox", &artBox);
-
- // rotate
- dict->lookup("Rotate", &obj1);
- if (obj1.isInt()) {
- rotate = obj1.getInt();
- }
- obj1.free();
- while (rotate < 0) {
- rotate += 360;
- }
- while (rotate >= 360) {
- rotate -= 360;
- }
-
- // misc attributes
- dict->lookup("LastModified", &lastModified);
- dict->lookup("BoxColorInfo", &boxColorInfo);
- dict->lookup("Group", &group);
- dict->lookup("Metadata", &metadata);
- dict->lookup("PieceInfo", &pieceInfo);
- dict->lookup("SeparationInfo", &separationInfo);
-
- // resource dictionary
- dict->lookup("Resources", &obj1);
- if (obj1.isDict()) {
- resources.free();
- obj1.copy(&resources);
- }
- obj1.free();
-}
-
-PageAttrs::~PageAttrs() {
- lastModified.free();
- boxColorInfo.free();
- group.free();
- metadata.free();
- pieceInfo.free();
- separationInfo.free();
- resources.free();
-}
-
-GBool PageAttrs::readBox(Dict *dict, const char *key, PDFRectangle *box) {
- PDFRectangle tmp;
- Object obj1, obj2;
- GBool ok;
-
- dict->lookup(key, &obj1);
- if (obj1.isArray() && obj1.arrayGetLength() == 4) {
- ok = gTrue;
- obj1.arrayGet(0, &obj2);
- if (obj2.isNum()) {
- tmp.x1 = obj2.getNum();
- } else {
- ok = gFalse;
- }
- obj2.free();
- obj1.arrayGet(1, &obj2);
- if (obj2.isNum()) {
- tmp.y1 = obj2.getNum();
- } else {
- ok = gFalse;
- }
- obj2.free();
- obj1.arrayGet(2, &obj2);
- if (obj2.isNum()) {
- tmp.x2 = obj2.getNum();
- } else {
- ok = gFalse;
- }
- obj2.free();
- obj1.arrayGet(3, &obj2);
- if (obj2.isNum()) {
- tmp.y2 = obj2.getNum();
- } else {
- ok = gFalse;
- }
- obj2.free();
- if (ok) {
- *box = tmp;
- }
- } else {
- ok = gFalse;
- }
- obj1.free();
- return ok;
-}
-
-//------------------------------------------------------------------------
-// Page
-//------------------------------------------------------------------------
-
-Page::Page(XRef *xrefA, int numA, Dict *pageDict, PageAttrs *attrsA) {
- ok = gTrue;
- xref = xrefA;
- num = numA;
-
- // get attributes
- attrs = attrsA;
-
- // annotations
- pageDict->lookupNF("Annots", &annots);
- if (!(annots.isRef() || annots.isArray() || annots.isNull())) {
- error(-1, "Page annotations object (page %d) is wrong type (%s)",
- num, annots.getTypeName());
- annots.free();
- goto err2;
- }
-
- // contents
- pageDict->lookupNF("Contents", &contents);
- if (!(contents.isRef() || contents.isArray() ||
- contents.isNull())) {
- error(-1, "Page contents object (page %d) is wrong type (%s)",
- num, contents.getTypeName());
- contents.free();
- goto err1;
- }
-
- return;
-
- err2:
- annots.initNull();
- err1:
- contents.initNull();
- ok = gFalse;
-}
-
-Page::~Page() {
- delete attrs;
- annots.free();
- contents.free();
-}
-
-void Page::display(OutputDev *out, double dpi, int rotate,
- Links *links, Catalog *catalog,
- GBool (*abortCheckCbk)(void *data),
- void *abortCheckCbkData) {
- displaySlice(out, dpi, rotate, -1, -1, -1, -1, links, catalog,
- abortCheckCbk, abortCheckCbkData);
-}
-
-void Page::displaySlice(OutputDev *out, double dpi, int rotate,
- int sliceX, int sliceY, int sliceW, int sliceH,
- Links *links, Catalog *catalog,
- GBool (*abortCheckCbk)(void *data),
- void *abortCheckCbkData) {
-#ifndef PDF_PARSER_ONLY
- PDFRectangle *mediaBox, *cropBox;
- PDFRectangle box;
- Gfx *gfx;
- Object obj;
- Link *link;
- Annots *annotList;
- double k;
- int i;
-
- rotate += getRotate();
- if (rotate >= 360) {
- rotate -= 360;
- } else if (rotate < 0) {
- rotate += 360;
- }
-
- mediaBox = getBox();
- if (sliceW >= 0 && sliceH >= 0) {
- k = 72.0 / dpi;
- if (rotate == 90) {
- if (out->upsideDown()) {
- box.x1 = mediaBox->x1 + k * sliceY;
- box.x2 = mediaBox->x1 + k * (sliceY + sliceH);
- } else {
- box.x1 = mediaBox->x2 - k * (sliceY + sliceH);
- box.x2 = mediaBox->x2 - k * sliceY;
- }
- box.y1 = mediaBox->y1 + k * sliceX;
- box.y2 = mediaBox->y1 + k * (sliceX + sliceW);
- } else if (rotate == 180) {
- box.x1 = mediaBox->x2 - k * (sliceX + sliceW);
- box.x2 = mediaBox->x2 - k * sliceX;
- if (out->upsideDown()) {
- box.y1 = mediaBox->y1 + k * sliceY;
- box.y2 = mediaBox->y1 + k * (sliceY + sliceH);
- } else {
- box.y1 = mediaBox->y2 - k * (sliceY + sliceH);
- box.y2 = mediaBox->y2 - k * sliceY;
- }
- } else if (rotate == 270) {
- if (out->upsideDown()) {
- box.x1 = mediaBox->x2 - k * (sliceY + sliceH);
- box.x2 = mediaBox->x2 - k * sliceY;
- } else {
- box.x1 = mediaBox->x1 + k * sliceY;
- box.x2 = mediaBox->x1 + k * (sliceY + sliceH);
- }
- box.y1 = mediaBox->y2 - k * (sliceX + sliceW);
- box.y2 = mediaBox->y2 - k * sliceX;
- } else {
- box.x1 = mediaBox->x1 + k * sliceX;
- box.x2 = mediaBox->x1 + k * (sliceX + sliceW);
- if (out->upsideDown()) {
- box.y1 = mediaBox->y2 - k * (sliceY + sliceH);
- box.y2 = mediaBox->y2 - k * sliceY;
- } else {
- box.y1 = mediaBox->y1 + k * sliceY;
- box.y2 = mediaBox->y1 + k * (sliceY + sliceH);
- }
- }
- } else {
- box = *mediaBox;
- }
- cropBox = getCropBox();
-
- if (globalParams->getPrintCommands()) {
- printf("***** MediaBox = ll:%g,%g ur:%g,%g\n",
- box.x1, box.y1, box.x2, box.y2);
- if (isCropped()) {
- printf("***** CropBox = ll:%g,%g ur:%g,%g\n",
- cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2);
- }
- printf("***** Rotate = %d\n", attrs->getRotate());
- }
-
- gfx = new Gfx(xref, out, num, attrs->getResourceDict(),
- dpi, &box, isCropped(), cropBox, rotate,
- abortCheckCbk, abortCheckCbkData);
- contents.fetch(xref, &obj);
- if (!obj.isNull()) {
- gfx->display(&obj);
- }
- obj.free();
-
- // draw links
- if (links) {
- for (i = 0; i < links->getNumLinks(); ++i) {
- link = links->getLink(i);
- out->drawLink(link, catalog);
- }
- out->dump();
- }
-
- // draw non-link annotations
- //~ need to reset CTM ???
- annotList = new Annots(xref, annots.fetch(xref, &obj));
- obj.free();
- if (annotList->getNumAnnots() > 0) {
- if (globalParams->getPrintCommands()) {
- printf("***** Annotations\n");
- }
- for (i = 0; i < annotList->getNumAnnots(); ++i) {
- annotList->getAnnot(i)->draw(gfx);
- }
- out->dump();
- }
- delete annotList;
-
- delete gfx;
-#endif
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Page.cpp b/filters/kword/pdf/xpdf/xpdf/Page.cpp
new file mode 100644
index 000000000..96cb4613d
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Page.cpp
@@ -0,0 +1,341 @@
+//========================================================================
+//
+// Page.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Link.h"
+#include "OutputDev.h"
+#ifndef PDF_PARSER_ONLY
+#include "Gfx.h"
+#include "Annot.h"
+#endif
+#include "Error.h"
+#include "Page.h"
+
+//------------------------------------------------------------------------
+// PageAttrs
+//------------------------------------------------------------------------
+
+PageAttrs::PageAttrs(PageAttrs *attrs, Dict *dict) {
+ Object obj1;
+ double w, h;
+
+ // get old/default values
+ if (attrs) {
+ mediaBox = attrs->mediaBox;
+ cropBox = attrs->cropBox;
+ haveCropBox = attrs->haveCropBox;
+ rotate = attrs->rotate;
+ attrs->resources.copy(&resources);
+ } else {
+ // set default MediaBox to 8.5" x 11" -- this shouldn't be necessary
+ // but some (non-compliant) PDF files don't specify a MediaBox
+ mediaBox.x1 = 0;
+ mediaBox.y1 = 0;
+ mediaBox.x2 = 612;
+ mediaBox.y2 = 792;
+ cropBox.x1 = cropBox.y1 = cropBox.x2 = cropBox.y2 = 0;
+ haveCropBox = gFalse;
+ rotate = 0;
+ resources.initNull();
+ }
+
+ // media box
+ readBox(dict, "MediaBox", &mediaBox);
+
+ // crop box
+ cropBox = mediaBox;
+ haveCropBox = readBox(dict, "CropBox", &cropBox);
+
+ // if the MediaBox is excessively larger than the CropBox,
+ // just use the CropBox
+ limitToCropBox = gFalse;
+ if (haveCropBox) {
+ w = 0.25 * (cropBox.x2 - cropBox.x1);
+ h = 0.25 * (cropBox.y2 - cropBox.y1);
+ if ((cropBox.x1 - mediaBox.x1) + (mediaBox.x2 - cropBox.x2) > w ||
+ (cropBox.y1 - mediaBox.y1) + (mediaBox.y2 - cropBox.y2) > h) {
+ limitToCropBox = gTrue;
+ }
+ }
+
+ // other boxes
+ bleedBox = cropBox;
+ readBox(dict, "BleedBox", &bleedBox);
+ trimBox = cropBox;
+ readBox(dict, "TrimBox", &trimBox);
+ artBox = cropBox;
+ readBox(dict, "ArtBox", &artBox);
+
+ // rotate
+ dict->lookup("Rotate", &obj1);
+ if (obj1.isInt()) {
+ rotate = obj1.getInt();
+ }
+ obj1.free();
+ while (rotate < 0) {
+ rotate += 360;
+ }
+ while (rotate >= 360) {
+ rotate -= 360;
+ }
+
+ // misc attributes
+ dict->lookup("LastModified", &lastModified);
+ dict->lookup("BoxColorInfo", &boxColorInfo);
+ dict->lookup("Group", &group);
+ dict->lookup("Metadata", &metadata);
+ dict->lookup("PieceInfo", &pieceInfo);
+ dict->lookup("SeparationInfo", &separationInfo);
+
+ // resource dictionary
+ dict->lookup("Resources", &obj1);
+ if (obj1.isDict()) {
+ resources.free();
+ obj1.copy(&resources);
+ }
+ obj1.free();
+}
+
+PageAttrs::~PageAttrs() {
+ lastModified.free();
+ boxColorInfo.free();
+ group.free();
+ metadata.free();
+ pieceInfo.free();
+ separationInfo.free();
+ resources.free();
+}
+
+GBool PageAttrs::readBox(Dict *dict, const char *key, PDFRectangle *box) {
+ PDFRectangle tmp;
+ Object obj1, obj2;
+ GBool ok;
+
+ dict->lookup(key, &obj1);
+ if (obj1.isArray() && obj1.arrayGetLength() == 4) {
+ ok = gTrue;
+ obj1.arrayGet(0, &obj2);
+ if (obj2.isNum()) {
+ tmp.x1 = obj2.getNum();
+ } else {
+ ok = gFalse;
+ }
+ obj2.free();
+ obj1.arrayGet(1, &obj2);
+ if (obj2.isNum()) {
+ tmp.y1 = obj2.getNum();
+ } else {
+ ok = gFalse;
+ }
+ obj2.free();
+ obj1.arrayGet(2, &obj2);
+ if (obj2.isNum()) {
+ tmp.x2 = obj2.getNum();
+ } else {
+ ok = gFalse;
+ }
+ obj2.free();
+ obj1.arrayGet(3, &obj2);
+ if (obj2.isNum()) {
+ tmp.y2 = obj2.getNum();
+ } else {
+ ok = gFalse;
+ }
+ obj2.free();
+ if (ok) {
+ *box = tmp;
+ }
+ } else {
+ ok = gFalse;
+ }
+ obj1.free();
+ return ok;
+}
+
+//------------------------------------------------------------------------
+// Page
+//------------------------------------------------------------------------
+
+Page::Page(XRef *xrefA, int numA, Dict *pageDict, PageAttrs *attrsA) {
+ ok = gTrue;
+ xref = xrefA;
+ num = numA;
+
+ // get attributes
+ attrs = attrsA;
+
+ // annotations
+ pageDict->lookupNF("Annots", &annots);
+ if (!(annots.isRef() || annots.isArray() || annots.isNull())) {
+ error(-1, "Page annotations object (page %d) is wrong type (%s)",
+ num, annots.getTypeName());
+ annots.free();
+ goto err2;
+ }
+
+ // contents
+ pageDict->lookupNF("Contents", &contents);
+ if (!(contents.isRef() || contents.isArray() ||
+ contents.isNull())) {
+ error(-1, "Page contents object (page %d) is wrong type (%s)",
+ num, contents.getTypeName());
+ contents.free();
+ goto err1;
+ }
+
+ return;
+
+ err2:
+ annots.initNull();
+ err1:
+ contents.initNull();
+ ok = gFalse;
+}
+
+Page::~Page() {
+ delete attrs;
+ annots.free();
+ contents.free();
+}
+
+void Page::display(OutputDev *out, double dpi, int rotate,
+ Links *links, Catalog *catalog,
+ GBool (*abortCheckCbk)(void *data),
+ void *abortCheckCbkData) {
+ displaySlice(out, dpi, rotate, -1, -1, -1, -1, links, catalog,
+ abortCheckCbk, abortCheckCbkData);
+}
+
+void Page::displaySlice(OutputDev *out, double dpi, int rotate,
+ int sliceX, int sliceY, int sliceW, int sliceH,
+ Links *links, Catalog *catalog,
+ GBool (*abortCheckCbk)(void *data),
+ void *abortCheckCbkData) {
+#ifndef PDF_PARSER_ONLY
+ PDFRectangle *mediaBox, *cropBox;
+ PDFRectangle box;
+ Gfx *gfx;
+ Object obj;
+ Link *link;
+ Annots *annotList;
+ double k;
+ int i;
+
+ rotate += getRotate();
+ if (rotate >= 360) {
+ rotate -= 360;
+ } else if (rotate < 0) {
+ rotate += 360;
+ }
+
+ mediaBox = getBox();
+ if (sliceW >= 0 && sliceH >= 0) {
+ k = 72.0 / dpi;
+ if (rotate == 90) {
+ if (out->upsideDown()) {
+ box.x1 = mediaBox->x1 + k * sliceY;
+ box.x2 = mediaBox->x1 + k * (sliceY + sliceH);
+ } else {
+ box.x1 = mediaBox->x2 - k * (sliceY + sliceH);
+ box.x2 = mediaBox->x2 - k * sliceY;
+ }
+ box.y1 = mediaBox->y1 + k * sliceX;
+ box.y2 = mediaBox->y1 + k * (sliceX + sliceW);
+ } else if (rotate == 180) {
+ box.x1 = mediaBox->x2 - k * (sliceX + sliceW);
+ box.x2 = mediaBox->x2 - k * sliceX;
+ if (out->upsideDown()) {
+ box.y1 = mediaBox->y1 + k * sliceY;
+ box.y2 = mediaBox->y1 + k * (sliceY + sliceH);
+ } else {
+ box.y1 = mediaBox->y2 - k * (sliceY + sliceH);
+ box.y2 = mediaBox->y2 - k * sliceY;
+ }
+ } else if (rotate == 270) {
+ if (out->upsideDown()) {
+ box.x1 = mediaBox->x2 - k * (sliceY + sliceH);
+ box.x2 = mediaBox->x2 - k * sliceY;
+ } else {
+ box.x1 = mediaBox->x1 + k * sliceY;
+ box.x2 = mediaBox->x1 + k * (sliceY + sliceH);
+ }
+ box.y1 = mediaBox->y2 - k * (sliceX + sliceW);
+ box.y2 = mediaBox->y2 - k * sliceX;
+ } else {
+ box.x1 = mediaBox->x1 + k * sliceX;
+ box.x2 = mediaBox->x1 + k * (sliceX + sliceW);
+ if (out->upsideDown()) {
+ box.y1 = mediaBox->y2 - k * (sliceY + sliceH);
+ box.y2 = mediaBox->y2 - k * sliceY;
+ } else {
+ box.y1 = mediaBox->y1 + k * sliceY;
+ box.y2 = mediaBox->y1 + k * (sliceY + sliceH);
+ }
+ }
+ } else {
+ box = *mediaBox;
+ }
+ cropBox = getCropBox();
+
+ if (globalParams->getPrintCommands()) {
+ printf("***** MediaBox = ll:%g,%g ur:%g,%g\n",
+ box.x1, box.y1, box.x2, box.y2);
+ if (isCropped()) {
+ printf("***** CropBox = ll:%g,%g ur:%g,%g\n",
+ cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2);
+ }
+ printf("***** Rotate = %d\n", attrs->getRotate());
+ }
+
+ gfx = new Gfx(xref, out, num, attrs->getResourceDict(),
+ dpi, &box, isCropped(), cropBox, rotate,
+ abortCheckCbk, abortCheckCbkData);
+ contents.fetch(xref, &obj);
+ if (!obj.isNull()) {
+ gfx->display(&obj);
+ }
+ obj.free();
+
+ // draw links
+ if (links) {
+ for (i = 0; i < links->getNumLinks(); ++i) {
+ link = links->getLink(i);
+ out->drawLink(link, catalog);
+ }
+ out->dump();
+ }
+
+ // draw non-link annotations
+ //~ need to reset CTM ???
+ annotList = new Annots(xref, annots.fetch(xref, &obj));
+ obj.free();
+ if (annotList->getNumAnnots() > 0) {
+ if (globalParams->getPrintCommands()) {
+ printf("***** Annotations\n");
+ }
+ for (i = 0; i < annotList->getNumAnnots(); ++i) {
+ annotList->getAnnot(i)->draw(gfx);
+ }
+ out->dump();
+ }
+ delete annotList;
+
+ delete gfx;
+#endif
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Parser.cc b/filters/kword/pdf/xpdf/xpdf/Parser.cc
deleted file mode 100644
index 4bcb0ceb8..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Parser.cc
+++ /dev/null
@@ -1,223 +0,0 @@
-//========================================================================
-//
-// Parser.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stddef.h>
-#include "Object.h"
-#include "Array.h"
-#include "Dict.h"
-#include "Parser.h"
-#include "XRef.h"
-#include "Error.h"
-#ifndef NO_DECRYPTION
-#include "Decrypt.h"
-#endif
-
-Parser::Parser(XRef *xrefA, Lexer *lexerA) {
- xref = xrefA;
- lexer = lexerA;
- inlineImg = 0;
- lexer->getObj(&buf1);
- lexer->getObj(&buf2);
-}
-
-Parser::~Parser() {
- buf1.free();
- buf2.free();
- delete lexer;
-}
-
-#ifndef NO_DECRYPTION
-Object *Parser::getObj(Object *obj,
- Guchar *fileKey, int keyLength,
- int objNum, int objGen) {
-#else
-Object *Parser::getObj(Object *obj) {
-#endif
- char *key;
- Stream *str;
- Object obj2;
- int num;
-#ifndef NO_DECRYPTION
- Decrypt *decrypt;
- GString *s;
- char *p;
- int i;
-#endif
-
- // refill buffer after inline image data
- if (inlineImg == 2) {
- buf1.free();
- buf2.free();
- lexer->getObj(&buf1);
- lexer->getObj(&buf2);
- inlineImg = 0;
- }
-
- // array
- if (buf1.isCmd("[")) {
- shift();
- obj->initArray(xref);
- while (!buf1.isCmd("]") && !buf1.isEOF())
-#ifndef NO_DECRYPTION
- obj->arrayAdd(getObj(&obj2, fileKey, keyLength, objNum, objGen));
-#else
- obj->arrayAdd(getObj(&obj2));
-#endif
- if (buf1.isEOF())
- error(getPos(), "End of file inside array");
- shift();
-
- // dictionary or stream
- } else if (buf1.isCmd("<<")) {
- shift();
- obj->initDict(xref);
- while (!buf1.isCmd(">>") && !buf1.isEOF()) {
- if (!buf1.isName()) {
- error(getPos(), "Dictionary key must be a name object");
- shift();
- } else {
- key = copyString(buf1.getName());
- shift();
- if (buf1.isEOF() || buf1.isError()) {
- gfree(key);
- break;
- }
-#ifndef NO_DECRYPTION
- obj->dictAdd(key, getObj(&obj2, fileKey, keyLength, objNum, objGen));
-#else
- obj->dictAdd(key, getObj(&obj2));
-#endif
- }
- }
- if (buf1.isEOF())
- error(getPos(), "End of file inside dictionary");
- if (buf2.isCmd("stream")) {
- if ((str = makeStream(obj))) {
- obj->initStream(str);
-#ifndef NO_DECRYPTION
- if (fileKey) {
- str->getBaseStream()->doDecryption(fileKey, keyLength,
- objNum, objGen);
- }
-#endif
- } else {
- obj->free();
- obj->initError();
- }
- } else {
- shift();
- }
-
- // indirect reference or integer
- } else if (buf1.isInt()) {
- num = buf1.getInt();
- shift();
- if (buf1.isInt() && buf2.isCmd("R")) {
- obj->initRef(num, buf1.getInt());
- shift();
- shift();
- } else {
- obj->initInt(num);
- }
-
-#ifndef NO_DECRYPTION
- // string
- } else if (buf1.isString() && fileKey) {
- buf1.copy(obj);
- s = obj->getString();
- decrypt = new Decrypt(fileKey, keyLength, objNum, objGen);
- for (i = 0, p = obj->getString()->getCString();
- i < s->getLength();
- ++i, ++p) {
- *p = decrypt->decryptByte(*p);
- }
- delete decrypt;
- shift();
-#endif
-
- // simple object
- } else {
- buf1.copy(obj);
- shift();
- }
-
- return obj;
-}
-
-Stream *Parser::makeStream(Object *dict) {
- Object obj;
- Stream *str;
- Guint pos, endPos, length;
-
- // get stream start position
- lexer->skipToNextLine();
- pos = lexer->getPos();
-
- // get length
- dict->dictLookup("Length", &obj);
- if (obj.isInt()) {
- length = (Guint)obj.getInt();
- obj.free();
- } else {
- error(getPos(), "Bad 'Length' attribute in stream");
- obj.free();
- return NULL;
- }
-
- // check for length in damaged file
- if (xref->getStreamEnd(pos, &endPos)) {
- length = endPos - pos;
- }
-
- // make base stream
- str = lexer->getStream()->getBaseStream()->makeSubStream(pos, gTrue,
- length, dict);
-
- // get filters
- str = str->addFilters(dict);
-
- // skip over stream data
- lexer->setPos(pos + length);
-
- // refill token buffers and check for 'endstream'
- shift(); // kill '>>'
- shift(); // kill 'stream'
- if (buf1.isCmd("endstream"))
- shift();
- else
- error(getPos(), "Missing 'endstream'");
-
- return str;
-}
-
-void Parser::shift() {
- if (inlineImg > 0) {
- if (inlineImg < 2) {
- ++inlineImg;
- } else {
- // in a damaged content stream, if 'ID' shows up in the middle
- // of a dictionary, we need to reset
- inlineImg = 0;
- }
- } else if (buf2.isCmd("ID")) {
- lexer->skipChar(); // skip char after 'ID' command
- inlineImg = 1;
- }
- buf1.free();
- buf1 = buf2;
- if (inlineImg > 0) // don't buffer inline image data
- buf2.initNull();
- else
- lexer->getObj(&buf2);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Parser.cpp b/filters/kword/pdf/xpdf/xpdf/Parser.cpp
new file mode 100644
index 000000000..3fb58d6b2
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Parser.cpp
@@ -0,0 +1,223 @@
+//========================================================================
+//
+// Parser.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stddef.h>
+#include "Object.h"
+#include "Array.h"
+#include "Dict.h"
+#include "Parser.h"
+#include "XRef.h"
+#include "Error.h"
+#ifndef NO_DECRYPTION
+#include "Decrypt.h"
+#endif
+
+Parser::Parser(XRef *xrefA, Lexer *lexerA) {
+ xref = xrefA;
+ lexer = lexerA;
+ inlineImg = 0;
+ lexer->getObj(&buf1);
+ lexer->getObj(&buf2);
+}
+
+Parser::~Parser() {
+ buf1.free();
+ buf2.free();
+ delete lexer;
+}
+
+#ifndef NO_DECRYPTION
+Object *Parser::getObj(Object *obj,
+ Guchar *fileKey, int keyLength,
+ int objNum, int objGen) {
+#else
+Object *Parser::getObj(Object *obj) {
+#endif
+ char *key;
+ Stream *str;
+ Object obj2;
+ int num;
+#ifndef NO_DECRYPTION
+ Decrypt *decrypt;
+ GString *s;
+ char *p;
+ int i;
+#endif
+
+ // refill buffer after inline image data
+ if (inlineImg == 2) {
+ buf1.free();
+ buf2.free();
+ lexer->getObj(&buf1);
+ lexer->getObj(&buf2);
+ inlineImg = 0;
+ }
+
+ // array
+ if (buf1.isCmd("[")) {
+ shift();
+ obj->initArray(xref);
+ while (!buf1.isCmd("]") && !buf1.isEOF())
+#ifndef NO_DECRYPTION
+ obj->arrayAdd(getObj(&obj2, fileKey, keyLength, objNum, objGen));
+#else
+ obj->arrayAdd(getObj(&obj2));
+#endif
+ if (buf1.isEOF())
+ error(getPos(), "End of file inside array");
+ shift();
+
+ // dictionary or stream
+ } else if (buf1.isCmd("<<")) {
+ shift();
+ obj->initDict(xref);
+ while (!buf1.isCmd(">>") && !buf1.isEOF()) {
+ if (!buf1.isName()) {
+ error(getPos(), "Dictionary key must be a name object");
+ shift();
+ } else {
+ key = copyString(buf1.getName());
+ shift();
+ if (buf1.isEOF() || buf1.isError()) {
+ gfree(key);
+ break;
+ }
+#ifndef NO_DECRYPTION
+ obj->dictAdd(key, getObj(&obj2, fileKey, keyLength, objNum, objGen));
+#else
+ obj->dictAdd(key, getObj(&obj2));
+#endif
+ }
+ }
+ if (buf1.isEOF())
+ error(getPos(), "End of file inside dictionary");
+ if (buf2.isCmd("stream")) {
+ if ((str = makeStream(obj))) {
+ obj->initStream(str);
+#ifndef NO_DECRYPTION
+ if (fileKey) {
+ str->getBaseStream()->doDecryption(fileKey, keyLength,
+ objNum, objGen);
+ }
+#endif
+ } else {
+ obj->free();
+ obj->initError();
+ }
+ } else {
+ shift();
+ }
+
+ // indirect reference or integer
+ } else if (buf1.isInt()) {
+ num = buf1.getInt();
+ shift();
+ if (buf1.isInt() && buf2.isCmd("R")) {
+ obj->initRef(num, buf1.getInt());
+ shift();
+ shift();
+ } else {
+ obj->initInt(num);
+ }
+
+#ifndef NO_DECRYPTION
+ // string
+ } else if (buf1.isString() && fileKey) {
+ buf1.copy(obj);
+ s = obj->getString();
+ decrypt = new Decrypt(fileKey, keyLength, objNum, objGen);
+ for (i = 0, p = obj->getString()->getCString();
+ i < s->getLength();
+ ++i, ++p) {
+ *p = decrypt->decryptByte(*p);
+ }
+ delete decrypt;
+ shift();
+#endif
+
+ // simple object
+ } else {
+ buf1.copy(obj);
+ shift();
+ }
+
+ return obj;
+}
+
+Stream *Parser::makeStream(Object *dict) {
+ Object obj;
+ Stream *str;
+ Guint pos, endPos, length;
+
+ // get stream start position
+ lexer->skipToNextLine();
+ pos = lexer->getPos();
+
+ // get length
+ dict->dictLookup("Length", &obj);
+ if (obj.isInt()) {
+ length = (Guint)obj.getInt();
+ obj.free();
+ } else {
+ error(getPos(), "Bad 'Length' attribute in stream");
+ obj.free();
+ return NULL;
+ }
+
+ // check for length in damaged file
+ if (xref->getStreamEnd(pos, &endPos)) {
+ length = endPos - pos;
+ }
+
+ // make base stream
+ str = lexer->getStream()->getBaseStream()->makeSubStream(pos, gTrue,
+ length, dict);
+
+ // get filters
+ str = str->addFilters(dict);
+
+ // skip over stream data
+ lexer->setPos(pos + length);
+
+ // refill token buffers and check for 'endstream'
+ shift(); // kill '>>'
+ shift(); // kill 'stream'
+ if (buf1.isCmd("endstream"))
+ shift();
+ else
+ error(getPos(), "Missing 'endstream'");
+
+ return str;
+}
+
+void Parser::shift() {
+ if (inlineImg > 0) {
+ if (inlineImg < 2) {
+ ++inlineImg;
+ } else {
+ // in a damaged content stream, if 'ID' shows up in the middle
+ // of a dictionary, we need to reset
+ inlineImg = 0;
+ }
+ } else if (buf2.isCmd("ID")) {
+ lexer->skipChar(); // skip char after 'ID' command
+ inlineImg = 1;
+ }
+ buf1.free();
+ buf1 = buf2;
+ if (inlineImg > 0) // don't buffer inline image data
+ buf2.initNull();
+ else
+ lexer->getObj(&buf2);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/SFont.cc b/filters/kword/pdf/xpdf/xpdf/SFont.cc
deleted file mode 100644
index 53214b08f..000000000
--- a/filters/kword/pdf/xpdf/xpdf/SFont.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-//========================================================================
-//
-// SFont.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "SFont.h"
-
-//------------------------------------------------------------------------
-
-SFontEngine::SFontEngine(Display *displayA, Visual *visualA, int depthA,
- Colormap colormapA) {
- display = displayA;
- visual = visualA;
- depth = depthA;
- colormap = colormapA;
-}
-
-SFontEngine::~SFontEngine() {
-}
-
-void SFontEngine::useTrueColor(int rMaxA, int rShiftA, int gMaxA, int gShiftA,
- int bMaxA, int bShiftA) {
- trueColor = gTrue;
- rMax = rMaxA;
- rShift = rShiftA;
- gMax = gMaxA;
- gShift = gShiftA;
- bMax = bMaxA;
- bShift = bShiftA;
-}
-
-void SFontEngine::useColorCube(Gulong *colorsA, int nRGBA) {
- trueColor = gFalse;
- colors = colorsA;
- nRGB = nRGBA;
- rMax = gMax = bMax = nRGB - 1;
-}
-
-Gulong SFontEngine::findColor(int r, int g, int b) {
- int r1, g1, b1;
- Gulong pix;
-
- r1 = ((r & 0xffff) * rMax) / 0xffff;
- g1 = ((g & 0xffff) * gMax) / 0xffff;
- b1 = ((b & 0xffff) * bMax) / 0xffff;
- if (trueColor) {
- pix = (r1 << rShift) + (g1 << gShift) + (b1 << bShift);
- } else {
- pix = colors[(r1 * nRGB + g1) * nRGB + b1];
- }
- return pix;
-}
-
-//------------------------------------------------------------------------
-
-SFontFile::SFontFile() {
-}
-
-SFontFile::~SFontFile() {
-}
-
-//------------------------------------------------------------------------
-
-SFont::SFont() {
-}
-
-SFont::~SFont() {
-}
-
-GBool SFont::getCharPath(CharCode c, Unicode u, GfxState *state) {
- return gFalse;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/SFont.cpp b/filters/kword/pdf/xpdf/xpdf/SFont.cpp
new file mode 100644
index 000000000..9899301cf
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/SFont.cpp
@@ -0,0 +1,81 @@
+//========================================================================
+//
+// SFont.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "SFont.h"
+
+//------------------------------------------------------------------------
+
+SFontEngine::SFontEngine(Display *displayA, Visual *visualA, int depthA,
+ Colormap colormapA) {
+ display = displayA;
+ visual = visualA;
+ depth = depthA;
+ colormap = colormapA;
+}
+
+SFontEngine::~SFontEngine() {
+}
+
+void SFontEngine::useTrueColor(int rMaxA, int rShiftA, int gMaxA, int gShiftA,
+ int bMaxA, int bShiftA) {
+ trueColor = gTrue;
+ rMax = rMaxA;
+ rShift = rShiftA;
+ gMax = gMaxA;
+ gShift = gShiftA;
+ bMax = bMaxA;
+ bShift = bShiftA;
+}
+
+void SFontEngine::useColorCube(Gulong *colorsA, int nRGBA) {
+ trueColor = gFalse;
+ colors = colorsA;
+ nRGB = nRGBA;
+ rMax = gMax = bMax = nRGB - 1;
+}
+
+Gulong SFontEngine::findColor(int r, int g, int b) {
+ int r1, g1, b1;
+ Gulong pix;
+
+ r1 = ((r & 0xffff) * rMax) / 0xffff;
+ g1 = ((g & 0xffff) * gMax) / 0xffff;
+ b1 = ((b & 0xffff) * bMax) / 0xffff;
+ if (trueColor) {
+ pix = (r1 << rShift) + (g1 << gShift) + (b1 << bShift);
+ } else {
+ pix = colors[(r1 * nRGB + g1) * nRGB + b1];
+ }
+ return pix;
+}
+
+//------------------------------------------------------------------------
+
+SFontFile::SFontFile() {
+}
+
+SFontFile::~SFontFile() {
+}
+
+//------------------------------------------------------------------------
+
+SFont::SFont() {
+}
+
+SFont::~SFont() {
+}
+
+GBool SFont::getCharPath(CharCode c, Unicode u, GfxState *state) {
+ return gFalse;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/Stream.cc b/filters/kword/pdf/xpdf/xpdf/Stream.cc
deleted file mode 100644
index 8c997d032..000000000
--- a/filters/kword/pdf/xpdf/xpdf/Stream.cc
+++ /dev/null
@@ -1,4544 +0,0 @@
-//========================================================================
-//
-// Stream.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <limits.h>
-#ifndef WIN32
-#include <unistd.h>
-#endif
-#include <string.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "gfile.h"
-#include "xpdf_config.h"
-#include "Error.h"
-#include "Object.h"
-#ifndef NO_DECRYPTION
-#include "Decrypt.h"
-#endif
-#include "Stream.h"
-#include "JBIG2Stream.h"
-#include "Stream-CCITT.h"
-
-#ifdef __DJGPP__
-static GBool setDJSYSFLAGS = gFalse;
-#endif
-
-#ifdef VMS
-#ifdef __GNUC__
-#define SEEK_SET 0
-#define SEEK_CUR 1
-#define SEEK_END 2
-#endif
-#endif
-
-//------------------------------------------------------------------------
-// Stream (base class)
-//------------------------------------------------------------------------
-
-Stream::Stream() {
- ref = 1;
-}
-
-Stream::~Stream() {
-}
-
-void Stream::close() {
-}
-
-int Stream::getRawChar() {
- error(-1, "Internal: called getRawChar() on non-predictor stream");
- return EOF;
-}
-
-char *Stream::getLine(char *buf, int size) {
- int i;
- int c;
-
- if (lookChar() == EOF)
- return NULL;
- for (i = 0; i < size - 1; ++i) {
- c = getChar();
- if (c == EOF || c == '\n')
- break;
- if (c == '\r') {
- if ((c = lookChar()) == '\n')
- getChar();
- break;
- }
- buf[i] = c;
- }
- buf[i] = '\0';
- return buf;
-}
-
-GString *Stream::getPSFilter(const char */*indent*/) {
- return new GString();
-}
-
-Stream *Stream::addFilters(Object *dict) {
- Object obj, obj2;
- Object params, params2;
- Stream *str;
- int i;
-
- str = this;
- dict->dictLookup("Filter", &obj);
- if (obj.isNull()) {
- obj.free();
- dict->dictLookup("F", &obj);
- }
- dict->dictLookup("DecodeParms", &params);
- if (params.isNull()) {
- params.free();
- dict->dictLookup("DP", &params);
- }
- if (obj.isName()) {
- str = makeFilter(obj.getName(), str, &params);
- } else if (obj.isArray()) {
- for (i = 0; i < obj.arrayGetLength(); ++i) {
- obj.arrayGet(i, &obj2);
- if (params.isArray())
- params.arrayGet(i, &params2);
- else
- params2.initNull();
- if (obj2.isName()) {
- str = makeFilter(obj2.getName(), str, &params2);
- } else {
- error(getPos(), "Bad filter name");
- str = new EOFStream(str);
- }
- obj2.free();
- params2.free();
- }
- } else if (!obj.isNull()) {
- error(getPos(), "Bad 'Filter' attribute in stream");
- }
- obj.free();
- params.free();
-
- return str;
-}
-
-Stream *Stream::makeFilter(const char *name, Stream *str, Object *params) {
- int pred; // parameters
- int colors;
- int bits;
- int early;
- int encoding;
- GBool endOfLine, byteAlign, endOfBlock, black;
- int columns, rows;
- Object globals, obj;
-
- if (!strcmp(name, "ASCIIHexDecode") || !strcmp(name, "AHx")) {
- str = new ASCIIHexStream(str);
- } else if (!strcmp(name, "ASCII85Decode") || !strcmp(name, "A85")) {
- str = new ASCII85Stream(str);
- } else if (!strcmp(name, "LZWDecode") || !strcmp(name, "LZW")) {
- pred = 1;
- columns = 1;
- colors = 1;
- bits = 8;
- early = 1;
- if (params->isDict()) {
- params->dictLookup("Predictor", &obj);
- if (obj.isInt())
- pred = obj.getInt();
- obj.free();
- params->dictLookup("Columns", &obj);
- if (obj.isInt())
- columns = obj.getInt();
- obj.free();
- params->dictLookup("Colors", &obj);
- if (obj.isInt())
- colors = obj.getInt();
- obj.free();
- params->dictLookup("BitsPerComponent", &obj);
- if (obj.isInt())
- bits = obj.getInt();
- obj.free();
- params->dictLookup("EarlyChange", &obj);
- if (obj.isInt())
- early = obj.getInt();
- obj.free();
- }
- str = new LZWStream(str, pred, columns, colors, bits, early);
- } else if (!strcmp(name, "RunLengthDecode") || !strcmp(name, "RL")) {
- str = new RunLengthStream(str);
- } else if (!strcmp(name, "CCITTFaxDecode") || !strcmp(name, "CCF")) {
- encoding = 0;
- endOfLine = gFalse;
- byteAlign = gFalse;
- columns = 1728;
- rows = 0;
- endOfBlock = gTrue;
- black = gFalse;
- if (params->isDict()) {
- params->dictLookup("K", &obj);
- if (obj.isInt()) {
- encoding = obj.getInt();
- }
- obj.free();
- params->dictLookup("EndOfLine", &obj);
- if (obj.isBool()) {
- endOfLine = obj.getBool();
- }
- obj.free();
- params->dictLookup("EncodedByteAlign", &obj);
- if (obj.isBool()) {
- byteAlign = obj.getBool();
- }
- obj.free();
- params->dictLookup("Columns", &obj);
- if (obj.isInt()) {
- columns = obj.getInt();
- }
- obj.free();
- params->dictLookup("Rows", &obj);
- if (obj.isInt()) {
- rows = obj.getInt();
- }
- obj.free();
- params->dictLookup("EndOfBlock", &obj);
- if (obj.isBool()) {
- endOfBlock = obj.getBool();
- }
- obj.free();
- params->dictLookup("BlackIs1", &obj);
- if (obj.isBool()) {
- black = obj.getBool();
- }
- obj.free();
- }
- str = new CCITTFaxStream(str, encoding, endOfLine, byteAlign,
- columns, rows, endOfBlock, black);
- } else if (!strcmp(name, "DCTDecode") || !strcmp(name, "DCT")) {
- str = new DCTStream(str);
- } else if (!strcmp(name, "FlateDecode") || !strcmp(name, "Fl")) {
- pred = 1;
- columns = 1;
- colors = 1;
- bits = 8;
- if (params->isDict()) {
- params->dictLookup("Predictor", &obj);
- if (obj.isInt())
- pred = obj.getInt();
- obj.free();
- params->dictLookup("Columns", &obj);
- if (obj.isInt())
- columns = obj.getInt();
- obj.free();
- params->dictLookup("Colors", &obj);
- if (obj.isInt())
- colors = obj.getInt();
- obj.free();
- params->dictLookup("BitsPerComponent", &obj);
- if (obj.isInt())
- bits = obj.getInt();
- obj.free();
- }
- str = new FlateStream(str, pred, columns, colors, bits);
- } else if (!strcmp(name, "JBIG2Decode")) {
- if (params->isDict()) {
- params->dictLookup("JBIG2Globals", &globals);
- }
- str = new JBIG2Stream(str, &globals);
- globals.free();
- } else {
- error(getPos(), "Unknown filter '%s'", name);
- str = new EOFStream(str);
- }
- return str;
-}
-
-//------------------------------------------------------------------------
-// BaseStream
-//------------------------------------------------------------------------
-
-BaseStream::BaseStream(Object *dictA) {
- dict = *dictA;
-#ifndef NO_DECRYPTION
- decrypt = NULL;
-#endif
-}
-
-BaseStream::~BaseStream() {
- dict.free();
-#ifndef NO_DECRYPTION
- if (decrypt)
- delete decrypt;
-#endif
-}
-
-#ifndef NO_DECRYPTION
-void BaseStream::doDecryption(Guchar *fileKey, int keyLength,
- int objNum, int objGen) {
- decrypt = new Decrypt(fileKey, keyLength, objNum, objGen);
-}
-#endif
-
-//------------------------------------------------------------------------
-// FilterStream
-//------------------------------------------------------------------------
-
-FilterStream::FilterStream(Stream *strA) {
- str = strA;
-}
-
-FilterStream::~FilterStream() {
-}
-
-void FilterStream::close() {
- str->close();
-}
-
-void FilterStream::setPos(Guint /*pos*/, int /*dir*/) {
- error(-1, "Internal: called setPos() on FilterStream");
-}
-
-//------------------------------------------------------------------------
-// ImageStream
-//------------------------------------------------------------------------
-
-ImageStream::ImageStream(Stream *strA, int widthA, int nCompsA, int nBitsA) {
- int imgLineSize;
-
- str = strA;
- width = widthA;
- nComps = nCompsA;
- nBits = nBitsA;
-
- nVals = width * nComps;
- if (nBits == 1) {
- imgLineSize = (nVals + 7) & ~7;
- } else {
- imgLineSize = nVals;
- }
- imgLine = (Guchar *)gmalloc(imgLineSize * sizeof(Guchar));
- imgIdx = nVals;
-}
-
-ImageStream::~ImageStream() {
- gfree(imgLine);
-}
-
-void ImageStream::reset() {
- str->reset();
-}
-
-GBool ImageStream::getPixel(Guchar *pix) {
- int i;
-
- if (imgIdx >= nVals) {
- getLine();
- imgIdx = 0;
- }
- for (i = 0; i < nComps; ++i) {
- pix[i] = imgLine[imgIdx++];
- }
- return gTrue;
-}
-
-Guchar *ImageStream::getLine() {
- Gulong buf, bitMask;
- int bits;
- int c;
- int i;
-
- if (nBits == 1) {
- for (i = 0; i < nVals; i += 8) {
- c = str->getChar();
- imgLine[i+0] = (Guchar)((c >> 7) & 1);
- imgLine[i+1] = (Guchar)((c >> 6) & 1);
- imgLine[i+2] = (Guchar)((c >> 5) & 1);
- imgLine[i+3] = (Guchar)((c >> 4) & 1);
- imgLine[i+4] = (Guchar)((c >> 3) & 1);
- imgLine[i+5] = (Guchar)((c >> 2) & 1);
- imgLine[i+6] = (Guchar)((c >> 1) & 1);
- imgLine[i+7] = (Guchar)(c & 1);
- }
- } else if (nBits == 8) {
- for (i = 0; i < nVals; ++i) {
- imgLine[i] = str->getChar();
- }
- } else {
- bitMask = (1 << nBits) - 1;
- buf = 0;
- bits = 0;
- for (i = 0; i < nVals; ++i) {
- if (bits < nBits) {
- buf = (buf << 8) | (str->getChar() & 0xff);
- bits += 8;
- }
- imgLine[i] = (Guchar)((buf >> (bits - nBits)) & bitMask);
- bits -= nBits;
- }
- }
- return imgLine;
-}
-
-void ImageStream::skipLine() {
- int n, i;
-
- n = (nVals * nBits + 7) >> 3;
- for (i = 0; i < n; ++i) {
- str->getChar();
- }
-}
-
-//------------------------------------------------------------------------
-// StreamPredictor
-//------------------------------------------------------------------------
-
-StreamPredictor::StreamPredictor(Stream *strA, int predictorA,
- int widthA, int nCompsA, int nBitsA) {
- str = strA;
- predictor = predictorA;
- width = widthA;
- nComps = nCompsA;
- nBits = nBitsA;
- predLine = NULL;
- ok = gFalse;
-
- nVals = width * nComps;
- pixBytes = (nComps * nBits + 7) >> 3;
- rowBytes = ((nVals * nBits + 7) >> 3) + pixBytes;
- if (width <= 0 || nComps <= 0 || nBits <= 0 ||
- nComps > 4 ||
- nBits > 16 ||
- width >= INT_MAX / nComps || // check for overflow in nVals
- nVals >= (INT_MAX - 7) / nBits) // check for overflow in rowBytes
- return;
-
- predLine = (Guchar *)gmalloc(rowBytes);
- memset(predLine, 0, rowBytes);
- predIdx = rowBytes;
-
- ok = gTrue;
-}
-
-StreamPredictor::~StreamPredictor() {
- gfree(predLine);
-}
-
-int StreamPredictor::lookChar() {
- if (predIdx >= rowBytes) {
- if (!getNextLine()) {
- return EOF;
- }
- }
- return predLine[predIdx];
-}
-
-int StreamPredictor::getChar() {
- if (predIdx >= rowBytes) {
- if (!getNextLine()) {
- return EOF;
- }
- }
- return predLine[predIdx++];
-}
-
-GBool StreamPredictor::getNextLine() {
- int curPred;
- Guchar upLeftBuf[4];
- int left, up, upLeft, p, pa, pb, pc;
- int c;
- Gulong inBuf, outBuf, bitMask;
- int inBits, outBits;
- int i, j, k;
-
- // get PNG optimum predictor number
- if (predictor == 15) {
- if ((curPred = str->getRawChar()) == EOF) {
- return gFalse;
- }
- curPred += 10;
- } else {
- curPred = predictor;
- }
-
- // read the raw line, apply PNG (byte) predictor
- upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
- for (i = pixBytes; i < rowBytes; ++i) {
- upLeftBuf[3] = upLeftBuf[2];
- upLeftBuf[2] = upLeftBuf[1];
- upLeftBuf[1] = upLeftBuf[0];
- upLeftBuf[0] = predLine[i];
- if ((c = str->getRawChar()) == EOF) {
- break;
- }
- switch (curPred) {
- case 11: // PNG sub
- predLine[i] = predLine[i - pixBytes] + (Guchar)c;
- break;
- case 12: // PNG up
- predLine[i] = predLine[i] + (Guchar)c;
- break;
- case 13: // PNG average
- predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) +
- (Guchar)c;
- break;
- case 14: // PNG Paeth
- left = predLine[i - pixBytes];
- up = predLine[i];
- upLeft = upLeftBuf[pixBytes];
- p = left + up - upLeft;
- if ((pa = p - left) < 0)
- pa = -pa;
- if ((pb = p - up) < 0)
- pb = -pb;
- if ((pc = p - upLeft) < 0)
- pc = -pc;
- if (pa <= pb && pa <= pc)
- predLine[i] = left + (Guchar)c;
- else if (pb <= pc)
- predLine[i] = up + (Guchar)c;
- else
- predLine[i] = upLeft + (Guchar)c;
- break;
- case 10: // PNG none
- default: // no predictor or TIFF predictor
- predLine[i] = (Guchar)c;
- break;
- }
- }
-
- // apply TIFF (component) predictor
- //~ this is completely untested
- if (predictor == 2) {
- if (nBits == 1) {
- inBuf = predLine[pixBytes - 1];
- for (i = pixBytes; i < rowBytes; i += 8) {
- // 1-bit add is just xor
- inBuf = (inBuf << 8) | predLine[i];
- predLine[i] ^= inBuf >> nComps;
- }
- } else if (nBits == 8) {
- for (i = pixBytes; i < rowBytes; ++i) {
- predLine[i] += predLine[i - nComps];
- }
- } else {
- upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
- bitMask = (1 << nBits) - 1;
- inBuf = outBuf = 0;
- inBits = outBits = 0;
- j = k = pixBytes;
- for (i = 0; i < nVals; ++i) {
- if (inBits < nBits) {
- inBuf = (inBuf << 8) | (predLine[j++] & 0xff);
- inBits += 8;
- }
- upLeftBuf[3] = upLeftBuf[2];
- upLeftBuf[2] = upLeftBuf[1];
- upLeftBuf[1] = upLeftBuf[0];
- upLeftBuf[0] = (upLeftBuf[nComps] +
- (inBuf >> (inBits - nBits))) & bitMask;
- outBuf = (outBuf << nBits) | upLeftBuf[0];
- inBits -= nBits;
- outBits += nBits;
- if (outBits > 8) {
- predLine[k++] = (Guchar)(outBuf >> (outBits - 8));
- }
- }
- if (outBits > 0) {
- predLine[k++] = (Guchar)(outBuf << (8 - outBits));
- }
- }
- }
-
- // reset to start of line
- predIdx = pixBytes;
-
- return gTrue;
-}
-
-//------------------------------------------------------------------------
-// FileStream
-//------------------------------------------------------------------------
-
-FileStream::FileStream(FILE *fA, Guint startA, GBool limitedA,
- Guint lengthA, Object *dictA):
- BaseStream(dictA) {
- f = fA;
- start = startA;
- limited = limitedA;
- length = lengthA;
- bufPtr = bufEnd = buf;
- bufPos = start;
- savePos = 0;
- saved = gFalse;
-}
-
-FileStream::~FileStream() {
- close();
-}
-
-Stream *FileStream::makeSubStream(Guint startA, GBool limitedA,
- Guint lengthA, Object *dictA) {
- return new FileStream(f, startA, limitedA, lengthA, dictA);
-}
-
-void FileStream::reset() {
-#ifdef HAVE_FSEEKO
- savePos = (Guint)ftello(f);
- fseeko(f, start, SEEK_SET);
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- savePos = (Guint)ftell64(f);
- fseek64(f, start, SEEK_SET);
-#else
- savePos = (Guint)ftell(f);
- fseek(f, start, SEEK_SET);
-#endif
- saved = gTrue;
- bufPtr = bufEnd = buf;
- bufPos = start;
-#ifndef NO_DECRYPTION
- if (decrypt)
- decrypt->reset();
-#endif
-}
-
-void FileStream::close() {
- if (saved) {
-#ifdef HAVE_FSEEKO
- fseeko(f, savePos, SEEK_SET);
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- fseek64(f, savePos, SEEK_SET);
-#else
- fseek(f, savePos, SEEK_SET);
-#endif
- saved = gFalse;
- }
-}
-
-GBool FileStream::fillBuf() {
- int n;
-#ifndef NO_DECRYPTION
- char *p;
-#endif
-
- bufPos += bufEnd - buf;
- bufPtr = bufEnd = buf;
- if (limited && bufPos >= start + length) {
- return gFalse;
- }
- if (limited && bufPos + fileStreamBufSize > start + length) {
- n = start + length - bufPos;
- } else {
- n = fileStreamBufSize;
- }
- n = fread(buf, 1, n, f);
- bufEnd = buf + n;
- if (bufPtr >= bufEnd) {
- return gFalse;
- }
-#ifndef NO_DECRYPTION
- if (decrypt) {
- for (p = buf; p < bufEnd; ++p) {
- *p = (char)decrypt->decryptByte((Guchar)*p);
- }
- }
-#endif
- return gTrue;
-}
-
-void FileStream::setPos(Guint pos, int dir) {
- Guint size;
-
- if (dir >= 0) {
-#ifdef HAVE_FSEEKO
- fseeko(f, pos, SEEK_SET);
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- fseek64(f, pos, SEEK_SET);
-#else
- fseek(f, pos, SEEK_SET);
-#endif
- bufPos = pos;
- } else {
-#ifdef HAVE_FSEEKO
- fseeko(f, 0, SEEK_END);
- size = (Guint)ftello(f);
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- fseek64(f, 0, SEEK_END);
- size = (Guint)ftell64(f);
-#else
- fseek(f, 0, SEEK_END);
- size = (Guint)ftell(f);
-#endif
- if (pos > size)
- pos = (Guint)size;
-#ifdef __CYGWIN32__
- //~ work around a bug in cygwin's implementation of fseek
- rewind(f);
-#endif
-#ifdef HAVE_FSEEKO
- fseeko(f, -(int)pos, SEEK_END);
- bufPos = (Guint)ftello(f);
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- fseek64(f, -(int)pos, SEEK_END);
- bufPos = (Guint)ftell64(f);
-#else
- fseek(f, -(int)pos, SEEK_END);
- bufPos = (Guint)ftell(f);
-#endif
- }
- bufPtr = bufEnd = buf;
-}
-
-void FileStream::moveStart(int delta) {
- start += delta;
- bufPtr = bufEnd = buf;
- bufPos = start;
-}
-
-//------------------------------------------------------------------------
-// MemStream
-//------------------------------------------------------------------------
-
-MemStream::MemStream(char *bufA, Guint lengthA, Object *dictA):
- BaseStream(dictA) {
- buf = bufA;
- needFree = gFalse;
- length = lengthA;
- bufEnd = buf + length;
- bufPtr = buf;
-}
-
-MemStream::~MemStream() {
- if (needFree) {
- gfree(buf);
- }
-}
-
-Stream *MemStream::makeSubStream(Guint start, GBool limited,
- Guint lengthA, Object *dictA) {
- Guint newLength;
-
- if (!limited || start + lengthA > length) {
- newLength = length - start;
- } else {
- newLength = lengthA;
- }
- return new MemStream(buf + start, newLength, dictA);
-}
-
-void MemStream::reset() {
- bufPtr = buf;
-#ifndef NO_DECRYPTION
- if (decrypt) {
- decrypt->reset();
- }
-#endif
-}
-
-void MemStream::close() {
-}
-
-void MemStream::setPos(Guint pos, int dir) {
- if (dir >= 0) {
- if (pos > length) {
- bufPtr = bufEnd;
- } else {
- bufPtr = buf + pos;
- }
- } else {
- if (pos > length) {
- bufPtr = buf;
- } else {
- bufPtr = bufEnd - pos;
- }
- }
-}
-
-void MemStream::moveStart(int delta) {
- buf += delta;
- bufPtr = buf;
-}
-
-#ifndef NO_DECRYPTION
-void MemStream::doDecryption(Guchar *fileKey, int keyLength,
- int objNum, int objGen) {
- char *newBuf;
- char *p, *q;
-
- this->BaseStream::doDecryption(fileKey, keyLength, objNum, objGen);
- if (decrypt) {
- newBuf = (char *)gmalloc(bufEnd - buf);
- for (p = buf, q = newBuf; p < bufEnd; ++p, ++q) {
- *q = (char)decrypt->decryptByte((Guchar)*p);
- }
- bufEnd = newBuf + (bufEnd - buf);
- bufPtr = newBuf + (bufPtr - buf);
- buf = newBuf;
- needFree = gTrue;
- }
-}
-#endif
-
-//------------------------------------------------------------------------
-// EmbedStream
-//------------------------------------------------------------------------
-
-EmbedStream::EmbedStream(Stream *strA, Object *dictA):
- BaseStream(dictA) {
- str = strA;
-}
-
-EmbedStream::~EmbedStream() {
-}
-
-Stream *EmbedStream::makeSubStream(Guint /*start*/, GBool /*limited*/,
- Guint /*length*/, Object */*dictA*/) {
- error(-1, "Internal: called makeSubStream() on EmbedStream");
- return NULL;
-}
-
-void EmbedStream::setPos(Guint /*pos*/, int /*dir*/) {
- error(-1, "Internal: called setPos() on EmbedStream");
-}
-
-Guint EmbedStream::getStart() {
- error(-1, "Internal: called getStart() on EmbedStream");
- return 0;
-}
-
-void EmbedStream::moveStart(int /*delta*/) {
- error(-1, "Internal: called moveStart() on EmbedStream");
-}
-
-//------------------------------------------------------------------------
-// ASCIIHexStream
-//------------------------------------------------------------------------
-
-ASCIIHexStream::ASCIIHexStream(Stream *strA):
- FilterStream(strA) {
- buf = EOF;
- eof = gFalse;
-}
-
-ASCIIHexStream::~ASCIIHexStream() {
- delete str;
-}
-
-void ASCIIHexStream::reset() {
- str->reset();
- buf = EOF;
- eof = gFalse;
-}
-
-int ASCIIHexStream::lookChar() {
- int c1, c2, x;
-
- if (buf != EOF)
- return buf;
- if (eof) {
- buf = EOF;
- return EOF;
- }
- do {
- c1 = str->getChar();
- } while (isspace(c1));
- if (c1 == '>') {
- eof = gTrue;
- buf = EOF;
- return buf;
- }
- do {
- c2 = str->getChar();
- } while (isspace(c2));
- if (c2 == '>') {
- eof = gTrue;
- c2 = '0';
- }
- if (c1 >= '0' && c1 <= '9') {
- x = (c1 - '0') << 4;
- } else if (c1 >= 'A' && c1 <= 'F') {
- x = (c1 - 'A' + 10) << 4;
- } else if (c1 >= 'a' && c1 <= 'f') {
- x = (c1 - 'a' + 10) << 4;
- } else if (c1 == EOF) {
- eof = gTrue;
- x = 0;
- } else {
- error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c1);
- x = 0;
- }
- if (c2 >= '0' && c2 <= '9') {
- x += c2 - '0';
- } else if (c2 >= 'A' && c2 <= 'F') {
- x += c2 - 'A' + 10;
- } else if (c2 >= 'a' && c2 <= 'f') {
- x += c2 - 'a' + 10;
- } else if (c2 == EOF) {
- eof = gTrue;
- x = 0;
- } else {
- error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c2);
- }
- buf = x & 0xff;
- return buf;
-}
-
-GString *ASCIIHexStream::getPSFilter(const char *indent) {
- GString *s;
-
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("/ASCIIHexDecode filter\n");
- return s;
-}
-
-GBool ASCIIHexStream::isBinary(GBool /*last*/) {
- return str->isBinary(gFalse);
-}
-
-//------------------------------------------------------------------------
-// ASCII85Stream
-//------------------------------------------------------------------------
-
-ASCII85Stream::ASCII85Stream(Stream *strA):
- FilterStream(strA) {
- index = n = 0;
- eof = gFalse;
-}
-
-ASCII85Stream::~ASCII85Stream() {
- delete str;
-}
-
-void ASCII85Stream::reset() {
- str->reset();
- index = n = 0;
- eof = gFalse;
-}
-
-int ASCII85Stream::lookChar() {
- int k;
- Gulong t;
-
- if (index >= n) {
- if (eof)
- return EOF;
- index = 0;
- do {
- c[0] = str->getChar();
- } while (c[0] == '\n' || c[0] == '\r');
- if (c[0] == '~' || c[0] == EOF) {
- eof = gTrue;
- n = 0;
- return EOF;
- } else if (c[0] == 'z') {
- b[0] = b[1] = b[2] = b[3] = 0;
- n = 4;
- } else {
- for (k = 1; k < 5; ++k) {
- do {
- c[k] = str->getChar();
- } while (c[k] == '\n' || c[k] == '\r');
- if (c[k] == '~' || c[k] == EOF)
- break;
- }
- n = k - 1;
- if (k < 5 && (c[k] == '~' || c[k] == EOF)) {
- for (++k; k < 5; ++k)
- c[k] = 0x21 + 84;
- eof = gTrue;
- }
- t = 0;
- for (k = 0; k < 5; ++k)
- t = t * 85 + (c[k] - 0x21);
- for (k = 3; k >= 0; --k) {
- b[k] = (int)(t & 0xff);
- t >>= 8;
- }
- }
- }
- return b[index];
-}
-
-GString *ASCII85Stream::getPSFilter(const char *indent) {
- GString *s;
-
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("/ASCII85Decode filter\n");
- return s;
-}
-
-GBool ASCII85Stream::isBinary(GBool /*last*/) {
- return str->isBinary(gFalse);
-}
-
-//------------------------------------------------------------------------
-// LZWStream
-//------------------------------------------------------------------------
-
-LZWStream::LZWStream(Stream *strA, int predictor, int columns, int colors,
- int bits, int earlyA):
- FilterStream(strA) {
- if (predictor != 1) {
- pred = new StreamPredictor(this, predictor, columns, colors, bits);
- if ( !pred->isOk()) {
- delete pred;
- pred = NULL;
- }
- } else {
- pred = NULL;
- }
- early = earlyA;
- eof = gFalse;
- inputBits = 0;
- clearTable();
-}
-
-LZWStream::~LZWStream() {
- if (pred) {
- delete pred;
- }
- delete str;
-}
-
-int LZWStream::getChar() {
- if (pred) {
- return pred->getChar();
- }
- if (eof) {
- return EOF;
- }
- if (seqIndex >= seqLength) {
- if (!processNextCode()) {
- return EOF;
- }
- }
- return seqBuf[seqIndex++];
-}
-
-int LZWStream::lookChar() {
- if (pred) {
- return pred->lookChar();
- }
- if (eof) {
- return EOF;
- }
- if (seqIndex >= seqLength) {
- if (!processNextCode()) {
- return EOF;
- }
- }
- return seqBuf[seqIndex];
-}
-
-int LZWStream::getRawChar() {
- if (eof) {
- return EOF;
- }
- if (seqIndex >= seqLength) {
- if (!processNextCode()) {
- return EOF;
- }
- }
- return seqBuf[seqIndex++];
-}
-
-void LZWStream::reset() {
- str->reset();
- eof = gFalse;
- inputBits = 0;
- clearTable();
-}
-
-GBool LZWStream::processNextCode() {
- int code;
- int nextLength;
- int i, j;
-
- // check for EOF
- if (eof) {
- return gFalse;
- }
-
- // check for eod and clear-table codes
- start:
- code = getCode();
- if (code == EOF || code == 257) {
- eof = gTrue;
- return gFalse;
- }
- if (code == 256) {
- clearTable();
- goto start;
- }
- if (nextCode >= 4097) {
- error(getPos(), "Bad LZW stream - expected clear-table code");
- clearTable();
- }
-
- // process the next code
- nextLength = seqLength + 1;
- if (code < 256) {
- seqBuf[0] = code;
- seqLength = 1;
- } else if (code < nextCode) {
- seqLength = table[code].length;
- for (i = seqLength - 1, j = code; i > 0; --i) {
- seqBuf[i] = table[j].tail;
- j = table[j].head;
- }
- seqBuf[0] = j;
- } else if (code == nextCode) {
- seqBuf[seqLength] = newChar;
- ++seqLength;
- } else {
- error(getPos(), "Bad LZW stream - unexpected code");
- eof = gTrue;
- return gFalse;
- }
- newChar = seqBuf[0];
- if (first) {
- first = gFalse;
- } else {
- table[nextCode].length = nextLength;
- table[nextCode].head = prevCode;
- table[nextCode].tail = newChar;
- ++nextCode;
- if (nextCode + early == 512)
- nextBits = 10;
- else if (nextCode + early == 1024)
- nextBits = 11;
- else if (nextCode + early == 2048)
- nextBits = 12;
- }
- prevCode = code;
-
- // reset buffer
- seqIndex = 0;
-
- return gTrue;
-}
-
-void LZWStream::clearTable() {
- nextCode = 258;
- nextBits = 9;
- seqIndex = seqLength = 0;
- first = gTrue;
-}
-
-int LZWStream::getCode() {
- int c;
- int code;
-
- while (inputBits < nextBits) {
- if ((c = str->getChar()) == EOF)
- return EOF;
- inputBuf = (inputBuf << 8) | (c & 0xff);
- inputBits += 8;
- }
- code = (inputBuf >> (inputBits - nextBits)) & ((1 << nextBits) - 1);
- inputBits -= nextBits;
- return code;
-}
-
-GString *LZWStream::getPSFilter(const char *indent) {
- GString *s;
-
- if (pred) {
- return NULL;
- }
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("/LZWDecode filter\n");
- return s;
-}
-
-GBool LZWStream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-//------------------------------------------------------------------------
-// RunLengthStream
-//------------------------------------------------------------------------
-
-RunLengthStream::RunLengthStream(Stream *strA):
- FilterStream(strA) {
- bufPtr = bufEnd = buf;
- eof = gFalse;
-}
-
-RunLengthStream::~RunLengthStream() {
- delete str;
-}
-
-void RunLengthStream::reset() {
- str->reset();
- bufPtr = bufEnd = buf;
- eof = gFalse;
-}
-
-GString *RunLengthStream::getPSFilter(const char *indent) {
- GString *s;
-
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("/RunLengthDecode filter\n");
- return s;
-}
-
-GBool RunLengthStream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-GBool RunLengthStream::fillBuf() {
- int c;
- int n, i;
-
- if (eof)
- return gFalse;
- c = str->getChar();
- if (c == 0x80 || c == EOF) {
- eof = gTrue;
- return gFalse;
- }
- if (c < 0x80) {
- n = c + 1;
- for (i = 0; i < n; ++i)
- buf[i] = (char)str->getChar();
- } else {
- n = 0x101 - c;
- c = str->getChar();
- for (i = 0; i < n; ++i)
- buf[i] = (char)c;
- }
- bufPtr = buf;
- bufEnd = buf + n;
- return gTrue;
-}
-
-//------------------------------------------------------------------------
-// CCITTFaxStream
-//------------------------------------------------------------------------
-
-#if 0
-CCITTFaxStream::CCITTFaxStream(Stream *strA, int encodingA, GBool endOfLineA,
- GBool byteAlignA, int columnsA, int rowsA,
- GBool endOfBlockA, GBool blackA):
- FilterStream(strA) {
- encoding = encodingA;
- endOfLine = endOfLineA;
- byteAlign = byteAlignA;
- columns = columnsA;
- if (columns < 1 || columns >= INT_MAX / sizeof(short)) {
- error(-1, "invalid number of columns");
- exit(1);
- }
- rows = rowsA;
- endOfBlock = endOfBlockA;
- black = blackA;
- refLine = (short *)gmalloc((columns + 3) * sizeof(short));
- codingLine = (short *)gmalloc((columns + 2) * sizeof(short));
-
- eof = gFalse;
- row = 0;
- nextLine2D = encoding < 0;
- inputBits = 0;
- codingLine[0] = 0;
- codingLine[1] = refLine[2] = columns;
- a0 = 1;
-
- buf = EOF;
-}
-
-CCITTFaxStream::~CCITTFaxStream() {
- delete str;
- gfree(refLine);
- gfree(codingLine);
-}
-
-void CCITTFaxStream::reset() {
- int n;
-
- str->reset();
- eof = gFalse;
- row = 0;
- nextLine2D = encoding < 0;
- inputBits = 0;
- codingLine[0] = 0;
- codingLine[1] = refLine[2] = columns;
- a0 = 1;
- buf = EOF;
-
- // get initial end-of-line marker and 2D encoding tag
- if (endOfBlock) {
- if (lookBits(12) == 0x001) {
- eatBits(12);
- }
- } else {
- for (n = 0; n < 11 && lookBits(n) == 0; ++n) ;
- if (n == 11 && lookBits(12) == 0x001) {
- eatBits(12);
- }
- }
- if (encoding > 0) {
- nextLine2D = !lookBits(1);
- eatBits(1);
- }
-}
-
-int CCITTFaxStream::lookChar() {
- short code1, code2, code3;
- int a0New;
-#if 0
- GBool err;
-#endif
- GBool gotEOL;
- int ret;
- int bits, i;
-
- // if at eof just return EOF
- if (eof && codingLine[a0] >= columns) {
- return EOF;
- }
-
- // read the next row
-#if 0
- err = gFalse;
-#endif
- if (codingLine[a0] >= columns) {
-
- // 2-D encoding
- if (nextLine2D) {
- for (i = 0; codingLine[i] < columns; ++i)
- refLine[i] = codingLine[i];
- refLine[i] = refLine[i + 1] = columns;
- b1 = 1;
- a0New = codingLine[a0 = 0] = 0;
- do {
- code1 = getTwoDimCode();
- switch (code1) {
- case twoDimPass:
- if (refLine[b1] < columns) {
- a0New = refLine[b1 + 1];
- b1 += 2;
- }
- break;
- case twoDimHoriz:
- if ((a0 & 1) == 0) {
- code1 = code2 = 0;
- do {
- code1 += code3 = getWhiteCode();
- } while (code3 >= 64);
- do {
- code2 += code3 = getBlackCode();
- } while (code3 >= 64);
- } else {
- code1 = code2 = 0;
- do {
- code1 += code3 = getBlackCode();
- } while (code3 >= 64);
- do {
- code2 += code3 = getWhiteCode();
- } while (code3 >= 64);
- }
- codingLine[a0 + 1] = a0New + code1;
- ++a0;
- a0New = codingLine[a0 + 1] = codingLine[a0] + code2;
- ++a0;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- break;
- case twoDimVert0:
- a0New = codingLine[++a0] = refLine[b1];
- if (refLine[b1] < columns) {
- ++b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- }
- break;
- case twoDimVertR1:
- a0New = codingLine[++a0] = refLine[b1] + 1;
- if (refLine[b1] < columns) {
- ++b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- }
- break;
- case twoDimVertL1:
- a0New = codingLine[++a0] = refLine[b1] - 1;
- --b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- break;
- case twoDimVertR2:
- a0New = codingLine[++a0] = refLine[b1] + 2;
- if (refLine[b1] < columns) {
- ++b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- }
- break;
- case twoDimVertL2:
- a0New = codingLine[++a0] = refLine[b1] - 2;
- --b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- break;
- case twoDimVertR3:
- a0New = codingLine[++a0] = refLine[b1] + 3;
- if (refLine[b1] < columns) {
- ++b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- }
- break;
- case twoDimVertL3:
- a0New = codingLine[++a0] = refLine[b1] - 3;
- --b1;
- while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
- b1 += 2;
- break;
- case EOF:
- eof = gTrue;
- codingLine[a0 = 0] = columns;
- return EOF;
- default:
- error(getPos(), "Bad 2D code %04x in CCITTFax stream", code1);
-#if 0
- err = gTrue;
- break;
-#else
- eof = gTrue;
- return EOF;
-#endif
- }
- } while (codingLine[a0] < columns);
-
- // 1-D encoding
- } else {
- codingLine[a0 = 0] = 0;
- while (1) {
- code1 = 0;
- do {
- code1 += code3 = getWhiteCode();
- } while (code3 >= 64);
- codingLine[a0+1] = codingLine[a0] + code1;
- ++a0;
- if (codingLine[a0] >= columns)
- break;
- code2 = 0;
- do {
- code2 += code3 = getBlackCode();
- } while (code3 >= 64);
- codingLine[a0+1] = codingLine[a0] + code2;
- ++a0;
- if (codingLine[a0] >= columns)
- break;
- }
- }
-
- if (codingLine[a0] != columns) {
- error(getPos(), "CCITTFax row is wrong length (%d)", codingLine[a0]);
-#if 0
- err = gTrue;
-#endif
- }
-
- // byte-align the row
- if (byteAlign) {
- inputBits &= ~7;
- }
-
- // check for end-of-line marker, skipping over any extra zero bits
- gotEOL = gFalse;
- if (!endOfBlock && row == rows - 1) {
- eof = gTrue;
- } else {
- code1 = lookBits(12);
- while (code1 == 0) {
- eatBits(1);
- code1 = lookBits(12);
- }
- if (code1 == 0x001) {
- eatBits(12);
- gotEOL = gTrue;
- } else if (code1 == EOF) {
- eof = gTrue;
- }
- }
-
- // get 2D encoding tag
- if (!eof && encoding > 0) {
- nextLine2D = !lookBits(1);
- eatBits(1);
- }
-
- // check for end-of-block marker
- if (endOfBlock && gotEOL) {
- code1 = lookBits(12);
- if (code1 == 0x001) {
- eatBits(12);
- if (encoding > 0) {
- lookBits(1);
- eatBits(1);
- }
- if (encoding >= 0) {
- for (i = 0; i < 4; ++i) {
- code1 = lookBits(12);
- if (code1 != 0x001) {
- error(getPos(), "Bad RTC code in CCITTFax stream");
- }
- eatBits(12);
- if (encoding > 0) {
- lookBits(1);
- eatBits(1);
- }
- }
- }
- eof = gTrue;
- }
- }
-
-#if 0
- // This looks for an end-of-line marker after an error, however
- // some (most?) CCITT streams in PDF files don't use end-of-line
- // markers, and the just-plow-on technique works better in those
- // cases.
- else if (err) {
- do {
- if (code1 == EOF) {
- eof = gTrue;
- return EOF;
- }
- eatBits(1);
- code1 = look13Bits();
- } while ((code1 >> 1) != 0x001);
- eatBits(12);
- codingLine[++a0] = columns;
- if (encoding > 0) {
- eatBits(1);
- nextLine2D = !(code1 & 1);
- }
- }
-#endif
-
- a0 = 0;
- outputBits = codingLine[1] - codingLine[0];
- if (outputBits == 0) {
- a0 = 1;
- outputBits = codingLine[2] - codingLine[1];
- }
-
- ++row;
- }
-
- // get a byte
- if (outputBits >= 8) {
- ret = ((a0 & 1) == 0) ? 0xff : 0x00;
- if ((outputBits -= 8) == 0) {
- ++a0;
- if (codingLine[a0] < columns) {
- outputBits = codingLine[a0 + 1] - codingLine[a0];
- }
- }
- } else {
- bits = 8;
- ret = 0;
- do {
- if (outputBits > bits) {
- i = bits;
- bits = 0;
- if ((a0 & 1) == 0) {
- ret |= 0xff >> (8 - i);
- }
- outputBits -= i;
- } else {
- i = outputBits;
- bits -= outputBits;
- if ((a0 & 1) == 0) {
- ret |= (0xff >> (8 - i)) << bits;
- }
- outputBits = 0;
- ++a0;
- if (codingLine[a0] < columns) {
- outputBits = codingLine[a0 + 1] - codingLine[a0];
- }
- }
- } while (bits > 0 && codingLine[a0] < columns);
- }
- buf = black ? (ret ^ 0xff) : ret;
- return buf;
-}
-
-short CCITTFaxStream::getTwoDimCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(7);
- p = &twoDimTab1[code];
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 1; n <= 7; ++n) {
- code = lookBits(n);
- if (n < 7) {
- code <<= 7 - n;
- }
- p = &twoDimTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad two dim code (%04x) in CCITTFax stream", code);
- return EOF;
-}
-
-short CCITTFaxStream::getWhiteCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(12);
- if ((code >> 5) == 0) {
- p = &whiteTab1[code];
- } else {
- p = &whiteTab2[code >> 3];
- }
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 1; n <= 9; ++n) {
- code = lookBits(n);
- if (n < 9) {
- code <<= 9 - n;
- }
- p = &whiteTab2[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- for (n = 11; n <= 12; ++n) {
- code = lookBits(n);
- if (n < 12) {
- code <<= 12 - n;
- }
- p = &whiteTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad white code (%04x) in CCITTFax stream", code);
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- eatBits(1);
- return 1;
-}
-
-short CCITTFaxStream::getBlackCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(13);
- if ((code >> 7) == 0) {
- p = &blackTab1[code];
- } else if ((code >> 9) == 0) {
- p = &blackTab2[(code >> 1) - 64];
- } else {
- p = &blackTab3[code >> 7];
- }
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 2; n <= 6; ++n) {
- code = lookBits(n);
- if (n < 6) {
- code <<= 6 - n;
- }
- p = &blackTab3[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- for (n = 7; n <= 12; ++n) {
- code = lookBits(n);
- if (n < 12) {
- code <<= 12 - n;
- }
- if (code >= 64) {
- p = &blackTab2[code - 64];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- for (n = 10; n <= 13; ++n) {
- code = lookBits(n);
- if (n < 13) {
- code <<= 13 - n;
- }
- p = &blackTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad black code (%04x) in CCITTFax stream", code);
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- eatBits(1);
- return 1;
-}
-
-short CCITTFaxStream::lookBits(int n) {
- int c;
-
- while (inputBits < n) {
- if ((c = str->getChar()) == EOF) {
- if (inputBits == 0) {
- return EOF;
- }
- // near the end of the stream, the caller may ask for more bits
- // than are available, but there may still be a valid code in
- // however many bits are available -- we need to return correct
- // data in this case
- return (inputBuf << (n - inputBits)) & (0xffff >> (16 - n));
- }
- inputBuf = (inputBuf << 8) + c;
- inputBits += 8;
- }
- return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
-}
-#else // secfix
-CCITTFaxStream::CCITTFaxStream(Stream *strA, int encodingA, GBool endOfLineA,
- GBool byteAlignA, int columnsA, int rowsA,
- GBool endOfBlockA, GBool blackA):
- FilterStream(strA) {
- encoding = encodingA;
- endOfLine = endOfLineA;
- byteAlign = byteAlignA;
- columns = columnsA;
- if (columns < 1) {
- columns = 1;
- } else if (columns > (INT_MAX - 2)/sizeof(int)) {
- columns = (INT_MAX - 2)/sizeof(int);
- }
- rows = rowsA;
- endOfBlock = endOfBlockA;
- black = blackA;
- // 0 <= codingLine[0] < codingLine[1] < ... < codingLine[n] = columns
- // ---> max codingLine size = columns + 1
- // refLine has one extra guard entry at the end
- // ---> max refLine size = columns + 2
- codingLine = (int *)gmalloc((columns + 1) * sizeof(int));
- refLine = (int *)gmalloc((columns + 2) * sizeof(int));
-
- eof = gFalse;
- row = 0;
- nextLine2D = encoding < 0;
- inputBits = 0;
- codingLine[0] = columns;
- a0i = 0;
- outputBits = 0;
-
- buf = EOF;
-}
-
-CCITTFaxStream::~CCITTFaxStream() {
- delete str;
- gfree(refLine);
- gfree(codingLine);
-}
-
-void CCITTFaxStream::reset() {
- short code1;
-
- str->reset();
- eof = gFalse;
- row = 0;
- nextLine2D = encoding < 0;
- inputBits = 0;
- codingLine[0] = columns;
- a0i = 0;
- outputBits = 0;
- buf = EOF;
-
- // skip any initial zero bits and end-of-line marker, and get the 2D
- // encoding tag
- while ((code1 = lookBits(12)) == 0) {
- eatBits(1);
- }
- if (code1 == 0x001) {
- eatBits(12);
- }
- if (encoding > 0) {
- nextLine2D = !lookBits(1);
- eatBits(1);
- }
-}
-
-inline void CCITTFaxStream::addPixels(int a1, int blackPixels) {
- if (a1 > codingLine[a0i]) {
- if (a1 > columns) {
- error(getPos(), "CCITTFax row is wrong length (%d)", a1);
- err = gTrue;
- a1 = columns;
- }
- if ((a0i & 1) ^ blackPixels) {
- ++a0i;
- }
- codingLine[a0i] = a1;
- }
-}
-
-inline void CCITTFaxStream::addPixelsNeg(int a1, int blackPixels) {
- if (a1 > codingLine[a0i]) {
- if (a1 > columns) {
- error(getPos(), "CCITTFax row is wrong length (%d)", a1);
- err = gTrue;
- a1 = columns;
- }
- if ((a0i & 1) ^ blackPixels) {
- ++a0i;
- }
- codingLine[a0i] = a1;
- } else if (a1 < codingLine[a0i]) {
- if (a1 < 0) {
- error(getPos(), "Invalid CCITTFax code");
- err = gTrue;
- a1 = 0;
- }
- while (a0i > 0 && a1 <= codingLine[a0i - 1]) {
- --a0i;
- }
- codingLine[a0i] = a1;
- }
-}
-
-int CCITTFaxStream::lookChar() {
- short code1, code2, code3;
- int b1i, blackPixels, i, bits;
- GBool gotEOL;
-
- if (buf != EOF) {
- return buf;
- }
-
- // read the next row
- if (outputBits == 0) {
-
- // if at eof just return EOF
- if (eof) {
- return EOF;
- }
-
- err = gFalse;
-
- // 2-D encoding
- if (nextLine2D) {
- for (i = 0; codingLine[i] < columns; ++i) {
- refLine[i] = codingLine[i];
- }
- refLine[i++] = columns;
- refLine[i] = columns;
- codingLine[0] = 0;
- a0i = 0;
- b1i = 0;
- blackPixels = 0;
- // invariant:
- // refLine[b1i-1] <= codingLine[a0i] < refLine[b1i] < refLine[b1i+1]
- // <= columns
- // exception at left edge:
- // codingLine[a0i = 0] = refLine[b1i = 0] = 0 is possible
- // exception at right edge:
- // refLine[b1i] = refLine[b1i+1] = columns is possible
- while (codingLine[a0i] < columns) {
- code1 = getTwoDimCode();
- switch (code1) {
- case twoDimPass:
- addPixels(refLine[b1i + 1], blackPixels);
- if (refLine[b1i + 1] < columns) {
- b1i += 2;
- }
- break;
- case twoDimHoriz:
- code1 = code2 = 0;
- if (blackPixels) {
- do {
- code1 += code3 = getBlackCode();
- } while (code3 >= 64);
- do {
- code2 += code3 = getWhiteCode();
- } while (code3 >= 64);
- } else {
- do {
- code1 += code3 = getWhiteCode();
- } while (code3 >= 64);
- do {
- code2 += code3 = getBlackCode();
- } while (code3 >= 64);
- }
- addPixels(codingLine[a0i] + code1, blackPixels);
- if (codingLine[a0i] < columns) {
- addPixels(codingLine[a0i] + code2, blackPixels ^ 1);
- }
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- break;
- case twoDimVertR3:
- addPixels(refLine[b1i] + 3, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- ++b1i;
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVertR2:
- addPixels(refLine[b1i] + 2, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- ++b1i;
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVertR1:
- addPixels(refLine[b1i] + 1, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- ++b1i;
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVert0:
- addPixels(refLine[b1i], blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- ++b1i;
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVertL3:
- addPixelsNeg(refLine[b1i] - 3, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- if (b1i > 0) {
- --b1i;
- } else {
- ++b1i;
- }
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVertL2:
- addPixelsNeg(refLine[b1i] - 2, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- if (b1i > 0) {
- --b1i;
- } else {
- ++b1i;
- }
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case twoDimVertL1:
- addPixelsNeg(refLine[b1i] - 1, blackPixels);
- blackPixels ^= 1;
- if (codingLine[a0i] < columns) {
- if (b1i > 0) {
- --b1i;
- } else {
- ++b1i;
- }
- while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
- b1i += 2;
- }
- }
- break;
- case EOF:
- addPixels(columns, 0);
- eof = gTrue;
- break;
- default:
- error(getPos(), "Bad 2D code %04x in CCITTFax stream", code1);
- addPixels(columns, 0);
- err = gTrue;
- break;
- }
- }
-
- // 1-D encoding
- } else {
- codingLine[0] = 0;
- a0i = 0;
- blackPixels = 0;
- while (codingLine[a0i] < columns) {
- code1 = 0;
- if (blackPixels) {
- do {
- code1 += code3 = getBlackCode();
- } while (code3 >= 64);
- } else {
- do {
- code1 += code3 = getWhiteCode();
- } while (code3 >= 64);
- }
- addPixels(codingLine[a0i] + code1, blackPixels);
- blackPixels ^= 1;
- }
- }
-
- // byte-align the row
- if (byteAlign) {
- inputBits &= ~7;
- }
-
- // check for end-of-line marker, skipping over any extra zero bits
- gotEOL = gFalse;
- if (!endOfBlock && row == rows - 1) {
- eof = gTrue;
- } else {
- code1 = lookBits(12);
- while (code1 == 0) {
- eatBits(1);
- code1 = lookBits(12);
- }
- if (code1 == 0x001) {
- eatBits(12);
- gotEOL = gTrue;
- } else if (code1 == EOF) {
- eof = gTrue;
- }
- }
-
- // get 2D encoding tag
- if (!eof && encoding > 0) {
- nextLine2D = !lookBits(1);
- eatBits(1);
- }
-
- // check for end-of-block marker
- if (endOfBlock && gotEOL) {
- code1 = lookBits(12);
- if (code1 == 0x001) {
- eatBits(12);
- if (encoding > 0) {
- lookBits(1);
- eatBits(1);
- }
- if (encoding >= 0) {
- for (i = 0; i < 4; ++i) {
- code1 = lookBits(12);
- if (code1 != 0x001) {
- error(getPos(), "Bad RTC code in CCITTFax stream");
- }
- eatBits(12);
- if (encoding > 0) {
- lookBits(1);
- eatBits(1);
- }
- }
- }
- eof = gTrue;
- }
-
- // look for an end-of-line marker after an error -- we only do
- // this if we know the stream contains end-of-line markers because
- // the "just plow on" technique tends to work better otherwise
- } else if (err && endOfLine) {
- while (1) {
- code1 = lookBits(13);
- if (code1 == EOF) {
- eof = gTrue;
- return EOF;
- }
- if ((code1 >> 1) == 0x001) {
- break;
- }
- eatBits(1);
- }
- eatBits(12);
- if (encoding > 0) {
- eatBits(1);
- nextLine2D = !(code1 & 1);
- }
- }
-
- // set up for output
- if (codingLine[0] > 0) {
- outputBits = codingLine[a0i = 0];
- } else {
- outputBits = codingLine[a0i = 1];
- }
-
- ++row;
- }
-
- // get a byte
- if (outputBits >= 8) {
- buf = (a0i & 1) ? 0x00 : 0xff;
- outputBits -= 8;
- if (outputBits == 0 && codingLine[a0i] < columns) {
- ++a0i;
- outputBits = codingLine[a0i] - codingLine[a0i - 1];
- }
- } else {
- bits = 8;
- buf = 0;
- do {
- if (outputBits > bits) {
- buf <<= bits;
- if (!(a0i & 1)) {
- buf |= 0xff >> (8 - bits);
- }
- outputBits -= bits;
- bits = 0;
- } else {
- buf <<= outputBits;
- if (!(a0i & 1)) {
- buf |= 0xff >> (8 - outputBits);
- }
- bits -= outputBits;
- outputBits = 0;
- if (codingLine[a0i] < columns) {
- ++a0i;
- outputBits = codingLine[a0i] - codingLine[a0i - 1];
- } else if (bits > 0) {
- buf <<= bits;
- bits = 0;
- }
- }
- } while (bits);
- }
- if (black) {
- buf ^= 0xff;
- }
- return buf;
-}
-
-short CCITTFaxStream::getTwoDimCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(7);
- p = &twoDimTab1[code];
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 1; n <= 7; ++n) {
- code = lookBits(n);
- if (n < 7) {
- code <<= 7 - n;
- }
- p = &twoDimTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad two dim code (%04x) in CCITTFax stream", code);
- return EOF;
-}
-
-short CCITTFaxStream::getWhiteCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(12);
- if (code == EOF) {
- return 1;
- }
- if ((code >> 5) == 0) {
- p = &whiteTab1[code];
- } else {
- p = &whiteTab2[code >> 3];
- }
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 1; n <= 9; ++n) {
- code = lookBits(n);
- if (code == EOF) {
- return 1;
- }
- if (n < 9) {
- code <<= 9 - n;
- }
- p = &whiteTab2[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- for (n = 11; n <= 12; ++n) {
- code = lookBits(n);
- if (code == EOF) {
- return 1;
- }
- if (n < 12) {
- code <<= 12 - n;
- }
- p = &whiteTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad white code (%04x) in CCITTFax stream", code);
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- eatBits(1);
- return 1;
-}
-
-short CCITTFaxStream::getBlackCode() {
- short code;
- CCITTCode *p;
- int n;
-
- code = 0; // make gcc happy
- if (endOfBlock) {
- code = lookBits(13);
- if (code == EOF) {
- return 1;
- }
- if ((code >> 7) == 0) {
- p = &blackTab1[code];
- } else if ((code >> 9) == 0 && (code >> 7) != 0) {
- p = &blackTab2[(code >> 1) - 64];
- } else {
- p = &blackTab3[code >> 7];
- }
- if (p->bits > 0) {
- eatBits(p->bits);
- return p->n;
- }
- } else {
- for (n = 2; n <= 6; ++n) {
- code = lookBits(n);
- if (code == EOF) {
- return 1;
- }
- if (n < 6) {
- code <<= 6 - n;
- }
- p = &blackTab3[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- for (n = 7; n <= 12; ++n) {
- code = lookBits(n);
- if (code == EOF) {
- return 1;
- }
- if (n < 12) {
- code <<= 12 - n;
- }
- if (code >= 64) {
- p = &blackTab2[code - 64];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- for (n = 10; n <= 13; ++n) {
- code = lookBits(n);
- if (code == EOF) {
- return 1;
- }
- if (n < 13) {
- code <<= 13 - n;
- }
- p = &blackTab1[code];
- if (p->bits == n) {
- eatBits(n);
- return p->n;
- }
- }
- }
- error(getPos(), "Bad black code (%04x) in CCITTFax stream", code);
- // eat a bit and return a positive number so that the caller doesn't
- // go into an infinite loop
- eatBits(1);
- return 1;
-}
-
-short CCITTFaxStream::lookBits(int n) {
- int c;
-
- while (inputBits < n) {
- if ((c = str->getChar()) == EOF) {
- if (inputBits == 0) {
- return EOF;
- }
- // near the end of the stream, the caller may ask for more bits
- // than are available, but there may still be a valid code in
- // however many bits are available -- we need to return correct
- // data in this case
- return (inputBuf << (n - inputBits)) & (0xffff >> (16 - n));
- }
- inputBuf = (inputBuf << 8) + c;
- inputBits += 8;
- }
- return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
-}
-
-#endif
-
-GString *CCITTFaxStream::getPSFilter(const char *indent) {
- GString *s;
- char s1[50];
-
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("<< ");
- if (encoding != 0) {
- sprintf(s1, "/K %d ", encoding);
- s->append(s1);
- }
- if (endOfLine) {
- s->append("/EndOfLine true ");
- }
- if (byteAlign) {
- s->append("/EncodedByteAlign true ");
- }
- sprintf(s1, "/Columns %d ", columns);
- s->append(s1);
- if (rows != 0) {
- sprintf(s1, "/Rows %d ", rows);
- s->append(s1);
- }
- if (!endOfBlock) {
- s->append("/EndOfBlock false ");
- }
- if (black) {
- s->append("/BlackIs1 true ");
- }
- s->append(">> /CCITTFaxDecode filter\n");
- return s;
-}
-
-GBool CCITTFaxStream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-//------------------------------------------------------------------------
-// DCTStream
-//------------------------------------------------------------------------
-
-// IDCT constants (20.12 fixed point format)
-#define dctCos1 4017 // cos(pi/16)
-#define dctSin1 799 // sin(pi/16)
-#define dctCos3 3406 // cos(3*pi/16)
-#define dctSin3 2276 // sin(3*pi/16)
-#define dctCos6 1567 // cos(6*pi/16)
-#define dctSin6 3784 // sin(6*pi/16)
-#define dctSqrt2 5793 // sqrt(2)
-#define dctSqrt1d2 2896 // sqrt(2) / 2
-
-// color conversion parameters (16.16 fixed point format)
-#define dctCrToR 91881 // 1.4020
-#define dctCbToG -22553 // -0.3441363
-#define dctCrToG -46802 // -0.71413636
-#define dctCbToB 116130 // 1.772
-
-// clip [-256,511] --> [0,255]
-#define dctClipOffset 256
-static Guchar dctClip[768];
-static int dctClipInit = 0;
-
-// zig zag decode map
-static int dctZigZag[64] = {
- 0,
- 1, 8,
- 16, 9, 2,
- 3, 10, 17, 24,
- 32, 25, 18, 11, 4,
- 5, 12, 19, 26, 33, 40,
- 48, 41, 34, 27, 20, 13, 6,
- 7, 14, 21, 28, 35, 42, 49, 56,
- 57, 50, 43, 36, 29, 22, 15,
- 23, 30, 37, 44, 51, 58,
- 59, 52, 45, 38, 31,
- 39, 46, 53, 60,
- 61, 54, 47,
- 55, 62,
- 63
-};
-
-DCTStream::DCTStream(Stream *strA):
- FilterStream(strA) {
- int i, j;
-
- progressive = interleaved = gFalse;
- width = height = 0;
- mcuWidth = mcuHeight = 0;
- numComps = 0;
- comp = 0;
- x = y = dy = 0;
- for (i = 0; i < 4; ++i) {
- for (j = 0; j < 32; ++j) {
- rowBuf[i][j] = NULL;
- }
- frameBuf[i] = NULL;
- }
-
- if (!dctClipInit) {
- for (i = -256; i < 0; ++i)
- dctClip[dctClipOffset + i] = 0;
- for (i = 0; i < 256; ++i)
- dctClip[dctClipOffset + i] = i;
- for (i = 256; i < 512; ++i)
- dctClip[dctClipOffset + i] = 255;
- dctClipInit = 1;
- }
-}
-
-DCTStream::~DCTStream() {
- int i, j;
-
- delete str;
- if (progressive || !interleaved) {
- for (i = 0; i < numComps; ++i) {
- gfree(frameBuf[i]);
- }
- } else {
- for (i = 0; i < numComps; ++i) {
- for (j = 0; j < mcuHeight; ++j) {
- gfree(rowBuf[i][j]);
- }
- }
- }
-}
-
-void DCTStream::reset() {
- int minHSample, minVSample;
- int i, j;
-
- str->reset();
-
- progressive = interleaved = gFalse;
- width = height = 0;
- numComps = 0;
- numQuantTables = 0;
- numDCHuffTables = 0;
- numACHuffTables = 0;
- colorXform = 0;
- gotAdobeMarker = gFalse;
- restartInterval = 0;
-
- if (!readHeader()) {
- y = height;
- return;
- }
-
- // compute MCU size
- mcuWidth = minHSample = compInfo[0].hSample;
- mcuHeight = minVSample = compInfo[0].vSample;
- for (i = 1; i < numComps; ++i) {
- if (compInfo[i].hSample < minHSample)
- minHSample = compInfo[i].hSample;
- if (compInfo[i].vSample < minVSample)
- minVSample = compInfo[i].vSample;
- if (compInfo[i].hSample > mcuWidth)
- mcuWidth = compInfo[i].hSample;
- if (compInfo[i].vSample > mcuHeight)
- mcuHeight = compInfo[i].vSample;
- }
- for (i = 0; i < numComps; ++i) {
- compInfo[i].hSample /= minHSample;
- compInfo[i].vSample /= minVSample;
- }
- mcuWidth = (mcuWidth / minHSample) * 8;
- mcuHeight = (mcuHeight / minVSample) * 8;
-
- // figure out color transform
- if (!gotAdobeMarker && numComps == 3) {
- if (compInfo[0].id == 1 && compInfo[1].id == 2 && compInfo[2].id == 3) {
- colorXform = 1;
- }
- }
-
- if (progressive || !interleaved) {
-
- // allocate a buffer for the whole image
- bufWidth = ((width + mcuWidth - 1) / mcuWidth) * mcuWidth;
- bufHeight = ((height + mcuHeight - 1) / mcuHeight) * mcuHeight;
- if (bufWidth <= 0 || bufHeight <= 0 ||
- bufWidth > INT_MAX / bufWidth / (int)sizeof(int)) {
- error(getPos(), "Invalid image size in DCT stream");
- y = height;
- return;
- }
- for (i = 0; i < numComps; ++i) {
- frameBuf[i] = (int *)gmalloc(bufWidth * bufHeight * sizeof(int));
- memset(frameBuf[i], 0, bufWidth * bufHeight * sizeof(int));
- }
-
- // read the image data
- do {
- restartMarker = 0xd0;
- restart();
- readScan();
- } while (readHeader());
-
- // decode
- decodeImage();
-
- // initialize counters
- comp = 0;
- x = 0;
- y = 0;
-
- } else {
-
- // allocate a buffer for one row of MCUs
- bufWidth = ((width + mcuWidth - 1) / mcuWidth) * mcuWidth;
- for (i = 0; i < numComps; ++i) {
- for (j = 0; j < mcuHeight; ++j) {
- rowBuf[i][j] = (Guchar *)gmalloc(bufWidth * sizeof(Guchar));
- }
- }
-
- // initialize counters
- comp = 0;
- x = 0;
- y = 0;
- dy = mcuHeight;
-
- restartMarker = 0xd0;
- restart();
- }
-}
-
-int DCTStream::getChar() {
- int c;
-
- if (y >= height) {
- return EOF;
- }
- if (progressive || !interleaved) {
- c = frameBuf[comp][y * bufWidth + x];
- if (++comp == numComps) {
- comp = 0;
- if (++x == width) {
- x = 0;
- ++y;
- }
- }
- } else {
- if (dy >= mcuHeight) {
- if (!readMCURow()) {
- y = height;
- return EOF;
- }
- comp = 0;
- x = 0;
- dy = 0;
- }
- c = rowBuf[comp][dy][x];
- if (++comp == numComps) {
- comp = 0;
- if (++x == width) {
- x = 0;
- ++y;
- ++dy;
- if (y == height) {
- readTrailer();
- }
- }
- }
- }
- return c;
-}
-
-int DCTStream::lookChar() {
- if (y >= height) {
- return EOF;
- }
- if (progressive || !interleaved) {
- return frameBuf[comp][y * bufWidth + x];
- } else {
- if (dy >= mcuHeight) {
- if (!readMCURow()) {
- y = height;
- return EOF;
- }
- comp = 0;
- x = 0;
- dy = 0;
- }
- return rowBuf[comp][dy][x];
- }
-}
-
-void DCTStream::restart() {
- int i;
-
- inputBits = 0;
- restartCtr = restartInterval;
- for (i = 0; i < numComps; ++i) {
- compInfo[i].prevDC = 0;
- }
- eobRun = 0;
-}
-
-// Read one row of MCUs from a sequential JPEG stream.
-GBool DCTStream::readMCURow() {
- int data1[64];
- Guchar data2[64];
- Guchar *p1, *p2;
- int pY, pCb, pCr, pR, pG, pB;
- int h, v, horiz, vert, hSub, vSub;
- int x1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
- int c;
-
- for (x1 = 0; x1 < width; x1 += mcuWidth) {
-
- // deal with restart marker
- if (restartInterval > 0 && restartCtr == 0) {
- c = readMarker();
- if (c != restartMarker) {
- error(getPos(), "Bad DCT data: incorrect restart marker");
- return gFalse;
- }
- if (++restartMarker == 0xd8)
- restartMarker = 0xd0;
- restart();
- }
-
- // read one MCU
- for (cc = 0; cc < numComps; ++cc) {
- h = compInfo[cc].hSample;
- v = compInfo[cc].vSample;
- horiz = mcuWidth / h;
- vert = mcuHeight / v;
- hSub = horiz / 8;
- vSub = vert / 8;
- for (y2 = 0; y2 < mcuHeight; y2 += vert) {
- for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
- if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]],
- &acHuffTables[scanInfo.acHuffTable[cc]],
- &compInfo[cc].prevDC,
- data1)) {
- return gFalse;
- }
- transformDataUnit(quantTables[compInfo[cc].quantTable],
- data1, data2);
- if (hSub == 1 && vSub == 1) {
- for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
- p1 = &rowBuf[cc][y2+y3][x1+x2];
- p1[0] = data2[i];
- p1[1] = data2[i+1];
- p1[2] = data2[i+2];
- p1[3] = data2[i+3];
- p1[4] = data2[i+4];
- p1[5] = data2[i+5];
- p1[6] = data2[i+6];
- p1[7] = data2[i+7];
- }
- } else if (hSub == 2 && vSub == 2) {
- for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
- p1 = &rowBuf[cc][y2+y3][x1+x2];
- p2 = &rowBuf[cc][y2+y3+1][x1+x2];
- p1[0] = p1[1] = p2[0] = p2[1] = data2[i];
- p1[2] = p1[3] = p2[2] = p2[3] = data2[i+1];
- p1[4] = p1[5] = p2[4] = p2[5] = data2[i+2];
- p1[6] = p1[7] = p2[6] = p2[7] = data2[i+3];
- p1[8] = p1[9] = p2[8] = p2[9] = data2[i+4];
- p1[10] = p1[11] = p2[10] = p2[11] = data2[i+5];
- p1[12] = p1[13] = p2[12] = p2[13] = data2[i+6];
- p1[14] = p1[15] = p2[14] = p2[15] = data2[i+7];
- }
- } else {
- i = 0;
- for (y3 = 0, y4 = 0; y3 < 8; ++y3, y4 += vSub) {
- for (x3 = 0, x4 = 0; x3 < 8; ++x3, x4 += hSub) {
- for (y5 = 0; y5 < vSub; ++y5)
- for (x5 = 0; x5 < hSub; ++x5)
- rowBuf[cc][y2+y4+y5][x1+x2+x4+x5] = data2[i];
- ++i;
- }
- }
- }
- }
- }
- }
- --restartCtr;
-
- // color space conversion
- if (colorXform) {
- // convert YCbCr to RGB
- if (numComps == 3) {
- for (y2 = 0; y2 < mcuHeight; ++y2) {
- for (x2 = 0; x2 < mcuWidth; ++x2) {
- pY = rowBuf[0][y2][x1+x2];
- pCb = rowBuf[1][y2][x1+x2] - 128;
- pCr = rowBuf[2][y2][x1+x2] - 128;
- pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
- rowBuf[0][y2][x1+x2] = dctClip[dctClipOffset + pR];
- pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32768) >> 16;
- rowBuf[1][y2][x1+x2] = dctClip[dctClipOffset + pG];
- pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
- rowBuf[2][y2][x1+x2] = dctClip[dctClipOffset + pB];
- }
- }
- // convert YCbCrK to CMYK (K is passed through unchanged)
- } else if (numComps == 4) {
- for (y2 = 0; y2 < mcuHeight; ++y2) {
- for (x2 = 0; x2 < mcuWidth; ++x2) {
- pY = rowBuf[0][y2][x1+x2];
- pCb = rowBuf[1][y2][x1+x2] - 128;
- pCr = rowBuf[2][y2][x1+x2] - 128;
- pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
- rowBuf[0][y2][x1+x2] = 255 - dctClip[dctClipOffset + pR];
- pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32768) >> 16;
- rowBuf[1][y2][x1+x2] = 255 - dctClip[dctClipOffset + pG];
- pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
- rowBuf[2][y2][x1+x2] = 255 - dctClip[dctClipOffset + pB];
- }
- }
- }
- }
- }
- return gTrue;
-}
-
-// Read one scan from a progressive or non-interleaved JPEG stream.
-void DCTStream::readScan() {
- int data[64];
- int x1, y1, dy1, x2, y2, y3, cc, i;
- int h, v, horiz, vert, hSub, vSub;
- int *p1;
- int c;
-
- if (scanInfo.numComps == 1) {
- for (cc = 0; cc < numComps; ++cc) {
- if (scanInfo.comp[cc]) {
- break;
- }
- }
- dy1 = mcuHeight / compInfo[cc].vSample;
- } else {
- dy1 = mcuHeight;
- }
-
- for (y1 = 0; y1 < bufHeight; y1 += dy1) {
- for (x1 = 0; x1 < bufWidth; x1 += mcuWidth) {
-
- // deal with restart marker
- if (restartInterval > 0 && restartCtr == 0) {
- c = readMarker();
- if (c != restartMarker) {
- error(getPos(), "Bad DCT data: incorrect restart marker");
- return;
- }
- if (++restartMarker == 0xd8) {
- restartMarker = 0xd0;
- }
- restart();
- }
-
- // read one MCU
- for (cc = 0; cc < numComps; ++cc) {
- if (!scanInfo.comp[cc]) {
- continue;
- }
-
- h = compInfo[cc].hSample;
- v = compInfo[cc].vSample;
- horiz = mcuWidth / h;
- vert = mcuHeight / v;
- hSub = horiz / 8;
- vSub = vert / 8;
- for (y2 = 0; y2 < dy1; y2 += vert) {
- for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
-
- // pull out the current values
- p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
- for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
- data[i] = p1[0];
- data[i+1] = p1[1];
- data[i+2] = p1[2];
- data[i+3] = p1[3];
- data[i+4] = p1[4];
- data[i+5] = p1[5];
- data[i+6] = p1[6];
- data[i+7] = p1[7];
- p1 += bufWidth * vSub;
- }
-
- // read one data unit
- if (progressive) {
- if (!readProgressiveDataUnit(
- &dcHuffTables[scanInfo.dcHuffTable[cc]],
- &acHuffTables[scanInfo.acHuffTable[cc]],
- &compInfo[cc].prevDC,
- data)) {
- return;
- }
- } else {
- if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]],
- &acHuffTables[scanInfo.acHuffTable[cc]],
- &compInfo[cc].prevDC,
- data)) {
- return;
- }
- }
-
- // add the data unit into frameBuf
- p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
- for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
- p1[0] = data[i];
- p1[1] = data[i+1];
- p1[2] = data[i+2];
- p1[3] = data[i+3];
- p1[4] = data[i+4];
- p1[5] = data[i+5];
- p1[6] = data[i+6];
- p1[7] = data[i+7];
- p1 += bufWidth * vSub;
- }
- }
- }
- }
- --restartCtr;
- }
- }
-}
-
-// Read one data unit from a sequential JPEG stream.
-GBool DCTStream::readDataUnit(DCTHuffTable *dcHuffTable,
- DCTHuffTable *acHuffTable,
- int *prevDC, int data[64]) {
- int run, size, amp;
- int c;
- int i, j;
-
- if ((size = readHuffSym(dcHuffTable)) == 9999) {
- return gFalse;
- }
- if (size > 0) {
- if ((amp = readAmp(size)) == 9999) {
- return gFalse;
- }
- } else {
- amp = 0;
- }
- data[0] = *prevDC += amp;
- for (i = 1; i < 64; ++i) {
- data[i] = 0;
- }
- i = 1;
- while (i < 64) {
- run = 0;
- while ((c = readHuffSym(acHuffTable)) == 0xf0 && run < 0x30) {
- run += 0x10;
- }
- if (c == 9999) {
- return gFalse;
- }
- if (c == 0x00) {
- break;
- } else {
- run += (c >> 4) & 0x0f;
- size = c & 0x0f;
- amp = readAmp(size);
- if (amp == 9999) {
- return gFalse;
- }
- i += run;
- j = dctZigZag[i++];
- data[j] = amp;
- }
- }
- return gTrue;
-}
-
-// Read one data unit from a sequential JPEG stream.
-GBool DCTStream::readProgressiveDataUnit(DCTHuffTable *dcHuffTable,
- DCTHuffTable *acHuffTable,
- int *prevDC, int data[64]) {
- int run, size, amp, bit, c;
- int i, j, k;
-
- // get the DC coefficient
- i = scanInfo.firstCoeff;
- if (i == 0) {
- if (scanInfo.ah == 0) {
- if ((size = readHuffSym(dcHuffTable)) == 9999) {
- return gFalse;
- }
- if (size > 0) {
- if ((amp = readAmp(size)) == 9999) {
- return gFalse;
- }
- } else {
- amp = 0;
- }
- data[0] += (*prevDC += amp) << scanInfo.al;
- } else {
- if ((bit = readBit()) == 9999) {
- return gFalse;
- }
- data[0] += bit << scanInfo.al;
- }
- ++i;
- }
- if (scanInfo.lastCoeff == 0) {
- return gTrue;
- }
-
- // check for an EOB run
- if (eobRun > 0) {
- while (i <= scanInfo.lastCoeff) {
- j = dctZigZag[i++];
- if (data[j] != 0) {
- if ((bit = readBit()) == EOF) {
- return gFalse;
- }
- if (bit) {
- data[j] += 1 << scanInfo.al;
- }
- }
- }
- --eobRun;
- return gTrue;
- }
-
- // read the AC coefficients
- while (i <= scanInfo.lastCoeff) {
- if ((c = readHuffSym(acHuffTable)) == 9999) {
- return gFalse;
- }
-
- // ZRL
- if (c == 0xf0) {
- k = 0;
- while (k < 16) {
- j = dctZigZag[i++];
- if (data[j] == 0) {
- ++k;
- } else {
- if ((bit = readBit()) == EOF) {
- return gFalse;
- }
- if (bit) {
- data[j] += 1 << scanInfo.al;
- }
- }
- }
-
- // EOB run
- } else if ((c & 0x0f) == 0x00) {
- j = c >> 4;
- eobRun = 0;
- for (k = 0; k < j; ++k) {
- if ((bit = readBit()) == EOF) {
- return 9999;
- }
- eobRun = (eobRun << 1) | bit;
- }
- eobRun += 1 << j;
- while (i <= scanInfo.lastCoeff) {
- j = dctZigZag[i++];
- if (data[j] != 0) {
- if ((bit = readBit()) == EOF) {
- return gFalse;
- }
- if (bit) {
- data[j] += 1 << scanInfo.al;
- }
- }
- }
- --eobRun;
- break;
-
- // zero run and one AC coefficient
- } else {
- run = (c >> 4) & 0x0f;
- size = c & 0x0f;
- if ((amp = readAmp(size)) == 9999) {
- return gFalse;
- }
- k = 0;
- do {
- j = dctZigZag[i++];
- while (data[j] != 0) {
- if ((bit = readBit()) == EOF) {
- return gFalse;
- }
- if (bit) {
- data[j] += 1 << scanInfo.al;
- }
- j = dctZigZag[i++];
- }
- ++k;
- } while (k <= run);
- data[j] = amp << scanInfo.al;
- }
- }
-
- return gTrue;
-}
-
-// Decode a progressive JPEG image.
-void DCTStream::decodeImage() {
- int dataIn[64];
- Guchar dataOut[64];
- Guchar *quantTable;
- int pY, pCb, pCr, pR, pG, pB;
- int x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
- int h, v, horiz, vert, hSub, vSub;
- int *p0, *p1, *p2;
-
- for (y1 = 0; y1 < bufHeight; y1 += mcuHeight) {
- for (x1 = 0; x1 < bufWidth; x1 += mcuWidth) {
- for (cc = 0; cc < numComps; ++cc) {
- quantTable = quantTables[compInfo[cc].quantTable];
- h = compInfo[cc].hSample;
- v = compInfo[cc].vSample;
- horiz = mcuWidth / h;
- vert = mcuHeight / v;
- hSub = horiz / 8;
- vSub = vert / 8;
- for (y2 = 0; y2 < mcuHeight; y2 += vert) {
- for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
-
- // pull out the coded data unit
- p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
- for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
- dataIn[i] = p1[0];
- dataIn[i+1] = p1[1];
- dataIn[i+2] = p1[2];
- dataIn[i+3] = p1[3];
- dataIn[i+4] = p1[4];
- dataIn[i+5] = p1[5];
- dataIn[i+6] = p1[6];
- dataIn[i+7] = p1[7];
- p1 += bufWidth * vSub;
- }
-
- // transform
- transformDataUnit(quantTable, dataIn, dataOut);
-
- // store back into frameBuf, doing replication for
- // subsampled components
- p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
- if (hSub == 1 && vSub == 1) {
- for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
- p1[0] = dataOut[i] & 0xff;
- p1[1] = dataOut[i+1] & 0xff;
- p1[2] = dataOut[i+2] & 0xff;
- p1[3] = dataOut[i+3] & 0xff;
- p1[4] = dataOut[i+4] & 0xff;
- p1[5] = dataOut[i+5] & 0xff;
- p1[6] = dataOut[i+6] & 0xff;
- p1[7] = dataOut[i+7] & 0xff;
- p1 += bufWidth;
- }
- } else if (hSub == 2 && vSub == 2) {
- p2 = p1 + bufWidth;
- for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
- p1[0] = p1[1] = p2[0] = p2[1] = dataOut[i] & 0xff;
- p1[2] = p1[3] = p2[2] = p2[3] = dataOut[i+1] & 0xff;
- p1[4] = p1[5] = p2[4] = p2[5] = dataOut[i+2] & 0xff;
- p1[6] = p1[7] = p2[6] = p2[7] = dataOut[i+3] & 0xff;
- p1[8] = p1[9] = p2[8] = p2[9] = dataOut[i+4] & 0xff;
- p1[10] = p1[11] = p2[10] = p2[11] = dataOut[i+5] & 0xff;
- p1[12] = p1[13] = p2[12] = p2[13] = dataOut[i+6] & 0xff;
- p1[14] = p1[15] = p2[14] = p2[15] = dataOut[i+7] & 0xff;
- p1 += bufWidth * 2;
- p2 += bufWidth * 2;
- }
- } else {
- i = 0;
- for (y3 = 0, y4 = 0; y3 < 8; ++y3, y4 += vSub) {
- for (x3 = 0, x4 = 0; x3 < 8; ++x3, x4 += hSub) {
- p2 = p1 + x4;
- for (y5 = 0; y5 < vSub; ++y5) {
- for (x5 = 0; x5 < hSub; ++x5) {
- p2[x5] = dataOut[i] & 0xff;
- }
- p2 += bufWidth;
- }
- ++i;
- }
- p1 += bufWidth * vSub;
- }
- }
- }
- }
- }
-
- // color space conversion
- if (colorXform) {
- // convert YCbCr to RGB
- if (numComps == 3) {
- for (y2 = 0; y2 < mcuHeight; ++y2) {
- p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
- p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
- p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
- for (x2 = 0; x2 < mcuWidth; ++x2) {
- pY = *p0;
- pCb = *p1 - 128;
- pCr = *p2 - 128;
- pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
- *p0++ = dctClip[dctClipOffset + pR];
- pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr +
- 32768) >> 16;
- *p1++ = dctClip[dctClipOffset + pG];
- pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
- *p2++ = dctClip[dctClipOffset + pB];
- }
- }
- // convert YCbCrK to CMYK (K is passed through unchanged)
- } else if (numComps == 4) {
- for (y2 = 0; y2 < mcuHeight; ++y2) {
- p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
- p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
- p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
- for (x2 = 0; x2 < mcuWidth; ++x2) {
- pY = *p0;
- pCb = *p1 - 128;
- pCr = *p2 - 128;
- pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
- *p0++ = 255 - dctClip[dctClipOffset + pR];
- pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr +
- 32768) >> 16;
- *p1++ = 255 - dctClip[dctClipOffset + pG];
- pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
- *p2++ = 255 - dctClip[dctClipOffset + pB];
- }
- }
- }
- }
- }
- }
-}
-
-// Transform one data unit -- this performs the dequantization and
-// IDCT steps. This IDCT algorithm is taken from:
-// Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
-// "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
-// IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
-// 988-991.
-// The stage numbers mentioned in the comments refer to Figure 1 in this
-// paper.
-void DCTStream::transformDataUnit(Guchar *quantTable,
- int dataIn[64], Guchar dataOut[64]) {
- int v0, v1, v2, v3, v4, v5, v6, v7, t;
- int *p;
- int i;
-
- // dequant
- for (i = 0; i < 64; ++i) {
- dataIn[i] *= quantTable[i];
- }
-
- // inverse DCT on rows
- for (i = 0; i < 64; i += 8) {
- p = dataIn + i;
-
- // check for all-zero AC coefficients
- if (p[1] == 0 && p[2] == 0 && p[3] == 0 &&
- p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] == 0) {
- t = (dctSqrt2 * p[0] + 512) >> 10;
- p[0] = t;
- p[1] = t;
- p[2] = t;
- p[3] = t;
- p[4] = t;
- p[5] = t;
- p[6] = t;
- p[7] = t;
- continue;
- }
-
- // stage 4
- v0 = (dctSqrt2 * p[0] + 128) >> 8;
- v1 = (dctSqrt2 * p[4] + 128) >> 8;
- v2 = p[2];
- v3 = p[6];
- v4 = (dctSqrt1d2 * (p[1] - p[7]) + 128) >> 8;
- v7 = (dctSqrt1d2 * (p[1] + p[7]) + 128) >> 8;
- v5 = p[3] << 4;
- v6 = p[5] << 4;
-
- // stage 3
- t = (v0 - v1+ 1) >> 1;
- v0 = (v0 + v1 + 1) >> 1;
- v1 = t;
- t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
- v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
- v3 = t;
- t = (v4 - v6 + 1) >> 1;
- v4 = (v4 + v6 + 1) >> 1;
- v6 = t;
- t = (v7 + v5 + 1) >> 1;
- v5 = (v7 - v5 + 1) >> 1;
- v7 = t;
-
- // stage 2
- t = (v0 - v3 + 1) >> 1;
- v0 = (v0 + v3 + 1) >> 1;
- v3 = t;
- t = (v1 - v2 + 1) >> 1;
- v1 = (v1 + v2 + 1) >> 1;
- v2 = t;
- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
- v7 = t;
- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
- v6 = t;
-
- // stage 1
- p[0] = v0 + v7;
- p[7] = v0 - v7;
- p[1] = v1 + v6;
- p[6] = v1 - v6;
- p[2] = v2 + v5;
- p[5] = v2 - v5;
- p[3] = v3 + v4;
- p[4] = v3 - v4;
- }
-
- // inverse DCT on columns
- for (i = 0; i < 8; ++i) {
- p = dataIn + i;
-
- // check for all-zero AC coefficients
- if (p[1*8] == 0 && p[2*8] == 0 && p[3*8] == 0 &&
- p[4*8] == 0 && p[5*8] == 0 && p[6*8] == 0 && p[7*8] == 0) {
- t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
- p[0*8] = t;
- p[1*8] = t;
- p[2*8] = t;
- p[3*8] = t;
- p[4*8] = t;
- p[5*8] = t;
- p[6*8] = t;
- p[7*8] = t;
- continue;
- }
-
- // stage 4
- v0 = (dctSqrt2 * p[0*8] + 2048) >> 12;
- v1 = (dctSqrt2 * p[4*8] + 2048) >> 12;
- v2 = p[2*8];
- v3 = p[6*8];
- v4 = (dctSqrt1d2 * (p[1*8] - p[7*8]) + 2048) >> 12;
- v7 = (dctSqrt1d2 * (p[1*8] + p[7*8]) + 2048) >> 12;
- v5 = p[3*8];
- v6 = p[5*8];
-
- // stage 3
- t = (v0 - v1 + 1) >> 1;
- v0 = (v0 + v1 + 1) >> 1;
- v1 = t;
- t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
- v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
- v3 = t;
- t = (v4 - v6 + 1) >> 1;
- v4 = (v4 + v6 + 1) >> 1;
- v6 = t;
- t = (v7 + v5 + 1) >> 1;
- v5 = (v7 - v5 + 1) >> 1;
- v7 = t;
-
- // stage 2
- t = (v0 - v3 + 1) >> 1;
- v0 = (v0 + v3 + 1) >> 1;
- v3 = t;
- t = (v1 - v2 + 1) >> 1;
- v1 = (v1 + v2 + 1) >> 1;
- v2 = t;
- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
- v7 = t;
- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
- v6 = t;
-
- // stage 1
- p[0*8] = v0 + v7;
- p[7*8] = v0 - v7;
- p[1*8] = v1 + v6;
- p[6*8] = v1 - v6;
- p[2*8] = v2 + v5;
- p[5*8] = v2 - v5;
- p[3*8] = v3 + v4;
- p[4*8] = v3 - v4;
- }
-
- // convert to 8-bit integers
- for (i = 0; i < 64; ++i) {
- dataOut[i] = dctClip[dctClipOffset + 128 + ((dataIn[i] + 8) >> 4)];
- }
-}
-
-int DCTStream::readHuffSym(DCTHuffTable *table) {
- Gushort code;
- int bit;
- int codeBits;
-
- code = 0;
- codeBits = 0;
- do {
- // add a bit to the code
- if ((bit = readBit()) == EOF)
- return 9999;
- code = (code << 1) + bit;
- ++codeBits;
-
- // look up code
- if (code - table->firstCode[codeBits] < table->numCodes[codeBits]) {
- code -= table->firstCode[codeBits];
- return table->sym[table->firstSym[codeBits] + code];
- }
- } while (codeBits < 16);
-
- error(getPos(), "Bad Huffman code in DCT stream");
- return 9999;
-}
-
-int DCTStream::readAmp(int size) {
- int amp, bit;
- int bits;
-
- amp = 0;
- for (bits = 0; bits < size; ++bits) {
- if ((bit = readBit()) == EOF)
- return 9999;
- amp = (amp << 1) + bit;
- }
- if (amp < (1 << (size - 1)))
- amp -= (1 << size) - 1;
- return amp;
-}
-
-int DCTStream::readBit() {
- int bit;
- int c, c2;
-
- if (inputBits == 0) {
- if ((c = str->getChar()) == EOF)
- return EOF;
- if (c == 0xff) {
- do {
- c2 = str->getChar();
- } while (c2 == 0xff);
- if (c2 != 0x00) {
- error(getPos(), "Bad DCT data: missing 00 after ff");
- return EOF;
- }
- }
- inputBuf = c;
- inputBits = 8;
- }
- bit = (inputBuf >> (inputBits - 1)) & 1;
- --inputBits;
- return bit;
-}
-
-GBool DCTStream::readHeader() {
- GBool doScan;
- int n;
- int c = 0;
- int i;
-
- // read headers
- doScan = gFalse;
- while (!doScan) {
- c = readMarker();
- switch (c) {
- case 0xc0: // SOF0
- if (!readBaselineSOF()) {
- return gFalse;
- }
- break;
- case 0xc2: // SOF2
- if (!readProgressiveSOF()) {
- return gFalse;
- }
- break;
- case 0xc4: // DHT
- if (!readHuffmanTables()) {
- return gFalse;
- }
- break;
- case 0xd8: // SOI
- break;
- case 0xd9: // EOI
- return gFalse;
- break;
- case 0xda: // SOS
- if (!readScanInfo()) {
- return gFalse;
- }
- doScan = gTrue;
- break;
- case 0xdb: // DQT
- if (!readQuantTables()) {
- return gFalse;
- }
- break;
- case 0xdd: // DRI
- if (!readRestartInterval()) {
- return gFalse;
- }
- break;
- case 0xee: // APP14
- if (!readAdobeMarker()) {
- return gFalse;
- }
- break;
- case EOF:
- error(getPos(), "Bad DCT header");
- return gFalse;
- default:
- // skip APPn / COM / etc.
- if (c >= 0xe0) {
- n = read16() - 2;
- for (i = 0; i < n; ++i) {
- str->getChar();
- }
- } else {
- error(getPos(), "Unknown DCT marker <%02x>", c);
- return gFalse;
- }
- break;
- }
- }
-
- return gTrue;
-}
-
-GBool DCTStream::readBaselineSOF() {
- int length;
- int prec;
- int i;
- int c;
-
- length = read16();
- prec = str->getChar();
- height = read16();
- width = read16();
- numComps = str->getChar();
- if (numComps <= 0 || numComps > 4) {
- numComps = 0;
- error(getPos(), "Bad number of components in DCT stream");
- return gFalse;
- }
- if (prec != 8) {
- error(getPos(), "Bad DCT precision %d", prec);
- return gFalse;
- }
- for (i = 0; i < numComps; ++i) {
- compInfo[i].id = str->getChar();
- c = str->getChar();
- compInfo[i].hSample = (c >> 4) & 0x0f;
- compInfo[i].vSample = c & 0x0f;
- compInfo[i].quantTable = str->getChar();
- }
- progressive = gFalse;
- return gTrue;
-}
-
-GBool DCTStream::readProgressiveSOF() {
- int length;
- int prec;
- int i;
- int c;
-
- length = read16();
- prec = str->getChar();
- height = read16();
- width = read16();
- numComps = str->getChar();
- if (numComps <= 0 || numComps > 4) {
- numComps = 0;
- error(getPos(), "Bad number of components in DCT stream");
- return gFalse;
- }
- if (prec != 8) {
- error(getPos(), "Bad DCT precision %d", prec);
- return gFalse;
- }
- for (i = 0; i < numComps; ++i) {
- compInfo[i].id = str->getChar();
- c = str->getChar();
- compInfo[i].hSample = (c >> 4) & 0x0f;
- compInfo[i].vSample = c & 0x0f;
- compInfo[i].quantTable = str->getChar();
- }
- progressive = gTrue;
- return gTrue;
-}
-
-GBool DCTStream::readScanInfo() {
- int length;
- int id, c;
- int i, j;
-
- length = read16() - 2;
- scanInfo.numComps = str->getChar();
- if (scanInfo.numComps <= 0 || scanInfo.numComps > 4) {
- scanInfo.numComps = 0;
- error(getPos(), "Bad number of components in DCT stream");
- return gFalse;
- }
- --length;
- if (length != 2 * scanInfo.numComps + 3) {
- error(getPos(), "Bad DCT scan info block");
- return gFalse;
- }
- interleaved = scanInfo.numComps == numComps;
- for (j = 0; j < numComps; ++j) {
- scanInfo.comp[j] = gFalse;
- }
- for (i = 0; i < scanInfo.numComps; ++i) {
- id = str->getChar();
- for (j = 0; j < numComps; ++j) {
- if (id == compInfo[j].id) {
- break;
- }
- }
- if (j == numComps) {
- error(getPos(), "Bad DCT component ID in scan info block");
- return gFalse;
- }
- scanInfo.comp[j] = gTrue;
- c = str->getChar();
- scanInfo.dcHuffTable[j] = (c >> 4) & 0x0f;
- scanInfo.acHuffTable[j] = c & 0x0f;
- }
- scanInfo.firstCoeff = str->getChar();
- scanInfo.lastCoeff = str->getChar();
- if (scanInfo.firstCoeff < 0 || scanInfo.lastCoeff > 63 ||
- scanInfo.firstCoeff > scanInfo.lastCoeff) {
- error(getPos(), "Bad DCT coefficient numbers in scan info block");
- return gFalse;
- }
- c = str->getChar();
- scanInfo.ah = (c >> 4) & 0x0f;
- scanInfo.al = c & 0x0f;
- return gTrue;
-}
-
-GBool DCTStream::readQuantTables() {
- int length;
- int i;
- int index;
-
- length = read16() - 2;
- while (length > 0) {
- index = str->getChar();
- if ((index & 0xf0) || index >= 4) {
- error(getPos(), "Bad DCT quantization table");
- return gFalse;
- }
- if (index == numQuantTables)
- numQuantTables = index + 1;
- for (i = 0; i < 64; ++i)
- quantTables[index][dctZigZag[i]] = str->getChar();
- length -= 65;
- }
- return gTrue;
-}
-
-GBool DCTStream::readHuffmanTables() {
- DCTHuffTable *tbl;
- int length;
- int index;
- Gushort code;
- Guchar sym;
- int i;
- int c;
-
- length = read16() - 2;
- while (length > 0) {
- index = str->getChar();
- --length;
- if ((index & ~0x10) >= 4 || (index & ~0x10) < 0) {
- error(getPos(), "Bad DCT Huffman table");
- return gFalse;
- }
- if (index & 0x10) {
- index &= 0x03;
- if (index >= numACHuffTables)
- numACHuffTables = index+1;
- tbl = &acHuffTables[index];
- } else {
- if (index >= numDCHuffTables)
- numDCHuffTables = index+1;
- tbl = &dcHuffTables[index];
- }
- sym = 0;
- code = 0;
- for (i = 1; i <= 16; ++i) {
- c = str->getChar();
- tbl->firstSym[i] = sym;
- tbl->firstCode[i] = code;
- tbl->numCodes[i] = c;
- sym += c;
- code = (code + c) << 1;
- }
- length -= 16;
- for (i = 0; i < sym; ++i)
- tbl->sym[i] = str->getChar();
- length -= sym;
- }
- return gTrue;
-}
-
-GBool DCTStream::readRestartInterval() {
- int length;
-
- length = read16();
- if (length != 4) {
- error(getPos(), "Bad DCT restart interval");
- return gFalse;
- }
- restartInterval = read16();
- return gTrue;
-}
-
-GBool DCTStream::readAdobeMarker() {
- int length, i;
- char buf[12];
- int c;
-
- length = read16();
- if (length < 14) {
- goto err;
- }
- for (i = 0; i < 12; ++i) {
- if ((c = str->getChar()) == EOF) {
- goto err;
- }
- buf[i] = c;
- }
- if (strncmp(buf, "Adobe", 5)) {
- goto err;
- }
- colorXform = buf[11];
- gotAdobeMarker = gTrue;
- for (i = 14; i < length; ++i) {
- if (str->getChar() == EOF) {
- goto err;
- }
- }
- return gTrue;
-
- err:
- error(getPos(), "Bad DCT Adobe APP14 marker");
- return gFalse;
-}
-
-GBool DCTStream::readTrailer() {
- int c;
-
- c = readMarker();
- if (c != 0xd9) { // EOI
- error(getPos(), "Bad DCT trailer");
- return gFalse;
- }
- return gTrue;
-}
-
-int DCTStream::readMarker() {
- int c;
-
- do {
- do {
- c = str->getChar();
- if(c == EOF) return EOF;
- } while (c != 0xff);
- do {
- c = str->getChar();
- if(c == EOF) return EOF;
- } while (c == 0xff);
- } while (c == 0x00);
- return c;
-}
-
-int DCTStream::read16() {
- int c1, c2;
-
- if ((c1 = str->getChar()) == EOF)
- return EOF;
- if ((c2 = str->getChar()) == EOF)
- return EOF;
- return (c1 << 8) + c2;
-}
-
-GString *DCTStream::getPSFilter(const char *indent) {
- GString *s;
-
- if (!(s = str->getPSFilter(indent))) {
- return NULL;
- }
- s->append(indent)->append("<< >> /DCTDecode filter\n");
- return s;
-}
-
-GBool DCTStream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-//------------------------------------------------------------------------
-// FlateStream
-//------------------------------------------------------------------------
-
-int FlateStream::codeLenCodeMap[flateMaxCodeLenCodes] = {
- 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
-};
-
-FlateDecode FlateStream::lengthDecode[flateMaxLitCodes-257] = {
- {0, 3},
- {0, 4},
- {0, 5},
- {0, 6},
- {0, 7},
- {0, 8},
- {0, 9},
- {0, 10},
- {1, 11},
- {1, 13},
- {1, 15},
- {1, 17},
- {2, 19},
- {2, 23},
- {2, 27},
- {2, 31},
- {3, 35},
- {3, 43},
- {3, 51},
- {3, 59},
- {4, 67},
- {4, 83},
- {4, 99},
- {4, 115},
- {5, 131},
- {5, 163},
- {5, 195},
- {5, 227},
- {0, 258}
-};
-
-FlateDecode FlateStream::distDecode[flateMaxDistCodes] = {
- { 0, 1},
- { 0, 2},
- { 0, 3},
- { 0, 4},
- { 1, 5},
- { 1, 7},
- { 2, 9},
- { 2, 13},
- { 3, 17},
- { 3, 25},
- { 4, 33},
- { 4, 49},
- { 5, 65},
- { 5, 97},
- { 6, 129},
- { 6, 193},
- { 7, 257},
- { 7, 385},
- { 8, 513},
- { 8, 769},
- { 9, 1025},
- { 9, 1537},
- {10, 2049},
- {10, 3073},
- {11, 4097},
- {11, 6145},
- {12, 8193},
- {12, 12289},
- {13, 16385},
- {13, 24577}
-};
-
-FlateStream::FlateStream(Stream *strA, int predictor, int columns,
- int colors, int bits):
- FilterStream(strA) {
- if (predictor != 1) {
- pred = new StreamPredictor(this, predictor, columns, colors, bits);
- if ( !pred->isOk()) {
- delete pred;
- pred = NULL;
- }
- } else {
- pred = NULL;
- }
- litCodeTab.codes = NULL;
- distCodeTab.codes = NULL;
-}
-
-FlateStream::~FlateStream() {
- gfree(litCodeTab.codes);
- gfree(distCodeTab.codes);
- if (pred) {
- delete pred;
- }
- delete str;
-}
-
-void FlateStream::reset() {
- int cmf, flg;
-
- index = 0;
- remain = 0;
- codeBuf = 0;
- codeSize = 0;
- compressedBlock = gFalse;
- endOfBlock = gTrue;
- eof = gTrue;
-
- str->reset();
-
- // read header
- //~ need to look at window size?
- endOfBlock = eof = gTrue;
- cmf = str->getChar();
- flg = str->getChar();
- if (cmf == EOF || flg == EOF)
- return;
- if ((cmf & 0x0f) != 0x08) {
- error(getPos(), "Unknown compression method in flate stream");
- return;
- }
- if ((((cmf << 8) + flg) % 31) != 0) {
- error(getPos(), "Bad FCHECK in flate stream");
- return;
- }
- if (flg & 0x20) {
- error(getPos(), "FDICT bit set in flate stream");
- return;
- }
-
- eof = gFalse;
-}
-
-int FlateStream::getChar() {
- int c;
-
- if (pred) {
- return pred->getChar();
- }
- while (remain == 0) {
- if (endOfBlock && eof)
- return EOF;
- readSome();
- }
- c = buf[index];
- index = (index + 1) & flateMask;
- --remain;
- return c;
-}
-
-int FlateStream::lookChar() {
- int c;
-
- if (pred) {
- return pred->lookChar();
- }
- while (remain == 0) {
- if (endOfBlock && eof)
- return EOF;
- readSome();
- }
- c = buf[index];
- return c;
-}
-
-int FlateStream::getRawChar() {
- int c;
-
- while (remain == 0) {
- if (endOfBlock && eof)
- return EOF;
- readSome();
- }
- c = buf[index];
- index = (index + 1) & flateMask;
- --remain;
- return c;
-}
-
-GString *FlateStream::getPSFilter(const char */*indent*/) {
- return NULL;
-}
-
-GBool FlateStream::isBinary(GBool /*last*/) {
- return str->isBinary(gTrue);
-}
-
-void FlateStream::readSome() {
- int code1, code2;
- int len, dist;
- int i, j, k;
- int c;
-
- if (endOfBlock) {
- if (!startBlock())
- return;
- }
-
- if (compressedBlock) {
- if ((code1 = getHuffmanCodeWord(&litCodeTab)) == EOF)
- goto err;
- if (code1 < 256) {
- buf[index] = code1;
- remain = 1;
- } else if (code1 == 256) {
- endOfBlock = gTrue;
- remain = 0;
- } else {
- code1 -= 257;
- code2 = lengthDecode[code1].bits;
- if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
- goto err;
- len = lengthDecode[code1].first + code2;
- if ((code1 = getHuffmanCodeWord(&distCodeTab)) == EOF)
- goto err;
- code2 = distDecode[code1].bits;
- if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
- goto err;
- dist = distDecode[code1].first + code2;
- i = index;
- j = (index - dist) & flateMask;
- for (k = 0; k < len; ++k) {
- buf[i] = buf[j];
- i = (i + 1) & flateMask;
- j = (j + 1) & flateMask;
- }
- remain = len;
- }
-
- } else {
- len = (blockLen < flateWindow) ? blockLen : flateWindow;
- for (i = 0, j = index; i < len; ++i, j = (j + 1) & flateMask) {
- if ((c = str->getChar()) == EOF) {
- endOfBlock = eof = gTrue;
- break;
- }
- buf[j] = c & 0xff;
- }
- remain = i;
- blockLen -= len;
- if (blockLen == 0)
- endOfBlock = gTrue;
- }
-
- return;
-
-err:
- error(getPos(), "Unexpected end of file in flate stream");
- endOfBlock = eof = gTrue;
- remain = 0;
-}
-
-GBool FlateStream::startBlock() {
- int blockHdr;
- int c;
- int check;
-
- // free the code tables from the previous block
- gfree(litCodeTab.codes);
- litCodeTab.codes = NULL;
- gfree(distCodeTab.codes);
- distCodeTab.codes = NULL;
-
- // read block header
- blockHdr = getCodeWord(3);
- if (blockHdr & 1)
- eof = gTrue;
- blockHdr >>= 1;
-
- // uncompressed block
- if (blockHdr == 0) {
- compressedBlock = gFalse;
- if ((c = str->getChar()) == EOF)
- goto err;
- blockLen = c & 0xff;
- if ((c = str->getChar()) == EOF)
- goto err;
- blockLen |= (c & 0xff) << 8;
- if ((c = str->getChar()) == EOF)
- goto err;
- check = c & 0xff;
- if ((c = str->getChar()) == EOF)
- goto err;
- check |= (c & 0xff) << 8;
- if (check != (~blockLen & 0xffff))
- error(getPos(), "Bad uncompressed block length in flate stream");
- codeBuf = 0;
- codeSize = 0;
-
- // compressed block with fixed codes
- } else if (blockHdr == 1) {
- compressedBlock = gTrue;
- loadFixedCodes();
-
- // compressed block with dynamic codes
- } else if (blockHdr == 2) {
- compressedBlock = gTrue;
- if (!readDynamicCodes()) {
- goto err;
- }
-
- // unknown block type
- } else {
- goto err;
- }
-
- endOfBlock = gFalse;
- return gTrue;
-
-err:
- error(getPos(), "Bad block header in flate stream");
- endOfBlock = eof = gTrue;
- return gFalse;
-}
-
-void FlateStream::loadFixedCodes() {
- int i;
-
- // build the literal code table
- for (i = 0; i <= 143; ++i) {
- codeLengths[i] = 8;
- }
- for (i = 144; i <= 255; ++i) {
- codeLengths[i] = 9;
- }
- for (i = 256; i <= 279; ++i) {
- codeLengths[i] = 7;
- }
- for (i = 280; i <= 287; ++i) {
- codeLengths[i] = 8;
- }
- compHuffmanCodes(codeLengths, flateMaxLitCodes, &litCodeTab);
-
- // build the distance code table
- for (i = 0; i < flateMaxDistCodes; ++i) {
- codeLengths[i] = 5;
- }
- compHuffmanCodes(codeLengths, flateMaxDistCodes, &distCodeTab);
-}
-
-GBool FlateStream::readDynamicCodes() {
- int numCodeLenCodes;
- int numLitCodes;
- int numDistCodes;
- int codeLenCodeLengths[flateMaxCodeLenCodes];
- FlateHuffmanTab codeLenCodeTab;
- int len, repeat, code;
- int i;
-
- // read lengths
- if ((numLitCodes = getCodeWord(5)) == EOF) {
- goto err;
- }
- numLitCodes += 257;
- if ((numDistCodes = getCodeWord(5)) == EOF) {
- goto err;
- }
- numDistCodes += 1;
- if ((numCodeLenCodes = getCodeWord(4)) == EOF) {
- goto err;
- }
- numCodeLenCodes += 4;
- if (numLitCodes > flateMaxLitCodes ||
- numDistCodes > flateMaxDistCodes ||
- numCodeLenCodes > flateMaxCodeLenCodes) {
- goto err;
- }
-
- // build the code length code table
- for (i = 0; i < flateMaxCodeLenCodes; ++i) {
- codeLenCodeLengths[i] = 0;
- }
- for (i = 0; i < numCodeLenCodes; ++i) {
- if ((codeLenCodeLengths[codeLenCodeMap[i]] = getCodeWord(3)) == -1) {
- goto err;
- }
- }
- compHuffmanCodes(codeLenCodeLengths, flateMaxCodeLenCodes, &codeLenCodeTab);
-
- // build the literal and distance code tables
- len = 0;
- repeat = 0;
- i = 0;
- while (i < numLitCodes + numDistCodes) {
- if ((code = getHuffmanCodeWord(&codeLenCodeTab)) == EOF) {
- goto err;
- }
- if (code == 16) {
- if ((repeat = getCodeWord(2)) == EOF) {
- goto err;
- }
- for (repeat += 3; repeat > 0; --repeat) {
- codeLengths[i++] = len;
- }
- } else if (code == 17) {
- if ((repeat = getCodeWord(3)) == EOF) {
- goto err;
- }
- len = 0;
- for (repeat += 3; repeat > 0; --repeat) {
- codeLengths[i++] = 0;
- }
- } else if (code == 18) {
- if ((repeat = getCodeWord(7)) == EOF) {
- goto err;
- }
- len = 0;
- for (repeat += 11; repeat > 0; --repeat) {
- codeLengths[i++] = 0;
- }
- } else {
- codeLengths[i++] = len = code;
- }
- }
- compHuffmanCodes(codeLengths, numLitCodes, &litCodeTab);
- compHuffmanCodes(codeLengths + numLitCodes, numDistCodes, &distCodeTab);
-
- gfree(codeLenCodeTab.codes);
- return gTrue;
-
-err:
- error(getPos(), "Bad dynamic code table in flate stream");
- gfree(codeLenCodeTab.codes);
- return gFalse;
-}
-
-// Convert an array <lengths> of <n> lengths, in value order, into a
-// Huffman code lookup table.
-void FlateStream::compHuffmanCodes(int *lengths, int n, FlateHuffmanTab *tab) {
- int tabSize, len, code, code2, skip, val, i, t;
-
- // find max code length
- tab->maxLen = 0;
- for (val = 0; val < n; ++val) {
- if (lengths[val] > tab->maxLen) {
- tab->maxLen = lengths[val];
- }
- }
-
- // allocate the table
- tabSize = 1 << tab->maxLen;
- tab->codes = (FlateCode *)gmalloc(tabSize * sizeof(FlateCode));
-
- // clear the table
- for (i = 0; i < tabSize; ++i) {
- tab->codes[i].len = 0;
- tab->codes[i].val = 0;
- }
-
- // build the table
- for (len = 1, code = 0, skip = 2;
- len <= tab->maxLen;
- ++len, code <<= 1, skip <<= 1) {
- for (val = 0; val < n; ++val) {
- if (lengths[val] == len) {
-
- // bit-reverse the code
- code2 = 0;
- t = code;
- for (i = 0; i < len; ++i) {
- code2 = (code2 << 1) | (t & 1);
- t >>= 1;
- }
-
- // fill in the table entries
- for (i = code2; i < tabSize; i += skip) {
- tab->codes[i].len = (Gushort)len;
- tab->codes[i].val = (Gushort)val;
- }
-
- ++code;
- }
- }
- }
-}
-
-int FlateStream::getHuffmanCodeWord(FlateHuffmanTab *tab) {
- FlateCode *code;
- int c;
-
- while (codeSize < tab->maxLen) {
- if ((c = str->getChar()) == EOF) {
- break;
- }
- codeBuf |= (c & 0xff) << codeSize;
- codeSize += 8;
- }
- code = &tab->codes[codeBuf & ((1 << tab->maxLen) - 1)];
- if (codeSize == 0 || codeSize < code->len || code->len == 0) {
- return EOF;
- }
- codeBuf >>= code->len;
- codeSize -= code->len;
- return (int)code->val;
-}
-
-int FlateStream::getCodeWord(int bits) {
- int c;
-
- while (codeSize < bits) {
- if ((c = str->getChar()) == EOF)
- return EOF;
- codeBuf |= (c & 0xff) << codeSize;
- codeSize += 8;
- }
- c = codeBuf & ((1 << bits) - 1);
- codeBuf >>= bits;
- codeSize -= bits;
- return c;
-}
-
-//------------------------------------------------------------------------
-// EOFStream
-//------------------------------------------------------------------------
-
-EOFStream::EOFStream(Stream *strA):
- FilterStream(strA) {
-}
-
-EOFStream::~EOFStream() {
- delete str;
-}
-
-//------------------------------------------------------------------------
-// FixedLengthEncoder
-//------------------------------------------------------------------------
-
-FixedLengthEncoder::FixedLengthEncoder(Stream *strA, int lengthA):
- FilterStream(strA) {
- length = lengthA;
- count = 0;
-}
-
-FixedLengthEncoder::~FixedLengthEncoder() {
- if (str->isEncoder())
- delete str;
-}
-
-void FixedLengthEncoder::reset() {
- str->reset();
- count = 0;
-}
-
-void FixedLengthEncoder::close() {
-}
-
-int FixedLengthEncoder::getChar() {
- if (length >= 0 && count >= length)
- return EOF;
- ++count;
- return str->getChar();
-}
-
-int FixedLengthEncoder::lookChar() {
- if (length >= 0 && count >= length)
- return EOF;
- return str->getChar();
-}
-
-//------------------------------------------------------------------------
-// ASCIIHexEncoder
-//------------------------------------------------------------------------
-
-ASCIIHexEncoder::ASCIIHexEncoder(Stream *strA):
- FilterStream(strA) {
- bufPtr = bufEnd = buf;
- lineLen = 0;
- eof = gFalse;
-}
-
-ASCIIHexEncoder::~ASCIIHexEncoder() {
- if (str->isEncoder()) {
- delete str;
- }
-}
-
-void ASCIIHexEncoder::reset() {
- str->reset();
- bufPtr = bufEnd = buf;
- lineLen = 0;
- eof = gFalse;
-}
-
-void ASCIIHexEncoder::close() {
-}
-
-GBool ASCIIHexEncoder::fillBuf() {
- static const char *hex = "0123456789abcdef";
- int c;
-
- if (eof) {
- return gFalse;
- }
- bufPtr = bufEnd = buf;
- if ((c = str->getChar()) == EOF) {
- *bufEnd++ = '>';
- eof = gTrue;
- } else {
- if (lineLen >= 64) {
- *bufEnd++ = '\n';
- lineLen = 0;
- }
- *bufEnd++ = hex[(c >> 4) & 0x0f];
- *bufEnd++ = hex[c & 0x0f];
- lineLen += 2;
- }
- return gTrue;
-}
-
-//------------------------------------------------------------------------
-// ASCII85Encoder
-//------------------------------------------------------------------------
-
-ASCII85Encoder::ASCII85Encoder(Stream *strA):
- FilterStream(strA) {
- bufPtr = bufEnd = buf;
- lineLen = 0;
- eof = gFalse;
-}
-
-ASCII85Encoder::~ASCII85Encoder() {
- if (str->isEncoder())
- delete str;
-}
-
-void ASCII85Encoder::reset() {
- str->reset();
- bufPtr = bufEnd = buf;
- lineLen = 0;
- eof = gFalse;
-}
-
-void ASCII85Encoder::close() {
-}
-
-GBool ASCII85Encoder::fillBuf() {
- Gulong t;
- char buf1[5];
- int c;
- int n, i;
-
- if (eof)
- return gFalse;
- t = 0;
- for (n = 0; n < 4; ++n) {
- if ((c = str->getChar()) == EOF)
- break;
- t = (t << 8) + c;
- }
- bufPtr = bufEnd = buf;
- if (n > 0) {
- if (n == 4 && t == 0) {
- *bufEnd++ = 'z';
- if (++lineLen == 65) {
- *bufEnd++ = '\n';
- lineLen = 0;
- }
- } else {
- if (n < 4)
- t <<= 8 * (4 - n);
- for (i = 4; i >= 0; --i) {
- buf1[i] = (char)(t % 85 + 0x21);
- t /= 85;
- }
- for (i = 0; i <= n; ++i) {
- *bufEnd++ = buf1[i];
- if (++lineLen == 65) {
- *bufEnd++ = '\n';
- lineLen = 0;
- }
- }
- }
- }
- if (n < 4) {
- *bufEnd++ = '~';
- *bufEnd++ = '>';
- eof = gTrue;
- }
- return bufPtr < bufEnd;
-}
-
-//------------------------------------------------------------------------
-// RunLengthEncoder
-//------------------------------------------------------------------------
-
-RunLengthEncoder::RunLengthEncoder(Stream *strA):
- FilterStream(strA) {
- bufPtr = bufEnd = nextEnd = buf;
- eof = gFalse;
-}
-
-RunLengthEncoder::~RunLengthEncoder() {
- if (str->isEncoder())
- delete str;
-}
-
-void RunLengthEncoder::reset() {
- str->reset();
- bufPtr = bufEnd = nextEnd = buf;
- eof = gFalse;
-}
-
-void RunLengthEncoder::close() {
-}
-
-//
-// When fillBuf finishes, buf[] looks like this:
-// +-----+--------------+-----------------+--
-// + tag | ... data ... | next 0, 1, or 2 |
-// +-----+--------------+-----------------+--
-// ^ ^ ^
-// bufPtr bufEnd nextEnd
-//
-GBool RunLengthEncoder::fillBuf() {
- int c, c1, c2;
- int n;
-
- // already hit EOF?
- if (eof)
- return gFalse;
-
- // grab two bytes
- if (nextEnd < bufEnd + 1) {
- if ((c1 = str->getChar()) == EOF) {
- eof = gTrue;
- return gFalse;
- }
- } else {
- c1 = bufEnd[0] & 0xff;
- }
- if (nextEnd < bufEnd + 2) {
- if ((c2 = str->getChar()) == EOF) {
- eof = gTrue;
- buf[0] = 0;
- buf[1] = c1;
- bufPtr = buf;
- bufEnd = &buf[2];
- return gTrue;
- }
- } else {
- c2 = bufEnd[1] & 0xff;
- }
-
- // check for repeat
- c = 0; // make gcc happy
- if (c1 == c2) {
- n = 2;
- while (n < 128 && (c = str->getChar()) == c1)
- ++n;
- buf[0] = (char)(257 - n);
- buf[1] = c1;
- bufEnd = &buf[2];
- if (c == EOF) {
- eof = gTrue;
- } else if (n < 128) {
- buf[2] = c;
- nextEnd = &buf[3];
- } else {
- nextEnd = bufEnd;
- }
-
- // get up to 128 chars
- } else {
- buf[1] = c1;
- buf[2] = c2;
- n = 2;
- while (n < 128) {
- if ((c = str->getChar()) == EOF) {
- eof = gTrue;
- break;
- }
- ++n;
- buf[n] = c;
- if (buf[n] == buf[n-1])
- break;
- }
- if (buf[n] == buf[n-1]) {
- buf[0] = (char)(n-2-1);
- bufEnd = &buf[n-1];
- nextEnd = &buf[n+1];
- } else {
- buf[0] = (char)(n-1);
- bufEnd = nextEnd = &buf[n+1];
- }
- }
- bufPtr = buf;
- return gTrue;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/Stream.cpp b/filters/kword/pdf/xpdf/xpdf/Stream.cpp
new file mode 100644
index 000000000..7b3dbb5d5
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/Stream.cpp
@@ -0,0 +1,4544 @@
+//========================================================================
+//
+// Stream.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <limits.h>
+#ifndef WIN32
+#include <unistd.h>
+#endif
+#include <string.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "gfile.h"
+#include "xpdf_config.h"
+#include "Error.h"
+#include "Object.h"
+#ifndef NO_DECRYPTION
+#include "Decrypt.h"
+#endif
+#include "Stream.h"
+#include "JBIG2Stream.h"
+#include "Stream-CCITT.h"
+
+#ifdef __DJGPP__
+static GBool setDJSYSFLAGS = gFalse;
+#endif
+
+#ifdef VMS
+#ifdef __GNUC__
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#endif
+#endif
+
+//------------------------------------------------------------------------
+// Stream (base class)
+//------------------------------------------------------------------------
+
+Stream::Stream() {
+ ref = 1;
+}
+
+Stream::~Stream() {
+}
+
+void Stream::close() {
+}
+
+int Stream::getRawChar() {
+ error(-1, "Internal: called getRawChar() on non-predictor stream");
+ return EOF;
+}
+
+char *Stream::getLine(char *buf, int size) {
+ int i;
+ int c;
+
+ if (lookChar() == EOF)
+ return NULL;
+ for (i = 0; i < size - 1; ++i) {
+ c = getChar();
+ if (c == EOF || c == '\n')
+ break;
+ if (c == '\r') {
+ if ((c = lookChar()) == '\n')
+ getChar();
+ break;
+ }
+ buf[i] = c;
+ }
+ buf[i] = '\0';
+ return buf;
+}
+
+GString *Stream::getPSFilter(const char */*indent*/) {
+ return new GString();
+}
+
+Stream *Stream::addFilters(Object *dict) {
+ Object obj, obj2;
+ Object params, params2;
+ Stream *str;
+ int i;
+
+ str = this;
+ dict->dictLookup("Filter", &obj);
+ if (obj.isNull()) {
+ obj.free();
+ dict->dictLookup("F", &obj);
+ }
+ dict->dictLookup("DecodeParms", &params);
+ if (params.isNull()) {
+ params.free();
+ dict->dictLookup("DP", &params);
+ }
+ if (obj.isName()) {
+ str = makeFilter(obj.getName(), str, &params);
+ } else if (obj.isArray()) {
+ for (i = 0; i < obj.arrayGetLength(); ++i) {
+ obj.arrayGet(i, &obj2);
+ if (params.isArray())
+ params.arrayGet(i, &params2);
+ else
+ params2.initNull();
+ if (obj2.isName()) {
+ str = makeFilter(obj2.getName(), str, &params2);
+ } else {
+ error(getPos(), "Bad filter name");
+ str = new EOFStream(str);
+ }
+ obj2.free();
+ params2.free();
+ }
+ } else if (!obj.isNull()) {
+ error(getPos(), "Bad 'Filter' attribute in stream");
+ }
+ obj.free();
+ params.free();
+
+ return str;
+}
+
+Stream *Stream::makeFilter(const char *name, Stream *str, Object *params) {
+ int pred; // parameters
+ int colors;
+ int bits;
+ int early;
+ int encoding;
+ GBool endOfLine, byteAlign, endOfBlock, black;
+ int columns, rows;
+ Object globals, obj;
+
+ if (!strcmp(name, "ASCIIHexDecode") || !strcmp(name, "AHx")) {
+ str = new ASCIIHexStream(str);
+ } else if (!strcmp(name, "ASCII85Decode") || !strcmp(name, "A85")) {
+ str = new ASCII85Stream(str);
+ } else if (!strcmp(name, "LZWDecode") || !strcmp(name, "LZW")) {
+ pred = 1;
+ columns = 1;
+ colors = 1;
+ bits = 8;
+ early = 1;
+ if (params->isDict()) {
+ params->dictLookup("Predictor", &obj);
+ if (obj.isInt())
+ pred = obj.getInt();
+ obj.free();
+ params->dictLookup("Columns", &obj);
+ if (obj.isInt())
+ columns = obj.getInt();
+ obj.free();
+ params->dictLookup("Colors", &obj);
+ if (obj.isInt())
+ colors = obj.getInt();
+ obj.free();
+ params->dictLookup("BitsPerComponent", &obj);
+ if (obj.isInt())
+ bits = obj.getInt();
+ obj.free();
+ params->dictLookup("EarlyChange", &obj);
+ if (obj.isInt())
+ early = obj.getInt();
+ obj.free();
+ }
+ str = new LZWStream(str, pred, columns, colors, bits, early);
+ } else if (!strcmp(name, "RunLengthDecode") || !strcmp(name, "RL")) {
+ str = new RunLengthStream(str);
+ } else if (!strcmp(name, "CCITTFaxDecode") || !strcmp(name, "CCF")) {
+ encoding = 0;
+ endOfLine = gFalse;
+ byteAlign = gFalse;
+ columns = 1728;
+ rows = 0;
+ endOfBlock = gTrue;
+ black = gFalse;
+ if (params->isDict()) {
+ params->dictLookup("K", &obj);
+ if (obj.isInt()) {
+ encoding = obj.getInt();
+ }
+ obj.free();
+ params->dictLookup("EndOfLine", &obj);
+ if (obj.isBool()) {
+ endOfLine = obj.getBool();
+ }
+ obj.free();
+ params->dictLookup("EncodedByteAlign", &obj);
+ if (obj.isBool()) {
+ byteAlign = obj.getBool();
+ }
+ obj.free();
+ params->dictLookup("Columns", &obj);
+ if (obj.isInt()) {
+ columns = obj.getInt();
+ }
+ obj.free();
+ params->dictLookup("Rows", &obj);
+ if (obj.isInt()) {
+ rows = obj.getInt();
+ }
+ obj.free();
+ params->dictLookup("EndOfBlock", &obj);
+ if (obj.isBool()) {
+ endOfBlock = obj.getBool();
+ }
+ obj.free();
+ params->dictLookup("BlackIs1", &obj);
+ if (obj.isBool()) {
+ black = obj.getBool();
+ }
+ obj.free();
+ }
+ str = new CCITTFaxStream(str, encoding, endOfLine, byteAlign,
+ columns, rows, endOfBlock, black);
+ } else if (!strcmp(name, "DCTDecode") || !strcmp(name, "DCT")) {
+ str = new DCTStream(str);
+ } else if (!strcmp(name, "FlateDecode") || !strcmp(name, "Fl")) {
+ pred = 1;
+ columns = 1;
+ colors = 1;
+ bits = 8;
+ if (params->isDict()) {
+ params->dictLookup("Predictor", &obj);
+ if (obj.isInt())
+ pred = obj.getInt();
+ obj.free();
+ params->dictLookup("Columns", &obj);
+ if (obj.isInt())
+ columns = obj.getInt();
+ obj.free();
+ params->dictLookup("Colors", &obj);
+ if (obj.isInt())
+ colors = obj.getInt();
+ obj.free();
+ params->dictLookup("BitsPerComponent", &obj);
+ if (obj.isInt())
+ bits = obj.getInt();
+ obj.free();
+ }
+ str = new FlateStream(str, pred, columns, colors, bits);
+ } else if (!strcmp(name, "JBIG2Decode")) {
+ if (params->isDict()) {
+ params->dictLookup("JBIG2Globals", &globals);
+ }
+ str = new JBIG2Stream(str, &globals);
+ globals.free();
+ } else {
+ error(getPos(), "Unknown filter '%s'", name);
+ str = new EOFStream(str);
+ }
+ return str;
+}
+
+//------------------------------------------------------------------------
+// BaseStream
+//------------------------------------------------------------------------
+
+BaseStream::BaseStream(Object *dictA) {
+ dict = *dictA;
+#ifndef NO_DECRYPTION
+ decrypt = NULL;
+#endif
+}
+
+BaseStream::~BaseStream() {
+ dict.free();
+#ifndef NO_DECRYPTION
+ if (decrypt)
+ delete decrypt;
+#endif
+}
+
+#ifndef NO_DECRYPTION
+void BaseStream::doDecryption(Guchar *fileKey, int keyLength,
+ int objNum, int objGen) {
+ decrypt = new Decrypt(fileKey, keyLength, objNum, objGen);
+}
+#endif
+
+//------------------------------------------------------------------------
+// FilterStream
+//------------------------------------------------------------------------
+
+FilterStream::FilterStream(Stream *strA) {
+ str = strA;
+}
+
+FilterStream::~FilterStream() {
+}
+
+void FilterStream::close() {
+ str->close();
+}
+
+void FilterStream::setPos(Guint /*pos*/, int /*dir*/) {
+ error(-1, "Internal: called setPos() on FilterStream");
+}
+
+//------------------------------------------------------------------------
+// ImageStream
+//------------------------------------------------------------------------
+
+ImageStream::ImageStream(Stream *strA, int widthA, int nCompsA, int nBitsA) {
+ int imgLineSize;
+
+ str = strA;
+ width = widthA;
+ nComps = nCompsA;
+ nBits = nBitsA;
+
+ nVals = width * nComps;
+ if (nBits == 1) {
+ imgLineSize = (nVals + 7) & ~7;
+ } else {
+ imgLineSize = nVals;
+ }
+ imgLine = (Guchar *)gmalloc(imgLineSize * sizeof(Guchar));
+ imgIdx = nVals;
+}
+
+ImageStream::~ImageStream() {
+ gfree(imgLine);
+}
+
+void ImageStream::reset() {
+ str->reset();
+}
+
+GBool ImageStream::getPixel(Guchar *pix) {
+ int i;
+
+ if (imgIdx >= nVals) {
+ getLine();
+ imgIdx = 0;
+ }
+ for (i = 0; i < nComps; ++i) {
+ pix[i] = imgLine[imgIdx++];
+ }
+ return gTrue;
+}
+
+Guchar *ImageStream::getLine() {
+ Gulong buf, bitMask;
+ int bits;
+ int c;
+ int i;
+
+ if (nBits == 1) {
+ for (i = 0; i < nVals; i += 8) {
+ c = str->getChar();
+ imgLine[i+0] = (Guchar)((c >> 7) & 1);
+ imgLine[i+1] = (Guchar)((c >> 6) & 1);
+ imgLine[i+2] = (Guchar)((c >> 5) & 1);
+ imgLine[i+3] = (Guchar)((c >> 4) & 1);
+ imgLine[i+4] = (Guchar)((c >> 3) & 1);
+ imgLine[i+5] = (Guchar)((c >> 2) & 1);
+ imgLine[i+6] = (Guchar)((c >> 1) & 1);
+ imgLine[i+7] = (Guchar)(c & 1);
+ }
+ } else if (nBits == 8) {
+ for (i = 0; i < nVals; ++i) {
+ imgLine[i] = str->getChar();
+ }
+ } else {
+ bitMask = (1 << nBits) - 1;
+ buf = 0;
+ bits = 0;
+ for (i = 0; i < nVals; ++i) {
+ if (bits < nBits) {
+ buf = (buf << 8) | (str->getChar() & 0xff);
+ bits += 8;
+ }
+ imgLine[i] = (Guchar)((buf >> (bits - nBits)) & bitMask);
+ bits -= nBits;
+ }
+ }
+ return imgLine;
+}
+
+void ImageStream::skipLine() {
+ int n, i;
+
+ n = (nVals * nBits + 7) >> 3;
+ for (i = 0; i < n; ++i) {
+ str->getChar();
+ }
+}
+
+//------------------------------------------------------------------------
+// StreamPredictor
+//------------------------------------------------------------------------
+
+StreamPredictor::StreamPredictor(Stream *strA, int predictorA,
+ int widthA, int nCompsA, int nBitsA) {
+ str = strA;
+ predictor = predictorA;
+ width = widthA;
+ nComps = nCompsA;
+ nBits = nBitsA;
+ predLine = NULL;
+ ok = gFalse;
+
+ nVals = width * nComps;
+ pixBytes = (nComps * nBits + 7) >> 3;
+ rowBytes = ((nVals * nBits + 7) >> 3) + pixBytes;
+ if (width <= 0 || nComps <= 0 || nBits <= 0 ||
+ nComps > 4 ||
+ nBits > 16 ||
+ width >= INT_MAX / nComps || // check for overflow in nVals
+ nVals >= (INT_MAX - 7) / nBits) // check for overflow in rowBytes
+ return;
+
+ predLine = (Guchar *)gmalloc(rowBytes);
+ memset(predLine, 0, rowBytes);
+ predIdx = rowBytes;
+
+ ok = gTrue;
+}
+
+StreamPredictor::~StreamPredictor() {
+ gfree(predLine);
+}
+
+int StreamPredictor::lookChar() {
+ if (predIdx >= rowBytes) {
+ if (!getNextLine()) {
+ return EOF;
+ }
+ }
+ return predLine[predIdx];
+}
+
+int StreamPredictor::getChar() {
+ if (predIdx >= rowBytes) {
+ if (!getNextLine()) {
+ return EOF;
+ }
+ }
+ return predLine[predIdx++];
+}
+
+GBool StreamPredictor::getNextLine() {
+ int curPred;
+ Guchar upLeftBuf[4];
+ int left, up, upLeft, p, pa, pb, pc;
+ int c;
+ Gulong inBuf, outBuf, bitMask;
+ int inBits, outBits;
+ int i, j, k;
+
+ // get PNG optimum predictor number
+ if (predictor == 15) {
+ if ((curPred = str->getRawChar()) == EOF) {
+ return gFalse;
+ }
+ curPred += 10;
+ } else {
+ curPred = predictor;
+ }
+
+ // read the raw line, apply PNG (byte) predictor
+ upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
+ for (i = pixBytes; i < rowBytes; ++i) {
+ upLeftBuf[3] = upLeftBuf[2];
+ upLeftBuf[2] = upLeftBuf[1];
+ upLeftBuf[1] = upLeftBuf[0];
+ upLeftBuf[0] = predLine[i];
+ if ((c = str->getRawChar()) == EOF) {
+ break;
+ }
+ switch (curPred) {
+ case 11: // PNG sub
+ predLine[i] = predLine[i - pixBytes] + (Guchar)c;
+ break;
+ case 12: // PNG up
+ predLine[i] = predLine[i] + (Guchar)c;
+ break;
+ case 13: // PNG average
+ predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) +
+ (Guchar)c;
+ break;
+ case 14: // PNG Paeth
+ left = predLine[i - pixBytes];
+ up = predLine[i];
+ upLeft = upLeftBuf[pixBytes];
+ p = left + up - upLeft;
+ if ((pa = p - left) < 0)
+ pa = -pa;
+ if ((pb = p - up) < 0)
+ pb = -pb;
+ if ((pc = p - upLeft) < 0)
+ pc = -pc;
+ if (pa <= pb && pa <= pc)
+ predLine[i] = left + (Guchar)c;
+ else if (pb <= pc)
+ predLine[i] = up + (Guchar)c;
+ else
+ predLine[i] = upLeft + (Guchar)c;
+ break;
+ case 10: // PNG none
+ default: // no predictor or TIFF predictor
+ predLine[i] = (Guchar)c;
+ break;
+ }
+ }
+
+ // apply TIFF (component) predictor
+ //~ this is completely untested
+ if (predictor == 2) {
+ if (nBits == 1) {
+ inBuf = predLine[pixBytes - 1];
+ for (i = pixBytes; i < rowBytes; i += 8) {
+ // 1-bit add is just xor
+ inBuf = (inBuf << 8) | predLine[i];
+ predLine[i] ^= inBuf >> nComps;
+ }
+ } else if (nBits == 8) {
+ for (i = pixBytes; i < rowBytes; ++i) {
+ predLine[i] += predLine[i - nComps];
+ }
+ } else {
+ upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
+ bitMask = (1 << nBits) - 1;
+ inBuf = outBuf = 0;
+ inBits = outBits = 0;
+ j = k = pixBytes;
+ for (i = 0; i < nVals; ++i) {
+ if (inBits < nBits) {
+ inBuf = (inBuf << 8) | (predLine[j++] & 0xff);
+ inBits += 8;
+ }
+ upLeftBuf[3] = upLeftBuf[2];
+ upLeftBuf[2] = upLeftBuf[1];
+ upLeftBuf[1] = upLeftBuf[0];
+ upLeftBuf[0] = (upLeftBuf[nComps] +
+ (inBuf >> (inBits - nBits))) & bitMask;
+ outBuf = (outBuf << nBits) | upLeftBuf[0];
+ inBits -= nBits;
+ outBits += nBits;
+ if (outBits > 8) {
+ predLine[k++] = (Guchar)(outBuf >> (outBits - 8));
+ }
+ }
+ if (outBits > 0) {
+ predLine[k++] = (Guchar)(outBuf << (8 - outBits));
+ }
+ }
+ }
+
+ // reset to start of line
+ predIdx = pixBytes;
+
+ return gTrue;
+}
+
+//------------------------------------------------------------------------
+// FileStream
+//------------------------------------------------------------------------
+
+FileStream::FileStream(FILE *fA, Guint startA, GBool limitedA,
+ Guint lengthA, Object *dictA):
+ BaseStream(dictA) {
+ f = fA;
+ start = startA;
+ limited = limitedA;
+ length = lengthA;
+ bufPtr = bufEnd = buf;
+ bufPos = start;
+ savePos = 0;
+ saved = gFalse;
+}
+
+FileStream::~FileStream() {
+ close();
+}
+
+Stream *FileStream::makeSubStream(Guint startA, GBool limitedA,
+ Guint lengthA, Object *dictA) {
+ return new FileStream(f, startA, limitedA, lengthA, dictA);
+}
+
+void FileStream::reset() {
+#ifdef HAVE_FSEEKO
+ savePos = (Guint)ftello(f);
+ fseeko(f, start, SEEK_SET);
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ savePos = (Guint)ftell64(f);
+ fseek64(f, start, SEEK_SET);
+#else
+ savePos = (Guint)ftell(f);
+ fseek(f, start, SEEK_SET);
+#endif
+ saved = gTrue;
+ bufPtr = bufEnd = buf;
+ bufPos = start;
+#ifndef NO_DECRYPTION
+ if (decrypt)
+ decrypt->reset();
+#endif
+}
+
+void FileStream::close() {
+ if (saved) {
+#ifdef HAVE_FSEEKO
+ fseeko(f, savePos, SEEK_SET);
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ fseek64(f, savePos, SEEK_SET);
+#else
+ fseek(f, savePos, SEEK_SET);
+#endif
+ saved = gFalse;
+ }
+}
+
+GBool FileStream::fillBuf() {
+ int n;
+#ifndef NO_DECRYPTION
+ char *p;
+#endif
+
+ bufPos += bufEnd - buf;
+ bufPtr = bufEnd = buf;
+ if (limited && bufPos >= start + length) {
+ return gFalse;
+ }
+ if (limited && bufPos + fileStreamBufSize > start + length) {
+ n = start + length - bufPos;
+ } else {
+ n = fileStreamBufSize;
+ }
+ n = fread(buf, 1, n, f);
+ bufEnd = buf + n;
+ if (bufPtr >= bufEnd) {
+ return gFalse;
+ }
+#ifndef NO_DECRYPTION
+ if (decrypt) {
+ for (p = buf; p < bufEnd; ++p) {
+ *p = (char)decrypt->decryptByte((Guchar)*p);
+ }
+ }
+#endif
+ return gTrue;
+}
+
+void FileStream::setPos(Guint pos, int dir) {
+ Guint size;
+
+ if (dir >= 0) {
+#ifdef HAVE_FSEEKO
+ fseeko(f, pos, SEEK_SET);
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ fseek64(f, pos, SEEK_SET);
+#else
+ fseek(f, pos, SEEK_SET);
+#endif
+ bufPos = pos;
+ } else {
+#ifdef HAVE_FSEEKO
+ fseeko(f, 0, SEEK_END);
+ size = (Guint)ftello(f);
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ fseek64(f, 0, SEEK_END);
+ size = (Guint)ftell64(f);
+#else
+ fseek(f, 0, SEEK_END);
+ size = (Guint)ftell(f);
+#endif
+ if (pos > size)
+ pos = (Guint)size;
+#ifdef __CYGWIN32__
+ //~ work around a bug in cygwin's implementation of fseek
+ rewind(f);
+#endif
+#ifdef HAVE_FSEEKO
+ fseeko(f, -(int)pos, SEEK_END);
+ bufPos = (Guint)ftello(f);
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ fseek64(f, -(int)pos, SEEK_END);
+ bufPos = (Guint)ftell64(f);
+#else
+ fseek(f, -(int)pos, SEEK_END);
+ bufPos = (Guint)ftell(f);
+#endif
+ }
+ bufPtr = bufEnd = buf;
+}
+
+void FileStream::moveStart(int delta) {
+ start += delta;
+ bufPtr = bufEnd = buf;
+ bufPos = start;
+}
+
+//------------------------------------------------------------------------
+// MemStream
+//------------------------------------------------------------------------
+
+MemStream::MemStream(char *bufA, Guint lengthA, Object *dictA):
+ BaseStream(dictA) {
+ buf = bufA;
+ needFree = gFalse;
+ length = lengthA;
+ bufEnd = buf + length;
+ bufPtr = buf;
+}
+
+MemStream::~MemStream() {
+ if (needFree) {
+ gfree(buf);
+ }
+}
+
+Stream *MemStream::makeSubStream(Guint start, GBool limited,
+ Guint lengthA, Object *dictA) {
+ Guint newLength;
+
+ if (!limited || start + lengthA > length) {
+ newLength = length - start;
+ } else {
+ newLength = lengthA;
+ }
+ return new MemStream(buf + start, newLength, dictA);
+}
+
+void MemStream::reset() {
+ bufPtr = buf;
+#ifndef NO_DECRYPTION
+ if (decrypt) {
+ decrypt->reset();
+ }
+#endif
+}
+
+void MemStream::close() {
+}
+
+void MemStream::setPos(Guint pos, int dir) {
+ if (dir >= 0) {
+ if (pos > length) {
+ bufPtr = bufEnd;
+ } else {
+ bufPtr = buf + pos;
+ }
+ } else {
+ if (pos > length) {
+ bufPtr = buf;
+ } else {
+ bufPtr = bufEnd - pos;
+ }
+ }
+}
+
+void MemStream::moveStart(int delta) {
+ buf += delta;
+ bufPtr = buf;
+}
+
+#ifndef NO_DECRYPTION
+void MemStream::doDecryption(Guchar *fileKey, int keyLength,
+ int objNum, int objGen) {
+ char *newBuf;
+ char *p, *q;
+
+ this->BaseStream::doDecryption(fileKey, keyLength, objNum, objGen);
+ if (decrypt) {
+ newBuf = (char *)gmalloc(bufEnd - buf);
+ for (p = buf, q = newBuf; p < bufEnd; ++p, ++q) {
+ *q = (char)decrypt->decryptByte((Guchar)*p);
+ }
+ bufEnd = newBuf + (bufEnd - buf);
+ bufPtr = newBuf + (bufPtr - buf);
+ buf = newBuf;
+ needFree = gTrue;
+ }
+}
+#endif
+
+//------------------------------------------------------------------------
+// EmbedStream
+//------------------------------------------------------------------------
+
+EmbedStream::EmbedStream(Stream *strA, Object *dictA):
+ BaseStream(dictA) {
+ str = strA;
+}
+
+EmbedStream::~EmbedStream() {
+}
+
+Stream *EmbedStream::makeSubStream(Guint /*start*/, GBool /*limited*/,
+ Guint /*length*/, Object */*dictA*/) {
+ error(-1, "Internal: called makeSubStream() on EmbedStream");
+ return NULL;
+}
+
+void EmbedStream::setPos(Guint /*pos*/, int /*dir*/) {
+ error(-1, "Internal: called setPos() on EmbedStream");
+}
+
+Guint EmbedStream::getStart() {
+ error(-1, "Internal: called getStart() on EmbedStream");
+ return 0;
+}
+
+void EmbedStream::moveStart(int /*delta*/) {
+ error(-1, "Internal: called moveStart() on EmbedStream");
+}
+
+//------------------------------------------------------------------------
+// ASCIIHexStream
+//------------------------------------------------------------------------
+
+ASCIIHexStream::ASCIIHexStream(Stream *strA):
+ FilterStream(strA) {
+ buf = EOF;
+ eof = gFalse;
+}
+
+ASCIIHexStream::~ASCIIHexStream() {
+ delete str;
+}
+
+void ASCIIHexStream::reset() {
+ str->reset();
+ buf = EOF;
+ eof = gFalse;
+}
+
+int ASCIIHexStream::lookChar() {
+ int c1, c2, x;
+
+ if (buf != EOF)
+ return buf;
+ if (eof) {
+ buf = EOF;
+ return EOF;
+ }
+ do {
+ c1 = str->getChar();
+ } while (isspace(c1));
+ if (c1 == '>') {
+ eof = gTrue;
+ buf = EOF;
+ return buf;
+ }
+ do {
+ c2 = str->getChar();
+ } while (isspace(c2));
+ if (c2 == '>') {
+ eof = gTrue;
+ c2 = '0';
+ }
+ if (c1 >= '0' && c1 <= '9') {
+ x = (c1 - '0') << 4;
+ } else if (c1 >= 'A' && c1 <= 'F') {
+ x = (c1 - 'A' + 10) << 4;
+ } else if (c1 >= 'a' && c1 <= 'f') {
+ x = (c1 - 'a' + 10) << 4;
+ } else if (c1 == EOF) {
+ eof = gTrue;
+ x = 0;
+ } else {
+ error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c1);
+ x = 0;
+ }
+ if (c2 >= '0' && c2 <= '9') {
+ x += c2 - '0';
+ } else if (c2 >= 'A' && c2 <= 'F') {
+ x += c2 - 'A' + 10;
+ } else if (c2 >= 'a' && c2 <= 'f') {
+ x += c2 - 'a' + 10;
+ } else if (c2 == EOF) {
+ eof = gTrue;
+ x = 0;
+ } else {
+ error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c2);
+ }
+ buf = x & 0xff;
+ return buf;
+}
+
+GString *ASCIIHexStream::getPSFilter(const char *indent) {
+ GString *s;
+
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("/ASCIIHexDecode filter\n");
+ return s;
+}
+
+GBool ASCIIHexStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gFalse);
+}
+
+//------------------------------------------------------------------------
+// ASCII85Stream
+//------------------------------------------------------------------------
+
+ASCII85Stream::ASCII85Stream(Stream *strA):
+ FilterStream(strA) {
+ index = n = 0;
+ eof = gFalse;
+}
+
+ASCII85Stream::~ASCII85Stream() {
+ delete str;
+}
+
+void ASCII85Stream::reset() {
+ str->reset();
+ index = n = 0;
+ eof = gFalse;
+}
+
+int ASCII85Stream::lookChar() {
+ int k;
+ Gulong t;
+
+ if (index >= n) {
+ if (eof)
+ return EOF;
+ index = 0;
+ do {
+ c[0] = str->getChar();
+ } while (c[0] == '\n' || c[0] == '\r');
+ if (c[0] == '~' || c[0] == EOF) {
+ eof = gTrue;
+ n = 0;
+ return EOF;
+ } else if (c[0] == 'z') {
+ b[0] = b[1] = b[2] = b[3] = 0;
+ n = 4;
+ } else {
+ for (k = 1; k < 5; ++k) {
+ do {
+ c[k] = str->getChar();
+ } while (c[k] == '\n' || c[k] == '\r');
+ if (c[k] == '~' || c[k] == EOF)
+ break;
+ }
+ n = k - 1;
+ if (k < 5 && (c[k] == '~' || c[k] == EOF)) {
+ for (++k; k < 5; ++k)
+ c[k] = 0x21 + 84;
+ eof = gTrue;
+ }
+ t = 0;
+ for (k = 0; k < 5; ++k)
+ t = t * 85 + (c[k] - 0x21);
+ for (k = 3; k >= 0; --k) {
+ b[k] = (int)(t & 0xff);
+ t >>= 8;
+ }
+ }
+ }
+ return b[index];
+}
+
+GString *ASCII85Stream::getPSFilter(const char *indent) {
+ GString *s;
+
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("/ASCII85Decode filter\n");
+ return s;
+}
+
+GBool ASCII85Stream::isBinary(GBool /*last*/) {
+ return str->isBinary(gFalse);
+}
+
+//------------------------------------------------------------------------
+// LZWStream
+//------------------------------------------------------------------------
+
+LZWStream::LZWStream(Stream *strA, int predictor, int columns, int colors,
+ int bits, int earlyA):
+ FilterStream(strA) {
+ if (predictor != 1) {
+ pred = new StreamPredictor(this, predictor, columns, colors, bits);
+ if ( !pred->isOk()) {
+ delete pred;
+ pred = NULL;
+ }
+ } else {
+ pred = NULL;
+ }
+ early = earlyA;
+ eof = gFalse;
+ inputBits = 0;
+ clearTable();
+}
+
+LZWStream::~LZWStream() {
+ if (pred) {
+ delete pred;
+ }
+ delete str;
+}
+
+int LZWStream::getChar() {
+ if (pred) {
+ return pred->getChar();
+ }
+ if (eof) {
+ return EOF;
+ }
+ if (seqIndex >= seqLength) {
+ if (!processNextCode()) {
+ return EOF;
+ }
+ }
+ return seqBuf[seqIndex++];
+}
+
+int LZWStream::lookChar() {
+ if (pred) {
+ return pred->lookChar();
+ }
+ if (eof) {
+ return EOF;
+ }
+ if (seqIndex >= seqLength) {
+ if (!processNextCode()) {
+ return EOF;
+ }
+ }
+ return seqBuf[seqIndex];
+}
+
+int LZWStream::getRawChar() {
+ if (eof) {
+ return EOF;
+ }
+ if (seqIndex >= seqLength) {
+ if (!processNextCode()) {
+ return EOF;
+ }
+ }
+ return seqBuf[seqIndex++];
+}
+
+void LZWStream::reset() {
+ str->reset();
+ eof = gFalse;
+ inputBits = 0;
+ clearTable();
+}
+
+GBool LZWStream::processNextCode() {
+ int code;
+ int nextLength;
+ int i, j;
+
+ // check for EOF
+ if (eof) {
+ return gFalse;
+ }
+
+ // check for eod and clear-table codes
+ start:
+ code = getCode();
+ if (code == EOF || code == 257) {
+ eof = gTrue;
+ return gFalse;
+ }
+ if (code == 256) {
+ clearTable();
+ goto start;
+ }
+ if (nextCode >= 4097) {
+ error(getPos(), "Bad LZW stream - expected clear-table code");
+ clearTable();
+ }
+
+ // process the next code
+ nextLength = seqLength + 1;
+ if (code < 256) {
+ seqBuf[0] = code;
+ seqLength = 1;
+ } else if (code < nextCode) {
+ seqLength = table[code].length;
+ for (i = seqLength - 1, j = code; i > 0; --i) {
+ seqBuf[i] = table[j].tail;
+ j = table[j].head;
+ }
+ seqBuf[0] = j;
+ } else if (code == nextCode) {
+ seqBuf[seqLength] = newChar;
+ ++seqLength;
+ } else {
+ error(getPos(), "Bad LZW stream - unexpected code");
+ eof = gTrue;
+ return gFalse;
+ }
+ newChar = seqBuf[0];
+ if (first) {
+ first = gFalse;
+ } else {
+ table[nextCode].length = nextLength;
+ table[nextCode].head = prevCode;
+ table[nextCode].tail = newChar;
+ ++nextCode;
+ if (nextCode + early == 512)
+ nextBits = 10;
+ else if (nextCode + early == 1024)
+ nextBits = 11;
+ else if (nextCode + early == 2048)
+ nextBits = 12;
+ }
+ prevCode = code;
+
+ // reset buffer
+ seqIndex = 0;
+
+ return gTrue;
+}
+
+void LZWStream::clearTable() {
+ nextCode = 258;
+ nextBits = 9;
+ seqIndex = seqLength = 0;
+ first = gTrue;
+}
+
+int LZWStream::getCode() {
+ int c;
+ int code;
+
+ while (inputBits < nextBits) {
+ if ((c = str->getChar()) == EOF)
+ return EOF;
+ inputBuf = (inputBuf << 8) | (c & 0xff);
+ inputBits += 8;
+ }
+ code = (inputBuf >> (inputBits - nextBits)) & ((1 << nextBits) - 1);
+ inputBits -= nextBits;
+ return code;
+}
+
+GString *LZWStream::getPSFilter(const char *indent) {
+ GString *s;
+
+ if (pred) {
+ return NULL;
+ }
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("/LZWDecode filter\n");
+ return s;
+}
+
+GBool LZWStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+//------------------------------------------------------------------------
+// RunLengthStream
+//------------------------------------------------------------------------
+
+RunLengthStream::RunLengthStream(Stream *strA):
+ FilterStream(strA) {
+ bufPtr = bufEnd = buf;
+ eof = gFalse;
+}
+
+RunLengthStream::~RunLengthStream() {
+ delete str;
+}
+
+void RunLengthStream::reset() {
+ str->reset();
+ bufPtr = bufEnd = buf;
+ eof = gFalse;
+}
+
+GString *RunLengthStream::getPSFilter(const char *indent) {
+ GString *s;
+
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("/RunLengthDecode filter\n");
+ return s;
+}
+
+GBool RunLengthStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+GBool RunLengthStream::fillBuf() {
+ int c;
+ int n, i;
+
+ if (eof)
+ return gFalse;
+ c = str->getChar();
+ if (c == 0x80 || c == EOF) {
+ eof = gTrue;
+ return gFalse;
+ }
+ if (c < 0x80) {
+ n = c + 1;
+ for (i = 0; i < n; ++i)
+ buf[i] = (char)str->getChar();
+ } else {
+ n = 0x101 - c;
+ c = str->getChar();
+ for (i = 0; i < n; ++i)
+ buf[i] = (char)c;
+ }
+ bufPtr = buf;
+ bufEnd = buf + n;
+ return gTrue;
+}
+
+//------------------------------------------------------------------------
+// CCITTFaxStream
+//------------------------------------------------------------------------
+
+#if 0
+CCITTFaxStream::CCITTFaxStream(Stream *strA, int encodingA, GBool endOfLineA,
+ GBool byteAlignA, int columnsA, int rowsA,
+ GBool endOfBlockA, GBool blackA):
+ FilterStream(strA) {
+ encoding = encodingA;
+ endOfLine = endOfLineA;
+ byteAlign = byteAlignA;
+ columns = columnsA;
+ if (columns < 1 || columns >= INT_MAX / sizeof(short)) {
+ error(-1, "invalid number of columns");
+ exit(1);
+ }
+ rows = rowsA;
+ endOfBlock = endOfBlockA;
+ black = blackA;
+ refLine = (short *)gmalloc((columns + 3) * sizeof(short));
+ codingLine = (short *)gmalloc((columns + 2) * sizeof(short));
+
+ eof = gFalse;
+ row = 0;
+ nextLine2D = encoding < 0;
+ inputBits = 0;
+ codingLine[0] = 0;
+ codingLine[1] = refLine[2] = columns;
+ a0 = 1;
+
+ buf = EOF;
+}
+
+CCITTFaxStream::~CCITTFaxStream() {
+ delete str;
+ gfree(refLine);
+ gfree(codingLine);
+}
+
+void CCITTFaxStream::reset() {
+ int n;
+
+ str->reset();
+ eof = gFalse;
+ row = 0;
+ nextLine2D = encoding < 0;
+ inputBits = 0;
+ codingLine[0] = 0;
+ codingLine[1] = refLine[2] = columns;
+ a0 = 1;
+ buf = EOF;
+
+ // get initial end-of-line marker and 2D encoding tag
+ if (endOfBlock) {
+ if (lookBits(12) == 0x001) {
+ eatBits(12);
+ }
+ } else {
+ for (n = 0; n < 11 && lookBits(n) == 0; ++n) ;
+ if (n == 11 && lookBits(12) == 0x001) {
+ eatBits(12);
+ }
+ }
+ if (encoding > 0) {
+ nextLine2D = !lookBits(1);
+ eatBits(1);
+ }
+}
+
+int CCITTFaxStream::lookChar() {
+ short code1, code2, code3;
+ int a0New;
+#if 0
+ GBool err;
+#endif
+ GBool gotEOL;
+ int ret;
+ int bits, i;
+
+ // if at eof just return EOF
+ if (eof && codingLine[a0] >= columns) {
+ return EOF;
+ }
+
+ // read the next row
+#if 0
+ err = gFalse;
+#endif
+ if (codingLine[a0] >= columns) {
+
+ // 2-D encoding
+ if (nextLine2D) {
+ for (i = 0; codingLine[i] < columns; ++i)
+ refLine[i] = codingLine[i];
+ refLine[i] = refLine[i + 1] = columns;
+ b1 = 1;
+ a0New = codingLine[a0 = 0] = 0;
+ do {
+ code1 = getTwoDimCode();
+ switch (code1) {
+ case twoDimPass:
+ if (refLine[b1] < columns) {
+ a0New = refLine[b1 + 1];
+ b1 += 2;
+ }
+ break;
+ case twoDimHoriz:
+ if ((a0 & 1) == 0) {
+ code1 = code2 = 0;
+ do {
+ code1 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ do {
+ code2 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ } else {
+ code1 = code2 = 0;
+ do {
+ code1 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ do {
+ code2 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ }
+ codingLine[a0 + 1] = a0New + code1;
+ ++a0;
+ a0New = codingLine[a0 + 1] = codingLine[a0] + code2;
+ ++a0;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ break;
+ case twoDimVert0:
+ a0New = codingLine[++a0] = refLine[b1];
+ if (refLine[b1] < columns) {
+ ++b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ }
+ break;
+ case twoDimVertR1:
+ a0New = codingLine[++a0] = refLine[b1] + 1;
+ if (refLine[b1] < columns) {
+ ++b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ }
+ break;
+ case twoDimVertL1:
+ a0New = codingLine[++a0] = refLine[b1] - 1;
+ --b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ break;
+ case twoDimVertR2:
+ a0New = codingLine[++a0] = refLine[b1] + 2;
+ if (refLine[b1] < columns) {
+ ++b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ }
+ break;
+ case twoDimVertL2:
+ a0New = codingLine[++a0] = refLine[b1] - 2;
+ --b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ break;
+ case twoDimVertR3:
+ a0New = codingLine[++a0] = refLine[b1] + 3;
+ if (refLine[b1] < columns) {
+ ++b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ }
+ break;
+ case twoDimVertL3:
+ a0New = codingLine[++a0] = refLine[b1] - 3;
+ --b1;
+ while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
+ b1 += 2;
+ break;
+ case EOF:
+ eof = gTrue;
+ codingLine[a0 = 0] = columns;
+ return EOF;
+ default:
+ error(getPos(), "Bad 2D code %04x in CCITTFax stream", code1);
+#if 0
+ err = gTrue;
+ break;
+#else
+ eof = gTrue;
+ return EOF;
+#endif
+ }
+ } while (codingLine[a0] < columns);
+
+ // 1-D encoding
+ } else {
+ codingLine[a0 = 0] = 0;
+ while (1) {
+ code1 = 0;
+ do {
+ code1 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ codingLine[a0+1] = codingLine[a0] + code1;
+ ++a0;
+ if (codingLine[a0] >= columns)
+ break;
+ code2 = 0;
+ do {
+ code2 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ codingLine[a0+1] = codingLine[a0] + code2;
+ ++a0;
+ if (codingLine[a0] >= columns)
+ break;
+ }
+ }
+
+ if (codingLine[a0] != columns) {
+ error(getPos(), "CCITTFax row is wrong length (%d)", codingLine[a0]);
+#if 0
+ err = gTrue;
+#endif
+ }
+
+ // byte-align the row
+ if (byteAlign) {
+ inputBits &= ~7;
+ }
+
+ // check for end-of-line marker, skipping over any extra zero bits
+ gotEOL = gFalse;
+ if (!endOfBlock && row == rows - 1) {
+ eof = gTrue;
+ } else {
+ code1 = lookBits(12);
+ while (code1 == 0) {
+ eatBits(1);
+ code1 = lookBits(12);
+ }
+ if (code1 == 0x001) {
+ eatBits(12);
+ gotEOL = gTrue;
+ } else if (code1 == EOF) {
+ eof = gTrue;
+ }
+ }
+
+ // get 2D encoding tag
+ if (!eof && encoding > 0) {
+ nextLine2D = !lookBits(1);
+ eatBits(1);
+ }
+
+ // check for end-of-block marker
+ if (endOfBlock && gotEOL) {
+ code1 = lookBits(12);
+ if (code1 == 0x001) {
+ eatBits(12);
+ if (encoding > 0) {
+ lookBits(1);
+ eatBits(1);
+ }
+ if (encoding >= 0) {
+ for (i = 0; i < 4; ++i) {
+ code1 = lookBits(12);
+ if (code1 != 0x001) {
+ error(getPos(), "Bad RTC code in CCITTFax stream");
+ }
+ eatBits(12);
+ if (encoding > 0) {
+ lookBits(1);
+ eatBits(1);
+ }
+ }
+ }
+ eof = gTrue;
+ }
+ }
+
+#if 0
+ // This looks for an end-of-line marker after an error, however
+ // some (most?) CCITT streams in PDF files don't use end-of-line
+ // markers, and the just-plow-on technique works better in those
+ // cases.
+ else if (err) {
+ do {
+ if (code1 == EOF) {
+ eof = gTrue;
+ return EOF;
+ }
+ eatBits(1);
+ code1 = look13Bits();
+ } while ((code1 >> 1) != 0x001);
+ eatBits(12);
+ codingLine[++a0] = columns;
+ if (encoding > 0) {
+ eatBits(1);
+ nextLine2D = !(code1 & 1);
+ }
+ }
+#endif
+
+ a0 = 0;
+ outputBits = codingLine[1] - codingLine[0];
+ if (outputBits == 0) {
+ a0 = 1;
+ outputBits = codingLine[2] - codingLine[1];
+ }
+
+ ++row;
+ }
+
+ // get a byte
+ if (outputBits >= 8) {
+ ret = ((a0 & 1) == 0) ? 0xff : 0x00;
+ if ((outputBits -= 8) == 0) {
+ ++a0;
+ if (codingLine[a0] < columns) {
+ outputBits = codingLine[a0 + 1] - codingLine[a0];
+ }
+ }
+ } else {
+ bits = 8;
+ ret = 0;
+ do {
+ if (outputBits > bits) {
+ i = bits;
+ bits = 0;
+ if ((a0 & 1) == 0) {
+ ret |= 0xff >> (8 - i);
+ }
+ outputBits -= i;
+ } else {
+ i = outputBits;
+ bits -= outputBits;
+ if ((a0 & 1) == 0) {
+ ret |= (0xff >> (8 - i)) << bits;
+ }
+ outputBits = 0;
+ ++a0;
+ if (codingLine[a0] < columns) {
+ outputBits = codingLine[a0 + 1] - codingLine[a0];
+ }
+ }
+ } while (bits > 0 && codingLine[a0] < columns);
+ }
+ buf = black ? (ret ^ 0xff) : ret;
+ return buf;
+}
+
+short CCITTFaxStream::getTwoDimCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(7);
+ p = &twoDimTab1[code];
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 1; n <= 7; ++n) {
+ code = lookBits(n);
+ if (n < 7) {
+ code <<= 7 - n;
+ }
+ p = &twoDimTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad two dim code (%04x) in CCITTFax stream", code);
+ return EOF;
+}
+
+short CCITTFaxStream::getWhiteCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(12);
+ if ((code >> 5) == 0) {
+ p = &whiteTab1[code];
+ } else {
+ p = &whiteTab2[code >> 3];
+ }
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 1; n <= 9; ++n) {
+ code = lookBits(n);
+ if (n < 9) {
+ code <<= 9 - n;
+ }
+ p = &whiteTab2[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ for (n = 11; n <= 12; ++n) {
+ code = lookBits(n);
+ if (n < 12) {
+ code <<= 12 - n;
+ }
+ p = &whiteTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad white code (%04x) in CCITTFax stream", code);
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ eatBits(1);
+ return 1;
+}
+
+short CCITTFaxStream::getBlackCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(13);
+ if ((code >> 7) == 0) {
+ p = &blackTab1[code];
+ } else if ((code >> 9) == 0) {
+ p = &blackTab2[(code >> 1) - 64];
+ } else {
+ p = &blackTab3[code >> 7];
+ }
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 2; n <= 6; ++n) {
+ code = lookBits(n);
+ if (n < 6) {
+ code <<= 6 - n;
+ }
+ p = &blackTab3[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ for (n = 7; n <= 12; ++n) {
+ code = lookBits(n);
+ if (n < 12) {
+ code <<= 12 - n;
+ }
+ if (code >= 64) {
+ p = &blackTab2[code - 64];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ for (n = 10; n <= 13; ++n) {
+ code = lookBits(n);
+ if (n < 13) {
+ code <<= 13 - n;
+ }
+ p = &blackTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad black code (%04x) in CCITTFax stream", code);
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ eatBits(1);
+ return 1;
+}
+
+short CCITTFaxStream::lookBits(int n) {
+ int c;
+
+ while (inputBits < n) {
+ if ((c = str->getChar()) == EOF) {
+ if (inputBits == 0) {
+ return EOF;
+ }
+ // near the end of the stream, the caller may ask for more bits
+ // than are available, but there may still be a valid code in
+ // however many bits are available -- we need to return correct
+ // data in this case
+ return (inputBuf << (n - inputBits)) & (0xffff >> (16 - n));
+ }
+ inputBuf = (inputBuf << 8) + c;
+ inputBits += 8;
+ }
+ return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
+}
+#else // secfix
+CCITTFaxStream::CCITTFaxStream(Stream *strA, int encodingA, GBool endOfLineA,
+ GBool byteAlignA, int columnsA, int rowsA,
+ GBool endOfBlockA, GBool blackA):
+ FilterStream(strA) {
+ encoding = encodingA;
+ endOfLine = endOfLineA;
+ byteAlign = byteAlignA;
+ columns = columnsA;
+ if (columns < 1) {
+ columns = 1;
+ } else if (columns > (INT_MAX - 2)/sizeof(int)) {
+ columns = (INT_MAX - 2)/sizeof(int);
+ }
+ rows = rowsA;
+ endOfBlock = endOfBlockA;
+ black = blackA;
+ // 0 <= codingLine[0] < codingLine[1] < ... < codingLine[n] = columns
+ // ---> max codingLine size = columns + 1
+ // refLine has one extra guard entry at the end
+ // ---> max refLine size = columns + 2
+ codingLine = (int *)gmalloc((columns + 1) * sizeof(int));
+ refLine = (int *)gmalloc((columns + 2) * sizeof(int));
+
+ eof = gFalse;
+ row = 0;
+ nextLine2D = encoding < 0;
+ inputBits = 0;
+ codingLine[0] = columns;
+ a0i = 0;
+ outputBits = 0;
+
+ buf = EOF;
+}
+
+CCITTFaxStream::~CCITTFaxStream() {
+ delete str;
+ gfree(refLine);
+ gfree(codingLine);
+}
+
+void CCITTFaxStream::reset() {
+ short code1;
+
+ str->reset();
+ eof = gFalse;
+ row = 0;
+ nextLine2D = encoding < 0;
+ inputBits = 0;
+ codingLine[0] = columns;
+ a0i = 0;
+ outputBits = 0;
+ buf = EOF;
+
+ // skip any initial zero bits and end-of-line marker, and get the 2D
+ // encoding tag
+ while ((code1 = lookBits(12)) == 0) {
+ eatBits(1);
+ }
+ if (code1 == 0x001) {
+ eatBits(12);
+ }
+ if (encoding > 0) {
+ nextLine2D = !lookBits(1);
+ eatBits(1);
+ }
+}
+
+inline void CCITTFaxStream::addPixels(int a1, int blackPixels) {
+ if (a1 > codingLine[a0i]) {
+ if (a1 > columns) {
+ error(getPos(), "CCITTFax row is wrong length (%d)", a1);
+ err = gTrue;
+ a1 = columns;
+ }
+ if ((a0i & 1) ^ blackPixels) {
+ ++a0i;
+ }
+ codingLine[a0i] = a1;
+ }
+}
+
+inline void CCITTFaxStream::addPixelsNeg(int a1, int blackPixels) {
+ if (a1 > codingLine[a0i]) {
+ if (a1 > columns) {
+ error(getPos(), "CCITTFax row is wrong length (%d)", a1);
+ err = gTrue;
+ a1 = columns;
+ }
+ if ((a0i & 1) ^ blackPixels) {
+ ++a0i;
+ }
+ codingLine[a0i] = a1;
+ } else if (a1 < codingLine[a0i]) {
+ if (a1 < 0) {
+ error(getPos(), "Invalid CCITTFax code");
+ err = gTrue;
+ a1 = 0;
+ }
+ while (a0i > 0 && a1 <= codingLine[a0i - 1]) {
+ --a0i;
+ }
+ codingLine[a0i] = a1;
+ }
+}
+
+int CCITTFaxStream::lookChar() {
+ short code1, code2, code3;
+ int b1i, blackPixels, i, bits;
+ GBool gotEOL;
+
+ if (buf != EOF) {
+ return buf;
+ }
+
+ // read the next row
+ if (outputBits == 0) {
+
+ // if at eof just return EOF
+ if (eof) {
+ return EOF;
+ }
+
+ err = gFalse;
+
+ // 2-D encoding
+ if (nextLine2D) {
+ for (i = 0; codingLine[i] < columns; ++i) {
+ refLine[i] = codingLine[i];
+ }
+ refLine[i++] = columns;
+ refLine[i] = columns;
+ codingLine[0] = 0;
+ a0i = 0;
+ b1i = 0;
+ blackPixels = 0;
+ // invariant:
+ // refLine[b1i-1] <= codingLine[a0i] < refLine[b1i] < refLine[b1i+1]
+ // <= columns
+ // exception at left edge:
+ // codingLine[a0i = 0] = refLine[b1i = 0] = 0 is possible
+ // exception at right edge:
+ // refLine[b1i] = refLine[b1i+1] = columns is possible
+ while (codingLine[a0i] < columns) {
+ code1 = getTwoDimCode();
+ switch (code1) {
+ case twoDimPass:
+ addPixels(refLine[b1i + 1], blackPixels);
+ if (refLine[b1i + 1] < columns) {
+ b1i += 2;
+ }
+ break;
+ case twoDimHoriz:
+ code1 = code2 = 0;
+ if (blackPixels) {
+ do {
+ code1 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ do {
+ code2 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ } else {
+ do {
+ code1 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ do {
+ code2 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ }
+ addPixels(codingLine[a0i] + code1, blackPixels);
+ if (codingLine[a0i] < columns) {
+ addPixels(codingLine[a0i] + code2, blackPixels ^ 1);
+ }
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ break;
+ case twoDimVertR3:
+ addPixels(refLine[b1i] + 3, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ ++b1i;
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVertR2:
+ addPixels(refLine[b1i] + 2, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ ++b1i;
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVertR1:
+ addPixels(refLine[b1i] + 1, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ ++b1i;
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVert0:
+ addPixels(refLine[b1i], blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ ++b1i;
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVertL3:
+ addPixelsNeg(refLine[b1i] - 3, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ if (b1i > 0) {
+ --b1i;
+ } else {
+ ++b1i;
+ }
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVertL2:
+ addPixelsNeg(refLine[b1i] - 2, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ if (b1i > 0) {
+ --b1i;
+ } else {
+ ++b1i;
+ }
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case twoDimVertL1:
+ addPixelsNeg(refLine[b1i] - 1, blackPixels);
+ blackPixels ^= 1;
+ if (codingLine[a0i] < columns) {
+ if (b1i > 0) {
+ --b1i;
+ } else {
+ ++b1i;
+ }
+ while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) {
+ b1i += 2;
+ }
+ }
+ break;
+ case EOF:
+ addPixels(columns, 0);
+ eof = gTrue;
+ break;
+ default:
+ error(getPos(), "Bad 2D code %04x in CCITTFax stream", code1);
+ addPixels(columns, 0);
+ err = gTrue;
+ break;
+ }
+ }
+
+ // 1-D encoding
+ } else {
+ codingLine[0] = 0;
+ a0i = 0;
+ blackPixels = 0;
+ while (codingLine[a0i] < columns) {
+ code1 = 0;
+ if (blackPixels) {
+ do {
+ code1 += code3 = getBlackCode();
+ } while (code3 >= 64);
+ } else {
+ do {
+ code1 += code3 = getWhiteCode();
+ } while (code3 >= 64);
+ }
+ addPixels(codingLine[a0i] + code1, blackPixels);
+ blackPixels ^= 1;
+ }
+ }
+
+ // byte-align the row
+ if (byteAlign) {
+ inputBits &= ~7;
+ }
+
+ // check for end-of-line marker, skipping over any extra zero bits
+ gotEOL = gFalse;
+ if (!endOfBlock && row == rows - 1) {
+ eof = gTrue;
+ } else {
+ code1 = lookBits(12);
+ while (code1 == 0) {
+ eatBits(1);
+ code1 = lookBits(12);
+ }
+ if (code1 == 0x001) {
+ eatBits(12);
+ gotEOL = gTrue;
+ } else if (code1 == EOF) {
+ eof = gTrue;
+ }
+ }
+
+ // get 2D encoding tag
+ if (!eof && encoding > 0) {
+ nextLine2D = !lookBits(1);
+ eatBits(1);
+ }
+
+ // check for end-of-block marker
+ if (endOfBlock && gotEOL) {
+ code1 = lookBits(12);
+ if (code1 == 0x001) {
+ eatBits(12);
+ if (encoding > 0) {
+ lookBits(1);
+ eatBits(1);
+ }
+ if (encoding >= 0) {
+ for (i = 0; i < 4; ++i) {
+ code1 = lookBits(12);
+ if (code1 != 0x001) {
+ error(getPos(), "Bad RTC code in CCITTFax stream");
+ }
+ eatBits(12);
+ if (encoding > 0) {
+ lookBits(1);
+ eatBits(1);
+ }
+ }
+ }
+ eof = gTrue;
+ }
+
+ // look for an end-of-line marker after an error -- we only do
+ // this if we know the stream contains end-of-line markers because
+ // the "just plow on" technique tends to work better otherwise
+ } else if (err && endOfLine) {
+ while (1) {
+ code1 = lookBits(13);
+ if (code1 == EOF) {
+ eof = gTrue;
+ return EOF;
+ }
+ if ((code1 >> 1) == 0x001) {
+ break;
+ }
+ eatBits(1);
+ }
+ eatBits(12);
+ if (encoding > 0) {
+ eatBits(1);
+ nextLine2D = !(code1 & 1);
+ }
+ }
+
+ // set up for output
+ if (codingLine[0] > 0) {
+ outputBits = codingLine[a0i = 0];
+ } else {
+ outputBits = codingLine[a0i = 1];
+ }
+
+ ++row;
+ }
+
+ // get a byte
+ if (outputBits >= 8) {
+ buf = (a0i & 1) ? 0x00 : 0xff;
+ outputBits -= 8;
+ if (outputBits == 0 && codingLine[a0i] < columns) {
+ ++a0i;
+ outputBits = codingLine[a0i] - codingLine[a0i - 1];
+ }
+ } else {
+ bits = 8;
+ buf = 0;
+ do {
+ if (outputBits > bits) {
+ buf <<= bits;
+ if (!(a0i & 1)) {
+ buf |= 0xff >> (8 - bits);
+ }
+ outputBits -= bits;
+ bits = 0;
+ } else {
+ buf <<= outputBits;
+ if (!(a0i & 1)) {
+ buf |= 0xff >> (8 - outputBits);
+ }
+ bits -= outputBits;
+ outputBits = 0;
+ if (codingLine[a0i] < columns) {
+ ++a0i;
+ outputBits = codingLine[a0i] - codingLine[a0i - 1];
+ } else if (bits > 0) {
+ buf <<= bits;
+ bits = 0;
+ }
+ }
+ } while (bits);
+ }
+ if (black) {
+ buf ^= 0xff;
+ }
+ return buf;
+}
+
+short CCITTFaxStream::getTwoDimCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(7);
+ p = &twoDimTab1[code];
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 1; n <= 7; ++n) {
+ code = lookBits(n);
+ if (n < 7) {
+ code <<= 7 - n;
+ }
+ p = &twoDimTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad two dim code (%04x) in CCITTFax stream", code);
+ return EOF;
+}
+
+short CCITTFaxStream::getWhiteCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(12);
+ if (code == EOF) {
+ return 1;
+ }
+ if ((code >> 5) == 0) {
+ p = &whiteTab1[code];
+ } else {
+ p = &whiteTab2[code >> 3];
+ }
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 1; n <= 9; ++n) {
+ code = lookBits(n);
+ if (code == EOF) {
+ return 1;
+ }
+ if (n < 9) {
+ code <<= 9 - n;
+ }
+ p = &whiteTab2[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ for (n = 11; n <= 12; ++n) {
+ code = lookBits(n);
+ if (code == EOF) {
+ return 1;
+ }
+ if (n < 12) {
+ code <<= 12 - n;
+ }
+ p = &whiteTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad white code (%04x) in CCITTFax stream", code);
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ eatBits(1);
+ return 1;
+}
+
+short CCITTFaxStream::getBlackCode() {
+ short code;
+ CCITTCode *p;
+ int n;
+
+ code = 0; // make gcc happy
+ if (endOfBlock) {
+ code = lookBits(13);
+ if (code == EOF) {
+ return 1;
+ }
+ if ((code >> 7) == 0) {
+ p = &blackTab1[code];
+ } else if ((code >> 9) == 0 && (code >> 7) != 0) {
+ p = &blackTab2[(code >> 1) - 64];
+ } else {
+ p = &blackTab3[code >> 7];
+ }
+ if (p->bits > 0) {
+ eatBits(p->bits);
+ return p->n;
+ }
+ } else {
+ for (n = 2; n <= 6; ++n) {
+ code = lookBits(n);
+ if (code == EOF) {
+ return 1;
+ }
+ if (n < 6) {
+ code <<= 6 - n;
+ }
+ p = &blackTab3[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ for (n = 7; n <= 12; ++n) {
+ code = lookBits(n);
+ if (code == EOF) {
+ return 1;
+ }
+ if (n < 12) {
+ code <<= 12 - n;
+ }
+ if (code >= 64) {
+ p = &blackTab2[code - 64];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ for (n = 10; n <= 13; ++n) {
+ code = lookBits(n);
+ if (code == EOF) {
+ return 1;
+ }
+ if (n < 13) {
+ code <<= 13 - n;
+ }
+ p = &blackTab1[code];
+ if (p->bits == n) {
+ eatBits(n);
+ return p->n;
+ }
+ }
+ }
+ error(getPos(), "Bad black code (%04x) in CCITTFax stream", code);
+ // eat a bit and return a positive number so that the caller doesn't
+ // go into an infinite loop
+ eatBits(1);
+ return 1;
+}
+
+short CCITTFaxStream::lookBits(int n) {
+ int c;
+
+ while (inputBits < n) {
+ if ((c = str->getChar()) == EOF) {
+ if (inputBits == 0) {
+ return EOF;
+ }
+ // near the end of the stream, the caller may ask for more bits
+ // than are available, but there may still be a valid code in
+ // however many bits are available -- we need to return correct
+ // data in this case
+ return (inputBuf << (n - inputBits)) & (0xffff >> (16 - n));
+ }
+ inputBuf = (inputBuf << 8) + c;
+ inputBits += 8;
+ }
+ return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
+}
+
+#endif
+
+GString *CCITTFaxStream::getPSFilter(const char *indent) {
+ GString *s;
+ char s1[50];
+
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("<< ");
+ if (encoding != 0) {
+ sprintf(s1, "/K %d ", encoding);
+ s->append(s1);
+ }
+ if (endOfLine) {
+ s->append("/EndOfLine true ");
+ }
+ if (byteAlign) {
+ s->append("/EncodedByteAlign true ");
+ }
+ sprintf(s1, "/Columns %d ", columns);
+ s->append(s1);
+ if (rows != 0) {
+ sprintf(s1, "/Rows %d ", rows);
+ s->append(s1);
+ }
+ if (!endOfBlock) {
+ s->append("/EndOfBlock false ");
+ }
+ if (black) {
+ s->append("/BlackIs1 true ");
+ }
+ s->append(">> /CCITTFaxDecode filter\n");
+ return s;
+}
+
+GBool CCITTFaxStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+//------------------------------------------------------------------------
+// DCTStream
+//------------------------------------------------------------------------
+
+// IDCT constants (20.12 fixed point format)
+#define dctCos1 4017 // cos(pi/16)
+#define dctSin1 799 // sin(pi/16)
+#define dctCos3 3406 // cos(3*pi/16)
+#define dctSin3 2276 // sin(3*pi/16)
+#define dctCos6 1567 // cos(6*pi/16)
+#define dctSin6 3784 // sin(6*pi/16)
+#define dctSqrt2 5793 // sqrt(2)
+#define dctSqrt1d2 2896 // sqrt(2) / 2
+
+// color conversion parameters (16.16 fixed point format)
+#define dctCrToR 91881 // 1.4020
+#define dctCbToG -22553 // -0.3441363
+#define dctCrToG -46802 // -0.71413636
+#define dctCbToB 116130 // 1.772
+
+// clip [-256,511] --> [0,255]
+#define dctClipOffset 256
+static Guchar dctClip[768];
+static int dctClipInit = 0;
+
+// zig zag decode map
+static int dctZigZag[64] = {
+ 0,
+ 1, 8,
+ 16, 9, 2,
+ 3, 10, 17, 24,
+ 32, 25, 18, 11, 4,
+ 5, 12, 19, 26, 33, 40,
+ 48, 41, 34, 27, 20, 13, 6,
+ 7, 14, 21, 28, 35, 42, 49, 56,
+ 57, 50, 43, 36, 29, 22, 15,
+ 23, 30, 37, 44, 51, 58,
+ 59, 52, 45, 38, 31,
+ 39, 46, 53, 60,
+ 61, 54, 47,
+ 55, 62,
+ 63
+};
+
+DCTStream::DCTStream(Stream *strA):
+ FilterStream(strA) {
+ int i, j;
+
+ progressive = interleaved = gFalse;
+ width = height = 0;
+ mcuWidth = mcuHeight = 0;
+ numComps = 0;
+ comp = 0;
+ x = y = dy = 0;
+ for (i = 0; i < 4; ++i) {
+ for (j = 0; j < 32; ++j) {
+ rowBuf[i][j] = NULL;
+ }
+ frameBuf[i] = NULL;
+ }
+
+ if (!dctClipInit) {
+ for (i = -256; i < 0; ++i)
+ dctClip[dctClipOffset + i] = 0;
+ for (i = 0; i < 256; ++i)
+ dctClip[dctClipOffset + i] = i;
+ for (i = 256; i < 512; ++i)
+ dctClip[dctClipOffset + i] = 255;
+ dctClipInit = 1;
+ }
+}
+
+DCTStream::~DCTStream() {
+ int i, j;
+
+ delete str;
+ if (progressive || !interleaved) {
+ for (i = 0; i < numComps; ++i) {
+ gfree(frameBuf[i]);
+ }
+ } else {
+ for (i = 0; i < numComps; ++i) {
+ for (j = 0; j < mcuHeight; ++j) {
+ gfree(rowBuf[i][j]);
+ }
+ }
+ }
+}
+
+void DCTStream::reset() {
+ int minHSample, minVSample;
+ int i, j;
+
+ str->reset();
+
+ progressive = interleaved = gFalse;
+ width = height = 0;
+ numComps = 0;
+ numQuantTables = 0;
+ numDCHuffTables = 0;
+ numACHuffTables = 0;
+ colorXform = 0;
+ gotAdobeMarker = gFalse;
+ restartInterval = 0;
+
+ if (!readHeader()) {
+ y = height;
+ return;
+ }
+
+ // compute MCU size
+ mcuWidth = minHSample = compInfo[0].hSample;
+ mcuHeight = minVSample = compInfo[0].vSample;
+ for (i = 1; i < numComps; ++i) {
+ if (compInfo[i].hSample < minHSample)
+ minHSample = compInfo[i].hSample;
+ if (compInfo[i].vSample < minVSample)
+ minVSample = compInfo[i].vSample;
+ if (compInfo[i].hSample > mcuWidth)
+ mcuWidth = compInfo[i].hSample;
+ if (compInfo[i].vSample > mcuHeight)
+ mcuHeight = compInfo[i].vSample;
+ }
+ for (i = 0; i < numComps; ++i) {
+ compInfo[i].hSample /= minHSample;
+ compInfo[i].vSample /= minVSample;
+ }
+ mcuWidth = (mcuWidth / minHSample) * 8;
+ mcuHeight = (mcuHeight / minVSample) * 8;
+
+ // figure out color transform
+ if (!gotAdobeMarker && numComps == 3) {
+ if (compInfo[0].id == 1 && compInfo[1].id == 2 && compInfo[2].id == 3) {
+ colorXform = 1;
+ }
+ }
+
+ if (progressive || !interleaved) {
+
+ // allocate a buffer for the whole image
+ bufWidth = ((width + mcuWidth - 1) / mcuWidth) * mcuWidth;
+ bufHeight = ((height + mcuHeight - 1) / mcuHeight) * mcuHeight;
+ if (bufWidth <= 0 || bufHeight <= 0 ||
+ bufWidth > INT_MAX / bufWidth / (int)sizeof(int)) {
+ error(getPos(), "Invalid image size in DCT stream");
+ y = height;
+ return;
+ }
+ for (i = 0; i < numComps; ++i) {
+ frameBuf[i] = (int *)gmalloc(bufWidth * bufHeight * sizeof(int));
+ memset(frameBuf[i], 0, bufWidth * bufHeight * sizeof(int));
+ }
+
+ // read the image data
+ do {
+ restartMarker = 0xd0;
+ restart();
+ readScan();
+ } while (readHeader());
+
+ // decode
+ decodeImage();
+
+ // initialize counters
+ comp = 0;
+ x = 0;
+ y = 0;
+
+ } else {
+
+ // allocate a buffer for one row of MCUs
+ bufWidth = ((width + mcuWidth - 1) / mcuWidth) * mcuWidth;
+ for (i = 0; i < numComps; ++i) {
+ for (j = 0; j < mcuHeight; ++j) {
+ rowBuf[i][j] = (Guchar *)gmalloc(bufWidth * sizeof(Guchar));
+ }
+ }
+
+ // initialize counters
+ comp = 0;
+ x = 0;
+ y = 0;
+ dy = mcuHeight;
+
+ restartMarker = 0xd0;
+ restart();
+ }
+}
+
+int DCTStream::getChar() {
+ int c;
+
+ if (y >= height) {
+ return EOF;
+ }
+ if (progressive || !interleaved) {
+ c = frameBuf[comp][y * bufWidth + x];
+ if (++comp == numComps) {
+ comp = 0;
+ if (++x == width) {
+ x = 0;
+ ++y;
+ }
+ }
+ } else {
+ if (dy >= mcuHeight) {
+ if (!readMCURow()) {
+ y = height;
+ return EOF;
+ }
+ comp = 0;
+ x = 0;
+ dy = 0;
+ }
+ c = rowBuf[comp][dy][x];
+ if (++comp == numComps) {
+ comp = 0;
+ if (++x == width) {
+ x = 0;
+ ++y;
+ ++dy;
+ if (y == height) {
+ readTrailer();
+ }
+ }
+ }
+ }
+ return c;
+}
+
+int DCTStream::lookChar() {
+ if (y >= height) {
+ return EOF;
+ }
+ if (progressive || !interleaved) {
+ return frameBuf[comp][y * bufWidth + x];
+ } else {
+ if (dy >= mcuHeight) {
+ if (!readMCURow()) {
+ y = height;
+ return EOF;
+ }
+ comp = 0;
+ x = 0;
+ dy = 0;
+ }
+ return rowBuf[comp][dy][x];
+ }
+}
+
+void DCTStream::restart() {
+ int i;
+
+ inputBits = 0;
+ restartCtr = restartInterval;
+ for (i = 0; i < numComps; ++i) {
+ compInfo[i].prevDC = 0;
+ }
+ eobRun = 0;
+}
+
+// Read one row of MCUs from a sequential JPEG stream.
+GBool DCTStream::readMCURow() {
+ int data1[64];
+ Guchar data2[64];
+ Guchar *p1, *p2;
+ int pY, pCb, pCr, pR, pG, pB;
+ int h, v, horiz, vert, hSub, vSub;
+ int x1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
+ int c;
+
+ for (x1 = 0; x1 < width; x1 += mcuWidth) {
+
+ // deal with restart marker
+ if (restartInterval > 0 && restartCtr == 0) {
+ c = readMarker();
+ if (c != restartMarker) {
+ error(getPos(), "Bad DCT data: incorrect restart marker");
+ return gFalse;
+ }
+ if (++restartMarker == 0xd8)
+ restartMarker = 0xd0;
+ restart();
+ }
+
+ // read one MCU
+ for (cc = 0; cc < numComps; ++cc) {
+ h = compInfo[cc].hSample;
+ v = compInfo[cc].vSample;
+ horiz = mcuWidth / h;
+ vert = mcuHeight / v;
+ hSub = horiz / 8;
+ vSub = vert / 8;
+ for (y2 = 0; y2 < mcuHeight; y2 += vert) {
+ for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
+ if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]],
+ &acHuffTables[scanInfo.acHuffTable[cc]],
+ &compInfo[cc].prevDC,
+ data1)) {
+ return gFalse;
+ }
+ transformDataUnit(quantTables[compInfo[cc].quantTable],
+ data1, data2);
+ if (hSub == 1 && vSub == 1) {
+ for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
+ p1 = &rowBuf[cc][y2+y3][x1+x2];
+ p1[0] = data2[i];
+ p1[1] = data2[i+1];
+ p1[2] = data2[i+2];
+ p1[3] = data2[i+3];
+ p1[4] = data2[i+4];
+ p1[5] = data2[i+5];
+ p1[6] = data2[i+6];
+ p1[7] = data2[i+7];
+ }
+ } else if (hSub == 2 && vSub == 2) {
+ for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
+ p1 = &rowBuf[cc][y2+y3][x1+x2];
+ p2 = &rowBuf[cc][y2+y3+1][x1+x2];
+ p1[0] = p1[1] = p2[0] = p2[1] = data2[i];
+ p1[2] = p1[3] = p2[2] = p2[3] = data2[i+1];
+ p1[4] = p1[5] = p2[4] = p2[5] = data2[i+2];
+ p1[6] = p1[7] = p2[6] = p2[7] = data2[i+3];
+ p1[8] = p1[9] = p2[8] = p2[9] = data2[i+4];
+ p1[10] = p1[11] = p2[10] = p2[11] = data2[i+5];
+ p1[12] = p1[13] = p2[12] = p2[13] = data2[i+6];
+ p1[14] = p1[15] = p2[14] = p2[15] = data2[i+7];
+ }
+ } else {
+ i = 0;
+ for (y3 = 0, y4 = 0; y3 < 8; ++y3, y4 += vSub) {
+ for (x3 = 0, x4 = 0; x3 < 8; ++x3, x4 += hSub) {
+ for (y5 = 0; y5 < vSub; ++y5)
+ for (x5 = 0; x5 < hSub; ++x5)
+ rowBuf[cc][y2+y4+y5][x1+x2+x4+x5] = data2[i];
+ ++i;
+ }
+ }
+ }
+ }
+ }
+ }
+ --restartCtr;
+
+ // color space conversion
+ if (colorXform) {
+ // convert YCbCr to RGB
+ if (numComps == 3) {
+ for (y2 = 0; y2 < mcuHeight; ++y2) {
+ for (x2 = 0; x2 < mcuWidth; ++x2) {
+ pY = rowBuf[0][y2][x1+x2];
+ pCb = rowBuf[1][y2][x1+x2] - 128;
+ pCr = rowBuf[2][y2][x1+x2] - 128;
+ pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
+ rowBuf[0][y2][x1+x2] = dctClip[dctClipOffset + pR];
+ pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32768) >> 16;
+ rowBuf[1][y2][x1+x2] = dctClip[dctClipOffset + pG];
+ pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
+ rowBuf[2][y2][x1+x2] = dctClip[dctClipOffset + pB];
+ }
+ }
+ // convert YCbCrK to CMYK (K is passed through unchanged)
+ } else if (numComps == 4) {
+ for (y2 = 0; y2 < mcuHeight; ++y2) {
+ for (x2 = 0; x2 < mcuWidth; ++x2) {
+ pY = rowBuf[0][y2][x1+x2];
+ pCb = rowBuf[1][y2][x1+x2] - 128;
+ pCr = rowBuf[2][y2][x1+x2] - 128;
+ pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
+ rowBuf[0][y2][x1+x2] = 255 - dctClip[dctClipOffset + pR];
+ pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32768) >> 16;
+ rowBuf[1][y2][x1+x2] = 255 - dctClip[dctClipOffset + pG];
+ pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
+ rowBuf[2][y2][x1+x2] = 255 - dctClip[dctClipOffset + pB];
+ }
+ }
+ }
+ }
+ }
+ return gTrue;
+}
+
+// Read one scan from a progressive or non-interleaved JPEG stream.
+void DCTStream::readScan() {
+ int data[64];
+ int x1, y1, dy1, x2, y2, y3, cc, i;
+ int h, v, horiz, vert, hSub, vSub;
+ int *p1;
+ int c;
+
+ if (scanInfo.numComps == 1) {
+ for (cc = 0; cc < numComps; ++cc) {
+ if (scanInfo.comp[cc]) {
+ break;
+ }
+ }
+ dy1 = mcuHeight / compInfo[cc].vSample;
+ } else {
+ dy1 = mcuHeight;
+ }
+
+ for (y1 = 0; y1 < bufHeight; y1 += dy1) {
+ for (x1 = 0; x1 < bufWidth; x1 += mcuWidth) {
+
+ // deal with restart marker
+ if (restartInterval > 0 && restartCtr == 0) {
+ c = readMarker();
+ if (c != restartMarker) {
+ error(getPos(), "Bad DCT data: incorrect restart marker");
+ return;
+ }
+ if (++restartMarker == 0xd8) {
+ restartMarker = 0xd0;
+ }
+ restart();
+ }
+
+ // read one MCU
+ for (cc = 0; cc < numComps; ++cc) {
+ if (!scanInfo.comp[cc]) {
+ continue;
+ }
+
+ h = compInfo[cc].hSample;
+ v = compInfo[cc].vSample;
+ horiz = mcuWidth / h;
+ vert = mcuHeight / v;
+ hSub = horiz / 8;
+ vSub = vert / 8;
+ for (y2 = 0; y2 < dy1; y2 += vert) {
+ for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
+
+ // pull out the current values
+ p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+ for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
+ data[i] = p1[0];
+ data[i+1] = p1[1];
+ data[i+2] = p1[2];
+ data[i+3] = p1[3];
+ data[i+4] = p1[4];
+ data[i+5] = p1[5];
+ data[i+6] = p1[6];
+ data[i+7] = p1[7];
+ p1 += bufWidth * vSub;
+ }
+
+ // read one data unit
+ if (progressive) {
+ if (!readProgressiveDataUnit(
+ &dcHuffTables[scanInfo.dcHuffTable[cc]],
+ &acHuffTables[scanInfo.acHuffTable[cc]],
+ &compInfo[cc].prevDC,
+ data)) {
+ return;
+ }
+ } else {
+ if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]],
+ &acHuffTables[scanInfo.acHuffTable[cc]],
+ &compInfo[cc].prevDC,
+ data)) {
+ return;
+ }
+ }
+
+ // add the data unit into frameBuf
+ p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+ for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
+ p1[0] = data[i];
+ p1[1] = data[i+1];
+ p1[2] = data[i+2];
+ p1[3] = data[i+3];
+ p1[4] = data[i+4];
+ p1[5] = data[i+5];
+ p1[6] = data[i+6];
+ p1[7] = data[i+7];
+ p1 += bufWidth * vSub;
+ }
+ }
+ }
+ }
+ --restartCtr;
+ }
+ }
+}
+
+// Read one data unit from a sequential JPEG stream.
+GBool DCTStream::readDataUnit(DCTHuffTable *dcHuffTable,
+ DCTHuffTable *acHuffTable,
+ int *prevDC, int data[64]) {
+ int run, size, amp;
+ int c;
+ int i, j;
+
+ if ((size = readHuffSym(dcHuffTable)) == 9999) {
+ return gFalse;
+ }
+ if (size > 0) {
+ if ((amp = readAmp(size)) == 9999) {
+ return gFalse;
+ }
+ } else {
+ amp = 0;
+ }
+ data[0] = *prevDC += amp;
+ for (i = 1; i < 64; ++i) {
+ data[i] = 0;
+ }
+ i = 1;
+ while (i < 64) {
+ run = 0;
+ while ((c = readHuffSym(acHuffTable)) == 0xf0 && run < 0x30) {
+ run += 0x10;
+ }
+ if (c == 9999) {
+ return gFalse;
+ }
+ if (c == 0x00) {
+ break;
+ } else {
+ run += (c >> 4) & 0x0f;
+ size = c & 0x0f;
+ amp = readAmp(size);
+ if (amp == 9999) {
+ return gFalse;
+ }
+ i += run;
+ j = dctZigZag[i++];
+ data[j] = amp;
+ }
+ }
+ return gTrue;
+}
+
+// Read one data unit from a sequential JPEG stream.
+GBool DCTStream::readProgressiveDataUnit(DCTHuffTable *dcHuffTable,
+ DCTHuffTable *acHuffTable,
+ int *prevDC, int data[64]) {
+ int run, size, amp, bit, c;
+ int i, j, k;
+
+ // get the DC coefficient
+ i = scanInfo.firstCoeff;
+ if (i == 0) {
+ if (scanInfo.ah == 0) {
+ if ((size = readHuffSym(dcHuffTable)) == 9999) {
+ return gFalse;
+ }
+ if (size > 0) {
+ if ((amp = readAmp(size)) == 9999) {
+ return gFalse;
+ }
+ } else {
+ amp = 0;
+ }
+ data[0] += (*prevDC += amp) << scanInfo.al;
+ } else {
+ if ((bit = readBit()) == 9999) {
+ return gFalse;
+ }
+ data[0] += bit << scanInfo.al;
+ }
+ ++i;
+ }
+ if (scanInfo.lastCoeff == 0) {
+ return gTrue;
+ }
+
+ // check for an EOB run
+ if (eobRun > 0) {
+ while (i <= scanInfo.lastCoeff) {
+ j = dctZigZag[i++];
+ if (data[j] != 0) {
+ if ((bit = readBit()) == EOF) {
+ return gFalse;
+ }
+ if (bit) {
+ data[j] += 1 << scanInfo.al;
+ }
+ }
+ }
+ --eobRun;
+ return gTrue;
+ }
+
+ // read the AC coefficients
+ while (i <= scanInfo.lastCoeff) {
+ if ((c = readHuffSym(acHuffTable)) == 9999) {
+ return gFalse;
+ }
+
+ // ZRL
+ if (c == 0xf0) {
+ k = 0;
+ while (k < 16) {
+ j = dctZigZag[i++];
+ if (data[j] == 0) {
+ ++k;
+ } else {
+ if ((bit = readBit()) == EOF) {
+ return gFalse;
+ }
+ if (bit) {
+ data[j] += 1 << scanInfo.al;
+ }
+ }
+ }
+
+ // EOB run
+ } else if ((c & 0x0f) == 0x00) {
+ j = c >> 4;
+ eobRun = 0;
+ for (k = 0; k < j; ++k) {
+ if ((bit = readBit()) == EOF) {
+ return 9999;
+ }
+ eobRun = (eobRun << 1) | bit;
+ }
+ eobRun += 1 << j;
+ while (i <= scanInfo.lastCoeff) {
+ j = dctZigZag[i++];
+ if (data[j] != 0) {
+ if ((bit = readBit()) == EOF) {
+ return gFalse;
+ }
+ if (bit) {
+ data[j] += 1 << scanInfo.al;
+ }
+ }
+ }
+ --eobRun;
+ break;
+
+ // zero run and one AC coefficient
+ } else {
+ run = (c >> 4) & 0x0f;
+ size = c & 0x0f;
+ if ((amp = readAmp(size)) == 9999) {
+ return gFalse;
+ }
+ k = 0;
+ do {
+ j = dctZigZag[i++];
+ while (data[j] != 0) {
+ if ((bit = readBit()) == EOF) {
+ return gFalse;
+ }
+ if (bit) {
+ data[j] += 1 << scanInfo.al;
+ }
+ j = dctZigZag[i++];
+ }
+ ++k;
+ } while (k <= run);
+ data[j] = amp << scanInfo.al;
+ }
+ }
+
+ return gTrue;
+}
+
+// Decode a progressive JPEG image.
+void DCTStream::decodeImage() {
+ int dataIn[64];
+ Guchar dataOut[64];
+ Guchar *quantTable;
+ int pY, pCb, pCr, pR, pG, pB;
+ int x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
+ int h, v, horiz, vert, hSub, vSub;
+ int *p0, *p1, *p2;
+
+ for (y1 = 0; y1 < bufHeight; y1 += mcuHeight) {
+ for (x1 = 0; x1 < bufWidth; x1 += mcuWidth) {
+ for (cc = 0; cc < numComps; ++cc) {
+ quantTable = quantTables[compInfo[cc].quantTable];
+ h = compInfo[cc].hSample;
+ v = compInfo[cc].vSample;
+ horiz = mcuWidth / h;
+ vert = mcuHeight / v;
+ hSub = horiz / 8;
+ vSub = vert / 8;
+ for (y2 = 0; y2 < mcuHeight; y2 += vert) {
+ for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
+
+ // pull out the coded data unit
+ p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+ for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
+ dataIn[i] = p1[0];
+ dataIn[i+1] = p1[1];
+ dataIn[i+2] = p1[2];
+ dataIn[i+3] = p1[3];
+ dataIn[i+4] = p1[4];
+ dataIn[i+5] = p1[5];
+ dataIn[i+6] = p1[6];
+ dataIn[i+7] = p1[7];
+ p1 += bufWidth * vSub;
+ }
+
+ // transform
+ transformDataUnit(quantTable, dataIn, dataOut);
+
+ // store back into frameBuf, doing replication for
+ // subsampled components
+ p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)];
+ if (hSub == 1 && vSub == 1) {
+ for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
+ p1[0] = dataOut[i] & 0xff;
+ p1[1] = dataOut[i+1] & 0xff;
+ p1[2] = dataOut[i+2] & 0xff;
+ p1[3] = dataOut[i+3] & 0xff;
+ p1[4] = dataOut[i+4] & 0xff;
+ p1[5] = dataOut[i+5] & 0xff;
+ p1[6] = dataOut[i+6] & 0xff;
+ p1[7] = dataOut[i+7] & 0xff;
+ p1 += bufWidth;
+ }
+ } else if (hSub == 2 && vSub == 2) {
+ p2 = p1 + bufWidth;
+ for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
+ p1[0] = p1[1] = p2[0] = p2[1] = dataOut[i] & 0xff;
+ p1[2] = p1[3] = p2[2] = p2[3] = dataOut[i+1] & 0xff;
+ p1[4] = p1[5] = p2[4] = p2[5] = dataOut[i+2] & 0xff;
+ p1[6] = p1[7] = p2[6] = p2[7] = dataOut[i+3] & 0xff;
+ p1[8] = p1[9] = p2[8] = p2[9] = dataOut[i+4] & 0xff;
+ p1[10] = p1[11] = p2[10] = p2[11] = dataOut[i+5] & 0xff;
+ p1[12] = p1[13] = p2[12] = p2[13] = dataOut[i+6] & 0xff;
+ p1[14] = p1[15] = p2[14] = p2[15] = dataOut[i+7] & 0xff;
+ p1 += bufWidth * 2;
+ p2 += bufWidth * 2;
+ }
+ } else {
+ i = 0;
+ for (y3 = 0, y4 = 0; y3 < 8; ++y3, y4 += vSub) {
+ for (x3 = 0, x4 = 0; x3 < 8; ++x3, x4 += hSub) {
+ p2 = p1 + x4;
+ for (y5 = 0; y5 < vSub; ++y5) {
+ for (x5 = 0; x5 < hSub; ++x5) {
+ p2[x5] = dataOut[i] & 0xff;
+ }
+ p2 += bufWidth;
+ }
+ ++i;
+ }
+ p1 += bufWidth * vSub;
+ }
+ }
+ }
+ }
+ }
+
+ // color space conversion
+ if (colorXform) {
+ // convert YCbCr to RGB
+ if (numComps == 3) {
+ for (y2 = 0; y2 < mcuHeight; ++y2) {
+ p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
+ p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
+ p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
+ for (x2 = 0; x2 < mcuWidth; ++x2) {
+ pY = *p0;
+ pCb = *p1 - 128;
+ pCr = *p2 - 128;
+ pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
+ *p0++ = dctClip[dctClipOffset + pR];
+ pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr +
+ 32768) >> 16;
+ *p1++ = dctClip[dctClipOffset + pG];
+ pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
+ *p2++ = dctClip[dctClipOffset + pB];
+ }
+ }
+ // convert YCbCrK to CMYK (K is passed through unchanged)
+ } else if (numComps == 4) {
+ for (y2 = 0; y2 < mcuHeight; ++y2) {
+ p0 = &frameBuf[0][(y1+y2) * bufWidth + x1];
+ p1 = &frameBuf[1][(y1+y2) * bufWidth + x1];
+ p2 = &frameBuf[2][(y1+y2) * bufWidth + x1];
+ for (x2 = 0; x2 < mcuWidth; ++x2) {
+ pY = *p0;
+ pCb = *p1 - 128;
+ pCr = *p2 - 128;
+ pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
+ *p0++ = 255 - dctClip[dctClipOffset + pR];
+ pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr +
+ 32768) >> 16;
+ *p1++ = 255 - dctClip[dctClipOffset + pG];
+ pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
+ *p2++ = 255 - dctClip[dctClipOffset + pB];
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+// Transform one data unit -- this performs the dequantization and
+// IDCT steps. This IDCT algorithm is taken from:
+// Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
+// "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
+// IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
+// 988-991.
+// The stage numbers mentioned in the comments refer to Figure 1 in this
+// paper.
+void DCTStream::transformDataUnit(Guchar *quantTable,
+ int dataIn[64], Guchar dataOut[64]) {
+ int v0, v1, v2, v3, v4, v5, v6, v7, t;
+ int *p;
+ int i;
+
+ // dequant
+ for (i = 0; i < 64; ++i) {
+ dataIn[i] *= quantTable[i];
+ }
+
+ // inverse DCT on rows
+ for (i = 0; i < 64; i += 8) {
+ p = dataIn + i;
+
+ // check for all-zero AC coefficients
+ if (p[1] == 0 && p[2] == 0 && p[3] == 0 &&
+ p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] == 0) {
+ t = (dctSqrt2 * p[0] + 512) >> 10;
+ p[0] = t;
+ p[1] = t;
+ p[2] = t;
+ p[3] = t;
+ p[4] = t;
+ p[5] = t;
+ p[6] = t;
+ p[7] = t;
+ continue;
+ }
+
+ // stage 4
+ v0 = (dctSqrt2 * p[0] + 128) >> 8;
+ v1 = (dctSqrt2 * p[4] + 128) >> 8;
+ v2 = p[2];
+ v3 = p[6];
+ v4 = (dctSqrt1d2 * (p[1] - p[7]) + 128) >> 8;
+ v7 = (dctSqrt1d2 * (p[1] + p[7]) + 128) >> 8;
+ v5 = p[3] << 4;
+ v6 = p[5] << 4;
+
+ // stage 3
+ t = (v0 - v1+ 1) >> 1;
+ v0 = (v0 + v1 + 1) >> 1;
+ v1 = t;
+ t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
+ v3 = t;
+ t = (v4 - v6 + 1) >> 1;
+ v4 = (v4 + v6 + 1) >> 1;
+ v6 = t;
+ t = (v7 + v5 + 1) >> 1;
+ v5 = (v7 - v5 + 1) >> 1;
+ v7 = t;
+
+ // stage 2
+ t = (v0 - v3 + 1) >> 1;
+ v0 = (v0 + v3 + 1) >> 1;
+ v3 = t;
+ t = (v1 - v2 + 1) >> 1;
+ v1 = (v1 + v2 + 1) >> 1;
+ v2 = t;
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
+ v7 = t;
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
+ v6 = t;
+
+ // stage 1
+ p[0] = v0 + v7;
+ p[7] = v0 - v7;
+ p[1] = v1 + v6;
+ p[6] = v1 - v6;
+ p[2] = v2 + v5;
+ p[5] = v2 - v5;
+ p[3] = v3 + v4;
+ p[4] = v3 - v4;
+ }
+
+ // inverse DCT on columns
+ for (i = 0; i < 8; ++i) {
+ p = dataIn + i;
+
+ // check for all-zero AC coefficients
+ if (p[1*8] == 0 && p[2*8] == 0 && p[3*8] == 0 &&
+ p[4*8] == 0 && p[5*8] == 0 && p[6*8] == 0 && p[7*8] == 0) {
+ t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
+ p[0*8] = t;
+ p[1*8] = t;
+ p[2*8] = t;
+ p[3*8] = t;
+ p[4*8] = t;
+ p[5*8] = t;
+ p[6*8] = t;
+ p[7*8] = t;
+ continue;
+ }
+
+ // stage 4
+ v0 = (dctSqrt2 * p[0*8] + 2048) >> 12;
+ v1 = (dctSqrt2 * p[4*8] + 2048) >> 12;
+ v2 = p[2*8];
+ v3 = p[6*8];
+ v4 = (dctSqrt1d2 * (p[1*8] - p[7*8]) + 2048) >> 12;
+ v7 = (dctSqrt1d2 * (p[1*8] + p[7*8]) + 2048) >> 12;
+ v5 = p[3*8];
+ v6 = p[5*8];
+
+ // stage 3
+ t = (v0 - v1 + 1) >> 1;
+ v0 = (v0 + v1 + 1) >> 1;
+ v1 = t;
+ t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
+ v3 = t;
+ t = (v4 - v6 + 1) >> 1;
+ v4 = (v4 + v6 + 1) >> 1;
+ v6 = t;
+ t = (v7 + v5 + 1) >> 1;
+ v5 = (v7 - v5 + 1) >> 1;
+ v7 = t;
+
+ // stage 2
+ t = (v0 - v3 + 1) >> 1;
+ v0 = (v0 + v3 + 1) >> 1;
+ v3 = t;
+ t = (v1 - v2 + 1) >> 1;
+ v1 = (v1 + v2 + 1) >> 1;
+ v2 = t;
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
+ v7 = t;
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
+ v6 = t;
+
+ // stage 1
+ p[0*8] = v0 + v7;
+ p[7*8] = v0 - v7;
+ p[1*8] = v1 + v6;
+ p[6*8] = v1 - v6;
+ p[2*8] = v2 + v5;
+ p[5*8] = v2 - v5;
+ p[3*8] = v3 + v4;
+ p[4*8] = v3 - v4;
+ }
+
+ // convert to 8-bit integers
+ for (i = 0; i < 64; ++i) {
+ dataOut[i] = dctClip[dctClipOffset + 128 + ((dataIn[i] + 8) >> 4)];
+ }
+}
+
+int DCTStream::readHuffSym(DCTHuffTable *table) {
+ Gushort code;
+ int bit;
+ int codeBits;
+
+ code = 0;
+ codeBits = 0;
+ do {
+ // add a bit to the code
+ if ((bit = readBit()) == EOF)
+ return 9999;
+ code = (code << 1) + bit;
+ ++codeBits;
+
+ // look up code
+ if (code - table->firstCode[codeBits] < table->numCodes[codeBits]) {
+ code -= table->firstCode[codeBits];
+ return table->sym[table->firstSym[codeBits] + code];
+ }
+ } while (codeBits < 16);
+
+ error(getPos(), "Bad Huffman code in DCT stream");
+ return 9999;
+}
+
+int DCTStream::readAmp(int size) {
+ int amp, bit;
+ int bits;
+
+ amp = 0;
+ for (bits = 0; bits < size; ++bits) {
+ if ((bit = readBit()) == EOF)
+ return 9999;
+ amp = (amp << 1) + bit;
+ }
+ if (amp < (1 << (size - 1)))
+ amp -= (1 << size) - 1;
+ return amp;
+}
+
+int DCTStream::readBit() {
+ int bit;
+ int c, c2;
+
+ if (inputBits == 0) {
+ if ((c = str->getChar()) == EOF)
+ return EOF;
+ if (c == 0xff) {
+ do {
+ c2 = str->getChar();
+ } while (c2 == 0xff);
+ if (c2 != 0x00) {
+ error(getPos(), "Bad DCT data: missing 00 after ff");
+ return EOF;
+ }
+ }
+ inputBuf = c;
+ inputBits = 8;
+ }
+ bit = (inputBuf >> (inputBits - 1)) & 1;
+ --inputBits;
+ return bit;
+}
+
+GBool DCTStream::readHeader() {
+ GBool doScan;
+ int n;
+ int c = 0;
+ int i;
+
+ // read headers
+ doScan = gFalse;
+ while (!doScan) {
+ c = readMarker();
+ switch (c) {
+ case 0xc0: // SOF0
+ if (!readBaselineSOF()) {
+ return gFalse;
+ }
+ break;
+ case 0xc2: // SOF2
+ if (!readProgressiveSOF()) {
+ return gFalse;
+ }
+ break;
+ case 0xc4: // DHT
+ if (!readHuffmanTables()) {
+ return gFalse;
+ }
+ break;
+ case 0xd8: // SOI
+ break;
+ case 0xd9: // EOI
+ return gFalse;
+ break;
+ case 0xda: // SOS
+ if (!readScanInfo()) {
+ return gFalse;
+ }
+ doScan = gTrue;
+ break;
+ case 0xdb: // DQT
+ if (!readQuantTables()) {
+ return gFalse;
+ }
+ break;
+ case 0xdd: // DRI
+ if (!readRestartInterval()) {
+ return gFalse;
+ }
+ break;
+ case 0xee: // APP14
+ if (!readAdobeMarker()) {
+ return gFalse;
+ }
+ break;
+ case EOF:
+ error(getPos(), "Bad DCT header");
+ return gFalse;
+ default:
+ // skip APPn / COM / etc.
+ if (c >= 0xe0) {
+ n = read16() - 2;
+ for (i = 0; i < n; ++i) {
+ str->getChar();
+ }
+ } else {
+ error(getPos(), "Unknown DCT marker <%02x>", c);
+ return gFalse;
+ }
+ break;
+ }
+ }
+
+ return gTrue;
+}
+
+GBool DCTStream::readBaselineSOF() {
+ int length;
+ int prec;
+ int i;
+ int c;
+
+ length = read16();
+ prec = str->getChar();
+ height = read16();
+ width = read16();
+ numComps = str->getChar();
+ if (numComps <= 0 || numComps > 4) {
+ numComps = 0;
+ error(getPos(), "Bad number of components in DCT stream");
+ return gFalse;
+ }
+ if (prec != 8) {
+ error(getPos(), "Bad DCT precision %d", prec);
+ return gFalse;
+ }
+ for (i = 0; i < numComps; ++i) {
+ compInfo[i].id = str->getChar();
+ c = str->getChar();
+ compInfo[i].hSample = (c >> 4) & 0x0f;
+ compInfo[i].vSample = c & 0x0f;
+ compInfo[i].quantTable = str->getChar();
+ }
+ progressive = gFalse;
+ return gTrue;
+}
+
+GBool DCTStream::readProgressiveSOF() {
+ int length;
+ int prec;
+ int i;
+ int c;
+
+ length = read16();
+ prec = str->getChar();
+ height = read16();
+ width = read16();
+ numComps = str->getChar();
+ if (numComps <= 0 || numComps > 4) {
+ numComps = 0;
+ error(getPos(), "Bad number of components in DCT stream");
+ return gFalse;
+ }
+ if (prec != 8) {
+ error(getPos(), "Bad DCT precision %d", prec);
+ return gFalse;
+ }
+ for (i = 0; i < numComps; ++i) {
+ compInfo[i].id = str->getChar();
+ c = str->getChar();
+ compInfo[i].hSample = (c >> 4) & 0x0f;
+ compInfo[i].vSample = c & 0x0f;
+ compInfo[i].quantTable = str->getChar();
+ }
+ progressive = gTrue;
+ return gTrue;
+}
+
+GBool DCTStream::readScanInfo() {
+ int length;
+ int id, c;
+ int i, j;
+
+ length = read16() - 2;
+ scanInfo.numComps = str->getChar();
+ if (scanInfo.numComps <= 0 || scanInfo.numComps > 4) {
+ scanInfo.numComps = 0;
+ error(getPos(), "Bad number of components in DCT stream");
+ return gFalse;
+ }
+ --length;
+ if (length != 2 * scanInfo.numComps + 3) {
+ error(getPos(), "Bad DCT scan info block");
+ return gFalse;
+ }
+ interleaved = scanInfo.numComps == numComps;
+ for (j = 0; j < numComps; ++j) {
+ scanInfo.comp[j] = gFalse;
+ }
+ for (i = 0; i < scanInfo.numComps; ++i) {
+ id = str->getChar();
+ for (j = 0; j < numComps; ++j) {
+ if (id == compInfo[j].id) {
+ break;
+ }
+ }
+ if (j == numComps) {
+ error(getPos(), "Bad DCT component ID in scan info block");
+ return gFalse;
+ }
+ scanInfo.comp[j] = gTrue;
+ c = str->getChar();
+ scanInfo.dcHuffTable[j] = (c >> 4) & 0x0f;
+ scanInfo.acHuffTable[j] = c & 0x0f;
+ }
+ scanInfo.firstCoeff = str->getChar();
+ scanInfo.lastCoeff = str->getChar();
+ if (scanInfo.firstCoeff < 0 || scanInfo.lastCoeff > 63 ||
+ scanInfo.firstCoeff > scanInfo.lastCoeff) {
+ error(getPos(), "Bad DCT coefficient numbers in scan info block");
+ return gFalse;
+ }
+ c = str->getChar();
+ scanInfo.ah = (c >> 4) & 0x0f;
+ scanInfo.al = c & 0x0f;
+ return gTrue;
+}
+
+GBool DCTStream::readQuantTables() {
+ int length;
+ int i;
+ int index;
+
+ length = read16() - 2;
+ while (length > 0) {
+ index = str->getChar();
+ if ((index & 0xf0) || index >= 4) {
+ error(getPos(), "Bad DCT quantization table");
+ return gFalse;
+ }
+ if (index == numQuantTables)
+ numQuantTables = index + 1;
+ for (i = 0; i < 64; ++i)
+ quantTables[index][dctZigZag[i]] = str->getChar();
+ length -= 65;
+ }
+ return gTrue;
+}
+
+GBool DCTStream::readHuffmanTables() {
+ DCTHuffTable *tbl;
+ int length;
+ int index;
+ Gushort code;
+ Guchar sym;
+ int i;
+ int c;
+
+ length = read16() - 2;
+ while (length > 0) {
+ index = str->getChar();
+ --length;
+ if ((index & ~0x10) >= 4 || (index & ~0x10) < 0) {
+ error(getPos(), "Bad DCT Huffman table");
+ return gFalse;
+ }
+ if (index & 0x10) {
+ index &= 0x03;
+ if (index >= numACHuffTables)
+ numACHuffTables = index+1;
+ tbl = &acHuffTables[index];
+ } else {
+ if (index >= numDCHuffTables)
+ numDCHuffTables = index+1;
+ tbl = &dcHuffTables[index];
+ }
+ sym = 0;
+ code = 0;
+ for (i = 1; i <= 16; ++i) {
+ c = str->getChar();
+ tbl->firstSym[i] = sym;
+ tbl->firstCode[i] = code;
+ tbl->numCodes[i] = c;
+ sym += c;
+ code = (code + c) << 1;
+ }
+ length -= 16;
+ for (i = 0; i < sym; ++i)
+ tbl->sym[i] = str->getChar();
+ length -= sym;
+ }
+ return gTrue;
+}
+
+GBool DCTStream::readRestartInterval() {
+ int length;
+
+ length = read16();
+ if (length != 4) {
+ error(getPos(), "Bad DCT restart interval");
+ return gFalse;
+ }
+ restartInterval = read16();
+ return gTrue;
+}
+
+GBool DCTStream::readAdobeMarker() {
+ int length, i;
+ char buf[12];
+ int c;
+
+ length = read16();
+ if (length < 14) {
+ goto err;
+ }
+ for (i = 0; i < 12; ++i) {
+ if ((c = str->getChar()) == EOF) {
+ goto err;
+ }
+ buf[i] = c;
+ }
+ if (strncmp(buf, "Adobe", 5)) {
+ goto err;
+ }
+ colorXform = buf[11];
+ gotAdobeMarker = gTrue;
+ for (i = 14; i < length; ++i) {
+ if (str->getChar() == EOF) {
+ goto err;
+ }
+ }
+ return gTrue;
+
+ err:
+ error(getPos(), "Bad DCT Adobe APP14 marker");
+ return gFalse;
+}
+
+GBool DCTStream::readTrailer() {
+ int c;
+
+ c = readMarker();
+ if (c != 0xd9) { // EOI
+ error(getPos(), "Bad DCT trailer");
+ return gFalse;
+ }
+ return gTrue;
+}
+
+int DCTStream::readMarker() {
+ int c;
+
+ do {
+ do {
+ c = str->getChar();
+ if(c == EOF) return EOF;
+ } while (c != 0xff);
+ do {
+ c = str->getChar();
+ if(c == EOF) return EOF;
+ } while (c == 0xff);
+ } while (c == 0x00);
+ return c;
+}
+
+int DCTStream::read16() {
+ int c1, c2;
+
+ if ((c1 = str->getChar()) == EOF)
+ return EOF;
+ if ((c2 = str->getChar()) == EOF)
+ return EOF;
+ return (c1 << 8) + c2;
+}
+
+GString *DCTStream::getPSFilter(const char *indent) {
+ GString *s;
+
+ if (!(s = str->getPSFilter(indent))) {
+ return NULL;
+ }
+ s->append(indent)->append("<< >> /DCTDecode filter\n");
+ return s;
+}
+
+GBool DCTStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+//------------------------------------------------------------------------
+// FlateStream
+//------------------------------------------------------------------------
+
+int FlateStream::codeLenCodeMap[flateMaxCodeLenCodes] = {
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+};
+
+FlateDecode FlateStream::lengthDecode[flateMaxLitCodes-257] = {
+ {0, 3},
+ {0, 4},
+ {0, 5},
+ {0, 6},
+ {0, 7},
+ {0, 8},
+ {0, 9},
+ {0, 10},
+ {1, 11},
+ {1, 13},
+ {1, 15},
+ {1, 17},
+ {2, 19},
+ {2, 23},
+ {2, 27},
+ {2, 31},
+ {3, 35},
+ {3, 43},
+ {3, 51},
+ {3, 59},
+ {4, 67},
+ {4, 83},
+ {4, 99},
+ {4, 115},
+ {5, 131},
+ {5, 163},
+ {5, 195},
+ {5, 227},
+ {0, 258}
+};
+
+FlateDecode FlateStream::distDecode[flateMaxDistCodes] = {
+ { 0, 1},
+ { 0, 2},
+ { 0, 3},
+ { 0, 4},
+ { 1, 5},
+ { 1, 7},
+ { 2, 9},
+ { 2, 13},
+ { 3, 17},
+ { 3, 25},
+ { 4, 33},
+ { 4, 49},
+ { 5, 65},
+ { 5, 97},
+ { 6, 129},
+ { 6, 193},
+ { 7, 257},
+ { 7, 385},
+ { 8, 513},
+ { 8, 769},
+ { 9, 1025},
+ { 9, 1537},
+ {10, 2049},
+ {10, 3073},
+ {11, 4097},
+ {11, 6145},
+ {12, 8193},
+ {12, 12289},
+ {13, 16385},
+ {13, 24577}
+};
+
+FlateStream::FlateStream(Stream *strA, int predictor, int columns,
+ int colors, int bits):
+ FilterStream(strA) {
+ if (predictor != 1) {
+ pred = new StreamPredictor(this, predictor, columns, colors, bits);
+ if ( !pred->isOk()) {
+ delete pred;
+ pred = NULL;
+ }
+ } else {
+ pred = NULL;
+ }
+ litCodeTab.codes = NULL;
+ distCodeTab.codes = NULL;
+}
+
+FlateStream::~FlateStream() {
+ gfree(litCodeTab.codes);
+ gfree(distCodeTab.codes);
+ if (pred) {
+ delete pred;
+ }
+ delete str;
+}
+
+void FlateStream::reset() {
+ int cmf, flg;
+
+ index = 0;
+ remain = 0;
+ codeBuf = 0;
+ codeSize = 0;
+ compressedBlock = gFalse;
+ endOfBlock = gTrue;
+ eof = gTrue;
+
+ str->reset();
+
+ // read header
+ //~ need to look at window size?
+ endOfBlock = eof = gTrue;
+ cmf = str->getChar();
+ flg = str->getChar();
+ if (cmf == EOF || flg == EOF)
+ return;
+ if ((cmf & 0x0f) != 0x08) {
+ error(getPos(), "Unknown compression method in flate stream");
+ return;
+ }
+ if ((((cmf << 8) + flg) % 31) != 0) {
+ error(getPos(), "Bad FCHECK in flate stream");
+ return;
+ }
+ if (flg & 0x20) {
+ error(getPos(), "FDICT bit set in flate stream");
+ return;
+ }
+
+ eof = gFalse;
+}
+
+int FlateStream::getChar() {
+ int c;
+
+ if (pred) {
+ return pred->getChar();
+ }
+ while (remain == 0) {
+ if (endOfBlock && eof)
+ return EOF;
+ readSome();
+ }
+ c = buf[index];
+ index = (index + 1) & flateMask;
+ --remain;
+ return c;
+}
+
+int FlateStream::lookChar() {
+ int c;
+
+ if (pred) {
+ return pred->lookChar();
+ }
+ while (remain == 0) {
+ if (endOfBlock && eof)
+ return EOF;
+ readSome();
+ }
+ c = buf[index];
+ return c;
+}
+
+int FlateStream::getRawChar() {
+ int c;
+
+ while (remain == 0) {
+ if (endOfBlock && eof)
+ return EOF;
+ readSome();
+ }
+ c = buf[index];
+ index = (index + 1) & flateMask;
+ --remain;
+ return c;
+}
+
+GString *FlateStream::getPSFilter(const char */*indent*/) {
+ return NULL;
+}
+
+GBool FlateStream::isBinary(GBool /*last*/) {
+ return str->isBinary(gTrue);
+}
+
+void FlateStream::readSome() {
+ int code1, code2;
+ int len, dist;
+ int i, j, k;
+ int c;
+
+ if (endOfBlock) {
+ if (!startBlock())
+ return;
+ }
+
+ if (compressedBlock) {
+ if ((code1 = getHuffmanCodeWord(&litCodeTab)) == EOF)
+ goto err;
+ if (code1 < 256) {
+ buf[index] = code1;
+ remain = 1;
+ } else if (code1 == 256) {
+ endOfBlock = gTrue;
+ remain = 0;
+ } else {
+ code1 -= 257;
+ code2 = lengthDecode[code1].bits;
+ if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
+ goto err;
+ len = lengthDecode[code1].first + code2;
+ if ((code1 = getHuffmanCodeWord(&distCodeTab)) == EOF)
+ goto err;
+ code2 = distDecode[code1].bits;
+ if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
+ goto err;
+ dist = distDecode[code1].first + code2;
+ i = index;
+ j = (index - dist) & flateMask;
+ for (k = 0; k < len; ++k) {
+ buf[i] = buf[j];
+ i = (i + 1) & flateMask;
+ j = (j + 1) & flateMask;
+ }
+ remain = len;
+ }
+
+ } else {
+ len = (blockLen < flateWindow) ? blockLen : flateWindow;
+ for (i = 0, j = index; i < len; ++i, j = (j + 1) & flateMask) {
+ if ((c = str->getChar()) == EOF) {
+ endOfBlock = eof = gTrue;
+ break;
+ }
+ buf[j] = c & 0xff;
+ }
+ remain = i;
+ blockLen -= len;
+ if (blockLen == 0)
+ endOfBlock = gTrue;
+ }
+
+ return;
+
+err:
+ error(getPos(), "Unexpected end of file in flate stream");
+ endOfBlock = eof = gTrue;
+ remain = 0;
+}
+
+GBool FlateStream::startBlock() {
+ int blockHdr;
+ int c;
+ int check;
+
+ // free the code tables from the previous block
+ gfree(litCodeTab.codes);
+ litCodeTab.codes = NULL;
+ gfree(distCodeTab.codes);
+ distCodeTab.codes = NULL;
+
+ // read block header
+ blockHdr = getCodeWord(3);
+ if (blockHdr & 1)
+ eof = gTrue;
+ blockHdr >>= 1;
+
+ // uncompressed block
+ if (blockHdr == 0) {
+ compressedBlock = gFalse;
+ if ((c = str->getChar()) == EOF)
+ goto err;
+ blockLen = c & 0xff;
+ if ((c = str->getChar()) == EOF)
+ goto err;
+ blockLen |= (c & 0xff) << 8;
+ if ((c = str->getChar()) == EOF)
+ goto err;
+ check = c & 0xff;
+ if ((c = str->getChar()) == EOF)
+ goto err;
+ check |= (c & 0xff) << 8;
+ if (check != (~blockLen & 0xffff))
+ error(getPos(), "Bad uncompressed block length in flate stream");
+ codeBuf = 0;
+ codeSize = 0;
+
+ // compressed block with fixed codes
+ } else if (blockHdr == 1) {
+ compressedBlock = gTrue;
+ loadFixedCodes();
+
+ // compressed block with dynamic codes
+ } else if (blockHdr == 2) {
+ compressedBlock = gTrue;
+ if (!readDynamicCodes()) {
+ goto err;
+ }
+
+ // unknown block type
+ } else {
+ goto err;
+ }
+
+ endOfBlock = gFalse;
+ return gTrue;
+
+err:
+ error(getPos(), "Bad block header in flate stream");
+ endOfBlock = eof = gTrue;
+ return gFalse;
+}
+
+void FlateStream::loadFixedCodes() {
+ int i;
+
+ // build the literal code table
+ for (i = 0; i <= 143; ++i) {
+ codeLengths[i] = 8;
+ }
+ for (i = 144; i <= 255; ++i) {
+ codeLengths[i] = 9;
+ }
+ for (i = 256; i <= 279; ++i) {
+ codeLengths[i] = 7;
+ }
+ for (i = 280; i <= 287; ++i) {
+ codeLengths[i] = 8;
+ }
+ compHuffmanCodes(codeLengths, flateMaxLitCodes, &litCodeTab);
+
+ // build the distance code table
+ for (i = 0; i < flateMaxDistCodes; ++i) {
+ codeLengths[i] = 5;
+ }
+ compHuffmanCodes(codeLengths, flateMaxDistCodes, &distCodeTab);
+}
+
+GBool FlateStream::readDynamicCodes() {
+ int numCodeLenCodes;
+ int numLitCodes;
+ int numDistCodes;
+ int codeLenCodeLengths[flateMaxCodeLenCodes];
+ FlateHuffmanTab codeLenCodeTab;
+ int len, repeat, code;
+ int i;
+
+ // read lengths
+ if ((numLitCodes = getCodeWord(5)) == EOF) {
+ goto err;
+ }
+ numLitCodes += 257;
+ if ((numDistCodes = getCodeWord(5)) == EOF) {
+ goto err;
+ }
+ numDistCodes += 1;
+ if ((numCodeLenCodes = getCodeWord(4)) == EOF) {
+ goto err;
+ }
+ numCodeLenCodes += 4;
+ if (numLitCodes > flateMaxLitCodes ||
+ numDistCodes > flateMaxDistCodes ||
+ numCodeLenCodes > flateMaxCodeLenCodes) {
+ goto err;
+ }
+
+ // build the code length code table
+ for (i = 0; i < flateMaxCodeLenCodes; ++i) {
+ codeLenCodeLengths[i] = 0;
+ }
+ for (i = 0; i < numCodeLenCodes; ++i) {
+ if ((codeLenCodeLengths[codeLenCodeMap[i]] = getCodeWord(3)) == -1) {
+ goto err;
+ }
+ }
+ compHuffmanCodes(codeLenCodeLengths, flateMaxCodeLenCodes, &codeLenCodeTab);
+
+ // build the literal and distance code tables
+ len = 0;
+ repeat = 0;
+ i = 0;
+ while (i < numLitCodes + numDistCodes) {
+ if ((code = getHuffmanCodeWord(&codeLenCodeTab)) == EOF) {
+ goto err;
+ }
+ if (code == 16) {
+ if ((repeat = getCodeWord(2)) == EOF) {
+ goto err;
+ }
+ for (repeat += 3; repeat > 0; --repeat) {
+ codeLengths[i++] = len;
+ }
+ } else if (code == 17) {
+ if ((repeat = getCodeWord(3)) == EOF) {
+ goto err;
+ }
+ len = 0;
+ for (repeat += 3; repeat > 0; --repeat) {
+ codeLengths[i++] = 0;
+ }
+ } else if (code == 18) {
+ if ((repeat = getCodeWord(7)) == EOF) {
+ goto err;
+ }
+ len = 0;
+ for (repeat += 11; repeat > 0; --repeat) {
+ codeLengths[i++] = 0;
+ }
+ } else {
+ codeLengths[i++] = len = code;
+ }
+ }
+ compHuffmanCodes(codeLengths, numLitCodes, &litCodeTab);
+ compHuffmanCodes(codeLengths + numLitCodes, numDistCodes, &distCodeTab);
+
+ gfree(codeLenCodeTab.codes);
+ return gTrue;
+
+err:
+ error(getPos(), "Bad dynamic code table in flate stream");
+ gfree(codeLenCodeTab.codes);
+ return gFalse;
+}
+
+// Convert an array <lengths> of <n> lengths, in value order, into a
+// Huffman code lookup table.
+void FlateStream::compHuffmanCodes(int *lengths, int n, FlateHuffmanTab *tab) {
+ int tabSize, len, code, code2, skip, val, i, t;
+
+ // find max code length
+ tab->maxLen = 0;
+ for (val = 0; val < n; ++val) {
+ if (lengths[val] > tab->maxLen) {
+ tab->maxLen = lengths[val];
+ }
+ }
+
+ // allocate the table
+ tabSize = 1 << tab->maxLen;
+ tab->codes = (FlateCode *)gmalloc(tabSize * sizeof(FlateCode));
+
+ // clear the table
+ for (i = 0; i < tabSize; ++i) {
+ tab->codes[i].len = 0;
+ tab->codes[i].val = 0;
+ }
+
+ // build the table
+ for (len = 1, code = 0, skip = 2;
+ len <= tab->maxLen;
+ ++len, code <<= 1, skip <<= 1) {
+ for (val = 0; val < n; ++val) {
+ if (lengths[val] == len) {
+
+ // bit-reverse the code
+ code2 = 0;
+ t = code;
+ for (i = 0; i < len; ++i) {
+ code2 = (code2 << 1) | (t & 1);
+ t >>= 1;
+ }
+
+ // fill in the table entries
+ for (i = code2; i < tabSize; i += skip) {
+ tab->codes[i].len = (Gushort)len;
+ tab->codes[i].val = (Gushort)val;
+ }
+
+ ++code;
+ }
+ }
+ }
+}
+
+int FlateStream::getHuffmanCodeWord(FlateHuffmanTab *tab) {
+ FlateCode *code;
+ int c;
+
+ while (codeSize < tab->maxLen) {
+ if ((c = str->getChar()) == EOF) {
+ break;
+ }
+ codeBuf |= (c & 0xff) << codeSize;
+ codeSize += 8;
+ }
+ code = &tab->codes[codeBuf & ((1 << tab->maxLen) - 1)];
+ if (codeSize == 0 || codeSize < code->len || code->len == 0) {
+ return EOF;
+ }
+ codeBuf >>= code->len;
+ codeSize -= code->len;
+ return (int)code->val;
+}
+
+int FlateStream::getCodeWord(int bits) {
+ int c;
+
+ while (codeSize < bits) {
+ if ((c = str->getChar()) == EOF)
+ return EOF;
+ codeBuf |= (c & 0xff) << codeSize;
+ codeSize += 8;
+ }
+ c = codeBuf & ((1 << bits) - 1);
+ codeBuf >>= bits;
+ codeSize -= bits;
+ return c;
+}
+
+//------------------------------------------------------------------------
+// EOFStream
+//------------------------------------------------------------------------
+
+EOFStream::EOFStream(Stream *strA):
+ FilterStream(strA) {
+}
+
+EOFStream::~EOFStream() {
+ delete str;
+}
+
+//------------------------------------------------------------------------
+// FixedLengthEncoder
+//------------------------------------------------------------------------
+
+FixedLengthEncoder::FixedLengthEncoder(Stream *strA, int lengthA):
+ FilterStream(strA) {
+ length = lengthA;
+ count = 0;
+}
+
+FixedLengthEncoder::~FixedLengthEncoder() {
+ if (str->isEncoder())
+ delete str;
+}
+
+void FixedLengthEncoder::reset() {
+ str->reset();
+ count = 0;
+}
+
+void FixedLengthEncoder::close() {
+}
+
+int FixedLengthEncoder::getChar() {
+ if (length >= 0 && count >= length)
+ return EOF;
+ ++count;
+ return str->getChar();
+}
+
+int FixedLengthEncoder::lookChar() {
+ if (length >= 0 && count >= length)
+ return EOF;
+ return str->getChar();
+}
+
+//------------------------------------------------------------------------
+// ASCIIHexEncoder
+//------------------------------------------------------------------------
+
+ASCIIHexEncoder::ASCIIHexEncoder(Stream *strA):
+ FilterStream(strA) {
+ bufPtr = bufEnd = buf;
+ lineLen = 0;
+ eof = gFalse;
+}
+
+ASCIIHexEncoder::~ASCIIHexEncoder() {
+ if (str->isEncoder()) {
+ delete str;
+ }
+}
+
+void ASCIIHexEncoder::reset() {
+ str->reset();
+ bufPtr = bufEnd = buf;
+ lineLen = 0;
+ eof = gFalse;
+}
+
+void ASCIIHexEncoder::close() {
+}
+
+GBool ASCIIHexEncoder::fillBuf() {
+ static const char *hex = "0123456789abcdef";
+ int c;
+
+ if (eof) {
+ return gFalse;
+ }
+ bufPtr = bufEnd = buf;
+ if ((c = str->getChar()) == EOF) {
+ *bufEnd++ = '>';
+ eof = gTrue;
+ } else {
+ if (lineLen >= 64) {
+ *bufEnd++ = '\n';
+ lineLen = 0;
+ }
+ *bufEnd++ = hex[(c >> 4) & 0x0f];
+ *bufEnd++ = hex[c & 0x0f];
+ lineLen += 2;
+ }
+ return gTrue;
+}
+
+//------------------------------------------------------------------------
+// ASCII85Encoder
+//------------------------------------------------------------------------
+
+ASCII85Encoder::ASCII85Encoder(Stream *strA):
+ FilterStream(strA) {
+ bufPtr = bufEnd = buf;
+ lineLen = 0;
+ eof = gFalse;
+}
+
+ASCII85Encoder::~ASCII85Encoder() {
+ if (str->isEncoder())
+ delete str;
+}
+
+void ASCII85Encoder::reset() {
+ str->reset();
+ bufPtr = bufEnd = buf;
+ lineLen = 0;
+ eof = gFalse;
+}
+
+void ASCII85Encoder::close() {
+}
+
+GBool ASCII85Encoder::fillBuf() {
+ Gulong t;
+ char buf1[5];
+ int c;
+ int n, i;
+
+ if (eof)
+ return gFalse;
+ t = 0;
+ for (n = 0; n < 4; ++n) {
+ if ((c = str->getChar()) == EOF)
+ break;
+ t = (t << 8) + c;
+ }
+ bufPtr = bufEnd = buf;
+ if (n > 0) {
+ if (n == 4 && t == 0) {
+ *bufEnd++ = 'z';
+ if (++lineLen == 65) {
+ *bufEnd++ = '\n';
+ lineLen = 0;
+ }
+ } else {
+ if (n < 4)
+ t <<= 8 * (4 - n);
+ for (i = 4; i >= 0; --i) {
+ buf1[i] = (char)(t % 85 + 0x21);
+ t /= 85;
+ }
+ for (i = 0; i <= n; ++i) {
+ *bufEnd++ = buf1[i];
+ if (++lineLen == 65) {
+ *bufEnd++ = '\n';
+ lineLen = 0;
+ }
+ }
+ }
+ }
+ if (n < 4) {
+ *bufEnd++ = '~';
+ *bufEnd++ = '>';
+ eof = gTrue;
+ }
+ return bufPtr < bufEnd;
+}
+
+//------------------------------------------------------------------------
+// RunLengthEncoder
+//------------------------------------------------------------------------
+
+RunLengthEncoder::RunLengthEncoder(Stream *strA):
+ FilterStream(strA) {
+ bufPtr = bufEnd = nextEnd = buf;
+ eof = gFalse;
+}
+
+RunLengthEncoder::~RunLengthEncoder() {
+ if (str->isEncoder())
+ delete str;
+}
+
+void RunLengthEncoder::reset() {
+ str->reset();
+ bufPtr = bufEnd = nextEnd = buf;
+ eof = gFalse;
+}
+
+void RunLengthEncoder::close() {
+}
+
+//
+// When fillBuf finishes, buf[] looks like this:
+// +-----+--------------+-----------------+--
+// + tag | ... data ... | next 0, 1, or 2 |
+// +-----+--------------+-----------------+--
+// ^ ^ ^
+// bufPtr bufEnd nextEnd
+//
+GBool RunLengthEncoder::fillBuf() {
+ int c, c1, c2;
+ int n;
+
+ // already hit EOF?
+ if (eof)
+ return gFalse;
+
+ // grab two bytes
+ if (nextEnd < bufEnd + 1) {
+ if ((c1 = str->getChar()) == EOF) {
+ eof = gTrue;
+ return gFalse;
+ }
+ } else {
+ c1 = bufEnd[0] & 0xff;
+ }
+ if (nextEnd < bufEnd + 2) {
+ if ((c2 = str->getChar()) == EOF) {
+ eof = gTrue;
+ buf[0] = 0;
+ buf[1] = c1;
+ bufPtr = buf;
+ bufEnd = &buf[2];
+ return gTrue;
+ }
+ } else {
+ c2 = bufEnd[1] & 0xff;
+ }
+
+ // check for repeat
+ c = 0; // make gcc happy
+ if (c1 == c2) {
+ n = 2;
+ while (n < 128 && (c = str->getChar()) == c1)
+ ++n;
+ buf[0] = (char)(257 - n);
+ buf[1] = c1;
+ bufEnd = &buf[2];
+ if (c == EOF) {
+ eof = gTrue;
+ } else if (n < 128) {
+ buf[2] = c;
+ nextEnd = &buf[3];
+ } else {
+ nextEnd = bufEnd;
+ }
+
+ // get up to 128 chars
+ } else {
+ buf[1] = c1;
+ buf[2] = c2;
+ n = 2;
+ while (n < 128) {
+ if ((c = str->getChar()) == EOF) {
+ eof = gTrue;
+ break;
+ }
+ ++n;
+ buf[n] = c;
+ if (buf[n] == buf[n-1])
+ break;
+ }
+ if (buf[n] == buf[n-1]) {
+ buf[0] = (char)(n-2-1);
+ bufEnd = &buf[n-1];
+ nextEnd = &buf[n+1];
+ } else {
+ buf[0] = (char)(n-1);
+ bufEnd = nextEnd = &buf[n+1];
+ }
+ }
+ bufPtr = buf;
+ return gTrue;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/T1Font.cc b/filters/kword/pdf/xpdf/xpdf/T1Font.cc
deleted file mode 100644
index 9815e4901..000000000
--- a/filters/kword/pdf/xpdf/xpdf/T1Font.cc
+++ /dev/null
@@ -1,535 +0,0 @@
-//========================================================================
-//
-// T1Font.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#if HAVE_T1LIB_H
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <math.h>
-#include <string.h>
-#include <X11/Xlib.h>
-#include "gmem.h"
-#include "GfxState.h"
-#include "T1Font.h"
-
-//------------------------------------------------------------------------
-
-int T1FontEngine::t1libInitCount = 0;
-
-//------------------------------------------------------------------------
-
-T1FontEngine::T1FontEngine(Display *displayA, Visual *visualA, int depthA,
- Colormap colormapA, GBool aaA, GBool aaHighA):
- SFontEngine(displayA, visualA, depthA, colormapA)
-{
- static unsigned long grayVals[17] = {
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
- };
-
- ok = gFalse;
- aa = aaA;
- aaHigh = aaHighA;
- //~ for multithreading: need a mutex here
- if (t1libInitCount == 0) {
- T1_SetBitmapPad(8);
- if (!T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE |
- T1_NO_AFM)) {
- return;
- }
- if (aa) {
- T1_AASetBitsPerPixel(8);
- if (aaHigh) {
- T1_AASetLevel(T1_AA_HIGH);
- T1_AAHSetGrayValues(grayVals);
- } else {
- T1_AASetLevel(T1_AA_LOW);
- T1_AASetGrayValues(0, 1, 2, 3, 4);
- }
- } else {
- T1_AANSetGrayValues(0, 1);
- }
- }
- ++t1libInitCount;
- ok = gTrue;
-}
-
-T1FontEngine::~T1FontEngine() {
- //~ for multithreading: need a mutex here
- if (--t1libInitCount == 0) {
- T1_CloseLib();
- }
-}
-
-//------------------------------------------------------------------------
-
-T1FontFile::T1FontFile(T1FontEngine *engineA, char *fontFileName,
- char **fontEnc, double *bboxA) {
- int encStrSize;
- char *encPtr;
- int i;
-
- ok = gFalse;
- engine = engineA;
- enc = NULL;
- encStr = NULL;
- for (i = 0; i < 4; ++i) {
- bbox[i] = bboxA[i];
- }
-
- // load the font file
- if ((id = T1_AddFont(fontFileName)) < 0) {
- return;
- }
- T1_LoadFont(id);
-
- // reencode it
- encStrSize = 0;
- for (i = 0; i < 256; ++i) {
- if (fontEnc[i]) {
- encStrSize += strlen(fontEnc[i]) + 1;
- }
- }
- enc = (char **)gmalloc(257 * sizeof(char *));
- encStr = (char *)gmalloc(encStrSize * sizeof(char));
- encPtr = encStr;
- for (i = 0; i < 256; ++i) {
- if (fontEnc[i]) {
- strcpy(encPtr, fontEnc[i]);
- enc[i] = encPtr;
- encPtr += strlen(encPtr) + 1;
- } else {
- enc[i] = ".notdef";
- }
- }
- enc[256] = "custom";
- T1_ReencodeFont(id, enc);
-
- ok = gTrue;
-}
-
-T1FontFile::~T1FontFile() {
- gfree(enc);
- gfree(encStr);
- if (id >= 0) {
- T1_DeleteFont(id);
- }
-}
-
-//------------------------------------------------------------------------
-
-T1Font::T1Font(T1FontFile *fontFileA, double *m) {
- T1FontEngine *engine;
- T1_TMATRIX matrix;
- BBox bbox;
- double bbx0, bby0, bbx1, bby1;
- int x, y, xMin, xMax, yMin, yMax;
- int i;
-
- ok = gFalse;
- fontFile = fontFileA;
- engine = fontFile->engine;
-
- id = T1_CopyFont(fontFile->id);
-
- // compute font size
- size = (float)sqrt(m[2]*m[2] + m[3]*m[3]);
-
- // transform the four corners of the font bounding box -- the min
- // and max values form the bounding box of the transformed font
- bbx0 = fontFile->bbox[0];
- bby0 = fontFile->bbox[1];
- bbx1 = fontFile->bbox[2];
- bby1 = fontFile->bbox[3];
- // some fonts in PDF files have bboxes which are just plain wrong,
- // so we check the font file's bbox too
- bbox = T1_GetFontBBox(id);
- if (0.001 * bbox.llx < bbx0) {
- bbx0 = 0.001 * bbox.llx;
- }
- if (0.001 * bbox.lly < bby0) {
- bby0 = 0.001 * bbox.lly;
- }
- if (0.001 * bbox.urx > bbx1) {
- bbx1 = 0.001 * bbox.urx;
- }
- if (0.001 * bbox.ury > bby1) {
- bby1 = 0.001 * bbox.ury;
- }
- // some fonts are completely broken, so we fake it (with values
- // large enough that most glyphs should fit)
- if (bbx0 == 0 && bby0 == 0 && bbx1 == 0 && bby1 == 0) {
- bbx0 = bby0 = -0.5;
- bbx1 = bby1 = 1.5;
- }
- x = (int)(m[0] * bbx0 + m[2] * bby0);
- xMin = xMax = x;
- y = (int)(m[1] * bbx0 + m[3] * bby0);
- yMin = yMax = y;
- x = (int)(m[0] * bbx0 + m[2] * bby1);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)(m[1] * bbx0 + m[3] * bby1);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)(m[0] * bbx1 + m[2] * bby0);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)(m[1] * bbx1 + m[3] * bby0);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)(m[0] * bbx1 + m[2] * bby1);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)(m[1] * bbx1 + m[3] * bby1);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- // This is a kludge: some buggy PDF generators embed fonts with
- // zero bounding boxes.
- if (xMax == xMin) {
- xMin = 0;
- xMax = (int)size;
- }
- if (yMax == yMin) {
- yMin = 0;
- yMax = (int)(1.2 * size);
- }
- // Another kludge: an unusually large xMin or yMin coordinate is
- // probably wrong.
- if (xMin > 0) {
- xMin = 0;
- }
- if (yMin > 0) {
- yMin = 0;
- }
- // Another kludge: t1lib doesn't correctly handle fonts with
- // real (non-integer) bounding box coordinates.
- if (xMax - xMin > 5000) {
- xMin = 0;
- xMax = (int)size;
- }
- if (yMax - yMin > 5000) {
- yMin = 0;
- yMax = (int)(1.2 * size);
- }
- // this should be (max - min + 1), but we add some padding to
- // deal with rounding errors
- glyphW = xMax - xMin + 3;
- glyphH = yMax - yMin + 3;
- if (engine->aa) {
- glyphSize = glyphW * glyphH;
- } else {
- glyphSize = ((glyphW + 7) >> 3) * glyphH;
- }
-
- // set up the glyph pixmap cache
- cacheAssoc = 8;
- if (glyphSize <= 256) {
- cacheSets = 8;
- } else if (glyphSize <= 512) {
- cacheSets = 4;
- } else if (glyphSize <= 1024) {
- cacheSets = 2;
- } else {
- cacheSets = 1;
- }
- cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
- cacheTags = (T1FontCacheTag *)gmalloc(cacheSets * cacheAssoc *
- sizeof(T1FontCacheTag));
- for (i = 0; i < cacheSets * cacheAssoc; ++i) {
- cacheTags[i].mru = i & (cacheAssoc - 1);
- }
-
- // create the XImage
- if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
- ZPixmap, 0, NULL, glyphW, glyphH, 8, 0))) {
- return;
- }
- image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
-
- // transform the font
- matrix.cxx = m[0] / size;
- matrix.cxy = m[1] / size;
- matrix.cyx = m[2] / size;
- matrix.cyy = m[3] / size;
- T1_TransformFont(id, &matrix);
-
- ok = gTrue;
-}
-
-T1Font::~T1Font() {
- gfree(cacheTags);
- gfree(cache);
- if (image) {
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
- }
- T1_DeleteFont(id);
-}
-
-GBool T1Font::drawChar(Drawable d, int w, int h, GC gc,
- int x, int y, int r, int g, int b,
- CharCode c, Unicode u) {
- T1FontEngine *engine;
- XColor xcolor;
- int bgR, bgG, bgB;
- Gulong colors[17];
- Guchar *p;
- int xOffset, yOffset, x0, y0, x1, y1, gw, gh, w0, h0;
- int xx, yy, xx1;
- Guchar pix, mPix;
- int i;
-
- engine = fontFile->engine;
-
- // generate the glyph pixmap
- if (!(p = getGlyphPixmap(c, &xOffset, &yOffset, &gw, &gh))) {
- return gFalse;
- }
-
- // compute: (x0,y0) = position in destination drawable
- // (x1,y1) = position in glyph image
- // (w0,h0) = size of image transfer
- x0 = x - xOffset;
- y0 = y - yOffset;
- x1 = 0;
- y1 = 0;
- w0 = gw;
- h0 = gh;
- if (x0 < 0) {
- x1 = -x0;
- w0 += x0;
- x0 = 0;
- }
- if (x0 + w0 > w) {
- w0 = w - x0;
- }
- if (w0 < 0) {
- return gTrue;
- }
- if (y0 < 0) {
- y1 = -y0;
- h0 += y0;
- y0 = 0;
- }
- if (y0 + h0 > h) {
- h0 = h - y0;
- }
- if (h0 < 0) {
- return gTrue;
- }
-
- // read the X image
- XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
- ZPixmap, image, x1, y1);
-
- if (engine->aa) {
-
- // compute the colors
- xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
- XQueryColor(engine->display, engine->colormap, &xcolor);
- bgR = xcolor.red;
- bgG = xcolor.green;
- bgB = xcolor.blue;
- if (engine->aaHigh) {
- mPix = 16;
- for (i = 1; i <= 16; ++i) {
- colors[i] = engine->findColor((i * r + (16 - i) * bgR) / 16,
- (i * g + (16 - i) * bgG) / 16,
- (i * b + (16 - i) * bgB) / 16);
- }
- } else {
- mPix = 4;
- colors[1] = engine->findColor((r + 3*bgR) / 4,
- (g + 3*bgG) / 4,
- (b + 3*bgB) / 4);
- colors[2] = engine->findColor((r + bgR) / 2,
- (g + bgG) / 2,
- (b + bgB) / 2);
- colors[3] = engine->findColor((3*r + bgR) / 4,
- (3*g + bgG) / 4,
- (3*b + bgB) / 4);
- colors[4] = engine->findColor(r, g, b);
- }
-
- // stuff the glyph pixmap into the X image
- for (yy = 0; yy < gh; ++yy) {
- for (xx = 0; xx < gw; ++xx) {
- pix = *p++;
- if (pix > 0) {
- if (pix > mPix) {
- pix = mPix;
- }
- XPutPixel(image, xx, yy, colors[pix]);
- }
- }
- }
-
- } else {
-
- // one color
- colors[1] = engine->findColor(r, g, b);
-
- // stuff the glyph bitmap into the X image
- for (yy = 0; yy < gh; ++yy) {
- for (xx = 0; xx < gw; xx += 8) {
- pix = *p++;
- for (xx1 = xx; xx1 < xx + 8 && xx1 < gw; ++xx1) {
- if (pix & 0x01) {
- XPutPixel(image, xx1, yy, colors[1]);
- }
- pix >>= 1;
- }
- }
- }
-
- }
-
- // draw the X image
- XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
-
- return gTrue;
-}
-
-Guchar *T1Font::getGlyphPixmap(CharCode c, int *x, int *y, int *w, int *h) {
- T1FontEngine *engine;
- GLYPH *glyph;
- int gSize;
- int i, j, k;
- Guchar *ret;
-
- engine = fontFile->engine;
-
- // check the cache
- i = (c & (cacheSets - 1)) * cacheAssoc;
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
- *x = cacheTags[i+j].x;
- *y = cacheTags[i+j].y;
- *w = cacheTags[i+j].w;
- *h = cacheTags[i+j].h;
- for (k = 0; k < cacheAssoc; ++k) {
- if (k != j &&
- (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
- ++cacheTags[i+k].mru;
- }
- }
- cacheTags[i+j].mru = 0x8000;
- return cache + (i+j) * glyphSize;
- }
- }
-
- // generate the glyph pixmap
- if (engine->aa) {
- glyph = T1_AASetChar(id, c, size, NULL);
- } else {
- glyph = T1_SetChar(id, c, size, NULL);
- }
- if (!glyph) {
- return NULL;
- }
- *x = -glyph->metrics.leftSideBearing;
- *y = glyph->metrics.ascent;
- *w = glyph->metrics.rightSideBearing - glyph->metrics.leftSideBearing;
- *h = glyph->metrics.ascent - glyph->metrics.descent;
- if (*w > glyphW || *h > glyphH) {
-#if 1 //~ debug
- fprintf(stderr, "Weird t1lib glyph size: %d > %d or %d > %d\n",
- *w, glyphW, *h, glyphH);
-#endif
- return NULL;
- }
-
- // store glyph pixmap in cache
- ret = NULL;
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
- cacheTags[i+j].mru = 0x8000;
- cacheTags[i+j].code = c;
- cacheTags[i+j].x = *x;
- cacheTags[i+j].y = *y;
- cacheTags[i+j].w = *w;
- cacheTags[i+j].h = *h;
- if (engine->aa) {
- gSize = *w * *h;
- } else {
- gSize = ((*w + 7) >> 3) * *h;
- }
- ret = cache + (i+j) * glyphSize;
- if (glyph->bits) {
- memcpy(ret, glyph->bits, gSize);
- } else {
- memset(ret, 0, gSize);
- }
- } else {
- ++cacheTags[i+j].mru;
- }
- }
- return ret;
-}
-
-GBool T1Font::getCharPath(CharCode c, Unicode u, GfxState *state) {
- T1_OUTLINE *outline;
- T1_PATHSEGMENT *seg;
- T1_BEZIERSEGMENT *bez;
- double x, y, x1, y1;
-
- outline = T1_GetCharOutline(id, c, size, NULL);
- x = 0;
- y = 0;
- for (seg = outline; seg; seg = seg->link) {
- switch (seg->type) {
- case T1_PATHTYPE_MOVE:
- x += seg->dest.x / 65536.0;
- y += seg->dest.y / 65536.0;
- state->moveTo(x, y);
- break;
- case T1_PATHTYPE_LINE:
- x += seg->dest.x / 65536.0;
- y += seg->dest.y / 65536.0;
- state->lineTo(x, y);
- break;
- case T1_PATHTYPE_BEZIER:
- bez = (T1_BEZIERSEGMENT *)seg;
- x1 = x + bez->dest.x / 65536.0;
- y1 = y + bez->dest.y / 65536.0;
- state->curveTo(x + bez->B.x / 65536.0, y + bez->B.y / 65536.0,
- x + bez->C.x / 65536.0, y + bez->C.y / 65536.0,
- x1, y1);
- x = x1;
- y = y1;
- break;
- }
- }
- T1_FreeOutline(outline);
- return gTrue;
-}
-
-#endif // HAVE_T1LIB_H
diff --git a/filters/kword/pdf/xpdf/xpdf/T1Font.cpp b/filters/kword/pdf/xpdf/xpdf/T1Font.cpp
new file mode 100644
index 000000000..350f7bd66
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/T1Font.cpp
@@ -0,0 +1,535 @@
+//========================================================================
+//
+// T1Font.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#if HAVE_T1LIB_H
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <math.h>
+#include <string.h>
+#include <X11/Xlib.h>
+#include "gmem.h"
+#include "GfxState.h"
+#include "T1Font.h"
+
+//------------------------------------------------------------------------
+
+int T1FontEngine::t1libInitCount = 0;
+
+//------------------------------------------------------------------------
+
+T1FontEngine::T1FontEngine(Display *displayA, Visual *visualA, int depthA,
+ Colormap colormapA, GBool aaA, GBool aaHighA):
+ SFontEngine(displayA, visualA, depthA, colormapA)
+{
+ static unsigned long grayVals[17] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
+ };
+
+ ok = gFalse;
+ aa = aaA;
+ aaHigh = aaHighA;
+ //~ for multithreading: need a mutex here
+ if (t1libInitCount == 0) {
+ T1_SetBitmapPad(8);
+ if (!T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE |
+ T1_NO_AFM)) {
+ return;
+ }
+ if (aa) {
+ T1_AASetBitsPerPixel(8);
+ if (aaHigh) {
+ T1_AASetLevel(T1_AA_HIGH);
+ T1_AAHSetGrayValues(grayVals);
+ } else {
+ T1_AASetLevel(T1_AA_LOW);
+ T1_AASetGrayValues(0, 1, 2, 3, 4);
+ }
+ } else {
+ T1_AANSetGrayValues(0, 1);
+ }
+ }
+ ++t1libInitCount;
+ ok = gTrue;
+}
+
+T1FontEngine::~T1FontEngine() {
+ //~ for multithreading: need a mutex here
+ if (--t1libInitCount == 0) {
+ T1_CloseLib();
+ }
+}
+
+//------------------------------------------------------------------------
+
+T1FontFile::T1FontFile(T1FontEngine *engineA, char *fontFileName,
+ char **fontEnc, double *bboxA) {
+ int encStrSize;
+ char *encPtr;
+ int i;
+
+ ok = gFalse;
+ engine = engineA;
+ enc = NULL;
+ encStr = NULL;
+ for (i = 0; i < 4; ++i) {
+ bbox[i] = bboxA[i];
+ }
+
+ // load the font file
+ if ((id = T1_AddFont(fontFileName)) < 0) {
+ return;
+ }
+ T1_LoadFont(id);
+
+ // reencode it
+ encStrSize = 0;
+ for (i = 0; i < 256; ++i) {
+ if (fontEnc[i]) {
+ encStrSize += strlen(fontEnc[i]) + 1;
+ }
+ }
+ enc = (char **)gmalloc(257 * sizeof(char *));
+ encStr = (char *)gmalloc(encStrSize * sizeof(char));
+ encPtr = encStr;
+ for (i = 0; i < 256; ++i) {
+ if (fontEnc[i]) {
+ strcpy(encPtr, fontEnc[i]);
+ enc[i] = encPtr;
+ encPtr += strlen(encPtr) + 1;
+ } else {
+ enc[i] = ".notdef";
+ }
+ }
+ enc[256] = "custom";
+ T1_ReencodeFont(id, enc);
+
+ ok = gTrue;
+}
+
+T1FontFile::~T1FontFile() {
+ gfree(enc);
+ gfree(encStr);
+ if (id >= 0) {
+ T1_DeleteFont(id);
+ }
+}
+
+//------------------------------------------------------------------------
+
+T1Font::T1Font(T1FontFile *fontFileA, double *m) {
+ T1FontEngine *engine;
+ T1_TMATRIX matrix;
+ BBox bbox;
+ double bbx0, bby0, bbx1, bby1;
+ int x, y, xMin, xMax, yMin, yMax;
+ int i;
+
+ ok = gFalse;
+ fontFile = fontFileA;
+ engine = fontFile->engine;
+
+ id = T1_CopyFont(fontFile->id);
+
+ // compute font size
+ size = (float)sqrt(m[2]*m[2] + m[3]*m[3]);
+
+ // transform the four corners of the font bounding box -- the min
+ // and max values form the bounding box of the transformed font
+ bbx0 = fontFile->bbox[0];
+ bby0 = fontFile->bbox[1];
+ bbx1 = fontFile->bbox[2];
+ bby1 = fontFile->bbox[3];
+ // some fonts in PDF files have bboxes which are just plain wrong,
+ // so we check the font file's bbox too
+ bbox = T1_GetFontBBox(id);
+ if (0.001 * bbox.llx < bbx0) {
+ bbx0 = 0.001 * bbox.llx;
+ }
+ if (0.001 * bbox.lly < bby0) {
+ bby0 = 0.001 * bbox.lly;
+ }
+ if (0.001 * bbox.urx > bbx1) {
+ bbx1 = 0.001 * bbox.urx;
+ }
+ if (0.001 * bbox.ury > bby1) {
+ bby1 = 0.001 * bbox.ury;
+ }
+ // some fonts are completely broken, so we fake it (with values
+ // large enough that most glyphs should fit)
+ if (bbx0 == 0 && bby0 == 0 && bbx1 == 0 && bby1 == 0) {
+ bbx0 = bby0 = -0.5;
+ bbx1 = bby1 = 1.5;
+ }
+ x = (int)(m[0] * bbx0 + m[2] * bby0);
+ xMin = xMax = x;
+ y = (int)(m[1] * bbx0 + m[3] * bby0);
+ yMin = yMax = y;
+ x = (int)(m[0] * bbx0 + m[2] * bby1);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)(m[1] * bbx0 + m[3] * bby1);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)(m[0] * bbx1 + m[2] * bby0);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)(m[1] * bbx1 + m[3] * bby0);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)(m[0] * bbx1 + m[2] * bby1);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)(m[1] * bbx1 + m[3] * bby1);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ // This is a kludge: some buggy PDF generators embed fonts with
+ // zero bounding boxes.
+ if (xMax == xMin) {
+ xMin = 0;
+ xMax = (int)size;
+ }
+ if (yMax == yMin) {
+ yMin = 0;
+ yMax = (int)(1.2 * size);
+ }
+ // Another kludge: an unusually large xMin or yMin coordinate is
+ // probably wrong.
+ if (xMin > 0) {
+ xMin = 0;
+ }
+ if (yMin > 0) {
+ yMin = 0;
+ }
+ // Another kludge: t1lib doesn't correctly handle fonts with
+ // real (non-integer) bounding box coordinates.
+ if (xMax - xMin > 5000) {
+ xMin = 0;
+ xMax = (int)size;
+ }
+ if (yMax - yMin > 5000) {
+ yMin = 0;
+ yMax = (int)(1.2 * size);
+ }
+ // this should be (max - min + 1), but we add some padding to
+ // deal with rounding errors
+ glyphW = xMax - xMin + 3;
+ glyphH = yMax - yMin + 3;
+ if (engine->aa) {
+ glyphSize = glyphW * glyphH;
+ } else {
+ glyphSize = ((glyphW + 7) >> 3) * glyphH;
+ }
+
+ // set up the glyph pixmap cache
+ cacheAssoc = 8;
+ if (glyphSize <= 256) {
+ cacheSets = 8;
+ } else if (glyphSize <= 512) {
+ cacheSets = 4;
+ } else if (glyphSize <= 1024) {
+ cacheSets = 2;
+ } else {
+ cacheSets = 1;
+ }
+ cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
+ cacheTags = (T1FontCacheTag *)gmalloc(cacheSets * cacheAssoc *
+ sizeof(T1FontCacheTag));
+ for (i = 0; i < cacheSets * cacheAssoc; ++i) {
+ cacheTags[i].mru = i & (cacheAssoc - 1);
+ }
+
+ // create the XImage
+ if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
+ ZPixmap, 0, NULL, glyphW, glyphH, 8, 0))) {
+ return;
+ }
+ image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
+
+ // transform the font
+ matrix.cxx = m[0] / size;
+ matrix.cxy = m[1] / size;
+ matrix.cyx = m[2] / size;
+ matrix.cyy = m[3] / size;
+ T1_TransformFont(id, &matrix);
+
+ ok = gTrue;
+}
+
+T1Font::~T1Font() {
+ gfree(cacheTags);
+ gfree(cache);
+ if (image) {
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+ }
+ T1_DeleteFont(id);
+}
+
+GBool T1Font::drawChar(Drawable d, int w, int h, GC gc,
+ int x, int y, int r, int g, int b,
+ CharCode c, Unicode u) {
+ T1FontEngine *engine;
+ XColor xcolor;
+ int bgR, bgG, bgB;
+ Gulong colors[17];
+ Guchar *p;
+ int xOffset, yOffset, x0, y0, x1, y1, gw, gh, w0, h0;
+ int xx, yy, xx1;
+ Guchar pix, mPix;
+ int i;
+
+ engine = fontFile->engine;
+
+ // generate the glyph pixmap
+ if (!(p = getGlyphPixmap(c, &xOffset, &yOffset, &gw, &gh))) {
+ return gFalse;
+ }
+
+ // compute: (x0,y0) = position in destination drawable
+ // (x1,y1) = position in glyph image
+ // (w0,h0) = size of image transfer
+ x0 = x - xOffset;
+ y0 = y - yOffset;
+ x1 = 0;
+ y1 = 0;
+ w0 = gw;
+ h0 = gh;
+ if (x0 < 0) {
+ x1 = -x0;
+ w0 += x0;
+ x0 = 0;
+ }
+ if (x0 + w0 > w) {
+ w0 = w - x0;
+ }
+ if (w0 < 0) {
+ return gTrue;
+ }
+ if (y0 < 0) {
+ y1 = -y0;
+ h0 += y0;
+ y0 = 0;
+ }
+ if (y0 + h0 > h) {
+ h0 = h - y0;
+ }
+ if (h0 < 0) {
+ return gTrue;
+ }
+
+ // read the X image
+ XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
+ ZPixmap, image, x1, y1);
+
+ if (engine->aa) {
+
+ // compute the colors
+ xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
+ XQueryColor(engine->display, engine->colormap, &xcolor);
+ bgR = xcolor.red;
+ bgG = xcolor.green;
+ bgB = xcolor.blue;
+ if (engine->aaHigh) {
+ mPix = 16;
+ for (i = 1; i <= 16; ++i) {
+ colors[i] = engine->findColor((i * r + (16 - i) * bgR) / 16,
+ (i * g + (16 - i) * bgG) / 16,
+ (i * b + (16 - i) * bgB) / 16);
+ }
+ } else {
+ mPix = 4;
+ colors[1] = engine->findColor((r + 3*bgR) / 4,
+ (g + 3*bgG) / 4,
+ (b + 3*bgB) / 4);
+ colors[2] = engine->findColor((r + bgR) / 2,
+ (g + bgG) / 2,
+ (b + bgB) / 2);
+ colors[3] = engine->findColor((3*r + bgR) / 4,
+ (3*g + bgG) / 4,
+ (3*b + bgB) / 4);
+ colors[4] = engine->findColor(r, g, b);
+ }
+
+ // stuff the glyph pixmap into the X image
+ for (yy = 0; yy < gh; ++yy) {
+ for (xx = 0; xx < gw; ++xx) {
+ pix = *p++;
+ if (pix > 0) {
+ if (pix > mPix) {
+ pix = mPix;
+ }
+ XPutPixel(image, xx, yy, colors[pix]);
+ }
+ }
+ }
+
+ } else {
+
+ // one color
+ colors[1] = engine->findColor(r, g, b);
+
+ // stuff the glyph bitmap into the X image
+ for (yy = 0; yy < gh; ++yy) {
+ for (xx = 0; xx < gw; xx += 8) {
+ pix = *p++;
+ for (xx1 = xx; xx1 < xx + 8 && xx1 < gw; ++xx1) {
+ if (pix & 0x01) {
+ XPutPixel(image, xx1, yy, colors[1]);
+ }
+ pix >>= 1;
+ }
+ }
+ }
+
+ }
+
+ // draw the X image
+ XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
+
+ return gTrue;
+}
+
+Guchar *T1Font::getGlyphPixmap(CharCode c, int *x, int *y, int *w, int *h) {
+ T1FontEngine *engine;
+ GLYPH *glyph;
+ int gSize;
+ int i, j, k;
+ Guchar *ret;
+
+ engine = fontFile->engine;
+
+ // check the cache
+ i = (c & (cacheSets - 1)) * cacheAssoc;
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
+ *x = cacheTags[i+j].x;
+ *y = cacheTags[i+j].y;
+ *w = cacheTags[i+j].w;
+ *h = cacheTags[i+j].h;
+ for (k = 0; k < cacheAssoc; ++k) {
+ if (k != j &&
+ (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
+ ++cacheTags[i+k].mru;
+ }
+ }
+ cacheTags[i+j].mru = 0x8000;
+ return cache + (i+j) * glyphSize;
+ }
+ }
+
+ // generate the glyph pixmap
+ if (engine->aa) {
+ glyph = T1_AASetChar(id, c, size, NULL);
+ } else {
+ glyph = T1_SetChar(id, c, size, NULL);
+ }
+ if (!glyph) {
+ return NULL;
+ }
+ *x = -glyph->metrics.leftSideBearing;
+ *y = glyph->metrics.ascent;
+ *w = glyph->metrics.rightSideBearing - glyph->metrics.leftSideBearing;
+ *h = glyph->metrics.ascent - glyph->metrics.descent;
+ if (*w > glyphW || *h > glyphH) {
+#if 1 //~ debug
+ fprintf(stderr, "Weird t1lib glyph size: %d > %d or %d > %d\n",
+ *w, glyphW, *h, glyphH);
+#endif
+ return NULL;
+ }
+
+ // store glyph pixmap in cache
+ ret = NULL;
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
+ cacheTags[i+j].mru = 0x8000;
+ cacheTags[i+j].code = c;
+ cacheTags[i+j].x = *x;
+ cacheTags[i+j].y = *y;
+ cacheTags[i+j].w = *w;
+ cacheTags[i+j].h = *h;
+ if (engine->aa) {
+ gSize = *w * *h;
+ } else {
+ gSize = ((*w + 7) >> 3) * *h;
+ }
+ ret = cache + (i+j) * glyphSize;
+ if (glyph->bits) {
+ memcpy(ret, glyph->bits, gSize);
+ } else {
+ memset(ret, 0, gSize);
+ }
+ } else {
+ ++cacheTags[i+j].mru;
+ }
+ }
+ return ret;
+}
+
+GBool T1Font::getCharPath(CharCode c, Unicode u, GfxState *state) {
+ T1_OUTLINE *outline;
+ T1_PATHSEGMENT *seg;
+ T1_BEZIERSEGMENT *bez;
+ double x, y, x1, y1;
+
+ outline = T1_GetCharOutline(id, c, size, NULL);
+ x = 0;
+ y = 0;
+ for (seg = outline; seg; seg = seg->link) {
+ switch (seg->type) {
+ case T1_PATHTYPE_MOVE:
+ x += seg->dest.x / 65536.0;
+ y += seg->dest.y / 65536.0;
+ state->moveTo(x, y);
+ break;
+ case T1_PATHTYPE_LINE:
+ x += seg->dest.x / 65536.0;
+ y += seg->dest.y / 65536.0;
+ state->lineTo(x, y);
+ break;
+ case T1_PATHTYPE_BEZIER:
+ bez = (T1_BEZIERSEGMENT *)seg;
+ x1 = x + bez->dest.x / 65536.0;
+ y1 = y + bez->dest.y / 65536.0;
+ state->curveTo(x + bez->B.x / 65536.0, y + bez->B.y / 65536.0,
+ x + bez->C.x / 65536.0, y + bez->C.y / 65536.0,
+ x1, y1);
+ x = x1;
+ y = y1;
+ break;
+ }
+ }
+ T1_FreeOutline(outline);
+ return gTrue;
+}
+
+#endif // HAVE_T1LIB_H
diff --git a/filters/kword/pdf/xpdf/xpdf/TTFont.cc b/filters/kword/pdf/xpdf/xpdf/TTFont.cc
deleted file mode 100644
index 6107fd43a..000000000
--- a/filters/kword/pdf/xpdf/xpdf/TTFont.cc
+++ /dev/null
@@ -1,480 +0,0 @@
-//========================================================================
-//
-// TTFont.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <string.h>
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "TTFont.h"
-
-//------------------------------------------------------------------------
-
-TTFontEngine::TTFontEngine(Display *displayA, Visual *visualA, int depthA,
- Colormap colormapA, GBool aaA):
- SFontEngine(displayA, visualA, depthA, colormapA) {
- static TT_Byte ttPalette[5] = {0, 1, 2, 3, 4};
-
- ok = gFalse;
- if (TT_Init_FreeType(&engine)) {
- return;
- }
- aa = aaA;
- if (aa) {
- if (TT_Set_Raster_Gray_Palette(engine, ttPalette)) {
- return;
- }
- }
- ok = gTrue;
-}
-
-TTFontEngine::~TTFontEngine() {
- TT_Done_FreeType(engine);
-}
-
-//------------------------------------------------------------------------
-
-TTFontFile::TTFontFile(TTFontEngine *engineA, char *fontFileName,
- char **fontEnc, GBool pdfFontHasEncoding) {
- TT_Face_Properties props;
- TT_UShort unicodeCmap, macRomanCmap, msSymbolCmap;
- TT_UShort platform, encoding, i;
- int j;
-
- ok = gFalse;
- engine = engineA;
- codeMap = NULL;
- if (TT_Open_Face(engine->engine, fontFileName, &face)) {
- return;
- }
- if (TT_Get_Face_Properties(face, &props)) {
- return;
- }
-
- // To match up with the Adobe-defined behaviour, we choose a cmap
- // like this:
- // 1. If the PDF font has an encoding:
- // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
- // and use the Unicode indexes, not the char codes.
- // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
- // and reverse map the char names through MacRomanEncoding to
- // get char codes.
- // 2. If the PDF font does not have an encoding:
- // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
- // and use char codes directly.
- // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
- // and use (0xf000 + char code).
- // 3. If none of these rules apply, use the first cmap and hope for
- // the best (this shouldn't happen).
- unicodeCmap = macRomanCmap = msSymbolCmap = 0xffff;
- for (i = 0; i < props.num_CharMaps; ++i) {
- if (!TT_Get_CharMap_ID(face, i, &platform, &encoding)) {
- if (platform == 3 && encoding == 1) {
- unicodeCmap = i;
- } else if (platform == 1 && encoding == 0) {
- macRomanCmap = i;
- } else if (platform == 3 && encoding == 0) {
- msSymbolCmap = i;
- }
- }
- }
- i = 0;
- mode = ttFontModeCharCode;
- charMapOffset = 0;
- if (pdfFontHasEncoding) {
- if (unicodeCmap != 0xffff) {
- i = unicodeCmap;
- mode = ttFontModeUnicode;
- } else if (macRomanCmap != 0xffff) {
- i = macRomanCmap;
- mode = ttFontModeCodeMap;
- codeMap = (Guchar *)gmalloc(256 * sizeof(Guchar));
- for (j = 0; j < 256; ++j) {
- if (fontEnc[j]) {
- codeMap[j] = (Guchar)globalParams->getMacRomanCharCode(fontEnc[j]);
- } else {
- codeMap[j] = 0;
- }
- }
- }
- } else {
- if (macRomanCmap != 0xffff) {
- i = macRomanCmap;
- mode = ttFontModeCharCode;
- } else if (msSymbolCmap != 0xffff) {
- i = msSymbolCmap;
- mode = ttFontModeCharCodeOffset;
- charMapOffset = 0xf000;
- }
- }
- TT_Get_CharMap(face, i, &charMap);
-
- ok = gTrue;
-}
-
-TTFontFile::TTFontFile(TTFontEngine *engineA, char *fontFileName,
- Gushort *cidToGIDA, int cidToGIDLenA) {
- ok = gFalse;
- engine = engineA;
- codeMap = NULL;
- cidToGID = cidToGIDA;
- cidToGIDLen = cidToGIDLenA;
- if (TT_Open_Face(engine->engine, fontFileName, &face)) {
- return;
- }
- mode = ttFontModeCIDToGIDMap;
- ok = gTrue;
-}
-
-TTFontFile::~TTFontFile() {
- TT_Close_Face(face);
- if (codeMap) {
- gfree(codeMap);
- }
-}
-
-//------------------------------------------------------------------------
-
-TTFont::TTFont(TTFontFile *fontFileA, double *m) {
- TTFontEngine *engine;
- TT_Face_Properties props;
- TT_Instance_Metrics metrics;
- int x, xMin, xMax;
- int y, yMin, yMax;
- int i;
-
- ok = gFalse;
- fontFile = fontFileA;
- engine = fontFile->engine;
- if (TT_New_Instance(fontFile->face, &instance) ||
- TT_Set_Instance_Resolutions(instance, 72, 72) ||
- TT_Set_Instance_CharSize(instance, 1000 * 64) ||
- TT_New_Glyph(fontFile->face, &glyph) ||
- TT_Get_Face_Properties(fontFile->face, &props) ||
- TT_Get_Instance_Metrics(instance, &metrics)) {
- return;
- }
-
- // transform the four corners of the font bounding box -- the min
- // and max values form the bounding box of the transformed font
- x = (int)((m[0] * props.header->xMin + m[2] * props.header->yMin) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- xMin = xMax = x;
- y = (int)((m[1] * props.header->xMin + m[3] * props.header->yMin) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- yMin = yMax = y;
- x = (int)((m[0] * props.header->xMin + m[2] * props.header->yMax) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * props.header->xMin + m[3] * props.header->yMax) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)((m[0] * props.header->xMax + m[2] * props.header->yMin) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * props.header->xMax + m[3] * props.header->yMin) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- x = (int)((m[0] * props.header->xMax + m[2] * props.header->yMax) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (x < xMin) {
- xMin = x;
- } else if (x > xMax) {
- xMax = x;
- }
- y = (int)((m[1] * props.header->xMax + m[3] * props.header->yMax) *
- 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
- if (y < yMin) {
- yMin = y;
- } else if (y > yMax) {
- yMax = y;
- }
- xOffset = -xMin;
- yOffset = -yMin;
- ras.width = xMax - xMin + 1;
- ras.rows = yMax - yMin + 1;
-
- // set up the Raster_Map structure
- if (engine->aa) {
- ras.width = (ras.width + 3) & ~3;
- ras.cols = ras.width;
- } else {
- ras.width = (ras.width + 7) & ~7;
- ras.cols = ras.width >> 3;
- }
- ras.flow = TT_Flow_Down;
- ras.size = ras.rows * ras.cols;
- ras.bitmap = gmalloc(ras.size);
-
- // set up the glyph pixmap cache
- cacheAssoc = 8;
- if (ras.size <= 256) {
- cacheSets = 8;
- } else if (ras.size <= 512) {
- cacheSets = 4;
- } else if (ras.size <= 1024) {
- cacheSets = 2;
- } else {
- cacheSets = 1;
- }
- cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * ras.size);
- cacheTags = (TTFontCacheTag *)gmalloc(cacheSets * cacheAssoc *
- sizeof(TTFontCacheTag));
- for (i = 0; i < cacheSets * cacheAssoc; ++i) {
- cacheTags[i].mru = i & (cacheAssoc - 1);
- }
-
- // create the XImage
- if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
- ZPixmap, 0, NULL, ras.width, ras.rows, 8, 0))) {
- return;
- }
- image->data = (char *)gmalloc(ras.rows * image->bytes_per_line);
-
- // compute the transform matrix
- matrix.xx = (TT_Fixed)(m[0] * 65.536);
- matrix.yx = (TT_Fixed)(m[1] * 65.536);
- matrix.xy = (TT_Fixed)(m[2] * 65.536);
- matrix.yy = (TT_Fixed)(m[3] * 65.536);
-
- ok = gTrue;
-}
-
-TTFont::~TTFont() {
- gfree(cacheTags);
- gfree(cache);
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
- gfree(ras.bitmap);
- TT_Done_Glyph(glyph);
- TT_Done_Instance(instance);
-}
-
-GBool TTFont::drawChar(Drawable d, int w, int h, GC gc,
- int x, int y, int r, int g, int b,
- CharCode c, Unicode u) {
- TTFontEngine *engine;
- XColor xcolor;
- int bgR, bgG, bgB;
- Gulong colors[5];
- TT_Byte *p;
- TT_Byte pix;
- int xx, yy, xx1;
- int x0, y0, x1, y1, w0, h0;
-
- engine = fontFile->engine;
-
- // compute: (x0,y0) = position in destination drawable
- // (x1,y1) = position in glyph image
- // (w0,h0) = size of image transfer
- x0 = x - xOffset;
- y0 = y - (ras.rows - yOffset);
- x1 = 0;
- y1 = 0;
- w0 = ras.width;
- h0 = ras.rows;
- if (x0 < 0) {
- x1 = -x0;
- w0 += x0;
- x0 = 0;
- }
- if (x0 + w0 > w) {
- w0 = w - x0;
- }
- if (w0 < 0) {
- return gTrue;
- }
- if (y0 < 0) {
- y1 = -y0;
- h0 += y0;
- y0 = 0;
- }
- if (y0 + h0 > h) {
- h0 = h - y0;
- }
- if (h0 < 0) {
- return gTrue;
- }
-
- // read the X image
- XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
- ZPixmap, image, x1, y1);
-
- // generate the glyph pixmap
- if (!getGlyphPixmap(c, u)) {
- return gFalse;
- }
-
- if (engine->aa) {
-
- // compute the colors
- xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
- XQueryColor(engine->display, engine->colormap, &xcolor);
- bgR = xcolor.red;
- bgG = xcolor.green;
- bgB = xcolor.blue;
- colors[1] = engine->findColor((r + 3*bgR) / 4,
- (g + 3*bgG) / 4,
- (b + 3*bgB) / 4);
- colors[2] = engine->findColor((r + bgR) / 2,
- (g + bgG) / 2,
- (b + bgB) / 2);
- colors[3] = engine->findColor((3*r + bgR) / 4,
- (3*g + bgG) / 4,
- (3*b + bgB) / 4);
- colors[4] = engine->findColor(r, g, b);
-
- // stuff the glyph pixmap into the X image
- p = (TT_Byte *)ras.bitmap;
- for (yy = 0; yy < ras.rows; ++yy) {
- for (xx = 0; xx < ras.width; ++xx) {
- pix = *p++;
- if (pix > 0) {
- if (pix > 4) {
- pix = 4;
- }
- XPutPixel(image, xx, yy, colors[pix]);
- }
- }
- }
-
- } else {
-
- // one color
- colors[1] = engine->findColor(r, g, b);
-
- // stuff the glyph bitmap into the X image
- p = (TT_Byte *)ras.bitmap;
- for (yy = 0; yy < ras.rows; ++yy) {
- for (xx = 0; xx < ras.width; xx += 8) {
- pix = *p++;
- for (xx1 = xx; xx1 < xx + 8 && xx1 < ras.width; ++xx1) {
- if (pix & 0x80) {
- XPutPixel(image, xx1, yy, colors[1]);
- }
- pix <<= 1;
- }
- }
- }
-
- }
-
- // draw the X image
- XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
-
- return gTrue;
-}
-
-GBool TTFont::getGlyphPixmap(CharCode c, Unicode u) {
- TT_UShort idx;
- TT_Outline outline;
- int i, j, k;
-
- // check the cache
- i = (c & (cacheSets - 1)) * cacheAssoc;
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
- memcpy(ras.bitmap, cache + (i+j) * ras.size, ras.size);
- for (k = 0; k < cacheAssoc; ++k) {
- if (k != j &&
- (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
- ++cacheTags[i+k].mru;
- }
- }
- cacheTags[i+j].mru = 0x8000;
- return gTrue;
- }
- }
-
- // generate the glyph pixmap or bitmap
- idx = 0; // make gcc happy
- switch (fontFile->mode) {
- case ttFontModeUnicode:
- idx = TT_Char_Index(fontFile->charMap, (TT_UShort)u);
- break;
- case ttFontModeCharCode:
- idx = TT_Char_Index(fontFile->charMap, (TT_UShort)c);
- break;
- case ttFontModeCharCodeOffset:
- idx = TT_Char_Index(fontFile->charMap,
- (TT_UShort)(c + fontFile->charMapOffset));
- break;
- case ttFontModeCodeMap:
- if (c <= 0xff) {
- idx = TT_Char_Index(fontFile->charMap,
- (TT_UShort)(fontFile->codeMap[c] & 0xff));
- } else {
- idx = 0;
- }
- break;
- case ttFontModeCIDToGIDMap:
- if (fontFile->cidToGIDLen) {
- if ((int)c < fontFile->cidToGIDLen) {
- idx = (TT_UShort)fontFile->cidToGID[c];
- } else {
- idx = (TT_UShort)0;
- }
- } else {
- idx = (TT_UShort)c;
- }
- break;
- }
- if (TT_Load_Glyph(instance, glyph, idx, TTLOAD_DEFAULT) ||
- TT_Get_Glyph_Outline(glyph, &outline)) {
- return gFalse;
- }
- TT_Transform_Outline(&outline, &matrix);
- memset(ras.bitmap, 0, ras.size);
- if (fontFile->engine->aa) {
- if (TT_Get_Glyph_Pixmap(glyph, &ras, xOffset * 64, yOffset * 64)) {
- return gFalse;
- }
- } else {
- if (TT_Get_Glyph_Bitmap(glyph, &ras, xOffset * 64, yOffset * 64)) {
- return gFalse;
- }
- }
-
- // store glyph pixmap in cache
- for (j = 0; j < cacheAssoc; ++j) {
- if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
- cacheTags[i+j].mru = 0x8000;
- cacheTags[i+j].code = c;
- memcpy(cache + (i+j) * ras.size, ras.bitmap, ras.size);
- } else {
- ++cacheTags[i+j].mru;
- }
- }
-
- return gTrue;
-}
-
-#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
diff --git a/filters/kword/pdf/xpdf/xpdf/TTFont.cpp b/filters/kword/pdf/xpdf/xpdf/TTFont.cpp
new file mode 100644
index 000000000..51761fbf1
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/TTFont.cpp
@@ -0,0 +1,480 @@
+//========================================================================
+//
+// TTFont.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <string.h>
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "TTFont.h"
+
+//------------------------------------------------------------------------
+
+TTFontEngine::TTFontEngine(Display *displayA, Visual *visualA, int depthA,
+ Colormap colormapA, GBool aaA):
+ SFontEngine(displayA, visualA, depthA, colormapA) {
+ static TT_Byte ttPalette[5] = {0, 1, 2, 3, 4};
+
+ ok = gFalse;
+ if (TT_Init_FreeType(&engine)) {
+ return;
+ }
+ aa = aaA;
+ if (aa) {
+ if (TT_Set_Raster_Gray_Palette(engine, ttPalette)) {
+ return;
+ }
+ }
+ ok = gTrue;
+}
+
+TTFontEngine::~TTFontEngine() {
+ TT_Done_FreeType(engine);
+}
+
+//------------------------------------------------------------------------
+
+TTFontFile::TTFontFile(TTFontEngine *engineA, char *fontFileName,
+ char **fontEnc, GBool pdfFontHasEncoding) {
+ TT_Face_Properties props;
+ TT_UShort unicodeCmap, macRomanCmap, msSymbolCmap;
+ TT_UShort platform, encoding, i;
+ int j;
+
+ ok = gFalse;
+ engine = engineA;
+ codeMap = NULL;
+ if (TT_Open_Face(engine->engine, fontFileName, &face)) {
+ return;
+ }
+ if (TT_Get_Face_Properties(face, &props)) {
+ return;
+ }
+
+ // To match up with the Adobe-defined behaviour, we choose a cmap
+ // like this:
+ // 1. If the PDF font has an encoding:
+ // 1a. If the TrueType font has a Microsoft Unicode cmap, use it,
+ // and use the Unicode indexes, not the char codes.
+ // 1b. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and reverse map the char names through MacRomanEncoding to
+ // get char codes.
+ // 2. If the PDF font does not have an encoding:
+ // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
+ // and use char codes directly.
+ // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
+ // and use (0xf000 + char code).
+ // 3. If none of these rules apply, use the first cmap and hope for
+ // the best (this shouldn't happen).
+ unicodeCmap = macRomanCmap = msSymbolCmap = 0xffff;
+ for (i = 0; i < props.num_CharMaps; ++i) {
+ if (!TT_Get_CharMap_ID(face, i, &platform, &encoding)) {
+ if (platform == 3 && encoding == 1) {
+ unicodeCmap = i;
+ } else if (platform == 1 && encoding == 0) {
+ macRomanCmap = i;
+ } else if (platform == 3 && encoding == 0) {
+ msSymbolCmap = i;
+ }
+ }
+ }
+ i = 0;
+ mode = ttFontModeCharCode;
+ charMapOffset = 0;
+ if (pdfFontHasEncoding) {
+ if (unicodeCmap != 0xffff) {
+ i = unicodeCmap;
+ mode = ttFontModeUnicode;
+ } else if (macRomanCmap != 0xffff) {
+ i = macRomanCmap;
+ mode = ttFontModeCodeMap;
+ codeMap = (Guchar *)gmalloc(256 * sizeof(Guchar));
+ for (j = 0; j < 256; ++j) {
+ if (fontEnc[j]) {
+ codeMap[j] = (Guchar)globalParams->getMacRomanCharCode(fontEnc[j]);
+ } else {
+ codeMap[j] = 0;
+ }
+ }
+ }
+ } else {
+ if (macRomanCmap != 0xffff) {
+ i = macRomanCmap;
+ mode = ttFontModeCharCode;
+ } else if (msSymbolCmap != 0xffff) {
+ i = msSymbolCmap;
+ mode = ttFontModeCharCodeOffset;
+ charMapOffset = 0xf000;
+ }
+ }
+ TT_Get_CharMap(face, i, &charMap);
+
+ ok = gTrue;
+}
+
+TTFontFile::TTFontFile(TTFontEngine *engineA, char *fontFileName,
+ Gushort *cidToGIDA, int cidToGIDLenA) {
+ ok = gFalse;
+ engine = engineA;
+ codeMap = NULL;
+ cidToGID = cidToGIDA;
+ cidToGIDLen = cidToGIDLenA;
+ if (TT_Open_Face(engine->engine, fontFileName, &face)) {
+ return;
+ }
+ mode = ttFontModeCIDToGIDMap;
+ ok = gTrue;
+}
+
+TTFontFile::~TTFontFile() {
+ TT_Close_Face(face);
+ if (codeMap) {
+ gfree(codeMap);
+ }
+}
+
+//------------------------------------------------------------------------
+
+TTFont::TTFont(TTFontFile *fontFileA, double *m) {
+ TTFontEngine *engine;
+ TT_Face_Properties props;
+ TT_Instance_Metrics metrics;
+ int x, xMin, xMax;
+ int y, yMin, yMax;
+ int i;
+
+ ok = gFalse;
+ fontFile = fontFileA;
+ engine = fontFile->engine;
+ if (TT_New_Instance(fontFile->face, &instance) ||
+ TT_Set_Instance_Resolutions(instance, 72, 72) ||
+ TT_Set_Instance_CharSize(instance, 1000 * 64) ||
+ TT_New_Glyph(fontFile->face, &glyph) ||
+ TT_Get_Face_Properties(fontFile->face, &props) ||
+ TT_Get_Instance_Metrics(instance, &metrics)) {
+ return;
+ }
+
+ // transform the four corners of the font bounding box -- the min
+ // and max values form the bounding box of the transformed font
+ x = (int)((m[0] * props.header->xMin + m[2] * props.header->yMin) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ xMin = xMax = x;
+ y = (int)((m[1] * props.header->xMin + m[3] * props.header->yMin) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ yMin = yMax = y;
+ x = (int)((m[0] * props.header->xMin + m[2] * props.header->yMax) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * props.header->xMin + m[3] * props.header->yMax) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)((m[0] * props.header->xMax + m[2] * props.header->yMin) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * props.header->xMax + m[3] * props.header->yMin) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ x = (int)((m[0] * props.header->xMax + m[2] * props.header->yMax) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (x < xMin) {
+ xMin = x;
+ } else if (x > xMax) {
+ xMax = x;
+ }
+ y = (int)((m[1] * props.header->xMax + m[3] * props.header->yMax) *
+ 0.001 * metrics.x_ppem / props.header->Units_Per_EM);
+ if (y < yMin) {
+ yMin = y;
+ } else if (y > yMax) {
+ yMax = y;
+ }
+ xOffset = -xMin;
+ yOffset = -yMin;
+ ras.width = xMax - xMin + 1;
+ ras.rows = yMax - yMin + 1;
+
+ // set up the Raster_Map structure
+ if (engine->aa) {
+ ras.width = (ras.width + 3) & ~3;
+ ras.cols = ras.width;
+ } else {
+ ras.width = (ras.width + 7) & ~7;
+ ras.cols = ras.width >> 3;
+ }
+ ras.flow = TT_Flow_Down;
+ ras.size = ras.rows * ras.cols;
+ ras.bitmap = gmalloc(ras.size);
+
+ // set up the glyph pixmap cache
+ cacheAssoc = 8;
+ if (ras.size <= 256) {
+ cacheSets = 8;
+ } else if (ras.size <= 512) {
+ cacheSets = 4;
+ } else if (ras.size <= 1024) {
+ cacheSets = 2;
+ } else {
+ cacheSets = 1;
+ }
+ cache = (Guchar *)gmalloc(cacheSets * cacheAssoc * ras.size);
+ cacheTags = (TTFontCacheTag *)gmalloc(cacheSets * cacheAssoc *
+ sizeof(TTFontCacheTag));
+ for (i = 0; i < cacheSets * cacheAssoc; ++i) {
+ cacheTags[i].mru = i & (cacheAssoc - 1);
+ }
+
+ // create the XImage
+ if (!(image = XCreateImage(engine->display, engine->visual, engine->depth,
+ ZPixmap, 0, NULL, ras.width, ras.rows, 8, 0))) {
+ return;
+ }
+ image->data = (char *)gmalloc(ras.rows * image->bytes_per_line);
+
+ // compute the transform matrix
+ matrix.xx = (TT_Fixed)(m[0] * 65.536);
+ matrix.yx = (TT_Fixed)(m[1] * 65.536);
+ matrix.xy = (TT_Fixed)(m[2] * 65.536);
+ matrix.yy = (TT_Fixed)(m[3] * 65.536);
+
+ ok = gTrue;
+}
+
+TTFont::~TTFont() {
+ gfree(cacheTags);
+ gfree(cache);
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+ gfree(ras.bitmap);
+ TT_Done_Glyph(glyph);
+ TT_Done_Instance(instance);
+}
+
+GBool TTFont::drawChar(Drawable d, int w, int h, GC gc,
+ int x, int y, int r, int g, int b,
+ CharCode c, Unicode u) {
+ TTFontEngine *engine;
+ XColor xcolor;
+ int bgR, bgG, bgB;
+ Gulong colors[5];
+ TT_Byte *p;
+ TT_Byte pix;
+ int xx, yy, xx1;
+ int x0, y0, x1, y1, w0, h0;
+
+ engine = fontFile->engine;
+
+ // compute: (x0,y0) = position in destination drawable
+ // (x1,y1) = position in glyph image
+ // (w0,h0) = size of image transfer
+ x0 = x - xOffset;
+ y0 = y - (ras.rows - yOffset);
+ x1 = 0;
+ y1 = 0;
+ w0 = ras.width;
+ h0 = ras.rows;
+ if (x0 < 0) {
+ x1 = -x0;
+ w0 += x0;
+ x0 = 0;
+ }
+ if (x0 + w0 > w) {
+ w0 = w - x0;
+ }
+ if (w0 < 0) {
+ return gTrue;
+ }
+ if (y0 < 0) {
+ y1 = -y0;
+ h0 += y0;
+ y0 = 0;
+ }
+ if (y0 + h0 > h) {
+ h0 = h - y0;
+ }
+ if (h0 < 0) {
+ return gTrue;
+ }
+
+ // read the X image
+ XGetSubImage(engine->display, d, x0, y0, w0, h0, (1 << engine->depth) - 1,
+ ZPixmap, image, x1, y1);
+
+ // generate the glyph pixmap
+ if (!getGlyphPixmap(c, u)) {
+ return gFalse;
+ }
+
+ if (engine->aa) {
+
+ // compute the colors
+ xcolor.pixel = XGetPixel(image, x1 + w0/2, y1 + h0/2);
+ XQueryColor(engine->display, engine->colormap, &xcolor);
+ bgR = xcolor.red;
+ bgG = xcolor.green;
+ bgB = xcolor.blue;
+ colors[1] = engine->findColor((r + 3*bgR) / 4,
+ (g + 3*bgG) / 4,
+ (b + 3*bgB) / 4);
+ colors[2] = engine->findColor((r + bgR) / 2,
+ (g + bgG) / 2,
+ (b + bgB) / 2);
+ colors[3] = engine->findColor((3*r + bgR) / 4,
+ (3*g + bgG) / 4,
+ (3*b + bgB) / 4);
+ colors[4] = engine->findColor(r, g, b);
+
+ // stuff the glyph pixmap into the X image
+ p = (TT_Byte *)ras.bitmap;
+ for (yy = 0; yy < ras.rows; ++yy) {
+ for (xx = 0; xx < ras.width; ++xx) {
+ pix = *p++;
+ if (pix > 0) {
+ if (pix > 4) {
+ pix = 4;
+ }
+ XPutPixel(image, xx, yy, colors[pix]);
+ }
+ }
+ }
+
+ } else {
+
+ // one color
+ colors[1] = engine->findColor(r, g, b);
+
+ // stuff the glyph bitmap into the X image
+ p = (TT_Byte *)ras.bitmap;
+ for (yy = 0; yy < ras.rows; ++yy) {
+ for (xx = 0; xx < ras.width; xx += 8) {
+ pix = *p++;
+ for (xx1 = xx; xx1 < xx + 8 && xx1 < ras.width; ++xx1) {
+ if (pix & 0x80) {
+ XPutPixel(image, xx1, yy, colors[1]);
+ }
+ pix <<= 1;
+ }
+ }
+ }
+
+ }
+
+ // draw the X image
+ XPutImage(engine->display, d, gc, image, x1, y1, x0, y0, w0, h0);
+
+ return gTrue;
+}
+
+GBool TTFont::getGlyphPixmap(CharCode c, Unicode u) {
+ TT_UShort idx;
+ TT_Outline outline;
+ int i, j, k;
+
+ // check the cache
+ i = (c & (cacheSets - 1)) * cacheAssoc;
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x8000) && cacheTags[i+j].code == c) {
+ memcpy(ras.bitmap, cache + (i+j) * ras.size, ras.size);
+ for (k = 0; k < cacheAssoc; ++k) {
+ if (k != j &&
+ (cacheTags[i+k].mru & 0x7fff) < (cacheTags[i+j].mru & 0x7fff)) {
+ ++cacheTags[i+k].mru;
+ }
+ }
+ cacheTags[i+j].mru = 0x8000;
+ return gTrue;
+ }
+ }
+
+ // generate the glyph pixmap or bitmap
+ idx = 0; // make gcc happy
+ switch (fontFile->mode) {
+ case ttFontModeUnicode:
+ idx = TT_Char_Index(fontFile->charMap, (TT_UShort)u);
+ break;
+ case ttFontModeCharCode:
+ idx = TT_Char_Index(fontFile->charMap, (TT_UShort)c);
+ break;
+ case ttFontModeCharCodeOffset:
+ idx = TT_Char_Index(fontFile->charMap,
+ (TT_UShort)(c + fontFile->charMapOffset));
+ break;
+ case ttFontModeCodeMap:
+ if (c <= 0xff) {
+ idx = TT_Char_Index(fontFile->charMap,
+ (TT_UShort)(fontFile->codeMap[c] & 0xff));
+ } else {
+ idx = 0;
+ }
+ break;
+ case ttFontModeCIDToGIDMap:
+ if (fontFile->cidToGIDLen) {
+ if ((int)c < fontFile->cidToGIDLen) {
+ idx = (TT_UShort)fontFile->cidToGID[c];
+ } else {
+ idx = (TT_UShort)0;
+ }
+ } else {
+ idx = (TT_UShort)c;
+ }
+ break;
+ }
+ if (TT_Load_Glyph(instance, glyph, idx, TTLOAD_DEFAULT) ||
+ TT_Get_Glyph_Outline(glyph, &outline)) {
+ return gFalse;
+ }
+ TT_Transform_Outline(&outline, &matrix);
+ memset(ras.bitmap, 0, ras.size);
+ if (fontFile->engine->aa) {
+ if (TT_Get_Glyph_Pixmap(glyph, &ras, xOffset * 64, yOffset * 64)) {
+ return gFalse;
+ }
+ } else {
+ if (TT_Get_Glyph_Bitmap(glyph, &ras, xOffset * 64, yOffset * 64)) {
+ return gFalse;
+ }
+ }
+
+ // store glyph pixmap in cache
+ for (j = 0; j < cacheAssoc; ++j) {
+ if ((cacheTags[i+j].mru & 0x7fff) == cacheAssoc - 1) {
+ cacheTags[i+j].mru = 0x8000;
+ cacheTags[i+j].code = c;
+ memcpy(cache + (i+j) * ras.size, ras.bitmap, ras.size);
+ } else {
+ ++cacheTags[i+j].mru;
+ }
+ }
+
+ return gTrue;
+}
+
+#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
diff --git a/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cc
deleted file mode 100644
index 8eb789032..000000000
--- a/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cc
+++ /dev/null
@@ -1,1243 +0,0 @@
-//========================================================================
-//
-// TextOutputDev.cc
-//
-// Copyright 1997-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <math.h>
-#include <ctype.h>
-#include "GString.h"
-#include "gmem.h"
-#include "config.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "UnicodeMap.h"
-#include "GfxState.h"
-#include "TextOutputDev.h"
-
-#ifdef MACOS
-// needed for setting type/creator of MacOS files
-#include "ICSupport.h"
-#endif
-
-//------------------------------------------------------------------------
-
-#define textOutSpace 0.2
-#define textOutColSpace 0.2
-
-//------------------------------------------------------------------------
-
-struct TextOutColumnEdge {
- double x, y0, y1;
-};
-
-//------------------------------------------------------------------------
-// TextBlock
-//------------------------------------------------------------------------
-
-TextBlock::TextBlock() {
- strings = NULL;
- next = NULL;
- xyNext = NULL;
- text = NULL;
- xRight = NULL;
- col = NULL;
-}
-
-TextBlock::~TextBlock() {
- TextString *p1, *p2;
-
- for (p1 = strings; p1; p1 = p2) {
- p2 = p1->next;
- delete p1;
- }
- gfree(text);
- gfree(xRight);
- gfree(col);
-}
-
-//------------------------------------------------------------------------
-// TextLine
-//------------------------------------------------------------------------
-
-TextLine::TextLine() {
- blocks = NULL;
- next = NULL;
-}
-
-TextLine::~TextLine() {
- TextBlock *p1, *p2;
-
- for (p1 = blocks; p1; p1 = p2) {
- p2 = p1->next;
- delete p1;
- }
-}
-
-//------------------------------------------------------------------------
-// TextString
-//------------------------------------------------------------------------
-
-TextString::TextString(GfxState *state, double x0, double y0,
- double fontSize) {
- GfxFont *font;
- double x, y;
-
- state->transform(x0, y0, &x, &y);
- if ((font = state->getFont())) {
- yMin = y - font->getAscent() * fontSize;
- yMax = y - font->getDescent() * fontSize;
- } else {
- // this means that the PDF file draws text without a current font,
- // which should never happen
- yMin = y - 0.95 * fontSize;
- yMax = y + 0.35 * fontSize;
- }
- if (yMin == yMax) {
- // this is a sanity check for a case that shouldn't happen -- but
- // if it does happen, we want to avoid dividing by zero later
- yMin = y;
- yMax = y + 1;
- }
- marked = gFalse;
- text = NULL;
- xRight = NULL;
- len = size = 0;
- next = NULL;
-}
-
-
-TextString::~TextString() {
- gfree(text);
- gfree(xRight);
-}
-
-void TextString::addChar(GfxState */*state*/, double x, double /*y*/,
- double dx, double /*dy*/, Unicode u) {
- if (len == size) {
- size += 16;
- text = (Unicode *)grealloc(text, size * sizeof(Unicode));
- xRight = (double *)grealloc(xRight, size * sizeof(double));
- }
- text[len] = u;
- if (len == 0) {
- xMin = x;
- }
- xMax = xRight[len] = x + dx;
- ++len;
-}
-
-//------------------------------------------------------------------------
-// TextPage
-//------------------------------------------------------------------------
-
-TextPage::TextPage(GBool rawOrderA) {
- rawOrder = rawOrderA;
- curStr = NULL;
- fontSize = 0;
- xyStrings = NULL;
- xyCur1 = xyCur2 = NULL;
- lines = NULL;
- nest = 0;
- nTinyChars = 0;
-}
-
-TextPage::~TextPage() {
- clear();
-}
-
-void TextPage::updateFont(GfxState *state) {
- GfxFont *font;
- double *fm;
- char *name;
- int code, mCode, letterCode, anyCode;
- double w;
-
- // adjust the font size
- fontSize = state->getTransformedFontSize();
- if ((font = state->getFont()) && font->getType() == fontType3) {
- // This is a hack which makes it possible to deal with some Type 3
- // fonts. The problem is that it's impossible to know what the
- // base coordinate system used in the font is without actually
- // rendering the font. This code tries to guess by looking at the
- // width of the character 'm' (which breaks if the font is a
- // subset that doesn't contain 'm').
- mCode = letterCode = anyCode = -1;
- for (code = 0; code < 256; ++code) {
- name = ((Gfx8BitFont *)font)->getCharName(code);
- if (name && name[0] == 'm' && name[1] == '\0') {
- mCode = code;
- }
- if (letterCode < 0 && name && name[1] == '\0' &&
- ((name[0] >= 'A' && name[0] <= 'Z') ||
- (name[0] >= 'a' && name[0] <= 'z'))) {
- letterCode = code;
- }
- if (anyCode < 0 && name && ((Gfx8BitFont *)font)->getWidth(code) > 0) {
- anyCode = code;
- }
- }
- if (mCode >= 0 &&
- (w = ((Gfx8BitFont *)font)->getWidth(mCode)) > 0) {
- // 0.6 is a generic average 'm' width -- yes, this is a hack
- fontSize *= w / 0.6;
- } else if (letterCode >= 0 &&
- (w = ((Gfx8BitFont *)font)->getWidth(letterCode)) > 0) {
- // even more of a hack: 0.5 is a generic letter width
- fontSize *= w / 0.5;
- } else if (anyCode >= 0 &&
- (w = ((Gfx8BitFont *)font)->getWidth(anyCode)) > 0) {
- // better than nothing: 0.5 is a generic character width
- fontSize *= w / 0.5;
- }
- fm = font->getFontMatrix();
- if (fm[0] != 0) {
- fontSize *= fabs(fm[3] / fm[0]);
- }
- }
-}
-
-void TextPage::beginString(GfxState *state, double x0, double y0) {
- // This check is needed because Type 3 characters can contain
- // text-drawing operations.
- if (curStr) {
- ++nest;
- return;
- }
-
- curStr = new TextString(state, x0, y0, fontSize);
-}
-
-void TextPage::addChar(GfxState *state, double x, double y,
- double dx, double dy, Unicode *u, int uLen) {
- double x1, y1, w1, h1, dx2, dy2;
- int n, i;
-
- state->transform(x, y, &x1, &y1);
- if (x1 < 0 || x1 > state->getPageWidth() ||
- y1 < 0 || y1 > state->getPageHeight()) {
- return;
- }
- state->textTransformDelta(state->getCharSpace() * state->getHorizScaling(),
- 0, &dx2, &dy2);
- dx -= dx2;
- dy -= dy2;
- state->transformDelta(dx, dy, &w1, &h1);
- if (!globalParams->getTextKeepTinyChars() &&
- fabs(w1) < 3 && fabs(h1) < 3) {
- if (++nTinyChars > 20000) {
- return;
- }
- }
- n = curStr->len;
- if (n > 0 && x1 - curStr->xRight[n-1] >
- 0.1 * (curStr->yMax - curStr->yMin)) {
- // large char spacing is sometimes used to move text around
- endString();
- beginString(state, x, y);
- }
- if (uLen == 1 && u[0] == (Unicode)0x20 &&
- w1 > 0.5 * (curStr->yMax - curStr->yMin)) {
- // large word spacing is sometimes used to move text around
- return;
- }
- if (uLen != 0) {
- w1 /= uLen;
- h1 /= uLen;
- }
- for (i = 0; i < uLen; ++i) {
- curStr->addChar(state, x1 + i*w1, y1 + i*h1, w1, h1, u[i]);
- }
-}
-
-void TextPage::endString() {
- // This check is needed because Type 3 characters can contain
- // text-drawing operations.
- if (nest > 0) {
- --nest;
- return;
- }
-
- addString(curStr);
- curStr = NULL;
-}
-
-void TextPage::addString(TextString *str) {
- TextString *p1, *p2;
-
- // throw away zero-length strings -- they don't have valid xMin/xMax
- // values, and they're useless anyway
- if (str->len == 0) {
- delete str;
- return;
- }
-
- // insert string in xy list
- if (rawOrder) {
- p1 = xyCur1;
- p2 = NULL;
- } else if ((!xyCur1 || xyBefore(xyCur1, str)) &&
- (!xyCur2 || xyBefore(str, xyCur2))) {
- p1 = xyCur1;
- p2 = xyCur2;
- } else if (xyCur1 && xyBefore(xyCur1, str)) {
- for (p1 = xyCur1, p2 = xyCur2; p2; p1 = p2, p2 = p2->next) {
- if (xyBefore(str, p2)) {
- break;
- }
- }
- xyCur2 = p2;
- } else {
- for (p1 = NULL, p2 = xyStrings; p2; p1 = p2, p2 = p2->next) {
- if (xyBefore(str, p2)) {
- break;
- }
- }
- xyCur2 = p2;
- }
- xyCur1 = str;
- if (p1) {
- p1->next = str;
- } else {
- xyStrings = str;
- }
- str->next = p2;
-}
-
-void TextPage::coalesce() {
- TextLine *line, *line0;
- TextBlock *yxBlocks, *xyBlocks, *blk, *blk0, *blk1, *blk2;
- TextString *str0, *str1, *str2, *str3, *str4;
- TextString *str1prev, *str2prev, *str3prev;
- TextOutColumnEdge *edges;
- UnicodeMap *uMap;
- GBool isUnicode;
- char buf[8];
- int edgesLength, edgesSize;
- double x, yMin, yMax;
- double space, fit1, fit2, h;
- int col1, col2, d;
- int i, j;
-
-#if 0 //~ for debugging
- for (str1 = xyStrings; str1; str1 = str1->next) {
- printf("x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
- str1->xMin, str1->xMax, str1->yMin, str1->yMax,
- (str1->yMax - str1->yMin));
- for (i = 0; i < str1->len; ++i) {
- fputc(str1->text[i] & 0xff, stdout);
- }
- printf("'\n");
- }
- printf("\n------------------------------------------------------------\n\n");
-#endif
-
- // build the list of column edges
- edges = NULL;
- edgesLength = edgesSize = 0;
- if (!rawOrder) {
- for (str1prev = NULL, str1 = xyStrings;
- str1;
- str1prev = str1, str1 = str1->next) {
- if (str1->marked) {
- continue;
- }
- h = str1->yMax - str1->yMin;
- if (str1prev && (str1->xMin - str1prev->xMax) / h < textOutColSpace) {
- continue;
- }
- x = str1->xMin;
- yMin = str1->yMin;
- yMax = str1->yMax;
- for (str2prev = str1, str2 = str1->next;
- str2;
- str2prev = str2, str2 = str2->next) {
- h = str2->yMax - str2->yMin;
- if (!str2->marked &&
- (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
- fabs(str2->xMin - x) < 0.5 &&
- str2->yMin - yMax < 0.3 * h &&
- yMin - str2->yMax < 0.3 * h) {
- break;
- }
- }
- if (str2) {
- if (str2->yMin < yMin) {
- yMin = str2->yMin;
- }
- if (str2->yMax > yMax) {
- yMax = str2->yMax;
- }
- str2->marked = gTrue;
- for (str3prev = str1, str3 = str1->next;
- str3;
- str3prev = str3, str3 = str3->next) {
- h = str3->yMax - str3->yMin;
- if (!str3->marked &&
- (str3->xMin - str3prev->xMax) / h > textOutColSpace &&
- fabs(str3->xMin - x) < 0.5 &&
- str3->yMin - yMax < 0.3 * h &&
- yMin - str3->yMax < 0.3 * h) {
- break;
- }
- }
- if (str3) {
- if (str3->yMin < yMin) {
- yMin = str3->yMin;
- }
- if (str3->yMax > yMax) {
- yMax = str3->yMax;
- }
- str3->marked = gTrue;
- do {
- for (str2prev = str1, str2 = str1->next;
- str2;
- str2prev = str2, str2 = str2->next) {
- h = str2->yMax - str2->yMin;
- if (!str2->marked &&
- (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
- fabs(str2->xMin - x) < 0.5 &&
- str2->yMin - yMax < 0.3 * h &&
- yMin - str2->yMax < 0.3 * h) {
- if (str2->yMin < yMin) {
- yMin = str2->yMin;
- }
- if (str2->yMax > yMax) {
- yMax = str2->yMax;
- }
- str2->marked = gTrue;
- break;
- }
- }
- } while (str2);
- if (edgesLength == edgesSize) {
- edgesSize = edgesSize ? 2 * edgesSize : 16;
- edges = (TextOutColumnEdge *)
- grealloc(edges, edgesSize * sizeof(TextOutColumnEdge));
- }
- edges[edgesLength].x = x;
- edges[edgesLength].y0 = yMin;
- edges[edgesLength].y1 = yMax;
- ++edgesLength;
- } else {
- str2->marked = gFalse;
- }
- }
- str1->marked = gTrue;
- }
- }
-
-#if 0 //~ for debugging
- printf("column edges:\n");
- for (i = 0; i < edgesLength; ++i) {
- printf("%d: x=%.2f y0=%.2f y1=%.2f\n",
- i, edges[i].x, edges[i].y0, edges[i].y1);
- }
- printf("\n------------------------------------------------------------\n\n");
-#endif
-
- // build the blocks
- yxBlocks = NULL;
- blk1 = blk2 = NULL;
- while (xyStrings) {
-
- // build the block
- str0 = xyStrings;
- xyStrings = xyStrings->next;
- str0->next = NULL;
- blk = new TextBlock();
- blk->strings = str0;
- blk->xMin = str0->xMin;
- blk->xMax = str0->xMax;
- blk->yMin = str0->yMin;
- blk->yMax = str0->yMax;
- while (xyStrings) {
- str1 = NULL;
- str2 = xyStrings;
- fit1 = coalesceFit(str0, str2);
- if (!rawOrder) {
- // look for best-fitting string
- space = str0->yMax - str0->yMin;
- for (str3 = xyStrings, str4 = xyStrings->next;
- str4 && str4->xMin - str0->xMax <= space;
- str3 = str4, str4 = str4->next) {
- fit2 = coalesceFit(str0, str4);
- if (fit2 < fit1) {
- str1 = str3;
- str2 = str4;
- fit1 = fit2;
- }
- }
- }
- if (fit1 > 1) {
- // no fit - we're done with this block
- break;
- }
-
- // if we've hit a column edge we're done with this block
- if (fit1 > 0.2) {
- for (i = 0; i < edgesLength; ++i) {
- if (str0->xMax < edges[i].x + 0.5 && edges[i].x - 0.5 < str2->xMin &&
- str0->yMin < edges[i].y1 && str0->yMax > edges[i].y0 &&
- str2->yMin < edges[i].y1 && str2->yMax > edges[i].y0) {
- break;
- }
- }
- if (i < edgesLength) {
- break;
- }
- }
-
- if (str1) {
- str1->next = str2->next;
- } else {
- xyStrings = str2->next;
- }
- str0->next = str2;
- str2->next = NULL;
- if (str2->xMax > blk->xMax) {
- blk->xMax = str2->xMax;
- }
- if (str2->yMin < blk->yMin) {
- blk->yMin = str2->yMin;
- }
- if (str2->yMax > blk->yMax) {
- blk->yMax = str2->yMax;
- }
- str0 = str2;
- }
-
- // insert block on list
- if (!rawOrder) {
- // insert block on list in yx order
- for (blk1 = NULL, blk2 = yxBlocks;
- blk2 && !yxBefore(blk, blk2);
- blk1 = blk2, blk2 = blk2->next) ;
- }
- blk->next = blk2;
- if (blk1) {
- blk1->next = blk;
- } else {
- yxBlocks = blk;
- }
- blk1 = blk;
- }
-
- gfree(edges);
-
- // the strings are now owned by the lines/blocks tree
- xyStrings = NULL;
-
- // build the block text
- uMap = globalParams->getTextEncoding();
- isUnicode = uMap ? uMap->isUnicode() : gFalse;
- for (blk = yxBlocks; blk; blk = blk->next) {
- blk->len = 0;
- for (str1 = blk->strings; str1; str1 = str1->next) {
- blk->len += str1->len;
- if (str1->next && str1->next->xMin - str1->xMax >
- textOutSpace * (str1->yMax - str1->yMin)) {
- str1->spaceAfter = gTrue;
- ++blk->len;
- } else {
- str1->spaceAfter = gFalse;
- }
- }
- blk->text = (Unicode *)gmalloc(blk->len * sizeof(Unicode));
- blk->xRight = (double *)gmalloc(blk->len * sizeof(double));
- blk->col = (int *)gmalloc(blk->len * sizeof(int));
- i = 0;
- for (str1 = blk->strings; str1; str1 = str1->next) {
- for (j = 0; j < str1->len; ++j) {
- blk->text[i] = str1->text[j];
- blk->xRight[i] = str1->xRight[j];
- ++i;
- }
- if (str1->spaceAfter) {
- blk->text[i] = (Unicode)0x0020;
- blk->xRight[i] = str1->next->xMin;
- ++i;
- }
- }
- blk->convertedLen = 0;
- for (j = 0; j < blk->len; ++j) {
- blk->col[j] = blk->convertedLen;
- if (isUnicode) {
- ++blk->convertedLen;
- } else if (uMap) {
- blk->convertedLen += uMap->mapUnicode(blk->text[j], buf, sizeof(buf));
- }
- }
- }
- if (uMap) {
- uMap->decRefCnt();
- }
-
-#if 0 //~ for debugging
- for (blk = yxBlocks; blk; blk = blk->next) {
- printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
- blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
- TextString *str;
- for (str = blk->strings; str; str = str->next) {
- printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f'",
- str->xMin, str->xMax, str->yMin, str->yMax,
- (str->yMax - str->yMin));
- for (i = 0; i < str->len; ++i) {
- fputc(str->text[i] & 0xff, stdout);
- }
- if (str->spaceAfter) {
- fputc(' ', stdout);
- }
- printf("'\n");
- }
- }
- printf("\n------------------------------------------------------------\n\n");
-#endif
-
- // build the lines
- lines = NULL;
- line0 = NULL;
- while (yxBlocks) {
- blk0 = yxBlocks;
- yxBlocks = yxBlocks->next;
- blk0->next = NULL;
- line = new TextLine();
- line->blocks = blk0;
- line->yMin = blk0->yMin;
- line->yMax = blk0->yMax;
- while (yxBlocks) {
-
- // remove duplicated text (fake boldface, shadowed text)
- h = blk0->yMax - blk0->yMin;
- if (yxBlocks->len == blk0->len &&
- !memcmp(yxBlocks->text, blk0->text,
- yxBlocks->len * sizeof(Unicode)) &&
- fabs(yxBlocks->yMin - blk0->yMin) / h < 0.2 &&
- fabs(yxBlocks->yMax - blk0->yMax) / h < 0.2 &&
- fabs(yxBlocks->xMin - blk0->xMin) / h < 0.2 &&
- fabs(yxBlocks->xMax - blk0->xMax) / h < 0.2) {
- blk1 = yxBlocks;
- yxBlocks = yxBlocks->next;
- delete blk1;
- continue;
- }
-
- if (rawOrder && yxBlocks->yMax < blk0->yMin) {
- break;
- }
- if (yxBlocks->yMin > 0.2*blk0->yMin + 0.8*blk0->yMax ||
- yxBlocks->xMin < blk0->xMax) {
- break;
- }
- blk1 = yxBlocks;
- yxBlocks = yxBlocks->next;
- blk0->next = blk1;
- blk1->next = NULL;
- if (blk1->yMin < line->yMin) {
- line->yMin = blk1->yMin;
- }
- if (blk1->yMax > line->yMax) {
- line->yMax = blk1->yMax;
- }
- blk0 = blk1;
- }
- if (line0) {
- line0->next = line;
- } else {
- lines = line;
- }
- line->next = NULL;
- line0 = line;
- }
-
-
- // sort the blocks into xy order
- xyBlocks = NULL;
- for (line = lines; line; line = line->next) {
- for (blk = line->blocks; blk; blk = blk->next) {
- for (blk1 = NULL, blk2 = xyBlocks;
- blk2 && !xyBefore(blk, blk2);
- blk1 = blk2, blk2 = blk2->xyNext) ;
- blk->xyNext = blk2;
- if (blk1) {
- blk1->xyNext = blk;
- } else {
- xyBlocks = blk;
- }
- }
- }
-
-#if 0 //~ for debugging
- for (blk = xyBlocks; blk; blk = blk->xyNext) {
- printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
- blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
- TextString *str;
- for (str = blk->strings; str; str = str->next) {
- printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
- str->xMin, str->xMax, str->yMin, str->yMax,
- (str->yMax - str->yMin));
- for (i = 0; i < str->len; ++i) {
- fputc(str->text[i] & 0xff, stdout);
- }
- printf("'\n");
- }
- }
- printf("\n------------------------------------------------------------\n\n");
-#endif
-
- // do column assignment
- for (blk1 = xyBlocks; blk1; blk1 = blk1->xyNext) {
- col1 = 0;
- for (blk2 = xyBlocks; blk2 != blk1; blk2 = blk2->xyNext) {
- if (blk1->xMin >= blk2->xMax) {
- d = (int)((blk1->xMin - blk2->xMax) /
- (0.4 * (blk1->yMax - blk1->yMin)));
- if (d > 4) {
- d = 4;
- }
- col2 = blk2->col[0] + blk2->convertedLen + d;
- if (col2 > col1) {
- col1 = col2;
- }
- } else if (blk1->xMin > blk2->xMin) {
- for (i = 0; i < blk2->len && blk1->xMin >= blk2->xRight[i]; ++i) ;
- col2 = blk2->col[i];
- if (col2 > col1) {
- col1 = col2;
- }
- }
- }
- for (j = 0; j < blk1->len; ++j) {
- blk1->col[j] += col1;
- }
- }
-
-#if 0 //~ for debugging
- for (line = lines; line; line = line->next) {
- printf("[line]\n");
- for (blk = line->blocks; blk; blk = blk->next) {
- printf("[block: col=%d, len=%d]\n", blk->col[0], blk->len);
- TextString *str;
- for (str = blk->strings; str; str = str->next) {
- printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
- str->xMin, str->xMax, str->yMin, str->yMax,
- (str->yMax - str->yMin));
- for (i = 0; i < str->len; ++i) {
- fputc(str->text[i] & 0xff, stdout);
- }
- if (str->spaceAfter) {
- printf(" [space]\n");
- }
- printf("'\n");
- }
- }
- }
- printf("\n------------------------------------------------------------\n\n");
-#endif
-}
-
-
-GBool TextPage::findText(Unicode *s, int len,
- GBool top, GBool bottom,
- double *xMin, double *yMin,
- double *xMax, double *yMax) {
- TextLine *line;
- TextBlock *blk;
- Unicode *p;
- Unicode u1, u2;
- int m, i, j;
- double x0, x1, x;
-
- // scan all blocks on page
- for (line = lines; line; line = line->next) {
- for (blk = line->blocks; blk; blk = blk->next) {
-
- // check: above top limit?
- if (!top && (blk->yMax < *yMin ||
- (blk->yMin < *yMin && blk->xMax <= *xMin))) {
- continue;
- }
-
- // check: below bottom limit?
- if (!bottom && (blk->yMin > *yMax ||
- (blk->yMax > *yMax && blk->xMin >= *xMax))) {
- return gFalse;
- }
-
- // search each position in this block
- m = blk->len;
- for (i = 0, p = blk->text; i <= m - len; ++i, ++p) {
-
- x0 = (i == 0) ? blk->xMin : blk->xRight[i-1];
- x1 = blk->xRight[i];
- x = 0.5 * (x0 + x1);
-
- // check: above top limit?
- if (!top && blk->yMin < *yMin) {
- if (x < *xMin) {
- continue;
- }
- }
-
- // check: below bottom limit?
- if (!bottom && blk->yMax > *yMax) {
- if (x > *xMax) {
- return gFalse;
- }
- }
-
- // compare the strings
- for (j = 0; j < len; ++j) {
-#if 1 //~ this lowercases Latin A-Z only -- this will eventually be
- //~ extended to handle other character sets
- if (p[j] >= 0x41 && p[j] <= 0x5a) {
- u1 = p[j] + 0x20;
- } else {
- u1 = p[j];
- }
- if (s[j] >= 0x41 && s[j] <= 0x5a) {
- u2 = s[j] + 0x20;
- } else {
- u2 = s[j];
- }
-#endif
- if (u1 != u2) {
- break;
- }
- }
-
- // found it
- if (j == len) {
- *xMin = x0;
- *xMax = blk->xRight[i + len - 1];
- *yMin = blk->yMin;
- *yMax = blk->yMax;
- return gTrue;
- }
- }
- }
- }
-
- return gFalse;
-}
-
-GString *TextPage::getText(double xMin, double yMin,
- double xMax, double yMax) {
- GString *s;
- UnicodeMap *uMap;
- GBool isUnicode;
- char space[8], eol[16], buf[8];
- int spaceLen, eolLen, len;
- TextLine *line;
- TextBlock *blk;
- double x0, x1, y;
- int firstCol, col, i;
- GBool multiLine;
-
- s = new GString();
-
- // get the output encoding
- if (!(uMap = globalParams->getTextEncoding())) {
- return s;
- }
- isUnicode = uMap->isUnicode();
- spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
- eolLen = 0; // make gcc happy
- switch (globalParams->getTextEOL()) {
- case eolUnix:
- eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
- break;
- case eolDOS:
- eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
- eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
- break;
- case eolMac:
- eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
- break;
- }
-
- // find the leftmost column
- multiLine = gFalse;
- firstCol = -1;
- for (line = lines; line; line = line->next) {
- if (line->yMin > yMax) {
- break;
- }
- if (line->yMax < yMin) {
- continue;
- }
-
- for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
- if (!blk || blk->xMin > xMax) {
- continue;
- }
-
- y = 0.5 * (blk->yMin + blk->yMax);
- if (y < yMin || y > yMax) {
- continue;
- }
-
- if (firstCol >= 0) {
- multiLine = gTrue;
- }
-
- i = 0;
- while (1) {
- x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
- x1 = blk->xRight[i];
- if (0.5 * (x0 + x1) > xMin) {
- break;
- }
- ++i;
- }
- col = blk->col[i];
-
- if (firstCol < 0 || col < firstCol) {
- firstCol = col;
- }
- }
-
- // extract the text
- for (line = lines; line; line = line->next) {
- if (line->yMin > yMax) {
- break;
- }
- if (line->yMax < yMin) {
- continue;
- }
-
- for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
- if (!blk || blk->xMin > xMax) {
- continue;
- }
-
- y = 0.5 * (blk->yMin + blk->yMax);
- if (y < yMin || y > yMax) {
- continue;
- }
-
- i = 0;
- while (1) {
- x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
- x1 = blk->xRight[i];
- if (0.5 * (x0 + x1) > xMin) {
- break;
- }
- ++i;
- }
-
- col = firstCol;
-
- do {
-
- // line this block up with the correct column
- for (; col < blk->col[i]; ++col) {
- s->append(space, spaceLen);
- }
-
- // print the block
- for (; i < blk->len; ++i) {
-
- x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
- x1 = blk->xRight[i];
- if (0.5 * (x0 + x1) > xMax) {
- break;
- }
-
- len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
- s->append(buf, len);
- col += isUnicode ? 1 : len;
- }
- if (i < blk->len) {
- break;
- }
-
- // next block
- blk = blk->next;
- i = 0;
-
- } while (blk && blk->xMin < xMax);
-
- if (multiLine) {
- s->append(eol, eolLen);
- }
- }
-
- uMap->decRefCnt();
-
- return s;
-}
-
-void TextPage::dump(void *outputStream, TextOutputFunc outputFunc) {
- UnicodeMap *uMap;
- char space[8], eol[16], eop[8], buf[8];
- int spaceLen, eolLen, eopLen, len;
- TextLine *line;
- TextBlock *blk;
- int col, d, i;
-
- // get the output encoding
- if (!(uMap = globalParams->getTextEncoding())) {
- return;
- }
- spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
- eolLen = 0; // make gcc happy
- switch (globalParams->getTextEOL()) {
- case eolUnix:
- eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
- break;
- case eolDOS:
- eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
- eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
- break;
- case eolMac:
- eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
- break;
- }
- eopLen = uMap->mapUnicode(0x0c, eop, sizeof(eop));
-
- // output
- for (line = lines; line; line = line->next) {
- col = 0;
- for (blk = line->blocks; blk; blk = blk->next) {
-
- // line this block up with the correct column
- if (rawOrder && col == 0) {
- col = blk->col[0];
- } else {
- for (; col < blk->col[0]; ++col) {
- (*outputFunc)(outputStream, space, spaceLen);
- }
- }
-
- // print the block
- for (i = 0; i < blk->len; ++i) {
- len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
- (*outputFunc)(outputStream, buf, len);
- }
- col += blk->convertedLen;
- }
-
- // print a return
- (*outputFunc)(outputStream, eol, eolLen);
-
- // print extra vertical space if necessary
- if (line->next) {
- d = (int)((line->next->yMin - line->yMax) /
- (line->blocks->strings->yMax - lines->blocks->strings->yMin)
- + 0.5);
- // various things (weird font matrices) can result in bogus
- // values here, so do a sanity check
- if (rawOrder && d > 2) {
- d = 2;
- } else if (!rawOrder && d > 5) {
- d = 5;
- }
- for (; d > 0; --d) {
- (*outputFunc)(outputStream, eol, eolLen);
- }
- }
- }
-
- // end of page
- (*outputFunc)(outputStream, eol, eolLen);
- (*outputFunc)(outputStream, eop, eopLen);
- (*outputFunc)(outputStream, eol, eolLen);
-
- uMap->decRefCnt();
-}
-
-// Returns true if <str1> should be inserted before <str2> in xy
-// order.
-GBool TextPage::xyBefore(TextString *str1, TextString *str2) {
- return str1->xMin < str2->xMin ||
- (str1->xMin == str2->xMin && str1->yMin < str2->yMin);
-}
-
-// Returns true if <blk1> should be inserted before <blk2> in xy
-// order.
-GBool TextPage::xyBefore(TextBlock *blk1, TextBlock *blk2) {
- return blk1->xMin < blk2->xMin ||
- (blk1->xMin == blk2->xMin && blk1->yMin < blk2->yMin);
-}
-
-// Returns true if <blk1> should be inserted before <blk2> in yx
-// order, allowing a little slack for vertically overlapping text.
-GBool TextPage::yxBefore(TextBlock *blk1, TextBlock *blk2) {
- double h1, h2, overlap;
-
- h1 = blk1->yMax - blk1->yMin;
- h2 = blk2->yMax - blk2->yMin;
- overlap = ((blk1->yMax < blk2->yMax ? blk1->yMax : blk2->yMax) -
- (blk1->yMin > blk2->yMin ? blk1->yMin : blk2->yMin)) /
- (h1 < h2 ? h1 : h2);
- if (overlap > 0.6) {
- return blk1->xMin < blk2->xMin;
- }
- return blk1->yMin < blk2->yMin;
-}
-
-double TextPage::coalesceFit(TextString *str1, TextString *str2) {
- double h1, h2, w1, w2, r, overlap, spacing;
-
- h1 = str1->yMax - str1->yMin;
- h2 = str2->yMax - str2->yMin;
- w1 = str1->xMax - str1->xMin;
- w2 = str2->xMax - str2->xMin;
- r = h1 / h2;
- if (r < (1.0 / 3.0) || r > 3) {
- return 10;
- }
- overlap = ((str1->yMax < str2->yMax ? str1->yMax : str2->yMax) -
- (str1->yMin > str2->yMin ? str1->yMin : str2->yMin)) /
- (h1 < h2 ? h1 : h2);
- if (overlap < 0.5) {
- return 10;
- }
- spacing = (str2->xMin - str1->xMax) / (h1 > h2 ? h1 : h2);
- if (spacing < -0.5) {
- return 10;
- }
- // separate text that overlaps - duplicated text (so that fake
- // boldface and shadowed text can be cleanly removed)
- if ((str2->xMin - str1->xMax) / (w1 < w2 ? w1 : w2) < -0.7) {
- return 10;
- }
- return spacing;
-}
-
-void TextPage::clear() {
- TextLine *p1, *p2;
- TextString *s1, *s2;
-
- if (curStr) {
- delete curStr;
- curStr = NULL;
- }
- if (lines) {
- for (p1 = lines; p1; p1 = p2) {
- p2 = p1->next;
- delete p1;
- }
- } else if (xyStrings) {
- for (s1 = xyStrings; s1; s1 = s2) {
- s2 = s1->next;
- delete s1;
- }
- }
- xyStrings = NULL;
- xyCur1 = xyCur2 = NULL;
- lines = NULL;
- nest = 0;
- nTinyChars = 0;
-}
-
-//------------------------------------------------------------------------
-// TextOutputDev
-//------------------------------------------------------------------------
-
-static void outputToFile(void *stream, char *text, int len) {
- fwrite(text, 1, len, (FILE *)stream);
-}
-
-TextOutputDev::TextOutputDev(char *fileName, GBool rawOrderA, GBool append) {
- text = NULL;
- rawOrder = rawOrderA;
- ok = gTrue;
-
- // open file
- needClose = gFalse;
- if (fileName) {
- if (!strcmp(fileName, "-")) {
- outputStream = stdout;
- } else if ((outputStream = fopen(fileName, append ? "ab" : "wb"))) {
- needClose = gTrue;
- } else {
- error(-1, "Couldn't open text file '%s'", fileName);
- ok = gFalse;
- return;
- }
- outputFunc = &outputToFile;
- } else {
- outputStream = NULL;
- }
-
- // set up text object
- text = new TextPage(rawOrder);
-}
-
-TextOutputDev::TextOutputDev(TextOutputFunc func, void *stream,
- GBool rawOrderA) {
- outputFunc = func;
- outputStream = stream;
- needClose = gFalse;
- rawOrder = rawOrderA;
- text = new TextPage(rawOrder);
- ok = gTrue;
-}
-
-TextOutputDev::~TextOutputDev() {
- if (needClose) {
-#ifdef MACOS
- ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
-#endif
- fclose((FILE *)outputStream);
- }
- if (text) {
- delete text;
- }
-}
-
-void TextOutputDev::startPage(int /*pageNum*/, GfxState */*state*/) {
- text->clear();
-}
-
-void TextOutputDev::endPage() {
- text->coalesce();
- if (outputStream) {
- text->dump(outputStream, outputFunc);
- }
-}
-
-void TextOutputDev::updateFont(GfxState *state) {
- text->updateFont(state);
-}
-
-void TextOutputDev::beginString(GfxState *state, GString */*s*/) {
- text->beginString(state, state->getCurX(), state->getCurY());
-}
-
-void TextOutputDev::endString(GfxState */*state*/) {
- text->endString();
-}
-
-void TextOutputDev::drawChar(GfxState *state, double x, double y,
- double dx, double dy,
- double /*originX*/, double /*originY*/,
- CharCode /*c*/, Unicode *u, int uLen) {
- text->addChar(state, x, y, dx, dy, u, uLen);
-}
-
-GBool TextOutputDev::findText(Unicode *s, int len,
- GBool top, GBool bottom,
- double *xMin, double *yMin,
- double *xMax, double *yMax) {
- return text->findText(s, len, top, bottom, xMin, yMin, xMax, yMax);
-}
-
-GString *TextOutputDev::getText(double xMin, double yMin,
- double xMax, double yMax) {
- return text->getText(xMin, yMin, xMax, yMax);
-}
-
diff --git a/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cpp
new file mode 100644
index 000000000..3266678fb
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/TextOutputDev.cpp
@@ -0,0 +1,1243 @@
+//========================================================================
+//
+// TextOutputDev.cpp
+//
+// Copyright 1997-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <math.h>
+#include <ctype.h>
+#include "GString.h"
+#include "gmem.h"
+#include "config.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "UnicodeMap.h"
+#include "GfxState.h"
+#include "TextOutputDev.h"
+
+#ifdef MACOS
+// needed for setting type/creator of MacOS files
+#include "ICSupport.h"
+#endif
+
+//------------------------------------------------------------------------
+
+#define textOutSpace 0.2
+#define textOutColSpace 0.2
+
+//------------------------------------------------------------------------
+
+struct TextOutColumnEdge {
+ double x, y0, y1;
+};
+
+//------------------------------------------------------------------------
+// TextBlock
+//------------------------------------------------------------------------
+
+TextBlock::TextBlock() {
+ strings = NULL;
+ next = NULL;
+ xyNext = NULL;
+ text = NULL;
+ xRight = NULL;
+ col = NULL;
+}
+
+TextBlock::~TextBlock() {
+ TextString *p1, *p2;
+
+ for (p1 = strings; p1; p1 = p2) {
+ p2 = p1->next;
+ delete p1;
+ }
+ gfree(text);
+ gfree(xRight);
+ gfree(col);
+}
+
+//------------------------------------------------------------------------
+// TextLine
+//------------------------------------------------------------------------
+
+TextLine::TextLine() {
+ blocks = NULL;
+ next = NULL;
+}
+
+TextLine::~TextLine() {
+ TextBlock *p1, *p2;
+
+ for (p1 = blocks; p1; p1 = p2) {
+ p2 = p1->next;
+ delete p1;
+ }
+}
+
+//------------------------------------------------------------------------
+// TextString
+//------------------------------------------------------------------------
+
+TextString::TextString(GfxState *state, double x0, double y0,
+ double fontSize) {
+ GfxFont *font;
+ double x, y;
+
+ state->transform(x0, y0, &x, &y);
+ if ((font = state->getFont())) {
+ yMin = y - font->getAscent() * fontSize;
+ yMax = y - font->getDescent() * fontSize;
+ } else {
+ // this means that the PDF file draws text without a current font,
+ // which should never happen
+ yMin = y - 0.95 * fontSize;
+ yMax = y + 0.35 * fontSize;
+ }
+ if (yMin == yMax) {
+ // this is a sanity check for a case that shouldn't happen -- but
+ // if it does happen, we want to avoid dividing by zero later
+ yMin = y;
+ yMax = y + 1;
+ }
+ marked = gFalse;
+ text = NULL;
+ xRight = NULL;
+ len = size = 0;
+ next = NULL;
+}
+
+
+TextString::~TextString() {
+ gfree(text);
+ gfree(xRight);
+}
+
+void TextString::addChar(GfxState */*state*/, double x, double /*y*/,
+ double dx, double /*dy*/, Unicode u) {
+ if (len == size) {
+ size += 16;
+ text = (Unicode *)grealloc(text, size * sizeof(Unicode));
+ xRight = (double *)grealloc(xRight, size * sizeof(double));
+ }
+ text[len] = u;
+ if (len == 0) {
+ xMin = x;
+ }
+ xMax = xRight[len] = x + dx;
+ ++len;
+}
+
+//------------------------------------------------------------------------
+// TextPage
+//------------------------------------------------------------------------
+
+TextPage::TextPage(GBool rawOrderA) {
+ rawOrder = rawOrderA;
+ curStr = NULL;
+ fontSize = 0;
+ xyStrings = NULL;
+ xyCur1 = xyCur2 = NULL;
+ lines = NULL;
+ nest = 0;
+ nTinyChars = 0;
+}
+
+TextPage::~TextPage() {
+ clear();
+}
+
+void TextPage::updateFont(GfxState *state) {
+ GfxFont *font;
+ double *fm;
+ char *name;
+ int code, mCode, letterCode, anyCode;
+ double w;
+
+ // adjust the font size
+ fontSize = state->getTransformedFontSize();
+ if ((font = state->getFont()) && font->getType() == fontType3) {
+ // This is a hack which makes it possible to deal with some Type 3
+ // fonts. The problem is that it's impossible to know what the
+ // base coordinate system used in the font is without actually
+ // rendering the font. This code tries to guess by looking at the
+ // width of the character 'm' (which breaks if the font is a
+ // subset that doesn't contain 'm').
+ mCode = letterCode = anyCode = -1;
+ for (code = 0; code < 256; ++code) {
+ name = ((Gfx8BitFont *)font)->getCharName(code);
+ if (name && name[0] == 'm' && name[1] == '\0') {
+ mCode = code;
+ }
+ if (letterCode < 0 && name && name[1] == '\0' &&
+ ((name[0] >= 'A' && name[0] <= 'Z') ||
+ (name[0] >= 'a' && name[0] <= 'z'))) {
+ letterCode = code;
+ }
+ if (anyCode < 0 && name && ((Gfx8BitFont *)font)->getWidth(code) > 0) {
+ anyCode = code;
+ }
+ }
+ if (mCode >= 0 &&
+ (w = ((Gfx8BitFont *)font)->getWidth(mCode)) > 0) {
+ // 0.6 is a generic average 'm' width -- yes, this is a hack
+ fontSize *= w / 0.6;
+ } else if (letterCode >= 0 &&
+ (w = ((Gfx8BitFont *)font)->getWidth(letterCode)) > 0) {
+ // even more of a hack: 0.5 is a generic letter width
+ fontSize *= w / 0.5;
+ } else if (anyCode >= 0 &&
+ (w = ((Gfx8BitFont *)font)->getWidth(anyCode)) > 0) {
+ // better than nothing: 0.5 is a generic character width
+ fontSize *= w / 0.5;
+ }
+ fm = font->getFontMatrix();
+ if (fm[0] != 0) {
+ fontSize *= fabs(fm[3] / fm[0]);
+ }
+ }
+}
+
+void TextPage::beginString(GfxState *state, double x0, double y0) {
+ // This check is needed because Type 3 characters can contain
+ // text-drawing operations.
+ if (curStr) {
+ ++nest;
+ return;
+ }
+
+ curStr = new TextString(state, x0, y0, fontSize);
+}
+
+void TextPage::addChar(GfxState *state, double x, double y,
+ double dx, double dy, Unicode *u, int uLen) {
+ double x1, y1, w1, h1, dx2, dy2;
+ int n, i;
+
+ state->transform(x, y, &x1, &y1);
+ if (x1 < 0 || x1 > state->getPageWidth() ||
+ y1 < 0 || y1 > state->getPageHeight()) {
+ return;
+ }
+ state->textTransformDelta(state->getCharSpace() * state->getHorizScaling(),
+ 0, &dx2, &dy2);
+ dx -= dx2;
+ dy -= dy2;
+ state->transformDelta(dx, dy, &w1, &h1);
+ if (!globalParams->getTextKeepTinyChars() &&
+ fabs(w1) < 3 && fabs(h1) < 3) {
+ if (++nTinyChars > 20000) {
+ return;
+ }
+ }
+ n = curStr->len;
+ if (n > 0 && x1 - curStr->xRight[n-1] >
+ 0.1 * (curStr->yMax - curStr->yMin)) {
+ // large char spacing is sometimes used to move text around
+ endString();
+ beginString(state, x, y);
+ }
+ if (uLen == 1 && u[0] == (Unicode)0x20 &&
+ w1 > 0.5 * (curStr->yMax - curStr->yMin)) {
+ // large word spacing is sometimes used to move text around
+ return;
+ }
+ if (uLen != 0) {
+ w1 /= uLen;
+ h1 /= uLen;
+ }
+ for (i = 0; i < uLen; ++i) {
+ curStr->addChar(state, x1 + i*w1, y1 + i*h1, w1, h1, u[i]);
+ }
+}
+
+void TextPage::endString() {
+ // This check is needed because Type 3 characters can contain
+ // text-drawing operations.
+ if (nest > 0) {
+ --nest;
+ return;
+ }
+
+ addString(curStr);
+ curStr = NULL;
+}
+
+void TextPage::addString(TextString *str) {
+ TextString *p1, *p2;
+
+ // throw away zero-length strings -- they don't have valid xMin/xMax
+ // values, and they're useless anyway
+ if (str->len == 0) {
+ delete str;
+ return;
+ }
+
+ // insert string in xy list
+ if (rawOrder) {
+ p1 = xyCur1;
+ p2 = NULL;
+ } else if ((!xyCur1 || xyBefore(xyCur1, str)) &&
+ (!xyCur2 || xyBefore(str, xyCur2))) {
+ p1 = xyCur1;
+ p2 = xyCur2;
+ } else if (xyCur1 && xyBefore(xyCur1, str)) {
+ for (p1 = xyCur1, p2 = xyCur2; p2; p1 = p2, p2 = p2->next) {
+ if (xyBefore(str, p2)) {
+ break;
+ }
+ }
+ xyCur2 = p2;
+ } else {
+ for (p1 = NULL, p2 = xyStrings; p2; p1 = p2, p2 = p2->next) {
+ if (xyBefore(str, p2)) {
+ break;
+ }
+ }
+ xyCur2 = p2;
+ }
+ xyCur1 = str;
+ if (p1) {
+ p1->next = str;
+ } else {
+ xyStrings = str;
+ }
+ str->next = p2;
+}
+
+void TextPage::coalesce() {
+ TextLine *line, *line0;
+ TextBlock *yxBlocks, *xyBlocks, *blk, *blk0, *blk1, *blk2;
+ TextString *str0, *str1, *str2, *str3, *str4;
+ TextString *str1prev, *str2prev, *str3prev;
+ TextOutColumnEdge *edges;
+ UnicodeMap *uMap;
+ GBool isUnicode;
+ char buf[8];
+ int edgesLength, edgesSize;
+ double x, yMin, yMax;
+ double space, fit1, fit2, h;
+ int col1, col2, d;
+ int i, j;
+
+#if 0 //~ for debugging
+ for (str1 = xyStrings; str1; str1 = str1->next) {
+ printf("x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
+ str1->xMin, str1->xMax, str1->yMin, str1->yMax,
+ (str1->yMax - str1->yMin));
+ for (i = 0; i < str1->len; ++i) {
+ fputc(str1->text[i] & 0xff, stdout);
+ }
+ printf("'\n");
+ }
+ printf("\n------------------------------------------------------------\n\n");
+#endif
+
+ // build the list of column edges
+ edges = NULL;
+ edgesLength = edgesSize = 0;
+ if (!rawOrder) {
+ for (str1prev = NULL, str1 = xyStrings;
+ str1;
+ str1prev = str1, str1 = str1->next) {
+ if (str1->marked) {
+ continue;
+ }
+ h = str1->yMax - str1->yMin;
+ if (str1prev && (str1->xMin - str1prev->xMax) / h < textOutColSpace) {
+ continue;
+ }
+ x = str1->xMin;
+ yMin = str1->yMin;
+ yMax = str1->yMax;
+ for (str2prev = str1, str2 = str1->next;
+ str2;
+ str2prev = str2, str2 = str2->next) {
+ h = str2->yMax - str2->yMin;
+ if (!str2->marked &&
+ (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
+ fabs(str2->xMin - x) < 0.5 &&
+ str2->yMin - yMax < 0.3 * h &&
+ yMin - str2->yMax < 0.3 * h) {
+ break;
+ }
+ }
+ if (str2) {
+ if (str2->yMin < yMin) {
+ yMin = str2->yMin;
+ }
+ if (str2->yMax > yMax) {
+ yMax = str2->yMax;
+ }
+ str2->marked = gTrue;
+ for (str3prev = str1, str3 = str1->next;
+ str3;
+ str3prev = str3, str3 = str3->next) {
+ h = str3->yMax - str3->yMin;
+ if (!str3->marked &&
+ (str3->xMin - str3prev->xMax) / h > textOutColSpace &&
+ fabs(str3->xMin - x) < 0.5 &&
+ str3->yMin - yMax < 0.3 * h &&
+ yMin - str3->yMax < 0.3 * h) {
+ break;
+ }
+ }
+ if (str3) {
+ if (str3->yMin < yMin) {
+ yMin = str3->yMin;
+ }
+ if (str3->yMax > yMax) {
+ yMax = str3->yMax;
+ }
+ str3->marked = gTrue;
+ do {
+ for (str2prev = str1, str2 = str1->next;
+ str2;
+ str2prev = str2, str2 = str2->next) {
+ h = str2->yMax - str2->yMin;
+ if (!str2->marked &&
+ (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
+ fabs(str2->xMin - x) < 0.5 &&
+ str2->yMin - yMax < 0.3 * h &&
+ yMin - str2->yMax < 0.3 * h) {
+ if (str2->yMin < yMin) {
+ yMin = str2->yMin;
+ }
+ if (str2->yMax > yMax) {
+ yMax = str2->yMax;
+ }
+ str2->marked = gTrue;
+ break;
+ }
+ }
+ } while (str2);
+ if (edgesLength == edgesSize) {
+ edgesSize = edgesSize ? 2 * edgesSize : 16;
+ edges = (TextOutColumnEdge *)
+ grealloc(edges, edgesSize * sizeof(TextOutColumnEdge));
+ }
+ edges[edgesLength].x = x;
+ edges[edgesLength].y0 = yMin;
+ edges[edgesLength].y1 = yMax;
+ ++edgesLength;
+ } else {
+ str2->marked = gFalse;
+ }
+ }
+ str1->marked = gTrue;
+ }
+ }
+
+#if 0 //~ for debugging
+ printf("column edges:\n");
+ for (i = 0; i < edgesLength; ++i) {
+ printf("%d: x=%.2f y0=%.2f y1=%.2f\n",
+ i, edges[i].x, edges[i].y0, edges[i].y1);
+ }
+ printf("\n------------------------------------------------------------\n\n");
+#endif
+
+ // build the blocks
+ yxBlocks = NULL;
+ blk1 = blk2 = NULL;
+ while (xyStrings) {
+
+ // build the block
+ str0 = xyStrings;
+ xyStrings = xyStrings->next;
+ str0->next = NULL;
+ blk = new TextBlock();
+ blk->strings = str0;
+ blk->xMin = str0->xMin;
+ blk->xMax = str0->xMax;
+ blk->yMin = str0->yMin;
+ blk->yMax = str0->yMax;
+ while (xyStrings) {
+ str1 = NULL;
+ str2 = xyStrings;
+ fit1 = coalesceFit(str0, str2);
+ if (!rawOrder) {
+ // look for best-fitting string
+ space = str0->yMax - str0->yMin;
+ for (str3 = xyStrings, str4 = xyStrings->next;
+ str4 && str4->xMin - str0->xMax <= space;
+ str3 = str4, str4 = str4->next) {
+ fit2 = coalesceFit(str0, str4);
+ if (fit2 < fit1) {
+ str1 = str3;
+ str2 = str4;
+ fit1 = fit2;
+ }
+ }
+ }
+ if (fit1 > 1) {
+ // no fit - we're done with this block
+ break;
+ }
+
+ // if we've hit a column edge we're done with this block
+ if (fit1 > 0.2) {
+ for (i = 0; i < edgesLength; ++i) {
+ if (str0->xMax < edges[i].x + 0.5 && edges[i].x - 0.5 < str2->xMin &&
+ str0->yMin < edges[i].y1 && str0->yMax > edges[i].y0 &&
+ str2->yMin < edges[i].y1 && str2->yMax > edges[i].y0) {
+ break;
+ }
+ }
+ if (i < edgesLength) {
+ break;
+ }
+ }
+
+ if (str1) {
+ str1->next = str2->next;
+ } else {
+ xyStrings = str2->next;
+ }
+ str0->next = str2;
+ str2->next = NULL;
+ if (str2->xMax > blk->xMax) {
+ blk->xMax = str2->xMax;
+ }
+ if (str2->yMin < blk->yMin) {
+ blk->yMin = str2->yMin;
+ }
+ if (str2->yMax > blk->yMax) {
+ blk->yMax = str2->yMax;
+ }
+ str0 = str2;
+ }
+
+ // insert block on list
+ if (!rawOrder) {
+ // insert block on list in yx order
+ for (blk1 = NULL, blk2 = yxBlocks;
+ blk2 && !yxBefore(blk, blk2);
+ blk1 = blk2, blk2 = blk2->next) ;
+ }
+ blk->next = blk2;
+ if (blk1) {
+ blk1->next = blk;
+ } else {
+ yxBlocks = blk;
+ }
+ blk1 = blk;
+ }
+
+ gfree(edges);
+
+ // the strings are now owned by the lines/blocks tree
+ xyStrings = NULL;
+
+ // build the block text
+ uMap = globalParams->getTextEncoding();
+ isUnicode = uMap ? uMap->isUnicode() : gFalse;
+ for (blk = yxBlocks; blk; blk = blk->next) {
+ blk->len = 0;
+ for (str1 = blk->strings; str1; str1 = str1->next) {
+ blk->len += str1->len;
+ if (str1->next && str1->next->xMin - str1->xMax >
+ textOutSpace * (str1->yMax - str1->yMin)) {
+ str1->spaceAfter = gTrue;
+ ++blk->len;
+ } else {
+ str1->spaceAfter = gFalse;
+ }
+ }
+ blk->text = (Unicode *)gmalloc(blk->len * sizeof(Unicode));
+ blk->xRight = (double *)gmalloc(blk->len * sizeof(double));
+ blk->col = (int *)gmalloc(blk->len * sizeof(int));
+ i = 0;
+ for (str1 = blk->strings; str1; str1 = str1->next) {
+ for (j = 0; j < str1->len; ++j) {
+ blk->text[i] = str1->text[j];
+ blk->xRight[i] = str1->xRight[j];
+ ++i;
+ }
+ if (str1->spaceAfter) {
+ blk->text[i] = (Unicode)0x0020;
+ blk->xRight[i] = str1->next->xMin;
+ ++i;
+ }
+ }
+ blk->convertedLen = 0;
+ for (j = 0; j < blk->len; ++j) {
+ blk->col[j] = blk->convertedLen;
+ if (isUnicode) {
+ ++blk->convertedLen;
+ } else if (uMap) {
+ blk->convertedLen += uMap->mapUnicode(blk->text[j], buf, sizeof(buf));
+ }
+ }
+ }
+ if (uMap) {
+ uMap->decRefCnt();
+ }
+
+#if 0 //~ for debugging
+ for (blk = yxBlocks; blk; blk = blk->next) {
+ printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
+ blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
+ TextString *str;
+ for (str = blk->strings; str; str = str->next) {
+ printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f'",
+ str->xMin, str->xMax, str->yMin, str->yMax,
+ (str->yMax - str->yMin));
+ for (i = 0; i < str->len; ++i) {
+ fputc(str->text[i] & 0xff, stdout);
+ }
+ if (str->spaceAfter) {
+ fputc(' ', stdout);
+ }
+ printf("'\n");
+ }
+ }
+ printf("\n------------------------------------------------------------\n\n");
+#endif
+
+ // build the lines
+ lines = NULL;
+ line0 = NULL;
+ while (yxBlocks) {
+ blk0 = yxBlocks;
+ yxBlocks = yxBlocks->next;
+ blk0->next = NULL;
+ line = new TextLine();
+ line->blocks = blk0;
+ line->yMin = blk0->yMin;
+ line->yMax = blk0->yMax;
+ while (yxBlocks) {
+
+ // remove duplicated text (fake boldface, shadowed text)
+ h = blk0->yMax - blk0->yMin;
+ if (yxBlocks->len == blk0->len &&
+ !memcmp(yxBlocks->text, blk0->text,
+ yxBlocks->len * sizeof(Unicode)) &&
+ fabs(yxBlocks->yMin - blk0->yMin) / h < 0.2 &&
+ fabs(yxBlocks->yMax - blk0->yMax) / h < 0.2 &&
+ fabs(yxBlocks->xMin - blk0->xMin) / h < 0.2 &&
+ fabs(yxBlocks->xMax - blk0->xMax) / h < 0.2) {
+ blk1 = yxBlocks;
+ yxBlocks = yxBlocks->next;
+ delete blk1;
+ continue;
+ }
+
+ if (rawOrder && yxBlocks->yMax < blk0->yMin) {
+ break;
+ }
+ if (yxBlocks->yMin > 0.2*blk0->yMin + 0.8*blk0->yMax ||
+ yxBlocks->xMin < blk0->xMax) {
+ break;
+ }
+ blk1 = yxBlocks;
+ yxBlocks = yxBlocks->next;
+ blk0->next = blk1;
+ blk1->next = NULL;
+ if (blk1->yMin < line->yMin) {
+ line->yMin = blk1->yMin;
+ }
+ if (blk1->yMax > line->yMax) {
+ line->yMax = blk1->yMax;
+ }
+ blk0 = blk1;
+ }
+ if (line0) {
+ line0->next = line;
+ } else {
+ lines = line;
+ }
+ line->next = NULL;
+ line0 = line;
+ }
+
+
+ // sort the blocks into xy order
+ xyBlocks = NULL;
+ for (line = lines; line; line = line->next) {
+ for (blk = line->blocks; blk; blk = blk->next) {
+ for (blk1 = NULL, blk2 = xyBlocks;
+ blk2 && !xyBefore(blk, blk2);
+ blk1 = blk2, blk2 = blk2->xyNext) ;
+ blk->xyNext = blk2;
+ if (blk1) {
+ blk1->xyNext = blk;
+ } else {
+ xyBlocks = blk;
+ }
+ }
+ }
+
+#if 0 //~ for debugging
+ for (blk = xyBlocks; blk; blk = blk->xyNext) {
+ printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
+ blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
+ TextString *str;
+ for (str = blk->strings; str; str = str->next) {
+ printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
+ str->xMin, str->xMax, str->yMin, str->yMax,
+ (str->yMax - str->yMin));
+ for (i = 0; i < str->len; ++i) {
+ fputc(str->text[i] & 0xff, stdout);
+ }
+ printf("'\n");
+ }
+ }
+ printf("\n------------------------------------------------------------\n\n");
+#endif
+
+ // do column assignment
+ for (blk1 = xyBlocks; blk1; blk1 = blk1->xyNext) {
+ col1 = 0;
+ for (blk2 = xyBlocks; blk2 != blk1; blk2 = blk2->xyNext) {
+ if (blk1->xMin >= blk2->xMax) {
+ d = (int)((blk1->xMin - blk2->xMax) /
+ (0.4 * (blk1->yMax - blk1->yMin)));
+ if (d > 4) {
+ d = 4;
+ }
+ col2 = blk2->col[0] + blk2->convertedLen + d;
+ if (col2 > col1) {
+ col1 = col2;
+ }
+ } else if (blk1->xMin > blk2->xMin) {
+ for (i = 0; i < blk2->len && blk1->xMin >= blk2->xRight[i]; ++i) ;
+ col2 = blk2->col[i];
+ if (col2 > col1) {
+ col1 = col2;
+ }
+ }
+ }
+ for (j = 0; j < blk1->len; ++j) {
+ blk1->col[j] += col1;
+ }
+ }
+
+#if 0 //~ for debugging
+ for (line = lines; line; line = line->next) {
+ printf("[line]\n");
+ for (blk = line->blocks; blk; blk = blk->next) {
+ printf("[block: col=%d, len=%d]\n", blk->col[0], blk->len);
+ TextString *str;
+ for (str = blk->strings; str; str = str->next) {
+ printf(" x=%.2f..%.2f y=%.2f..%.2f size=%.2f '",
+ str->xMin, str->xMax, str->yMin, str->yMax,
+ (str->yMax - str->yMin));
+ for (i = 0; i < str->len; ++i) {
+ fputc(str->text[i] & 0xff, stdout);
+ }
+ if (str->spaceAfter) {
+ printf(" [space]\n");
+ }
+ printf("'\n");
+ }
+ }
+ }
+ printf("\n------------------------------------------------------------\n\n");
+#endif
+}
+
+
+GBool TextPage::findText(Unicode *s, int len,
+ GBool top, GBool bottom,
+ double *xMin, double *yMin,
+ double *xMax, double *yMax) {
+ TextLine *line;
+ TextBlock *blk;
+ Unicode *p;
+ Unicode u1, u2;
+ int m, i, j;
+ double x0, x1, x;
+
+ // scan all blocks on page
+ for (line = lines; line; line = line->next) {
+ for (blk = line->blocks; blk; blk = blk->next) {
+
+ // check: above top limit?
+ if (!top && (blk->yMax < *yMin ||
+ (blk->yMin < *yMin && blk->xMax <= *xMin))) {
+ continue;
+ }
+
+ // check: below bottom limit?
+ if (!bottom && (blk->yMin > *yMax ||
+ (blk->yMax > *yMax && blk->xMin >= *xMax))) {
+ return gFalse;
+ }
+
+ // search each position in this block
+ m = blk->len;
+ for (i = 0, p = blk->text; i <= m - len; ++i, ++p) {
+
+ x0 = (i == 0) ? blk->xMin : blk->xRight[i-1];
+ x1 = blk->xRight[i];
+ x = 0.5 * (x0 + x1);
+
+ // check: above top limit?
+ if (!top && blk->yMin < *yMin) {
+ if (x < *xMin) {
+ continue;
+ }
+ }
+
+ // check: below bottom limit?
+ if (!bottom && blk->yMax > *yMax) {
+ if (x > *xMax) {
+ return gFalse;
+ }
+ }
+
+ // compare the strings
+ for (j = 0; j < len; ++j) {
+#if 1 //~ this lowercases Latin A-Z only -- this will eventually be
+ //~ extended to handle other character sets
+ if (p[j] >= 0x41 && p[j] <= 0x5a) {
+ u1 = p[j] + 0x20;
+ } else {
+ u1 = p[j];
+ }
+ if (s[j] >= 0x41 && s[j] <= 0x5a) {
+ u2 = s[j] + 0x20;
+ } else {
+ u2 = s[j];
+ }
+#endif
+ if (u1 != u2) {
+ break;
+ }
+ }
+
+ // found it
+ if (j == len) {
+ *xMin = x0;
+ *xMax = blk->xRight[i + len - 1];
+ *yMin = blk->yMin;
+ *yMax = blk->yMax;
+ return gTrue;
+ }
+ }
+ }
+ }
+
+ return gFalse;
+}
+
+GString *TextPage::getText(double xMin, double yMin,
+ double xMax, double yMax) {
+ GString *s;
+ UnicodeMap *uMap;
+ GBool isUnicode;
+ char space[8], eol[16], buf[8];
+ int spaceLen, eolLen, len;
+ TextLine *line;
+ TextBlock *blk;
+ double x0, x1, y;
+ int firstCol, col, i;
+ GBool multiLine;
+
+ s = new GString();
+
+ // get the output encoding
+ if (!(uMap = globalParams->getTextEncoding())) {
+ return s;
+ }
+ isUnicode = uMap->isUnicode();
+ spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
+ eolLen = 0; // make gcc happy
+ switch (globalParams->getTextEOL()) {
+ case eolUnix:
+ eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
+ break;
+ case eolDOS:
+ eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
+ eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
+ break;
+ case eolMac:
+ eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
+ break;
+ }
+
+ // find the leftmost column
+ multiLine = gFalse;
+ firstCol = -1;
+ for (line = lines; line; line = line->next) {
+ if (line->yMin > yMax) {
+ break;
+ }
+ if (line->yMax < yMin) {
+ continue;
+ }
+
+ for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
+ if (!blk || blk->xMin > xMax) {
+ continue;
+ }
+
+ y = 0.5 * (blk->yMin + blk->yMax);
+ if (y < yMin || y > yMax) {
+ continue;
+ }
+
+ if (firstCol >= 0) {
+ multiLine = gTrue;
+ }
+
+ i = 0;
+ while (1) {
+ x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
+ x1 = blk->xRight[i];
+ if (0.5 * (x0 + x1) > xMin) {
+ break;
+ }
+ ++i;
+ }
+ col = blk->col[i];
+
+ if (firstCol < 0 || col < firstCol) {
+ firstCol = col;
+ }
+ }
+
+ // extract the text
+ for (line = lines; line; line = line->next) {
+ if (line->yMin > yMax) {
+ break;
+ }
+ if (line->yMax < yMin) {
+ continue;
+ }
+
+ for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
+ if (!blk || blk->xMin > xMax) {
+ continue;
+ }
+
+ y = 0.5 * (blk->yMin + blk->yMax);
+ if (y < yMin || y > yMax) {
+ continue;
+ }
+
+ i = 0;
+ while (1) {
+ x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
+ x1 = blk->xRight[i];
+ if (0.5 * (x0 + x1) > xMin) {
+ break;
+ }
+ ++i;
+ }
+
+ col = firstCol;
+
+ do {
+
+ // line this block up with the correct column
+ for (; col < blk->col[i]; ++col) {
+ s->append(space, spaceLen);
+ }
+
+ // print the block
+ for (; i < blk->len; ++i) {
+
+ x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
+ x1 = blk->xRight[i];
+ if (0.5 * (x0 + x1) > xMax) {
+ break;
+ }
+
+ len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
+ s->append(buf, len);
+ col += isUnicode ? 1 : len;
+ }
+ if (i < blk->len) {
+ break;
+ }
+
+ // next block
+ blk = blk->next;
+ i = 0;
+
+ } while (blk && blk->xMin < xMax);
+
+ if (multiLine) {
+ s->append(eol, eolLen);
+ }
+ }
+
+ uMap->decRefCnt();
+
+ return s;
+}
+
+void TextPage::dump(void *outputStream, TextOutputFunc outputFunc) {
+ UnicodeMap *uMap;
+ char space[8], eol[16], eop[8], buf[8];
+ int spaceLen, eolLen, eopLen, len;
+ TextLine *line;
+ TextBlock *blk;
+ int col, d, i;
+
+ // get the output encoding
+ if (!(uMap = globalParams->getTextEncoding())) {
+ return;
+ }
+ spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
+ eolLen = 0; // make gcc happy
+ switch (globalParams->getTextEOL()) {
+ case eolUnix:
+ eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
+ break;
+ case eolDOS:
+ eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
+ eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
+ break;
+ case eolMac:
+ eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
+ break;
+ }
+ eopLen = uMap->mapUnicode(0x0c, eop, sizeof(eop));
+
+ // output
+ for (line = lines; line; line = line->next) {
+ col = 0;
+ for (blk = line->blocks; blk; blk = blk->next) {
+
+ // line this block up with the correct column
+ if (rawOrder && col == 0) {
+ col = blk->col[0];
+ } else {
+ for (; col < blk->col[0]; ++col) {
+ (*outputFunc)(outputStream, space, spaceLen);
+ }
+ }
+
+ // print the block
+ for (i = 0; i < blk->len; ++i) {
+ len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
+ (*outputFunc)(outputStream, buf, len);
+ }
+ col += blk->convertedLen;
+ }
+
+ // print a return
+ (*outputFunc)(outputStream, eol, eolLen);
+
+ // print extra vertical space if necessary
+ if (line->next) {
+ d = (int)((line->next->yMin - line->yMax) /
+ (line->blocks->strings->yMax - lines->blocks->strings->yMin)
+ + 0.5);
+ // various things (weird font matrices) can result in bogus
+ // values here, so do a sanity check
+ if (rawOrder && d > 2) {
+ d = 2;
+ } else if (!rawOrder && d > 5) {
+ d = 5;
+ }
+ for (; d > 0; --d) {
+ (*outputFunc)(outputStream, eol, eolLen);
+ }
+ }
+ }
+
+ // end of page
+ (*outputFunc)(outputStream, eol, eolLen);
+ (*outputFunc)(outputStream, eop, eopLen);
+ (*outputFunc)(outputStream, eol, eolLen);
+
+ uMap->decRefCnt();
+}
+
+// Returns true if <str1> should be inserted before <str2> in xy
+// order.
+GBool TextPage::xyBefore(TextString *str1, TextString *str2) {
+ return str1->xMin < str2->xMin ||
+ (str1->xMin == str2->xMin && str1->yMin < str2->yMin);
+}
+
+// Returns true if <blk1> should be inserted before <blk2> in xy
+// order.
+GBool TextPage::xyBefore(TextBlock *blk1, TextBlock *blk2) {
+ return blk1->xMin < blk2->xMin ||
+ (blk1->xMin == blk2->xMin && blk1->yMin < blk2->yMin);
+}
+
+// Returns true if <blk1> should be inserted before <blk2> in yx
+// order, allowing a little slack for vertically overlapping text.
+GBool TextPage::yxBefore(TextBlock *blk1, TextBlock *blk2) {
+ double h1, h2, overlap;
+
+ h1 = blk1->yMax - blk1->yMin;
+ h2 = blk2->yMax - blk2->yMin;
+ overlap = ((blk1->yMax < blk2->yMax ? blk1->yMax : blk2->yMax) -
+ (blk1->yMin > blk2->yMin ? blk1->yMin : blk2->yMin)) /
+ (h1 < h2 ? h1 : h2);
+ if (overlap > 0.6) {
+ return blk1->xMin < blk2->xMin;
+ }
+ return blk1->yMin < blk2->yMin;
+}
+
+double TextPage::coalesceFit(TextString *str1, TextString *str2) {
+ double h1, h2, w1, w2, r, overlap, spacing;
+
+ h1 = str1->yMax - str1->yMin;
+ h2 = str2->yMax - str2->yMin;
+ w1 = str1->xMax - str1->xMin;
+ w2 = str2->xMax - str2->xMin;
+ r = h1 / h2;
+ if (r < (1.0 / 3.0) || r > 3) {
+ return 10;
+ }
+ overlap = ((str1->yMax < str2->yMax ? str1->yMax : str2->yMax) -
+ (str1->yMin > str2->yMin ? str1->yMin : str2->yMin)) /
+ (h1 < h2 ? h1 : h2);
+ if (overlap < 0.5) {
+ return 10;
+ }
+ spacing = (str2->xMin - str1->xMax) / (h1 > h2 ? h1 : h2);
+ if (spacing < -0.5) {
+ return 10;
+ }
+ // separate text that overlaps - duplicated text (so that fake
+ // boldface and shadowed text can be cleanly removed)
+ if ((str2->xMin - str1->xMax) / (w1 < w2 ? w1 : w2) < -0.7) {
+ return 10;
+ }
+ return spacing;
+}
+
+void TextPage::clear() {
+ TextLine *p1, *p2;
+ TextString *s1, *s2;
+
+ if (curStr) {
+ delete curStr;
+ curStr = NULL;
+ }
+ if (lines) {
+ for (p1 = lines; p1; p1 = p2) {
+ p2 = p1->next;
+ delete p1;
+ }
+ } else if (xyStrings) {
+ for (s1 = xyStrings; s1; s1 = s2) {
+ s2 = s1->next;
+ delete s1;
+ }
+ }
+ xyStrings = NULL;
+ xyCur1 = xyCur2 = NULL;
+ lines = NULL;
+ nest = 0;
+ nTinyChars = 0;
+}
+
+//------------------------------------------------------------------------
+// TextOutputDev
+//------------------------------------------------------------------------
+
+static void outputToFile(void *stream, char *text, int len) {
+ fwrite(text, 1, len, (FILE *)stream);
+}
+
+TextOutputDev::TextOutputDev(char *fileName, GBool rawOrderA, GBool append) {
+ text = NULL;
+ rawOrder = rawOrderA;
+ ok = gTrue;
+
+ // open file
+ needClose = gFalse;
+ if (fileName) {
+ if (!strcmp(fileName, "-")) {
+ outputStream = stdout;
+ } else if ((outputStream = fopen(fileName, append ? "ab" : "wb"))) {
+ needClose = gTrue;
+ } else {
+ error(-1, "Couldn't open text file '%s'", fileName);
+ ok = gFalse;
+ return;
+ }
+ outputFunc = &outputToFile;
+ } else {
+ outputStream = NULL;
+ }
+
+ // set up text object
+ text = new TextPage(rawOrder);
+}
+
+TextOutputDev::TextOutputDev(TextOutputFunc func, void *stream,
+ GBool rawOrderA) {
+ outputFunc = func;
+ outputStream = stream;
+ needClose = gFalse;
+ rawOrder = rawOrderA;
+ text = new TextPage(rawOrder);
+ ok = gTrue;
+}
+
+TextOutputDev::~TextOutputDev() {
+ if (needClose) {
+#ifdef MACOS
+ ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
+#endif
+ fclose((FILE *)outputStream);
+ }
+ if (text) {
+ delete text;
+ }
+}
+
+void TextOutputDev::startPage(int /*pageNum*/, GfxState */*state*/) {
+ text->clear();
+}
+
+void TextOutputDev::endPage() {
+ text->coalesce();
+ if (outputStream) {
+ text->dump(outputStream, outputFunc);
+ }
+}
+
+void TextOutputDev::updateFont(GfxState *state) {
+ text->updateFont(state);
+}
+
+void TextOutputDev::beginString(GfxState *state, GString */*s*/) {
+ text->beginString(state, state->getCurX(), state->getCurY());
+}
+
+void TextOutputDev::endString(GfxState */*state*/) {
+ text->endString();
+}
+
+void TextOutputDev::drawChar(GfxState *state, double x, double y,
+ double dx, double dy,
+ double /*originX*/, double /*originY*/,
+ CharCode /*c*/, Unicode *u, int uLen) {
+ text->addChar(state, x, y, dx, dy, u, uLen);
+}
+
+GBool TextOutputDev::findText(Unicode *s, int len,
+ GBool top, GBool bottom,
+ double *xMin, double *yMin,
+ double *xMax, double *yMax) {
+ return text->findText(s, len, top, bottom, xMin, yMin, xMax, yMax);
+}
+
+GString *TextOutputDev::getText(double xMin, double yMin,
+ double xMax, double yMax) {
+ return text->getText(xMin, yMin, xMax, yMax);
+}
+
diff --git a/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cc b/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cc
deleted file mode 100644
index fe1185d7d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cc
+++ /dev/null
@@ -1,268 +0,0 @@
-//========================================================================
-//
-// UnicodeMap.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include "gmem.h"
-#include "gfile.h"
-#include "GString.h"
-#include "GList.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "UnicodeMap.h"
-
-//------------------------------------------------------------------------
-
-#define maxExtCode 16
-
-struct UnicodeMapExt {
- Unicode u; // Unicode char
- char code[maxExtCode];
- Guint nBytes;
-};
-
-//------------------------------------------------------------------------
-
-UnicodeMap *UnicodeMap::parse(GString *encodingNameA) {
- FILE *f;
- UnicodeMap *map;
- UnicodeMapRange *range;
- UnicodeMapExt *eMap;
- int size, eMapsSize;
- char buf[256];
- unsigned int x;
- int line, nBytes, i;
- char *tok1, *tok2, *tok3;
-
- if (!(f = globalParams->getUnicodeMapFile(encodingNameA))) {
- error(-1, "Couldn't find unicodeMap file for the '%s' encoding",
- encodingNameA->getCString());
- return NULL;
- }
-
- map = new UnicodeMap(encodingNameA->copy());
-
- size = 8;
- map->ranges = (UnicodeMapRange *)gmalloc(size * sizeof(UnicodeMapRange));
- eMapsSize = 0;
-
- line = 1;
- while (getLine(buf, sizeof(buf), f)) {
- if ((tok1 = strtok(buf, " \t\r\n")) &&
- (tok2 = strtok(NULL, " \t\r\n"))) {
- if (!(tok3 = strtok(NULL, " \t\r\n"))) {
- tok3 = tok2;
- tok2 = tok1;
- }
- nBytes = strlen(tok3) / 2;
- if (nBytes <= 4) {
- if (map->len == size) {
- size *= 2;
- map->ranges = (UnicodeMapRange *)
- grealloc(map->ranges, size * sizeof(UnicodeMapRange));
- }
- range = &map->ranges[map->len];
- sscanf(tok1, "%x", &range->start);
- sscanf(tok2, "%x", &range->end);
- sscanf(tok3, "%x", &range->code);
- range->nBytes = nBytes;
- ++map->len;
- } else if (tok2 == tok1) {
- if (map->eMapsLen == eMapsSize) {
- eMapsSize += 16;
- map->eMaps = (UnicodeMapExt *)
- grealloc(map->eMaps, eMapsSize * sizeof(UnicodeMapExt));
- }
- eMap = &map->eMaps[map->eMapsLen];
- sscanf(tok1, "%x", &eMap->u);
- for (i = 0; i < nBytes; ++i) {
- sscanf(tok3 + i*2, "%2x", &x);
- eMap->code[i] = (char)x;
- }
- eMap->nBytes = nBytes;
- ++map->eMapsLen;
- } else {
- error(-1, "Bad line (%d) in unicodeMap file for the '%s' encoding",
- line, encodingNameA->getCString());
- }
- } else {
- error(-1, "Bad line (%d) in unicodeMap file for the '%s' encoding",
- line, encodingNameA->getCString());
- }
- ++line;
- }
-
- fclose(f);
-
- return map;
-}
-
-UnicodeMap::UnicodeMap(GString *encodingNameA) {
- encodingName = encodingNameA;
- unicodeOut = gFalse;
- kind = unicodeMapUser;
- ranges = NULL;
- len = 0;
- eMaps = NULL;
- eMapsLen = 0;
- refCnt = 1;
-}
-
-UnicodeMap::UnicodeMap(const char *encodingNameA, GBool unicodeOutA,
- UnicodeMapRange *rangesA, int lenA) {
- encodingName = new GString(encodingNameA);
- unicodeOut = unicodeOutA;
- kind = unicodeMapResident;
- ranges = rangesA;
- len = lenA;
- eMaps = NULL;
- eMapsLen = 0;
- refCnt = 1;
-}
-
-UnicodeMap::UnicodeMap(const char *encodingNameA, GBool unicodeOutA,
- UnicodeMapFunc funcA) {
- encodingName = new GString(encodingNameA);
- unicodeOut = unicodeOutA;
- kind = unicodeMapFunc;
- func = funcA;
- eMaps = NULL;
- eMapsLen = 0;
- refCnt = 1;
-}
-
-UnicodeMap::~UnicodeMap() {
- delete encodingName;
- if (kind == unicodeMapUser && ranges) {
- gfree(ranges);
- }
- if (eMaps) {
- gfree(eMaps);
- }
-}
-
-void UnicodeMap::incRefCnt() {
- ++refCnt;
-}
-
-void UnicodeMap::decRefCnt() {
- if (--refCnt == 0) {
- delete this;
- }
-}
-
-GBool UnicodeMap::match(GString *encodingNameA) {
- return !encodingName->cmp(encodingNameA);
-}
-
-int UnicodeMap::mapUnicode(Unicode u, char *buf, int bufSize) {
- int a, b, m, n, i, j;
- Guint code;
-
- if (kind == unicodeMapFunc) {
- return (*func)(u, buf, bufSize);
- }
-
- a = 0;
- b = len;
- if (u < ranges[a].start) {
- return 0;
- }
- // invariant: ranges[a].start <= u < ranges[b].start
- while (b - a > 1) {
- m = (a + b) / 2;
- if (u >= ranges[m].start) {
- a = m;
- } else if (u < ranges[m].start) {
- b = m;
- }
- }
- if (u <= ranges[a].end) {
- n = ranges[a].nBytes;
- if (n > bufSize) {
- return 0;
- }
- code = ranges[a].code + (u - ranges[a].start);
- for (i = n - 1; i >= 0; --i) {
- buf[i] = (char)(code & 0xff);
- code >>= 8;
- }
- return n;
- }
-
- for (i = 0; i < eMapsLen; ++i) {
- if (eMaps[i].u == u) {
- n = eMaps[i].nBytes;
- for (j = 0; j < n; ++j) {
- buf[j] = eMaps[i].code[j];
- }
- return n;
- }
- }
-
- return 0;
-}
-
-//------------------------------------------------------------------------
-
-UnicodeMapCache::UnicodeMapCache() {
- int i;
-
- for (i = 0; i < unicodeMapCacheSize; ++i) {
- cache[i] = NULL;
- }
-}
-
-UnicodeMapCache::~UnicodeMapCache() {
- int i;
-
- for (i = 0; i < unicodeMapCacheSize; ++i) {
- if (cache[i]) {
- cache[i]->decRefCnt();
- }
- }
-}
-
-UnicodeMap *UnicodeMapCache::getUnicodeMap(GString *encodingName) {
- UnicodeMap *map;
- int i, j;
-
- if (cache[0] && cache[0]->match(encodingName)) {
- cache[0]->incRefCnt();
- return cache[0];
- }
- for (i = 1; i < unicodeMapCacheSize; ++i) {
- if (cache[i] && cache[i]->match(encodingName)) {
- map = cache[i];
- for (j = i; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = map;
- map->incRefCnt();
- return map;
- }
- }
- if ((map = UnicodeMap::parse(encodingName))) {
- if (cache[unicodeMapCacheSize - 1]) {
- cache[unicodeMapCacheSize - 1]->decRefCnt();
- }
- for (j = unicodeMapCacheSize - 1; j >= 1; --j) {
- cache[j] = cache[j - 1];
- }
- cache[0] = map;
- map->incRefCnt();
- return map;
- }
- return NULL;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cpp b/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cpp
new file mode 100644
index 000000000..dce0cae7a
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/UnicodeMap.cpp
@@ -0,0 +1,268 @@
+//========================================================================
+//
+// UnicodeMap.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "gmem.h"
+#include "gfile.h"
+#include "GString.h"
+#include "GList.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "UnicodeMap.h"
+
+//------------------------------------------------------------------------
+
+#define maxExtCode 16
+
+struct UnicodeMapExt {
+ Unicode u; // Unicode char
+ char code[maxExtCode];
+ Guint nBytes;
+};
+
+//------------------------------------------------------------------------
+
+UnicodeMap *UnicodeMap::parse(GString *encodingNameA) {
+ FILE *f;
+ UnicodeMap *map;
+ UnicodeMapRange *range;
+ UnicodeMapExt *eMap;
+ int size, eMapsSize;
+ char buf[256];
+ unsigned int x;
+ int line, nBytes, i;
+ char *tok1, *tok2, *tok3;
+
+ if (!(f = globalParams->getUnicodeMapFile(encodingNameA))) {
+ error(-1, "Couldn't find unicodeMap file for the '%s' encoding",
+ encodingNameA->getCString());
+ return NULL;
+ }
+
+ map = new UnicodeMap(encodingNameA->copy());
+
+ size = 8;
+ map->ranges = (UnicodeMapRange *)gmalloc(size * sizeof(UnicodeMapRange));
+ eMapsSize = 0;
+
+ line = 1;
+ while (getLine(buf, sizeof(buf), f)) {
+ if ((tok1 = strtok(buf, " \t\r\n")) &&
+ (tok2 = strtok(NULL, " \t\r\n"))) {
+ if (!(tok3 = strtok(NULL, " \t\r\n"))) {
+ tok3 = tok2;
+ tok2 = tok1;
+ }
+ nBytes = strlen(tok3) / 2;
+ if (nBytes <= 4) {
+ if (map->len == size) {
+ size *= 2;
+ map->ranges = (UnicodeMapRange *)
+ grealloc(map->ranges, size * sizeof(UnicodeMapRange));
+ }
+ range = &map->ranges[map->len];
+ sscanf(tok1, "%x", &range->start);
+ sscanf(tok2, "%x", &range->end);
+ sscanf(tok3, "%x", &range->code);
+ range->nBytes = nBytes;
+ ++map->len;
+ } else if (tok2 == tok1) {
+ if (map->eMapsLen == eMapsSize) {
+ eMapsSize += 16;
+ map->eMaps = (UnicodeMapExt *)
+ grealloc(map->eMaps, eMapsSize * sizeof(UnicodeMapExt));
+ }
+ eMap = &map->eMaps[map->eMapsLen];
+ sscanf(tok1, "%x", &eMap->u);
+ for (i = 0; i < nBytes; ++i) {
+ sscanf(tok3 + i*2, "%2x", &x);
+ eMap->code[i] = (char)x;
+ }
+ eMap->nBytes = nBytes;
+ ++map->eMapsLen;
+ } else {
+ error(-1, "Bad line (%d) in unicodeMap file for the '%s' encoding",
+ line, encodingNameA->getCString());
+ }
+ } else {
+ error(-1, "Bad line (%d) in unicodeMap file for the '%s' encoding",
+ line, encodingNameA->getCString());
+ }
+ ++line;
+ }
+
+ fclose(f);
+
+ return map;
+}
+
+UnicodeMap::UnicodeMap(GString *encodingNameA) {
+ encodingName = encodingNameA;
+ unicodeOut = gFalse;
+ kind = unicodeMapUser;
+ ranges = NULL;
+ len = 0;
+ eMaps = NULL;
+ eMapsLen = 0;
+ refCnt = 1;
+}
+
+UnicodeMap::UnicodeMap(const char *encodingNameA, GBool unicodeOutA,
+ UnicodeMapRange *rangesA, int lenA) {
+ encodingName = new GString(encodingNameA);
+ unicodeOut = unicodeOutA;
+ kind = unicodeMapResident;
+ ranges = rangesA;
+ len = lenA;
+ eMaps = NULL;
+ eMapsLen = 0;
+ refCnt = 1;
+}
+
+UnicodeMap::UnicodeMap(const char *encodingNameA, GBool unicodeOutA,
+ UnicodeMapFunc funcA) {
+ encodingName = new GString(encodingNameA);
+ unicodeOut = unicodeOutA;
+ kind = unicodeMapFunc;
+ func = funcA;
+ eMaps = NULL;
+ eMapsLen = 0;
+ refCnt = 1;
+}
+
+UnicodeMap::~UnicodeMap() {
+ delete encodingName;
+ if (kind == unicodeMapUser && ranges) {
+ gfree(ranges);
+ }
+ if (eMaps) {
+ gfree(eMaps);
+ }
+}
+
+void UnicodeMap::incRefCnt() {
+ ++refCnt;
+}
+
+void UnicodeMap::decRefCnt() {
+ if (--refCnt == 0) {
+ delete this;
+ }
+}
+
+GBool UnicodeMap::match(GString *encodingNameA) {
+ return !encodingName->cmp(encodingNameA);
+}
+
+int UnicodeMap::mapUnicode(Unicode u, char *buf, int bufSize) {
+ int a, b, m, n, i, j;
+ Guint code;
+
+ if (kind == unicodeMapFunc) {
+ return (*func)(u, buf, bufSize);
+ }
+
+ a = 0;
+ b = len;
+ if (u < ranges[a].start) {
+ return 0;
+ }
+ // invariant: ranges[a].start <= u < ranges[b].start
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ if (u >= ranges[m].start) {
+ a = m;
+ } else if (u < ranges[m].start) {
+ b = m;
+ }
+ }
+ if (u <= ranges[a].end) {
+ n = ranges[a].nBytes;
+ if (n > bufSize) {
+ return 0;
+ }
+ code = ranges[a].code + (u - ranges[a].start);
+ for (i = n - 1; i >= 0; --i) {
+ buf[i] = (char)(code & 0xff);
+ code >>= 8;
+ }
+ return n;
+ }
+
+ for (i = 0; i < eMapsLen; ++i) {
+ if (eMaps[i].u == u) {
+ n = eMaps[i].nBytes;
+ for (j = 0; j < n; ++j) {
+ buf[j] = eMaps[i].code[j];
+ }
+ return n;
+ }
+ }
+
+ return 0;
+}
+
+//------------------------------------------------------------------------
+
+UnicodeMapCache::UnicodeMapCache() {
+ int i;
+
+ for (i = 0; i < unicodeMapCacheSize; ++i) {
+ cache[i] = NULL;
+ }
+}
+
+UnicodeMapCache::~UnicodeMapCache() {
+ int i;
+
+ for (i = 0; i < unicodeMapCacheSize; ++i) {
+ if (cache[i]) {
+ cache[i]->decRefCnt();
+ }
+ }
+}
+
+UnicodeMap *UnicodeMapCache::getUnicodeMap(GString *encodingName) {
+ UnicodeMap *map;
+ int i, j;
+
+ if (cache[0] && cache[0]->match(encodingName)) {
+ cache[0]->incRefCnt();
+ return cache[0];
+ }
+ for (i = 1; i < unicodeMapCacheSize; ++i) {
+ if (cache[i] && cache[i]->match(encodingName)) {
+ map = cache[i];
+ for (j = i; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = map;
+ map->incRefCnt();
+ return map;
+ }
+ }
+ if ((map = UnicodeMap::parse(encodingName))) {
+ if (cache[unicodeMapCacheSize - 1]) {
+ cache[unicodeMapCacheSize - 1]->decRefCnt();
+ }
+ for (j = unicodeMapCacheSize - 1; j >= 1; --j) {
+ cache[j] = cache[j - 1];
+ }
+ cache[0] = map;
+ map->incRefCnt();
+ return map;
+ }
+ return NULL;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/XOutputDev.cc
deleted file mode 100644
index 3c58f5650..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XOutputDev.cc
+++ /dev/null
@@ -1,3690 +0,0 @@
-//========================================================================
-//
-// XOutputDev.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <unistd.h>
-#include <string.h>
-#include <ctype.h>
-#include <math.h>
-#include "gmem.h"
-#include "gfile.h"
-#include "GString.h"
-#include "GList.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Link.h"
-#include "GfxState.h"
-#include "GfxFont.h"
-#include "UnicodeMap.h"
-#include "CharCodeToUnicode.h"
-#include "FontFile.h"
-#include "Error.h"
-#include "TextOutputDev.h"
-#include "XOutputDev.h"
-#if HAVE_T1LIB_H
-#include "T1Font.h"
-#endif
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-#include "FTFont.h"
-#endif
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-#include "TTFont.h"
-#endif
-
-#ifdef VMS
-#if (__VMS_VER < 70000000)
-extern "C" int unlink(char *filename);
-#endif
-#endif
-
-#ifdef XlibSpecificationRelease
-#if XlibSpecificationRelease < 5
-typedef char *XPointer;
-#endif
-#else
-typedef char *XPointer;
-#endif
-
-//------------------------------------------------------------------------
-// Constants and macros
-//------------------------------------------------------------------------
-
-#define xoutRound(x) ((int)(x + 0.5))
-
-#define maxCurveSplits 6 // max number of splits when recursively
- // drawing Bezier curves
-
-//------------------------------------------------------------------------
-// Font substitutions
-//------------------------------------------------------------------------
-
-struct XOutFontSubst {
- char *name;
- double mWidth;
-};
-
-// index: {symbolic:12, fixed:8, serif:4, sans-serif:0} + bold*2 + italic
-static XOutFontSubst xOutSubstFonts[16] = {
- {"Helvetica", 0.833},
- {"Helvetica-Oblique", 0.833},
- {"Helvetica-Bold", 0.889},
- {"Helvetica-BoldOblique", 0.889},
- {"Times-Roman", 0.788},
- {"Times-Italic", 0.722},
- {"Times-Bold", 0.833},
- {"Times-BoldItalic", 0.778},
- {"Courier", 0.600},
- {"Courier-Oblique", 0.600},
- {"Courier-Bold", 0.600},
- {"Courier-BoldOblique", 0.600},
- {"Symbol", 0.576},
- {"Symbol", 0.576},
- {"Symbol", 0.576},
- {"Symbol", 0.576}
-};
-
-//------------------------------------------------------------------------
-
-static void outputToFile(void *stream, char *data, int len) {
- fwrite(data, 1, len, (FILE *)stream);
-}
-
-//------------------------------------------------------------------------
-// XOutputFont
-//------------------------------------------------------------------------
-
-XOutputFont::XOutputFont(Ref *idA, double m11OrigA, double m12OrigA,
- double m21OrigA, double m22OrigA,
- double m11A, double m12A, double m21A, double m22A,
- Display *displayA, XOutputDev *xOutA) {
- id = *idA;
- display = displayA;
- xOut = xOutA;
- m11Orig = m11OrigA;
- m12Orig = m12OrigA;
- m21Orig = m21OrigA;
- m22Orig = m22OrigA;
- m11 = m11A;
- m12 = m12A;
- m21 = m21A;
- m22 = m22A;
-}
-
-XOutputFont::~XOutputFont() {
-}
-
-void XOutputFont::getCharPath(GfxState *state,
- CharCode c, Unicode *u, int ulen) {
-}
-
-#if HAVE_T1LIB_H
-//------------------------------------------------------------------------
-// XOutputT1Font
-//------------------------------------------------------------------------
-
-XOutputT1Font::XOutputT1Font(Ref *idA, T1FontFile *fontFileA,
- double m11OrigA, double m12OrigA,
- double m21OrigA, double m22OrigA,
- double m11A, double m12A,
- double m21A, double m22A,
- Display *displayA, XOutputDev *xOutA):
- XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
- m11A, m12A, m21A, m22A, displayA, xOutA)
-{
- double matrix[4];
-
- fontFile = fontFileA;
-
- // create the transformed instance
- matrix[0] = m11;
- matrix[1] = -m12;
- matrix[2] = m21;
- matrix[3] = -m22;
- font = new T1Font(fontFile, matrix);
-}
-
-XOutputT1Font::~XOutputT1Font() {
- if (font) {
- delete font;
- }
-}
-
-GBool XOutputT1Font::isOk() {
- return font != NULL;
-}
-
-void XOutputT1Font::updateGC(GC gc) {
-}
-
-void XOutputT1Font::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
- GC gc, GfxRGB *rgb,
- double x, double y, double dx, double dy,
- CharCode c, Unicode *u, int uLen) {
- font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
- (int)(rgb->r * 65535), (int)(rgb->g * 65535),
- (int)(rgb->b * 65535), c, u[0]);
-}
-
-void XOutputT1Font::getCharPath(GfxState *state,
- CharCode c, Unicode *u, int uLen) {
- font->getCharPath(c, u[0], state);
-}
-#endif // HAVE_T1LIB_H
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-//------------------------------------------------------------------------
-// XOutputFTFont
-//------------------------------------------------------------------------
-
-XOutputFTFont::XOutputFTFont(Ref *idA, FTFontFile *fontFileA,
- double m11OrigA, double m12OrigA,
- double m21OrigA, double m22OrigA,
- double m11A, double m12A,
- double m21A, double m22A,
- Display *displayA, XOutputDev *xOutA):
- XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
- m11A, m12A, m21A, m22A, displayA, xOutA)
-{
- double matrix[4];
-
- fontFile = fontFileA;
-
- // create the transformed instance
- matrix[0] = m11;
- matrix[1] = -m12;
- matrix[2] = m21;
- matrix[3] = -m22;
- font = new FTFont(fontFile, matrix);
-}
-
-XOutputFTFont::~XOutputFTFont() {
- if (font) {
- delete font;
- }
-}
-
-GBool XOutputFTFont::isOk() {
- return font != NULL;
-}
-
-void XOutputFTFont::updateGC(GC gc) {
-}
-
-void XOutputFTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
- GC gc, GfxRGB *rgb,
- double x, double y, double dx, double dy,
- CharCode c, Unicode *u, int uLen) {
- font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
- (int)(rgb->r * 65535), (int)(rgb->g * 65535),
- (int)(rgb->b * 65535), c, uLen > 0 ? u[0] : 0);
-}
-
-void XOutputFTFont::getCharPath(GfxState *state,
- CharCode c, Unicode *u, int uLen) {
- font->getCharPath(c, u[0], state);
-}
-#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-//------------------------------------------------------------------------
-// XOutputTTFont
-//------------------------------------------------------------------------
-
-XOutputTTFont::XOutputTTFont(Ref *idA, TTFontFile *fontFileA,
- double m11OrigA, double m12OrigA,
- double m21OrigA, double m22OrigA,
- double m11A, double m12A,
- double m21A, double m22A,
- Display *displayA, XOutputDev *xOutA):
- XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
- m11A, m12A, m21A, m22A, displayA, xOutA)
-{
- double matrix[4];
-
- fontFile = fontFileA;
-
- // create the transformed instance
- matrix[0] = m11;
- matrix[1] = -m12;
- matrix[2] = m21;
- matrix[3] = -m22;
- font = new TTFont(fontFile, matrix);
-}
-
-XOutputTTFont::~XOutputTTFont() {
- if (font) {
- delete font;
- }
-}
-
-GBool XOutputTTFont::isOk() {
- return font != NULL;
-}
-
-void XOutputTTFont::updateGC(GC gc) {
-}
-
-void XOutputTTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
- GC gc, GfxRGB *rgb,
- double x, double y, double dx, double dy,
- CharCode c, Unicode *u, int uLen) {
- font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
- (int)(rgb->r * 65535), (int)(rgb->g * 65535),
- (int)(rgb->b * 65535), c, u[0]);
-}
-#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-//------------------------------------------------------------------------
-// XOutputServer8BitFont
-//------------------------------------------------------------------------
-
-// Copy <fmt>, substituting <val> for one occurrence of "%s", into
-// <buf>.
-static void stringSubst(char *buf, int bufSize, char *fmt, char *val) {
- char *p, *q;
- int i;
-
- i = 0;
- p = fmt;
- while (*p) {
- if (p[0] == '%' && p[1] == 's') {
- q = val;
- while (*q && i < bufSize - 1) {
- buf[i++] = *q++;
- }
- p += 2;
- } else {
- if (i < bufSize - 1) {
- buf[i++] = *p;
- }
- ++p;
- }
- }
- buf[i] = '\0';
-}
-
-XOutputServer8BitFont::XOutputServer8BitFont(Ref *idA, GString *xlfdFmt,
- UnicodeMap *xUMapA,
- CharCodeToUnicode *fontUMap,
- double m11OrigA, double m12OrigA,
- double m21OrigA, double m22OrigA,
- double m11A, double m12A,
- double m21A, double m22A,
- Display *displayA,
- XOutputDev *xOutA):
- XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
- m11A, m12A, m21A, m22A, displayA, xOutA)
-{
- double size, ntm11, ntm12, ntm21, ntm22;
- GBool rotated;
- int startSize, sz;
- char fontName[500], fontSize[100];
- Unicode u;
- char buf;
- int i;
-
- // compute size and normalized transform matrix
- size = sqrt(m21*m21 + m22*m22);
- ntm11 = m11 / size;
- ntm12 = -m12 / size;
- ntm21 = m21 / size;
- ntm22 = -m22 / size;
-
- // try to get a rotated font?
- rotated = !(ntm11 > 0 && ntm22 > 0 &&
- fabs(ntm11 / ntm22 - 1) < 0.2 &&
- fabs(ntm12) < 0.01 &&
- fabs(ntm21) < 0.01);
-
- // open X font -- if font is not found (which means the server can't
- // scale fonts), try progressively smaller and then larger sizes
- startSize = (int)size;
- if (rotated) {
- sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
- ntm11<0 ? "~" : "", fabs(ntm11 * size),
- ntm12<0 ? "~" : "", fabs(ntm12 * size),
- ntm21<0 ? "~" : "", fabs(ntm21 * size),
- ntm22<0 ? "~" : "", fabs(ntm22 * size));
- } else {
- sprintf(fontSize, "%d", startSize);
- }
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
- xFont = XLoadQueryFont(display, fontName);
- if (!xFont) {
- for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
- sprintf(fontSize, "%d", sz);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
- if ((xFont = XLoadQueryFont(display, fontName)))
- break;
- }
- if (!xFont) {
- for (sz = startSize + 1; sz < startSize + 10; ++sz) {
- sprintf(fontSize, "%d", sz);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
- fontSize);
- if ((xFont = XLoadQueryFont(display, fontName))) {
- break;
- }
- }
- if (!xFont) {
- sprintf(fontSize, "%d", startSize);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
- fontSize);
- error(-1, "Failed to open font: '%s'", fontName);
- return;
- }
- }
- }
-
- // Construct char code map.
- xUMap = xUMapA;
- for (i = 0; i < 256; ++i) {
- if (fontUMap->mapToUnicode((CID)i, &u, 1) == 1 &&
- xUMap->mapUnicode(u, &buf, 1) == 1) {
- map[i] = buf & 0xff;
- } else {
- map[i] = 0;
- }
- }
-}
-
-XOutputServer8BitFont::~XOutputServer8BitFont() {
- if (xFont) {
- XFreeFont(display, xFont);
- }
-}
-
-GBool XOutputServer8BitFont::isOk() {
- return xFont != NULL;
-}
-
-void XOutputServer8BitFont::updateGC(GC gc) {
- XSetFont(display, gc, xFont->fid);
-}
-
-void XOutputServer8BitFont::drawChar(GfxState *state, Pixmap pixmap,
- int w, int h, GC gc, GfxRGB *rgb,
- double x, double y, double dx, double dy,
- CharCode c, Unicode *u, int uLen) {
- Gushort c1;
- char buf[8];
- double dx1, dy1;
- int m, n, i, j, k;
-
- c1 = map[c];
- if (c1 > 0) {
- buf[0] = (char)c1;
- XDrawString(display, pixmap, gc, xoutRound(x), xoutRound(y), buf, 1);
- } else {
- // substituted character, using more than one character
- n = 0;
- for (i = 0; i < uLen; ++i) {
- n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
- }
- if (n > 0) {
- dx1 = dx / n;
- dy1 = dy / n;
- k = 0;
- for (i = 0; i < uLen; ++i) {
- m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
- for (j = 0; j < m; ++j) {
- XDrawString(display, pixmap, gc,
- xoutRound(x + k*dx1), xoutRound(y + k*dy1),
- buf + j, 1);
- ++k;
- }
- }
- }
- }
-}
-
-//------------------------------------------------------------------------
-// XOutputServer16BitFont
-//------------------------------------------------------------------------
-
-XOutputServer16BitFont::XOutputServer16BitFont(Ref *idA, GString *xlfdFmt,
- UnicodeMap *xUMapA,
- CharCodeToUnicode *fontUMap,
- double m11OrigA,
- double m12OrigA,
- double m21OrigA,
- double m22OrigA,
- double m11A, double m12A,
- double m21A, double m22A,
- Display *displayA,
- XOutputDev *xOutA):
- XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
- m11A, m12A, m21A, m22A, displayA, xOutA)
-{
- double size, ntm11, ntm12, ntm21, ntm22;
- GBool rotated;
- int startSize, sz;
- char fontName[500], fontSize[100];
-
- xUMap = xUMapA;
- xUMap->incRefCnt();
-
- // compute size and normalized transform matrix
- size = sqrt(m21*m21 + m22*m22);
- ntm11 = m11 / size;
- ntm12 = -m12 / size;
- ntm21 = m21 / size;
- ntm22 = -m22 / size;
-
- // try to get a rotated font?
- rotated = !(ntm11 > 0 && ntm22 > 0 &&
- fabs(ntm11 / ntm22 - 1) < 0.2 &&
- fabs(ntm12) < 0.01 &&
- fabs(ntm21) < 0.01);
-
- // open X font -- if font is not found (which means the server can't
- // scale fonts), try progressively smaller and then larger sizes
- startSize = (int)size;
- if (rotated) {
- sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
- ntm11<0 ? "~" : "", fabs(ntm11 * size),
- ntm12<0 ? "~" : "", fabs(ntm12 * size),
- ntm21<0 ? "~" : "", fabs(ntm21 * size),
- ntm22<0 ? "~" : "", fabs(ntm22 * size));
- } else {
- sprintf(fontSize, "%d", startSize);
- }
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
- xFont = XLoadQueryFont(display, fontName);
- if (!xFont) {
- for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
- sprintf(fontSize, "%d", sz);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
- if ((xFont = XLoadQueryFont(display, fontName)))
- break;
- }
- if (!xFont) {
- for (sz = startSize + 1; sz < startSize + 10; ++sz) {
- sprintf(fontSize, "%d", sz);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
- fontSize);
- if ((xFont = XLoadQueryFont(display, fontName))) {
- break;
- }
- }
- if (!xFont) {
- sprintf(fontSize, "%d", startSize);
- stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
- fontSize);
- error(-1, "Failed to open font: '%s'", fontName);
- return;
- }
- }
- }
-}
-
-XOutputServer16BitFont::~XOutputServer16BitFont() {
- xUMap->decRefCnt();
- if (xFont) {
- XFreeFont(display, xFont);
- }
-}
-
-GBool XOutputServer16BitFont::isOk() {
- return xFont != NULL;
-}
-
-void XOutputServer16BitFont::updateGC(GC gc) {
- XSetFont(display, gc, xFont->fid);
-}
-
-void XOutputServer16BitFont::drawChar(GfxState *state, Pixmap pixmap,
- int w, int h, GC gc, GfxRGB *rgb,
- double x, double y, double dx, double dy,
- CharCode c, Unicode *u, int uLen) {
- char buf[16];
- XChar2b c1;
- double dx1, dy1;
- int m, n, i, j, k;
-
- n = 0;
- for (i = 0; i < uLen; ++i) {
- n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
- }
- if (n > 0) {
- dx1 = dx / n;
- dy1 = dy / n;
- k = 0;
- for (i = 0; i < uLen; ++i) {
- m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
- for (j = 0; j+1 < m; j += 2) {
- c1.byte1 = buf[j];
- c1.byte2 = buf[j+1];
- XDrawString16(display, pixmap, gc,
- xoutRound(x + k*dx1), xoutRound(y + k*dy1),
- &c1, 1);
- ++k;
- }
- }
- } else if (c != 0) {
- // some PDF files use CID 0, which is .notdef, so just ignore it
- error(-1, "Unknown character (CID=%d Unicode=%04x)",
- c, uLen > 0 ? u[0] : (Unicode)0);
- }
-}
-
-//------------------------------------------------------------------------
-// XOutputFontCache
-//------------------------------------------------------------------------
-
-#if HAVE_T1LIB_H
-XOutputT1FontFile::~XOutputT1FontFile() {
- delete fontFile;
- if (tmpFileName) {
- unlink(tmpFileName->getCString());
- delete tmpFileName;
- }
-}
-#endif
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-XOutputFTFontFile::~XOutputFTFontFile() {
- delete fontFile;
- if (tmpFileName) {
- unlink(tmpFileName->getCString());
- delete tmpFileName;
- }
-}
-#endif
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-XOutputTTFontFile::~XOutputTTFontFile() {
- delete fontFile;
- if (tmpFileName) {
- unlink(tmpFileName->getCString());
- delete tmpFileName;
- }
-}
-#endif
-
-XOutputFontCache::XOutputFontCache(Display *displayA, Guint depthA,
- XOutputDev *xOutA,
- FontRastControl t1libControlA,
- FontRastControl freetypeControlA) {
- display = displayA;
- depth = depthA;
- xOut = xOutA;
-
-#if HAVE_T1LIB_H
- t1Engine = NULL;
- t1libControl = t1libControlA;
-#endif
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- ftEngine = NULL;
-#endif
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- ttEngine = NULL;
-#endif
-#if HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H
- freetypeControl = freetypeControlA;
-#endif
-
- clear();
-}
-
-XOutputFontCache::~XOutputFontCache() {
- delFonts();
-}
-
-void XOutputFontCache::startDoc(int screenNum, Visual *visual,
- Colormap colormap, GBool trueColor,
- int rMul, int gMul, int bMul,
- int rShift, int gShift, int bShift,
- Gulong *colors, int numColors) {
- delFonts();
- clear();
-
-#if HAVE_T1LIB_H
- if (t1libControl != fontRastNone) {
- t1Engine = new T1FontEngine(display, visual, depth, colormap,
- t1libControl == fontRastAALow ||
- t1libControl == fontRastAAHigh,
- t1libControl == fontRastAAHigh);
- if (t1Engine->isOk()) {
- if (trueColor) {
- t1Engine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
- } else {
- t1Engine->useColorCube(colors, numColors);
- }
- } else {
- delete t1Engine;
- t1Engine = NULL;
- }
- }
-#endif // HAVE_T1LIB_H
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- ftEngine = new FTFontEngine(display, visual, depth, colormap,
- freetypeControl == fontRastAALow ||
- freetypeControl == fontRastAAHigh);
- if (ftEngine->isOk()) {
- if (trueColor) {
- ftEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
- } else {
- ftEngine->useColorCube(colors, numColors);
- }
- } else {
- delete ftEngine;
- ftEngine = NULL;
- }
- }
-#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- ttEngine = new TTFontEngine(display, visual, depth, colormap,
- freetypeControl == fontRastAALow ||
- freetypeControl == fontRastAAHigh);
- if (ttEngine->isOk()) {
- if (trueColor) {
- ttEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
- } else {
- ttEngine->useColorCube(colors, numColors);
- }
- } else {
- delete ttEngine;
- ttEngine = NULL;
- }
- }
-#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-}
-
-void XOutputFontCache::delFonts() {
- int i;
-
- for (i = 0; i < nFonts; ++i) {
- delete fonts[i];
- }
-
-#if HAVE_T1LIB_H
- // delete Type 1 font files
- deleteGList(t1FontFiles, XOutputT1FontFile);
- if (t1Engine) {
- delete t1Engine;
- }
-#endif
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- // delete FreeType font files
- deleteGList(ftFontFiles, XOutputFTFontFile);
- if (ftEngine) {
- delete ftEngine;
- }
-#endif
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- // delete TrueType fonts
- deleteGList(ttFontFiles, XOutputTTFontFile);
- if (ttEngine) {
- delete ttEngine;
- }
-#endif
-}
-
-void XOutputFontCache::clear() {
- int i;
-
- for (i = 0; i < xOutFontCacheSize; ++i) {
- fonts[i] = NULL;
- }
- nFonts = 0;
-
-#if HAVE_T1LIB_H
- // clear Type 1 font files
- t1FontFiles = new GList();
-#endif
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- // clear FreeType font cache
- ftFontFiles = new GList();
-#endif
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- // clear TrueType font cache
- ttFontFiles = new GList();
-#endif
-}
-
-XOutputFont *XOutputFontCache::getFont(XRef *xref, GfxFont *gfxFont,
- double m11, double m12,
- double m21, double m22) {
- XOutputFont *font;
- DisplayFontParam *dfp;
- GString *substName;
- double m11New, m12New, m21New, m22New;
- double w1, w2, v;
- double *fm;
- char *name;
- int index;
- int code;
- int i, j;
-
- // is it the most recently used font?
- if (nFonts > 0 && fonts[0]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
- return fonts[0];
- }
-
- // is it in the cache?
- for (i = 1; i < nFonts; ++i) {
- if (fonts[i]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
- font = fonts[i];
- for (j = i; j > 0; --j) {
- fonts[j] = fonts[j-1];
- }
- fonts[0] = font;
- return font;
- }
- }
-
- // try for a cached FontFile, an embedded font, or an external font
- // file
- font = NULL;
- switch (gfxFont->getType()) {
- case fontType1:
- case fontType1C:
-#if HAVE_T1LIB_H
- if (t1libControl != fontRastNone) {
- font = tryGetT1Font(xref, gfxFont, m11, m12, m21, m22);
- }
-#endif
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (!font) {
- if (freetypeControl != fontRastNone) {
- font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
- }
- }
-#endif
- break;
- case fontTrueType:
- case fontCIDType2:
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
- }
-#endif
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- font = tryGetTTFont(xref, gfxFont, m11, m12, m21, m22);
- }
-#endif
- break;
- case fontCIDType0C:
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
- }
-#endif
- break;
- default:
- break;
- }
-
- if (!font) {
-
- // search for a display font mapping
- dfp = NULL;
- if (gfxFont->isCIDFont()) {
- if (((GfxCIDFont *)gfxFont)->getCollection()) {
- dfp = globalParams->
- getDisplayCIDFont(gfxFont->getName(),
- ((GfxCIDFont *)gfxFont)->getCollection());
- } else {
- // this error (no CMap file) was already reported by GfxFont
- return NULL;
- }
- } else {
- if (gfxFont->getName()) {
- dfp = globalParams->getDisplayFont(gfxFont->getName());
- }
- }
- if (dfp) {
- font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
- }
-
- // substitute a font (8-bit fonts only)
- if (!font && !gfxFont->isCIDFont()) {
-
- // choose a substitute font
- if (gfxFont->isFixedWidth()) {
- index = 8;
- } else if (gfxFont->isSerif()) {
- index = 4;
- } else {
- index = 0;
- }
- if (gfxFont->isBold()) {
- index += 2;
- }
- if (gfxFont->isItalic()) {
- index += 1;
- }
- substName = new GString(xOutSubstFonts[index].name);
-
- // adjust the font matrix -- compare the width of 'm' in the
- // original font and the substituted font
- m11New = m11;
- m12New = m12;
- m21New = m21;
- m22New = m22;
- for (code = 0; code < 256; ++code) {
- if ((name = ((Gfx8BitFont *)gfxFont)->getCharName(code)) &&
- name[0] == 'm' && name[1] == '\0') {
- break;
- }
- }
- if (code < 256) {
- w1 = ((Gfx8BitFont *)gfxFont)->getWidth(code);
- w2 = xOutSubstFonts[index].mWidth;
- if (gfxFont->getType() == fontType3) {
- // This is a hack which makes it possible to substitute for some
- // Type 3 fonts. The problem is that it's impossible to know what
- // the base coordinate system used in the font is without actually
- // rendering the font. This code tries to guess by looking at the
- // width of the character 'm' (which breaks if the font is a
- // subset that doesn't contain 'm').
- if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
- w1 /= w2;
- m11New *= w1;
- m12New *= w1;
- m21New *= w1;
- m22New *= w1;
- }
- fm = gfxFont->getFontMatrix();
- v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
- m21New *= v;
- m22New *= v;
- } else if (!gfxFont->isSymbolic()) {
- // if real font is substantially narrower than substituted
- // font, reduce the font size accordingly
- if (w1 > 0.01 && w1 < 0.9 * w2) {
- w1 /= w2;
- m11New *= w1;
- m21New *= w1;
- }
- }
- }
-
- // get the font
- dfp = globalParams->getDisplayFont(substName);
- delete substName;
- if (!dfp) {
- // this should never happen since GlobalParams sets up default
- // mappings for the Base-14 fonts
- error(-1, "Couldn't find a font for '%s'",
- gfxFont->getName()->getCString());
- return NULL;
- }
- font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
- m11New, m12New, m21New, m22New, gTrue);
- }
- }
-
- // check for error
- if (!font) {
- // This will happen if the user specifies a bogus font in the
- // config file (a non-existent font file or a font that requires a
- // rasterizer that is disabled or wasn't built in), or if a CID
- // font has no associated font in the config file.
- if (gfxFont->isCIDFont()) {
- error(-1, "Couldn't find a font for the '%s' character collection",
- ((GfxCIDFont *)gfxFont)->getCollection()->getCString());
- } else {
- error(-1, "Couldn't find a font for '%s'",
- gfxFont->getName() ?
- gfxFont->getName()->getCString() : "[unnamed]");
- }
- return NULL;
- }
-
- // insert font in cache
- if (nFonts == xOutFontCacheSize) {
- --nFonts;
- delete fonts[nFonts];
- }
- for (j = nFonts; j > 0; --j) {
- fonts[j] = fonts[j-1];
- }
- fonts[0] = font;
- ++nFonts;
-
- return font;
-}
-
-XOutputFont *XOutputFontCache::tryGetFont(XRef *xref, DisplayFontParam *dfp,
- GfxFont *gfxFont,
- double m11Orig, double m12Orig,
- double m21Orig, double m22Orig,
- double m11, double m12,
- double m21, double m22,
- GBool subst) {
- XOutputFont *font;
-
- font = NULL;
-
- // create the new font
- switch (dfp->kind) {
-
- case displayFontX:
- font = tryGetServerFont(dfp->x.xlfd, dfp->x.encoding, gfxFont,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22);
- break;
-
- case displayFontT1:
-#if HAVE_T1LIB_H
- if (t1libControl != fontRastNone) {
- font = tryGetT1FontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, subst);
- }
-#endif
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (!font) {
- if (freetypeControl != fontRastNone) {
- font = tryGetFTFontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, subst);
- }
- }
-#endif
-#if !((FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)) || defined(HAVE_T1LIB_H))
- error(-1, "Config file specifies a Type 1 font,");
- error(-1, "but xpdf was not built with t1lib or FreeType2 support");
-#endif
- break;
-
- case displayFontTT:
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- font = tryGetFTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, subst);
- }
-#endif
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- if (freetypeControl != fontRastNone) {
- font = tryGetTTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, subst);
- }
-#endif
-#if !(HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
- error(-1, "Config file specifies a TrueType font,");
- error(-1, "but xpdf was not built with FreeType support");
- dfp = NULL;
-#endif
- break;
- }
-
- return font;
-}
-
-#if HAVE_T1LIB_H
-XOutputFont *XOutputFontCache::tryGetT1Font(XRef *xref,
- GfxFont *gfxFont,
- double m11, double m12,
- double m21, double m22) {
- Ref *id;
- XOutputT1FontFile *xFontFile;
- XOutputFont *font;
- Ref embRef;
- GString *fileName;
- FILE *f;
- char *fontBuf;
- int fontLen;
- Type1CFontFile *ff;
- Object refObj, strObj;
- int c;
- int i;
-
- // check the already available font files
- id = gfxFont->getID();
- for (i = 0; i < t1FontFiles->getLength(); ++i) {
- xFontFile = (XOutputT1FontFile *)t1FontFiles->get(i);
- if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
- !xFontFile->subst) {
- font = new XOutputT1Font(id, xFontFile->fontFile,
- m11, m12, m21, m22,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
- }
- }
-
- // check for an embedded font
- if (gfxFont->getEmbeddedFontID(&embRef)) {
-
- // create the font file
- fileName = NULL;
- if (!openTempFile(&fileName, &f, "wb", NULL)) {
- error(-1, "Couldn't create temporary Type 1 font file");
- return NULL;
- }
- if (gfxFont->getType() == fontType1C) {
- if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
- fclose(f);
- return NULL;
- }
- ff = new Type1CFontFile(fontBuf, fontLen);
- ff->convertToType1(outputToFile, f);
- delete ff;
- gfree(fontBuf);
- } else { // fontType1
- refObj.initRef(embRef.num, embRef.gen);
- refObj.fetch(xref, &strObj);
- refObj.free();
- strObj.streamReset();
- while ((c = strObj.streamGetChar()) != EOF) {
- fputc(c, f);
- }
- strObj.streamClose();
- strObj.free();
- }
- fclose(f);
-
- // create the Font
- font = tryGetT1FontFromFile(xref, fileName, gTrue, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- // on systems with Unix hard link semantics, this will remove the
- // last link to the temp file
- unlink(fileName->getCString());
-
- delete fileName;
-
- // check for an external font file
- } else if ((fileName = gfxFont->getExtFontFile())) {
- font = tryGetT1FontFromFile(xref, fileName, gFalse, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- } else {
- font = NULL;
- }
-
- return font;
-}
-
-XOutputFont *XOutputFontCache::tryGetT1FontFromFile(XRef *xref,
- GString *fileName,
- GBool deleteFile,
- GfxFont *gfxFont,
- double m11Orig,
- double m12Orig,
- double m21Orig,
- double m22Orig,
- double m11, double m12,
- double m21, double m22,
- GBool subst) {
- Ref *id;
- T1FontFile *fontFile;
- XOutputFont *font;
-
- // create the t1lib font file
- fontFile = new T1FontFile(t1Engine, fileName->getCString(),
- ((Gfx8BitFont *)gfxFont)->getEncoding(),
- gfxFont->getFontBBox());
- if (!fontFile->isOk()) {
- error(-1, "Couldn't create t1lib font from '%s'",
- fileName->getCString());
- delete fontFile;
- if (deleteFile) {
- unlink(fileName->getCString());
- }
- return NULL;
- }
-
- // add to list
- id = gfxFont->getID();
- t1FontFiles->append(new XOutputT1FontFile(id->num, id->gen,
- subst, fontFile,
- deleteFile ? fileName->copy()
- : (GString *)NULL));
-
- // create the Font
- font = new XOutputT1Font(gfxFont->getID(), fontFile,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
-}
-#endif // HAVE_T1LIB_H
-
-#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-XOutputFont *XOutputFontCache::tryGetFTFont(XRef *xref,
- GfxFont *gfxFont,
- double m11, double m12,
- double m21, double m22) {
- Ref *id;
- XOutputFTFontFile *xFontFile;
- XOutputFont *font;
- Ref embRef;
- GString *fileName;
- FILE *f;
-#if 1 //~ need this until FT can handle fonts with missing tables
- char *fontBuf;
- int fontLen;
- TrueTypeFontFile *ff;
-#endif
- Object refObj, strObj;
- int c;
- int i;
-
- // check the already available font files
- id = gfxFont->getID();
- for (i = 0; i < ftFontFiles->getLength(); ++i) {
- xFontFile = (XOutputFTFontFile *)ftFontFiles->get(i);
- if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
- !xFontFile->subst) {
- font = new XOutputFTFont(id, xFontFile->fontFile,
- m11, m12, m21, m22,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
- }
- }
-
- // check for an embedded font
- if (gfxFont->getEmbeddedFontID(&embRef)) {
-
- // create the font file
- fileName = NULL;
- if (!openTempFile(&fileName, &f, "wb", NULL)) {
- error(-1, "Couldn't create temporary TrueType font file");
- return NULL;
- }
-#if 1 //~ need this until FT can handle fonts with missing tables
- if (gfxFont->getType() == fontTrueType ||
- gfxFont->getType() == fontCIDType2) {
- if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
- fclose(f);
- return NULL;
- }
- ff = new TrueTypeFontFile(fontBuf, fontLen);
- ff->writeTTF(f);
- delete ff;
- gfree(fontBuf);
- } else {
- refObj.initRef(embRef.num, embRef.gen);
- refObj.fetch(xref, &strObj);
- refObj.free();
- strObj.streamReset();
- while ((c = strObj.streamGetChar()) != EOF) {
- fputc(c, f);
- }
- strObj.streamClose();
- strObj.free();
- }
-#else
- refObj.initRef(embRef.num, embRef.gen);
- refObj.fetch(xref, &strObj);
- refObj.free();
- strObj.streamReset();
- while ((c = strObj.streamGetChar()) != EOF) {
- fputc(c, f);
- }
- strObj.streamClose();
- strObj.free();
-#endif
- fclose(f);
-
- // create the Font
- font = tryGetFTFontFromFile(xref, fileName, gTrue, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- // on systems with Unix hard link semantics, this will remove the
- // last link to the temp file
- unlink(fileName->getCString());
-
- delete fileName;
-
- // check for an external font file
- } else if ((fileName = gfxFont->getExtFontFile())) {
- font = tryGetFTFontFromFile(xref, fileName, gFalse, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- } else {
- font = NULL;
- }
-
- return font;
-}
-
-XOutputFont *XOutputFontCache::tryGetFTFontFromFile(XRef *xref,
- GString *fileName,
- GBool deleteFile,
- GfxFont *gfxFont,
- double m11Orig,
- double m12Orig,
- double m21Orig,
- double m22Orig,
- double m11, double m12,
- double m21, double m22,
- GBool subst) {
- Ref *id;
- FTFontFile *fontFile;
- XOutputFont *font;
-
- // create the FreeType font file
- if (gfxFont->isCIDFont()) {
- if (gfxFont->getType() == fontCIDType2) {
- fontFile = new FTFontFile(ftEngine, fileName->getCString(),
- ((GfxCIDFont *)gfxFont)->getCIDToGID(),
- ((GfxCIDFont *)gfxFont)->getCIDToGIDLen());
- } else { // fontCIDType0C
- fontFile = new FTFontFile(ftEngine, fileName->getCString());
- }
- } else {
- fontFile = new FTFontFile(ftEngine, fileName->getCString(),
- ((Gfx8BitFont *)gfxFont)->getEncoding(),
- ((Gfx8BitFont *)gfxFont)->getHasEncoding());
- }
- if (!fontFile->isOk()) {
- error(-1, "Couldn't create FreeType font from '%s'",
- fileName->getCString());
- delete fontFile;
- if (deleteFile) {
- unlink(fileName->getCString());
- }
- return NULL;
- }
-
- // add to list
- id = gfxFont->getID();
- ftFontFiles->append(new XOutputFTFontFile(id->num, id->gen,
- subst, fontFile,
- deleteFile ? fileName->copy()
- : (GString *)NULL));
-
- // create the Font
- font = new XOutputFTFont(gfxFont->getID(), fontFile,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
-}
-#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-XOutputFont *XOutputFontCache::tryGetTTFont(XRef *xref,
- GfxFont *gfxFont,
- double m11, double m12,
- double m21, double m22) {
- Ref *id;
- XOutputTTFontFile *xFontFile;
- XOutputFont *font;
- Ref embRef;
- GString *fileName;
- FILE *f;
- Object refObj, strObj;
- int c;
- int i;
-
- // check the already available font files
- id = gfxFont->getID();
- xFontFile = NULL;
- for (i = 0; i < ttFontFiles->getLength(); ++i) {
- xFontFile = (XOutputTTFontFile *)ttFontFiles->get(i);
- if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
- !xFontFile->subst) {
- font = new XOutputTTFont(id, xFontFile->fontFile,
- m11, m12, m21, m22,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
- }
- }
-
- // check for an embedded font
- if (gfxFont->getEmbeddedFontID(&embRef)) {
-
- // create the font file
- fileName = NULL;
- if (!openTempFile(&fileName, &f, "wb", NULL)) {
- error(-1, "Couldn't create temporary TrueType font file");
- return NULL;
- }
- refObj.initRef(embRef.num, embRef.gen);
- refObj.fetch(xref, &strObj);
- refObj.free();
- strObj.streamReset();
- while ((c = strObj.streamGetChar()) != EOF) {
- fputc(c, f);
- }
- strObj.streamClose();
- strObj.free();
- fclose(f);
-
- // create the Font
- font = tryGetTTFontFromFile(xref, fileName, gTrue, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- // on systems with Unix hard link semantics, this will remove the
- // last link to the temp file
- unlink(fileName->getCString());
-
- delete fileName;
-
- } else if ((fileName = gfxFont->getExtFontFile())) {
- font = tryGetTTFontFromFile(xref, fileName, gFalse, gfxFont,
- m11, m12, m21, m22,
- m11, m12, m21, m22, gFalse);
-
- } else {
- font = NULL;
- }
-
- return font;
-}
-
-XOutputFont *XOutputFontCache::tryGetTTFontFromFile(XRef *xref,
- GString *fileName,
- GBool deleteFile,
- GfxFont *gfxFont,
- double m11Orig,
- double m12Orig,
- double m21Orig,
- double m22Orig,
- double m11, double m12,
- double m21, double m22,
- GBool subst) {
- Ref *id;
- TTFontFile *fontFile;
- XOutputFont *font;
-
- // create the FreeType font file
- if (gfxFont->isCIDFont()) {
- // fontCIDType2
- fontFile = new TTFontFile(ttEngine, fileName->getCString(),
- ((GfxCIDFont *)gfxFont)->getCIDToGID(),
- ((GfxCIDFont *)gfxFont)->getCIDToGIDLen());
- } else {
- fontFile = new TTFontFile(ttEngine, fileName->getCString(),
- ((Gfx8BitFont *)gfxFont)->getEncoding(),
- ((Gfx8BitFont *)gfxFont)->getHasEncoding());
- }
- if (!fontFile->isOk()) {
- error(-1, "Couldn't create FreeType font from '%s'",
- fileName->getCString());
- delete fontFile;
- if (deleteFile) {
- unlink(fileName->getCString());
- }
- return NULL;
- }
-
- // add to list
- id = gfxFont->getID();
- ttFontFiles->append(new XOutputTTFontFile(id->num, id->gen,
- subst, fontFile,
- deleteFile ? fileName->copy()
- : (GString *)NULL));
-
- // create the Font
- font = new XOutputTTFont(gfxFont->getID(), fontFile,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22, display, xOut);
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
-}
-#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
-
-XOutputFont *XOutputFontCache::tryGetServerFont(GString *xlfd,
- GString *encodingName,
- GfxFont *gfxFont,
- double m11Orig, double m12Orig,
- double m21Orig, double m22Orig,
- double m11, double m12,
- double m21, double m22) {
- XOutputFont *font;
- UnicodeMap *uMap;
- CharCodeToUnicode *ctu;
-
- uMap = globalParams->getUnicodeMap(encodingName);
- if (gfxFont->isCIDFont()) {
- ctu = ((GfxCIDFont *)gfxFont)->getToUnicode();
- font = new XOutputServer16BitFont(gfxFont->getID(), xlfd, uMap, ctu,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22,
- display, xOut);
- ctu->decRefCnt();
- } else {
- ctu = ((Gfx8BitFont *)gfxFont)->getToUnicode();
- font = new XOutputServer8BitFont(gfxFont->getID(), xlfd, uMap, ctu,
- m11Orig, m12Orig, m21Orig, m22Orig,
- m11, m12, m21, m22,
- display, xOut);
- ctu->decRefCnt();
- }
- uMap->decRefCnt();
- if (!font->isOk()) {
- delete font;
- return NULL;
- }
- return font;
-}
-
-//------------------------------------------------------------------------
-// T3FontCache
-//------------------------------------------------------------------------
-
-struct T3FontCacheTag {
- Gushort code;
- Gushort mru; // valid bit (0x8000) and MRU index
- double wx, wy; // untransformed glyph metrics
-};
-
-class T3FontCache {
-public:
-
- T3FontCache(Ref *fontID, double m11A, double m12A,
- double m21A, double m22A,
- int glyphXA, int glyphYA, int glyphWA, int glyphHA,
- Display *displayA, Visual *visual, Guint depth,
- Pixmap origPixmap);
- ~T3FontCache();
- GBool matches(Ref *idA, double m11A, double m12A,
- double m21A, double m22A)
- { return fontID.num == idA->num && fontID.gen == idA->gen &&
- m11 == m11A && m12 == m12A && m21 == m21A && m22 == m22A; }
-
- Ref fontID; // PDF font ID
- double m11, m12, m21, m22; // transform matrix
- int glyphX, glyphY; // pixel offset of glyph pixmaps
- int glyphW, glyphH; // size of glyph pixmaps, in pixels
- int glyphSize; // size of glyph pixmaps, in bytes
- int cacheSets; // number of sets in cache
- int cacheAssoc; // cache associativity (glyphs per set)
- Guchar *cacheData; // glyph pixmap cache
- T3FontCacheTag *cacheTags; // cache tags, i.e., char codes
- Display *display;
- Pixmap pixmap;
- XImage *image;
-};
-
-T3FontCache::T3FontCache(Ref *fontIDA, double m11A, double m12A,
- double m21A, double m22A,
- int glyphXA, int glyphYA, int glyphWA, int glyphHA,
- Display *displayA, Visual *visual, Guint depth,
- Pixmap origPixmap) {
- int i;
-
- fontID = *fontIDA;
- m11 = m11A;
- m12 = m12A;
- m21 = m21A;
- m22 = m22A;
- glyphX = glyphXA;
- glyphY = glyphYA;
- glyphW = glyphWA;
- glyphH = glyphHA;
- glyphSize = glyphW * glyphH;
- cacheAssoc = 8;
- if (glyphSize <= 256) {
- cacheSets = 8;
- } else if (glyphSize <= 512) {
- cacheSets = 4;
- } else if (glyphSize <= 1024) {
- cacheSets = 2;
- } else {
- cacheSets = 1;
- }
- cacheData = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
- cacheTags = (T3FontCacheTag *)gmalloc(cacheSets * cacheAssoc *
- sizeof(T3FontCacheTag));
- for (i = 0; i < cacheSets * cacheAssoc; ++i) {
- cacheTags[i].mru = i & (cacheAssoc - 1);
- }
- display = displayA;
- pixmap = XCreatePixmap(display, origPixmap, glyphW, glyphH, depth);
- image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL,
- glyphW, glyphH, 8, 0);
- image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
-}
-
-T3FontCache::~T3FontCache() {
- gfree(cacheData);
- gfree(cacheTags);
- XFreePixmap(display, pixmap);
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
-}
-
-struct T3GlyphStack {
- GBool cacheable;
- Gushort code;
- T3FontCache *cache;
- int cacheIdx;
- T3FontCacheTag *cacheTag;
- Guchar *cacheData;
- double x, y;
- Unicode *u;
- int uLen;
- GfxRGB color;
- int origPixmapW, origPixmapH;
- Pixmap origPixmap;
- GC origStrokeGC;
- GC origFillGC;
- Region origClipRegion;
- double origCTM4, origCTM5;
- double wx, wy; // untransformed glyph metrics
- T3GlyphStack *next;
-};
-
-//------------------------------------------------------------------------
-// XOutputDev
-//------------------------------------------------------------------------
-
-XOutputDev::XOutputDev(Display *displayA, int screenNumA,
- Visual *visualA, Colormap colormapA,
- GBool reverseVideoA, unsigned long paperColorA,
- GBool installCmap, int rgbCubeSize,
- int forceDepth) {
- XVisualInfo visualTempl;
- XVisualInfo *visualList;
- int nVisuals;
- Gulong mask;
- XColor xcolor;
- XColor *xcolors;
- int r, g, b, n, m;
- GBool ok;
-
- // no document yet
- xref = NULL;
-
- // display / screen / visual / colormap
- display = displayA;
- screenNum = screenNumA;
- visual = visualA;
- colormap = colormapA;
-
- // no pixmap yet
- pixmapW = pixmapH = 0;
-
- // check for TrueColor visual
- if (forceDepth != 0) {
- depth = forceDepth;
- trueColor = depth >= 16;
- } else {
- visualTempl.visualid = XVisualIDFromVisual(visual);
- visualList = XGetVisualInfo(display, VisualIDMask,
- &visualTempl, &nVisuals);
- if (nVisuals < 1) {
- // this shouldn't happen
- XFree((XPointer)visualList);
- visualList = XGetVisualInfo(display, VisualNoMask, &visualTempl,
- &nVisuals);
- }
- depth = visualList->depth;
- if (visualList->c_class == TrueColor) {
- trueColor = gTrue;
- for (mask = visualList->red_mask, rShift = 0;
- mask && !(mask & 1);
- mask >>= 1, ++rShift) ;
- rMul = (int)mask;
- for (mask = visualList->green_mask, gShift = 0;
- mask && !(mask & 1);
- mask >>= 1, ++gShift) ;
- gMul = (int)mask;
- for (mask = visualList->blue_mask, bShift = 0;
- mask && !(mask & 1);
- mask >>= 1, ++bShift) ;
- bMul = (int)mask;
- } else {
- trueColor = gFalse;
- }
- XFree((XPointer)visualList);
- }
-
- // allocate a color cube
- if (!trueColor) {
- redMap[BlackPixel(display, screenNum) & 0xff] = 0;
- redMap[WhitePixel(display, screenNum) & 0xff] = 1;
-
- // set colors in private colormap
- if (installCmap) {
- for (numColors = 6; numColors >= 2; --numColors) {
- m = numColors * numColors * numColors;
- if (XAllocColorCells(display, colormap, False, NULL, 0, colors, m)) {
- break;
- }
- }
- if (numColors >= 2) {
- m = numColors * numColors * numColors;
- xcolors = (XColor *)gmalloc(m * sizeof(XColor));
- n = 0;
- for (r = 0; r < numColors; ++r) {
- for (g = 0; g < numColors; ++g) {
- for (b = 0; b < numColors; ++b) {
- xcolors[n].pixel = colors[n];
- xcolors[n].red = (r * 65535) / (numColors - 1);
- xcolors[n].green = (g * 65535) / (numColors - 1);
- xcolors[n].blue = (b * 65535) / (numColors - 1);
- xcolors[n].flags = DoRed | DoGreen | DoBlue;
- redMap[xcolors[n].pixel & 0xff] = xcolors[n].red / 65535.0;
- ++n;
- }
- }
- }
- XStoreColors(display, colormap, xcolors, m);
- gfree(xcolors);
- } else {
- numColors = 1;
- colors[0] = BlackPixel(display, screenNum);
- colors[1] = WhitePixel(display, screenNum);
- }
-
- // allocate colors in shared colormap
- } else {
- if (rgbCubeSize > maxRGBCube) {
- rgbCubeSize = maxRGBCube;
- }
- ok = gFalse;
- for (numColors = rgbCubeSize; numColors >= 2; --numColors) {
- ok = gTrue;
- n = 0;
- for (r = 0; r < numColors && ok; ++r) {
- for (g = 0; g < numColors && ok; ++g) {
- for (b = 0; b < numColors && ok; ++b) {
- if (n == 0) {
- colors[n] = BlackPixel(display, screenNum);
- redMap[colors[n] & 0xff] = 0;
- ++n;
- } else {
- xcolor.red = (r * 65535) / (numColors - 1);
- xcolor.green = (g * 65535) / (numColors - 1);
- xcolor.blue = (b * 65535) / (numColors - 1);
- if (XAllocColor(display, colormap, &xcolor)) {
- colors[n++] = xcolor.pixel;
- redMap[xcolor.pixel & 0xff] = xcolor.red / 65535.0;
- } else {
- ok = gFalse;
- }
- }
- }
- }
- }
- if (ok) {
- break;
- }
- XFreeColors(display, colormap, &colors[1], n-1, 0);
- }
- if (!ok) {
- numColors = 1;
- colors[0] = BlackPixel(display, screenNum);
- colors[1] = WhitePixel(display, screenNum);
- }
- }
- }
-
- // misc parameters
- reverseVideo = reverseVideoA;
- paperColor = paperColorA;
-
- // set up the font cache and fonts
- gfxFont = NULL;
- font = NULL;
- fontCache = new XOutputFontCache(display, depth, this,
- globalParams->getT1libControl(),
- globalParams->getFreeTypeControl());
- nT3Fonts = 0;
- t3GlyphStack = NULL;
-
- // empty state stack
- save = NULL;
-
- // create text object
- text = new TextPage(gFalse);
-}
-
-XOutputDev::~XOutputDev() {
- int i;
-
- delete fontCache;
- for (i = 0; i < nT3Fonts; ++i) {
- delete t3FontCache[i];
- }
- delete text;
-}
-
-void XOutputDev::startDoc(XRef *xrefA) {
- int i;
-
- xref = xrefA;
- fontCache->startDoc(screenNum, visual, colormap, trueColor, rMul, gMul, bMul,
- rShift, gShift, bShift, colors, numColors);
- for (i = 0; i < nT3Fonts; ++i) {
- delete t3FontCache[i];
- }
- nT3Fonts = 0;
-}
-
-void XOutputDev::startPage(int pageNum, GfxState *state) {
- XGCValues gcValues;
- XRectangle rect;
-
- // default line flatness
- flatness = 0;
-
- // allocate GCs
- gcValues.foreground = BlackPixel(display, screenNum);
- gcValues.background = WhitePixel(display, screenNum);
- gcValues.line_width = 0;
- gcValues.line_style = LineSolid;
- strokeGC = XCreateGC(display, pixmap,
- GCForeground | GCBackground | GCLineWidth | GCLineStyle,
- &gcValues);
- fillGC = XCreateGC(display, pixmap,
- GCForeground | GCBackground | GCLineWidth | GCLineStyle,
- &gcValues);
- gcValues.foreground = paperColor;
- paperGC = XCreateGC(display, pixmap,
- GCForeground | GCBackground | GCLineWidth | GCLineStyle,
- &gcValues);
-
- // initialize clip region
- clipRegion = XCreateRegion();
- rect.x = rect.y = 0;
- rect.width = pixmapW;
- rect.height = pixmapH;
- XUnionRectWithRegion(&rect, clipRegion, clipRegion);
- XSetRegion(display, strokeGC, clipRegion);
- XSetRegion(display, fillGC, clipRegion);
-
- // clear font
- gfxFont = NULL;
- font = NULL;
-
- // clear window
- XFillRectangle(display, pixmap, paperGC, 0, 0, pixmapW, pixmapH);
-
- // clear text object
- text->clear();
-}
-
-void XOutputDev::endPage() {
- XOutputState *s;
-
- text->coalesce();
-
- // clear state stack, free all GCs, free the clip region
- while (save) {
- s = save;
- save = save->next;
- XFreeGC(display, s->strokeGC);
- XFreeGC(display, s->fillGC);
- XDestroyRegion(s->clipRegion);
- delete s;
- }
- XFreeGC(display, strokeGC);
- XFreeGC(display, fillGC);
- XFreeGC(display, paperGC);
- XDestroyRegion(clipRegion);
-}
-
-void XOutputDev::drawLink(Link *link, Catalog *catalog) {
- double x1, y1, x2, y2, w;
- GfxRGB rgb;
- XPoint points[5];
- int x, y;
-
- link->getBorder(&x1, &y1, &x2, &y2, &w);
- if (w > 0) {
- rgb.r = 0;
- rgb.g = 0;
- rgb.b = 1;
- XSetForeground(display, strokeGC, findColor(&rgb));
- XSetLineAttributes(display, strokeGC, xoutRound(w),
- LineSolid, CapRound, JoinRound);
- cvtUserToDev(x1, y1, &x, &y);
- points[0].x = points[4].x = x;
- points[0].y = points[4].y = y;
- cvtUserToDev(x2, y1, &x, &y);
- points[1].x = x;
- points[1].y = y;
- cvtUserToDev(x2, y2, &x, &y);
- points[2].x = x;
- points[2].y = y;
- cvtUserToDev(x1, y2, &x, &y);
- points[3].x = x;
- points[3].y = y;
- XDrawLines(display, pixmap, strokeGC, points, 5, CoordModeOrigin);
- }
-}
-
-void XOutputDev::saveState(GfxState *state) {
- XOutputState *s;
- XGCValues values;
-
- // save current state
- s = new XOutputState;
- s->strokeGC = strokeGC;
- s->fillGC = fillGC;
- s->clipRegion = clipRegion;
-
- // push onto state stack
- s->next = save;
- save = s;
-
- // create a new current state by copying
- strokeGC = XCreateGC(display, pixmap, 0, &values);
- XCopyGC(display, s->strokeGC, 0xffffffff, strokeGC);
- fillGC = XCreateGC(display, pixmap, 0, &values);
- XCopyGC(display, s->fillGC, 0xffffffff, fillGC);
- clipRegion = XCreateRegion();
- XUnionRegion(s->clipRegion, clipRegion, clipRegion);
- XSetRegion(display, strokeGC, clipRegion);
- XSetRegion(display, fillGC, clipRegion);
-}
-
-void XOutputDev::restoreState(GfxState *state) {
- XOutputState *s;
-
- if (save) {
- // kill current state
- XFreeGC(display, strokeGC);
- XFreeGC(display, fillGC);
- XDestroyRegion(clipRegion);
-
- // restore state
- flatness = state->getFlatness();
- strokeGC = save->strokeGC;
- fillGC = save->fillGC;
- clipRegion = save->clipRegion;
- XSetRegion(display, strokeGC, clipRegion);
- XSetRegion(display, fillGC, clipRegion);
-
- // pop state stack
- s = save;
- save = save->next;
- delete s;
- }
-}
-
-void XOutputDev::updateAll(GfxState *state) {
- updateLineAttrs(state, gTrue);
- updateFlatness(state);
- updateMiterLimit(state);
- updateFillColor(state);
- updateStrokeColor(state);
- updateFont(state);
-}
-
-void XOutputDev::updateCTM(GfxState *state, double m11, double m12,
- double m21, double m22, double m31, double m32) {
- updateLineAttrs(state, gTrue);
-}
-
-void XOutputDev::updateLineDash(GfxState *state) {
- updateLineAttrs(state, gTrue);
-}
-
-void XOutputDev::updateFlatness(GfxState *state) {
- flatness = state->getFlatness();
-}
-
-void XOutputDev::updateLineJoin(GfxState *state) {
- updateLineAttrs(state, gFalse);
-}
-
-void XOutputDev::updateLineCap(GfxState *state) {
- updateLineAttrs(state, gFalse);
-}
-
-// unimplemented
-void XOutputDev::updateMiterLimit(GfxState *state) {
-}
-
-void XOutputDev::updateLineWidth(GfxState *state) {
- updateLineAttrs(state, gFalse);
-}
-
-void XOutputDev::updateLineAttrs(GfxState *state, GBool updateDash) {
- double width;
- int cap, join;
- double *dashPattern;
- int dashLength;
- double dashStart;
- char dashList[20];
- int i;
-
- width = state->getTransformedLineWidth();
- switch (state->getLineCap()) {
- case 0: cap = CapButt; break;
- case 1: cap = CapRound; break;
- case 2: cap = CapProjecting; break;
- default:
- error(-1, "Bad line cap style (%d)", state->getLineCap());
- cap = CapButt;
- break;
- }
- switch (state->getLineJoin()) {
- case 0: join = JoinMiter; break;
- case 1: join = JoinRound; break;
- case 2: join = JoinBevel; break;
- default:
- error(-1, "Bad line join style (%d)", state->getLineJoin());
- join = JoinMiter;
- break;
- }
- state->getLineDash(&dashPattern, &dashLength, &dashStart);
-#if 1 //~ work around a bug in XFree86 (???)
- if (dashLength > 0 && cap == CapProjecting) {
- cap = CapButt;
- }
-#endif
- XSetLineAttributes(display, strokeGC, xoutRound(width),
- dashLength > 0 ? LineOnOffDash : LineSolid,
- cap, join);
- if (updateDash && dashLength > 0) {
- if (dashLength > 20)
- dashLength = 20;
- for (i = 0; i < dashLength; ++i) {
- dashList[i] = xoutRound(state->transformWidth(dashPattern[i]));
- if (dashList[i] == 0)
- dashList[i] = 1;
- }
- XSetDashes(display, strokeGC, xoutRound(dashStart), dashList, dashLength);
- }
-}
-
-void XOutputDev::updateFillColor(GfxState *state) {
- GfxRGB rgb;
-
- state->getFillRGB(&rgb);
- if (reverseVideo) {
- rgb.r = 1 - rgb.r;
- rgb.g = 1 - rgb.g;
- rgb.b = 1 - rgb.b;
- }
- XSetForeground(display, fillGC, findColor(&rgb));
-}
-
-void XOutputDev::updateStrokeColor(GfxState *state) {
- GfxRGB rgb;
-
- state->getStrokeRGB(&rgb);
- if (reverseVideo) {
- rgb.r = 1 - rgb.r;
- rgb.g = 1 - rgb.g;
- rgb.b = 1 - rgb.b;
- }
- XSetForeground(display, strokeGC, findColor(&rgb));
-}
-
-void XOutputDev::updateFont(GfxState *state) {
- double m11, m12, m21, m22;
-
- text->updateFont(state);
-
- if (!(gfxFont = state->getFont())) {
- font = NULL;
- return;
- }
- if (gfxFont->getType() == fontType3) {
- font = NULL;
- return;
- }
- state->getFontTransMat(&m11, &m12, &m21, &m22);
- m11 *= state->getHorizScaling();
- m12 *= state->getHorizScaling();
- font = fontCache->getFont(xref, gfxFont, m11, m12, m21, m22);
- if (font) {
- font->updateGC(fillGC);
- font->updateGC(strokeGC);
- }
-}
-
-void XOutputDev::stroke(GfxState *state) {
- XPoint *points;
- int *lengths;
- int n, size, numPoints, i, j;
-
- // transform points
- n = convertPath(state, &points, &size, &numPoints, &lengths, gFalse);
-
- // draw each subpath
- j = 0;
- for (i = 0; i < n; ++i) {
- XDrawLines(display, pixmap, strokeGC, points + j, lengths[i],
- CoordModeOrigin);
- j += lengths[i];
- }
-
- // free points and lengths arrays
- if (points != tmpPoints)
- gfree(points);
- if (lengths != tmpLengths)
- gfree(lengths);
-}
-
-void XOutputDev::fill(GfxState *state) {
- doFill(state, WindingRule);
-}
-
-void XOutputDev::eoFill(GfxState *state) {
- doFill(state, EvenOddRule);
-}
-
-//
-// X doesn't color the pixels on the right-most and bottom-most
-// borders of a polygon. This means that one-pixel-thick polygons
-// are not colored at all. I think this is supposed to be a
-// feature, but I can't figure out why. So after it fills a
-// polygon, it also draws lines around the border. This is done
-// only for single-component polygons, since it's not very
-// compatible with the compound polygon kludge (see convertPath()).
-//
-void XOutputDev::doFill(GfxState *state, int rule) {
- XPoint *points;
- int *lengths;
- int n, size, numPoints, i, j;
-
- // set fill rule
- XSetFillRule(display, fillGC, rule);
-
- // transform points, build separate polygons
- n = convertPath(state, &points, &size, &numPoints, &lengths, gTrue);
-
- // fill them
- j = 0;
- for (i = 0; i < n; ++i) {
- XFillPolygon(display, pixmap, fillGC, points + j, lengths[i],
- Complex, CoordModeOrigin);
- if (state->getPath()->getNumSubpaths() == 1) {
- XDrawLines(display, pixmap, fillGC, points + j, lengths[i],
- CoordModeOrigin);
- }
- j += lengths[i] + 1;
- }
-
- // free points and lengths arrays
- if (points != tmpPoints)
- gfree(points);
- if (lengths != tmpLengths)
- gfree(lengths);
-}
-
-void XOutputDev::clip(GfxState *state) {
- doClip(state, WindingRule);
-}
-
-void XOutputDev::eoClip(GfxState *state) {
- doClip(state, EvenOddRule);
-}
-
-void XOutputDev::doClip(GfxState *state, int rule) {
- Region region, region2;
- XPoint *points;
- int *lengths;
- int n, size, numPoints, i, j;
-
- // transform points, build separate polygons
- n = convertPath(state, &points, &size, &numPoints, &lengths, gTrue);
-
- // construct union of subpath regions
- // (XPolygonRegion chokes if there aren't at least three points --
- // this happens if the PDF file does moveto/closepath/clip, which
- // sets an empty clipping region)
- if (lengths[0] > 2) {
- region = XPolygonRegion(points, lengths[0], rule);
- } else {
- region = XCreateRegion();
- }
- j = lengths[0] + 1;
- for (i = 1; i < n; ++i) {
- if (lengths[i] > 2) {
- region2 = XPolygonRegion(points + j, lengths[i], rule);
- } else {
- region2 = XCreateRegion();
- }
- XUnionRegion(region2, region, region);
- XDestroyRegion(region2);
- j += lengths[i] + 1;
- }
-
- // intersect region with clipping region
- XIntersectRegion(region, clipRegion, clipRegion);
- XDestroyRegion(region);
- XSetRegion(display, strokeGC, clipRegion);
- XSetRegion(display, fillGC, clipRegion);
-
- // free points and lengths arrays
- if (points != tmpPoints)
- gfree(points);
- if (lengths != tmpLengths)
- gfree(lengths);
-}
-
-//
-// Transform points in the path and convert curves to line segments.
-// Builds a set of subpaths and returns the number of subpaths.
-// If <fillHack> is set, close any unclosed subpaths and activate a
-// kludge for polygon fills: First, it divides up the subpaths into
-// non-overlapping polygons by simply comparing bounding rectangles.
-// Then it connects subaths within a single compound polygon to a single
-// point so that X can fill the polygon (sort of).
-//
-int XOutputDev::convertPath(GfxState *state, XPoint **points, int *size,
- int *numPoints, int **lengths, GBool fillHack) {
- GfxPath *path;
- BoundingRect *rects;
- BoundingRect rect;
- int n, i, ii, j, k, k0;
-
- // get path and number of subpaths
- path = state->getPath();
- n = path->getNumSubpaths();
-
- // allocate lengths array
- if (n < numTmpSubpaths)
- *lengths = tmpLengths;
- else
- *lengths = (int *)gmalloc(n * sizeof(int));
-
- // allocate bounding rectangles array
- if (fillHack) {
- if (n < numTmpSubpaths)
- rects = tmpRects;
- else
- rects = (BoundingRect *)gmalloc(n * sizeof(BoundingRect));
- } else {
- rects = NULL;
- }
-
- // do each subpath
- *points = tmpPoints;
- *size = numTmpPoints;
- *numPoints = 0;
- for (i = 0; i < n; ++i) {
-
- // transform the points
- j = *numPoints;
- convertSubpath(state, path->getSubpath(i), points, size, numPoints);
-
- // construct bounding rectangle
- if (fillHack) {
- rects[i].xMin = rects[i].xMax = (*points)[j].x;
- rects[i].yMin = rects[i].yMax = (*points)[j].y;
- for (k = j + 1; k < *numPoints; ++k) {
- if ((*points)[k].x < rects[i].xMin)
- rects[i].xMin = (*points)[k].x;
- else if ((*points)[k].x > rects[i].xMax)
- rects[i].xMax = (*points)[k].x;
- if ((*points)[k].y < rects[i].yMin)
- rects[i].yMin = (*points)[k].y;
- else if ((*points)[k].y > rects[i].yMax)
- rects[i].yMax = (*points)[k].y;
- }
- }
-
- // close subpath if necessary
- if (fillHack && ((*points)[*numPoints-1].x != (*points)[j].x ||
- (*points)[*numPoints-1].y != (*points)[j].y)) {
- addPoint(points, size, numPoints, (*points)[j].x, (*points)[j].y);
- }
-
- // length of this subpath
- (*lengths)[i] = *numPoints - j;
-
- // leave an extra point for compound fill hack
- if (fillHack)
- addPoint(points, size, numPoints, 0, 0);
- }
-
- // kludge: munge any points that are *way* out of bounds - these can
- // crash certain (buggy) X servers
- for (i = 0; i < *numPoints; ++i) {
- if ((*points)[i].x < -pixmapW) {
- (*points)[i].x = -pixmapW;
- } else if ((*points)[i].x > 2 * pixmapW) {
- (*points)[i].x = 2 * pixmapW;
- }
- if ((*points)[i].y < -pixmapH) {
- (*points)[i].y = -pixmapH;
- } else if ((*points)[i].y > 2 * pixmapH) {
- (*points)[i].y = 2 * pixmapH;
- }
- }
-
- // combine compound polygons
- if (fillHack) {
- i = j = k = 0;
- while (i < n) {
-
- // start with subpath i
- rect = rects[i];
- (*lengths)[j] = (*lengths)[i];
- k0 = k;
- (*points)[k + (*lengths)[i]] = (*points)[k0];
- k += (*lengths)[i] + 1;
- ++i;
-
- // combine overlapping polygons
- do {
-
- // look for the first subsequent subpath, if any, which overlaps
- for (ii = i; ii < n; ++ii) {
- if (rects[ii].xMax > rects[i].xMin &&
- rects[ii].xMin < rects[i].xMax &&
- rects[ii].yMax > rects[i].yMin &&
- rects[ii].yMin < rects[i].yMax) {
- break;
- }
- }
-
- // if there is an overlap, combine the polygons
- if (ii < n) {
- for (; i <= ii; ++i) {
- if (rects[i].xMin < rect.xMin)
- rect.xMin = rects[j].xMin;
- if (rects[i].xMax > rect.xMax)
- rect.xMax = rects[j].xMax;
- if (rects[i].yMin < rect.yMin)
- rect.yMin = rects[j].yMin;
- if (rects[i].yMax > rect.yMax)
- rect.yMax = rects[j].yMax;
- (*lengths)[j] += (*lengths)[i] + 1;
- (*points)[k + (*lengths)[i]] = (*points)[k0];
- k += (*lengths)[i] + 1;
- }
- }
- } while (ii < n && i < n);
-
- ++j;
- }
-
- // free bounding rectangles
- if (rects != tmpRects)
- gfree(rects);
-
- n = j;
- }
-
- return n;
-}
-
-//
-// Transform points in a single subpath and convert curves to line
-// segments.
-//
-void XOutputDev::convertSubpath(GfxState *state, GfxSubpath *subpath,
- XPoint **points, int *size, int *n) {
- double x0, y0, x1, y1, x2, y2, x3, y3;
- int m, i;
-
- m = subpath->getNumPoints();
- i = 0;
- while (i < m) {
- if (i >= 1 && subpath->getCurve(i)) {
- state->transform(subpath->getX(i-1), subpath->getY(i-1), &x0, &y0);
- state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
- state->transform(subpath->getX(i+1), subpath->getY(i+1), &x2, &y2);
- state->transform(subpath->getX(i+2), subpath->getY(i+2), &x3, &y3);
- doCurve(points, size, n, x0, y0, x1, y1, x2, y2, x3, y3);
- i += 3;
- } else {
- state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
- addPoint(points, size, n, xoutRound(x1), xoutRound(y1));
- ++i;
- }
- }
-}
-
-//
-// Subdivide a Bezier curve. This uses floating point to avoid
-// propagating rounding errors. (The curves look noticeably more
-// jagged with integer arithmetic.)
-//
-void XOutputDev::doCurve(XPoint **points, int *size, int *n,
- double x0, double y0, double x1, double y1,
- double x2, double y2, double x3, double y3) {
- double x[(1<<maxCurveSplits)+1][3];
- double y[(1<<maxCurveSplits)+1][3];
- int next[1<<maxCurveSplits];
- int p1, p2, p3;
- double xx1, yy1, xx2, yy2;
- double dx, dy, mx, my, d1, d2;
- double xl0, yl0, xl1, yl1, xl2, yl2;
- double xr0, yr0, xr1, yr1, xr2, yr2, xr3, yr3;
- double xh, yh;
- double flat;
-
- flat = (double)(flatness * flatness);
- if (flat < 1)
- flat = 1;
-
- // initial segment
- p1 = 0;
- p2 = 1<<maxCurveSplits;
- x[p1][0] = x0; y[p1][0] = y0;
- x[p1][1] = x1; y[p1][1] = y1;
- x[p1][2] = x2; y[p1][2] = y2;
- x[p2][0] = x3; y[p2][0] = y3;
- next[p1] = p2;
-
- while (p1 < (1<<maxCurveSplits)) {
-
- // get next segment
- xl0 = x[p1][0]; yl0 = y[p1][0];
- xx1 = x[p1][1]; yy1 = y[p1][1];
- xx2 = x[p1][2]; yy2 = y[p1][2];
- p2 = next[p1];
- xr3 = x[p2][0]; yr3 = y[p2][0];
-
- // compute distances from control points to midpoint of the
- // straight line (this is a bit of a hack, but it's much faster
- // than computing the actual distances to the line)
- mx = (xl0 + xr3) * 0.5;
- my = (yl0 + yr3) * 0.5;
- dx = xx1 - mx;
- dy = yy1 - my;
- d1 = dx*dx + dy*dy;
- dx = xx2 - mx;
- dy = yy2 - my;
- d2 = dx*dx + dy*dy;
-
- // if curve is flat enough, or no more divisions allowed then
- // add the straight line segment
- if (p2 - p1 <= 1 || (d1 <= flat && d2 <= flat)) {
- addPoint(points, size, n, xoutRound(xr3), xoutRound(yr3));
- p1 = p2;
-
- // otherwise, subdivide the curve
- } else {
- xl1 = (xl0 + xx1) * 0.5;
- yl1 = (yl0 + yy1) * 0.5;
- xh = (xx1 + xx2) * 0.5;
- yh = (yy1 + yy2) * 0.5;
- xl2 = (xl1 + xh) * 0.5;
- yl2 = (yl1 + yh) * 0.5;
- xr2 = (xx2 + xr3) * 0.5;
- yr2 = (yy2 + yr3) * 0.5;
- xr1 = (xh + xr2) * 0.5;
- yr1 = (yh + yr2) * 0.5;
- xr0 = (xl2 + xr1) * 0.5;
- yr0 = (yl2 + yr1) * 0.5;
-
- // add the new subdivision points
- p3 = (p1 + p2) / 2;
- x[p1][1] = xl1; y[p1][1] = yl1;
- x[p1][2] = xl2; y[p1][2] = yl2;
- next[p1] = p3;
- x[p3][0] = xr0; y[p3][0] = yr0;
- x[p3][1] = xr1; y[p3][1] = yr1;
- x[p3][2] = xr2; y[p3][2] = yr2;
- next[p3] = p2;
- }
- }
-}
-
-//
-// Add a point to the points array. (This would use a generic resizable
-// array type if C++ supported parameterized types in some reasonable
-// way -- templates are a disgusting kludge.)
-//
-void XOutputDev::addPoint(XPoint **points, int *size, int *k, int x, int y) {
- if (*k >= *size) {
- *size += 32;
- if (*points == tmpPoints) {
- *points = (XPoint *)gmalloc(*size * sizeof(XPoint));
- memcpy(*points, tmpPoints, *k * sizeof(XPoint));
- } else {
- *points = (XPoint *)grealloc(*points, *size * sizeof(XPoint));
- }
- }
- (*points)[*k].x = x;
- (*points)[*k].y = y;
- ++(*k);
-}
-
-void XOutputDev::beginString(GfxState *state, GString *s) {
- text->beginString(state, state->getCurX(), state->getCurY());
-}
-
-void XOutputDev::endString(GfxState *state) {
- text->endString();
-}
-
-void XOutputDev::drawChar(GfxState *state, double x, double y,
- double dx, double dy,
- double originX, double originY,
- CharCode code, Unicode *u, int uLen) {
- int render;
- double x1, y1, dx1, dy1;
- GfxRGB rgb;
- double saveCurX, saveCurY;
- double *ctm;
- double saveCTM[6];
-
- text->addChar(state, x, y, dx, dy, u, uLen);
-
- if (!font) {
- return;
- }
-
- // check for invisible text -- this is used by Acrobat Capture
- render = state->getRender();
- if ((render & 3) == 3) {
- return;
- }
-
- x -= originX;
- y -= originY;
- state->transform(x, y, &x1, &y1);
- state->transformDelta(dx, dy, &dx1, &dy1);
-
- // fill
- if (!(render & 1)) {
- state->getFillRGB(&rgb);
- if (reverseVideo) {
- rgb.r = 1 - rgb.r;
- rgb.g = 1 - rgb.g;
- rgb.b = 1 - rgb.b;
- }
- font->drawChar(state, pixmap, pixmapW, pixmapH, fillGC, &rgb,
- x1, y1, dx1, dy1, code, u, uLen);
- }
-
- // stroke
- if ((render & 3) == 1 || (render & 3) == 2) {
- if (font->hasGetCharPath()) {
- saveCurX = state->getCurX();
- saveCurY = state->getCurY();
- ctm = state->getCTM();
- memcpy(saveCTM, ctm, 6 * sizeof(double));
- state->setCTM(1, 0, 0, 1, x1, y1);
- font->getCharPath(state, code, u, uLen);
- stroke(state);
- state->clearPath();
- state->setCTM(saveCTM[0], saveCTM[1], saveCTM[2], saveCTM[3],
- saveCTM[4], saveCTM[5]);
- state->moveTo(saveCurX, saveCurY);
- } else {
- // can't stroke the outline, so just fill it using the stroke
- // color
- state->getStrokeRGB(&rgb);
- if (reverseVideo) {
- rgb.r = 1 - rgb.r;
- rgb.g = 1 - rgb.g;
- rgb.b = 1 - rgb.b;
- }
- font->drawChar(state, pixmap, pixmapW, pixmapH, strokeGC, &rgb,
- x1, y1, dx1, dy1, code, u, uLen);
- }
- }
-
-#if 0 //~ unimplemented: clipping to char path
- // clip
- if (render & 4) {
- }
-#endif
-}
-
-GBool XOutputDev::beginType3Char(GfxState *state,
- CharCode code, Unicode *u, int uLen) {
- Ref *fontID;
- double *ctm, *bbox;
- GfxRGB color;
- T3FontCache *t3Font;
- T3GlyphStack *t3gs;
- double x1, y1, xMin, yMin, xMax, yMax, xt, yt;
- int i, j;
-
- if (!gfxFont) {
- return gFalse;
- }
- fontID = gfxFont->getID();
- ctm = state->getCTM();
- state->transform(0, 0, &xt, &yt);
-
- // is it the first (MRU) font in the cache?
- if (!(nT3Fonts > 0 &&
- t3FontCache[0]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3]))) {
-
- // is the font elsewhere in the cache?
- for (i = 1; i < nT3Fonts; ++i) {
- if (t3FontCache[i]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3])) {
- t3Font = t3FontCache[i];
- for (j = i; j > 0; --j) {
- t3FontCache[j] = t3FontCache[j - 1];
- }
- t3FontCache[0] = t3Font;
- break;
- }
- }
- if (i >= nT3Fonts) {
-
- // create new entry in the font cache
- if (nT3Fonts == xOutT3FontCacheSize) {
- delete t3FontCache[nT3Fonts - 1];
- --nT3Fonts;
- }
- for (j = nT3Fonts; j > 0; --j) {
- t3FontCache[j] = t3FontCache[j - 1];
- }
- ++nT3Fonts;
- bbox = gfxFont->getFontBBox();
- if (bbox[0] == 0 && bbox[1] == 0 && bbox[2] == 0 && bbox[3] == 0) {
- // broken bounding box -- just take a guess
- xMin = xt - 5;
- xMax = xMin + 30;
- yMax = yt + 15;
- yMin = yMax - 45;
- } else {
- state->transform(bbox[0], bbox[1], &x1, &y1);
- xMin = xMax = x1;
- yMin = yMax = y1;
- state->transform(bbox[0], bbox[3], &x1, &y1);
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
- state->transform(bbox[2], bbox[1], &x1, &y1);
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
- state->transform(bbox[2], bbox[3], &x1, &y1);
- if (x1 < xMin) {
- xMin = x1;
- } else if (x1 > xMax) {
- xMax = x1;
- }
- if (y1 < yMin) {
- yMin = y1;
- } else if (y1 > yMax) {
- yMax = y1;
- }
- }
- t3FontCache[0] = new T3FontCache(fontID, ctm[0], ctm[1], ctm[2], ctm[3],
- (int)floor(xMin - xt),
- (int)floor(yMin - yt),
- (int)ceil(xMax) - (int)floor(xMin) + 3,
- (int)ceil(yMax) - (int)floor(yMin) + 3,
- display, visual, depth, pixmap);
- }
- }
- t3Font = t3FontCache[0];
-
- // is the glyph in the cache?
- i = (code & (t3Font->cacheSets - 1)) * t3Font->cacheAssoc;
- for (j = 0; j < t3Font->cacheAssoc; ++j) {
- if ((t3Font->cacheTags[i+j].mru & 0x8000) &&
- t3Font->cacheTags[i+j].code == code) {
- state->getFillRGB(&color);
- if (reverseVideo) {
- color.r = 1 - color.r;
- color.g = 1 - color.g;
- color.b = 1 - color.b;
- }
- text->addChar(state, 0, 0,
- t3Font->cacheTags[i+j].wx, t3Font->cacheTags[i+j].wy,
- u, uLen);
- drawType3Glyph(t3Font, &t3Font->cacheTags[i+j],
- t3Font->cacheData + (i+j) * t3Font->glyphSize,
- xt, yt, &color);
- return gTrue;
- }
- }
-
- // push a new Type 3 glyph record
- t3gs = new T3GlyphStack();
- t3gs->next = t3GlyphStack;
- t3GlyphStack = t3gs;
- t3GlyphStack->cacheable = gFalse;
- t3GlyphStack->code = code;
- t3GlyphStack->cache = t3Font;
- t3GlyphStack->cacheIdx = i;
- t3GlyphStack->x = xt;
- t3GlyphStack->y = yt;
- t3GlyphStack->u = u;
- t3GlyphStack->uLen = uLen;
-
- return gFalse;
-}
-
-void XOutputDev::endType3Char(GfxState *state) {
- XImage *image;
- Guchar *p;
- int x, y;
- Gulong pixel;
- double alpha;
- T3GlyphStack *t3gs;
- double *ctm;
-
- if (t3GlyphStack->cacheable) {
- image = t3GlyphStack->cache->image;
- XGetSubImage(display, pixmap, 0, 0,
- t3GlyphStack->cache->glyphW, t3GlyphStack->cache->glyphH,
- (1 << depth) - 1, ZPixmap, image, 0, 0);
- p = t3GlyphStack->cacheData;
- for (y = 0; y < t3GlyphStack->cache->glyphH; ++y) {
- for (x = 0; x < t3GlyphStack->cache->glyphW; ++x) {
- pixel = XGetPixel(image, x, y);
- if (trueColor) {
- alpha = (double)((pixel >> rShift) & rMul) / (double)rMul;
- } else {
- alpha = redMap[pixel & 0xff];
- }
- if (alpha <= 0.2) {
- *p++ = 4;
- } else if (alpha <= 0.4) {
- *p++ = 3;
- } else if (alpha <= 0.6) {
- *p++ = 2;
- } else if (alpha <= 0.8) {
- *p++ = 1;
- } else {
- *p++ = 0;
- }
- }
- }
- XDestroyRegion(clipRegion);
- XFreeGC(display, strokeGC);
- XFreeGC(display, fillGC);
- pixmapW = t3GlyphStack->origPixmapW;
- pixmapH = t3GlyphStack->origPixmapH;
- pixmap = t3GlyphStack->origPixmap;
- strokeGC = t3GlyphStack->origStrokeGC;
- fillGC = t3GlyphStack->origFillGC;
- clipRegion = t3GlyphStack->origClipRegion;
- drawType3Glyph(t3GlyphStack->cache,
- t3GlyphStack->cacheTag, t3GlyphStack->cacheData,
- t3GlyphStack->x, t3GlyphStack->y, &t3GlyphStack->color);
- // the CTM must be restored here in order for TextPage::addChar to
- // work correctly
- ctm = state->getCTM();
- state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3],
- t3GlyphStack->origCTM4, t3GlyphStack->origCTM5);
- }
- text->addChar(state, 0, 0, t3GlyphStack->wx, t3GlyphStack->wy,
- t3GlyphStack->u, t3GlyphStack->uLen);
- t3gs = t3GlyphStack;
- t3GlyphStack = t3gs->next;
- delete t3gs;
-}
-
-void XOutputDev::drawType3Glyph(T3FontCache *t3Font,
- T3FontCacheTag *tag, Guchar *data,
- double x, double y, GfxRGB *color) {
- XImage *image;
- XColor xcolor;
- GfxRGB bg, rgb;
- Gulong map[5];
- Gulong pixel;
- Guchar *p;
- int x0, y0, w0, h0, x1, y1;
- int ix, iy;
-
- // compute: (x0,y0) = position in destination pixmap
- // (x1,y1) = position in the XImage
- // (w0,h0) = size of XImage transfer
- x0 = xoutRound(x + t3Font->glyphX);
- y0 = xoutRound(y + t3Font->glyphY);
- x1 = 0;
- y1 = 0;
- w0 = t3Font->glyphW;
- h0 = t3Font->glyphH;
- if (x0 < 0) {
- x1 = -x0;
- w0 += x0;
- x0 = 0;
- }
- if (x0 + w0 > pixmapW) {
- w0 = pixmapW - x0;
- }
- if (w0 <= 0) {
- return;
- }
- if (y0 < 0) {
- y1 = -y0;
- h0 += y0;
- y0 = 0;
- }
- if (y0 + h0 > pixmapH) {
- h0 = pixmapH - y0;
- }
- if (h0 <= 0) {
- return;
- }
-
- image = t3Font->image;
- XGetSubImage(display, pixmap, x0, y0, w0, h0,
- (1 << depth) - 1, ZPixmap, image, x1, y1);
- xcolor.pixel = XGetPixel(image, t3Font->glyphW / 2, t3Font->glyphH / 2);
- XQueryColor(display, colormap, &xcolor);
- bg.r = xcolor.red / 65535.0;
- bg.g = xcolor.green / 65535.0;
- bg.b = xcolor.blue / 65535.0;
- rgb.r = 0.25 * (color->r + 3 * bg.r);
- rgb.g = 0.25 * (color->g + 3 * bg.g);
- rgb.b = 0.25 * (color->b + 3 * bg.b);
- map[1] = findColor(&rgb);
- rgb.r = 0.5 * (color->r + bg.r);
- rgb.g = 0.5 * (color->g + bg.g);
- rgb.b = 0.5 * (color->b + bg.b);
- map[2] = findColor(&rgb);
- rgb.r = 0.25 * (3 * color->r + bg.r);
- rgb.g = 0.25 * (3 * color->g + bg.g);
- rgb.b = 0.25 * (3 * color->b + bg.b);
- map[3] = findColor(&rgb);
- map[4] = findColor(color);
- p = data;
- for (iy = 0; iy < t3Font->glyphH; ++iy) {
- for (ix = 0; ix < t3Font->glyphW; ++ix) {
- pixel = *p++;
- if (pixel > 0) {
- XPutPixel(image, ix, iy, map[pixel]);
- }
- }
- }
- XPutImage(display, pixmap, fillGC, image, x1, y1, x0, y0, w0, h0);
-}
-
-void XOutputDev::type3D0(GfxState *state, double wx, double wy) {
- t3GlyphStack->wx = wx;
- t3GlyphStack->wy = wy;
-}
-
-void XOutputDev::type3D1(GfxState *state, double wx, double wy,
- double llx, double lly, double urx, double ury) {
- GfxColor fgColor;
- XGCValues gcValues;
- XRectangle rect;
- double *ctm;
- T3FontCache *t3Font;
- int i, j;
-
- // allocate a cache entry
- t3GlyphStack->cacheable = gTrue;
- t3Font = t3GlyphStack->cache;
- i = t3GlyphStack->cacheIdx;
- for (j = 0; j < t3Font->cacheAssoc; ++j) {
- if ((t3Font->cacheTags[i+j].mru & 0x7fff) == t3Font->cacheAssoc - 1) {
- t3Font->cacheTags[i+j].mru = 0x8000;
- t3Font->cacheTags[i+j].code = t3GlyphStack->code;
- t3GlyphStack->cacheTag = &t3Font->cacheTags[i+j];
- t3GlyphStack->cacheData = t3Font->cacheData + (i+j) * t3Font->glyphSize;
- } else {
- ++t3Font->cacheTags[i+j].mru;
- }
- }
- t3GlyphStack->wx = wx;
- t3GlyphStack->wy = wy;
- t3GlyphStack->cacheTag->wx = wx;
- t3GlyphStack->cacheTag->wy = wy;
-
- // prepare to rasterize the glyph
- //~ do we need to handle both fill and stroke color?
- state->getFillRGB(&t3GlyphStack->color);
- if (reverseVideo) {
- t3GlyphStack->color.r = 1 - t3GlyphStack->color.r;
- t3GlyphStack->color.g = 1 - t3GlyphStack->color.g;
- t3GlyphStack->color.b = 1 - t3GlyphStack->color.b;
- }
- fgColor.c[0] = reverseVideo ? 1 : 0;
- state->setFillColorSpace(new GfxDeviceGrayColorSpace());
- state->setFillColor(&fgColor);
- state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
- state->setStrokeColor(&fgColor);
- t3GlyphStack->origPixmapW = pixmapW;
- t3GlyphStack->origPixmapH = pixmapH;
- t3GlyphStack->origPixmap = pixmap;
- t3GlyphStack->origStrokeGC = strokeGC;
- t3GlyphStack->origFillGC = fillGC;
- t3GlyphStack->origClipRegion = clipRegion;
- pixmapW = t3GlyphStack->cache->glyphW;
- pixmapH = t3GlyphStack->cache->glyphH;
- pixmap = t3GlyphStack->cache->pixmap;
- gcValues.foreground = BlackPixel(display, screenNum);
- gcValues.background = WhitePixel(display, screenNum);
- gcValues.line_width = 0;
- gcValues.line_style = LineSolid;
- strokeGC = XCreateGC(display, pixmap,
- GCForeground | GCBackground | GCLineWidth | GCLineStyle,
- &gcValues);
- updateLineAttrs(state, gTrue);
- gcValues.foreground = WhitePixel(display, screenNum);
- fillGC = XCreateGC(display, pixmap,
- GCForeground | GCBackground | GCLineWidth | GCLineStyle,
- &gcValues);
- XFillRectangle(display, pixmap, fillGC, 0, 0, pixmapW, pixmapH);
- XSetForeground(display, fillGC, BlackPixel(display, screenNum));
- clipRegion = XCreateRegion();
- rect.x = rect.y = 0;
- rect.width = pixmapW;
- rect.height = pixmapH;
- XUnionRectWithRegion(&rect, clipRegion, clipRegion);
- XSetRegion(display, strokeGC, clipRegion);
- XSetRegion(display, fillGC, clipRegion);
- ctm = state->getCTM();
- t3GlyphStack->origCTM4 = ctm[4];
- t3GlyphStack->origCTM5 = ctm[5];
- state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3],
- -t3GlyphStack->cache->glyphX, -t3GlyphStack->cache->glyphY);
-}
-
-inline Gulong XOutputDev::findColor(GfxRGB *x, GfxRGB *err) {
- double gray;
- int r, g, b;
- Gulong pixel;
-
- if (trueColor) {
- r = xoutRound(x->r * rMul);
- g = xoutRound(x->g * gMul);
- b = xoutRound(x->b * bMul);
- pixel = ((Gulong)r << rShift) +
- ((Gulong)g << gShift) +
- ((Gulong)b << bShift);
- err->r = x->r - (double)r / rMul;
- err->g = x->g - (double)g / gMul;
- err->b = x->b - (double)b / bMul;
- } else if (numColors == 1) {
- gray = 0.299 * x->r + 0.587 * x->g + 0.114 * x->b;
- if (gray < 0.5) {
- pixel = colors[0];
- err->r = x->r;
- err->g = x->g;
- err->b = x->b;
- } else {
- pixel = colors[1];
- err->r = x->r - 1;
- err->g = x->g - 1;
- err->b = x->b - 1;
- }
- } else {
- r = xoutRound(x->r * (numColors - 1));
- g = xoutRound(x->g * (numColors - 1));
- b = xoutRound(x->b * (numColors - 1));
- pixel = colors[(r * numColors + g) * numColors + b];
- err->r = x->r - (double)r / (numColors - 1);
- err->g = x->g - (double)g / (numColors - 1);
- err->b = x->b - (double)b / (numColors - 1);
- }
- return pixel;
-}
-
-Gulong XOutputDev::findColor(GfxRGB *rgb) {
- int r, g, b;
- double gray;
- Gulong pixel;
-
- if (trueColor) {
- r = xoutRound(rgb->r * rMul);
- g = xoutRound(rgb->g * gMul);
- b = xoutRound(rgb->b * bMul);
- pixel = ((Gulong)r << rShift) +
- ((Gulong)g << gShift) +
- ((Gulong)b << bShift);
- } else if (numColors == 1) {
- gray = 0.299 * rgb->r + 0.587 * rgb->g + 0.114 * rgb->b;
- if (gray < 0.5)
- pixel = colors[0];
- else
- pixel = colors[1];
- } else {
- r = xoutRound(rgb->r * (numColors - 1));
- g = xoutRound(rgb->g * (numColors - 1));
- b = xoutRound(rgb->b * (numColors - 1));
-#if 0 // this makes things worse as often as better
- // even a very light color shouldn't map to white
- if (r == numColors - 1 && g == numColors - 1 && b == numColors - 1) {
- if (color->getR() < 0.95)
- --r;
- if (color->getG() < 0.95)
- --g;
- if (color->getB() < 0.95)
- --b;
- }
-#endif
- pixel = colors[(r * numColors + g) * numColors + b];
- }
- return pixel;
-}
-
-void XOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
- int width, int height, GBool invert,
- GBool inlineImg) {
- ImageStream *imgStr;
- XImage *image;
- double *ctm;
- GBool rot;
- double xScale, yScale, xShear, yShear;
- int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
- int ulx, uly, llx, lly, urx, ury, lrx, lry;
- int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
- int bx0, by0, bx1, by1, bw, bh;
- int cx0, cy0, cx1, cy1, cw, ch;
- int yp, yq, yt, yStep, lastYStep;
- int xp, xq, xt, xStep, xSrc;
- GfxRGB rgb;
- Guchar *pixBuf;
- int imgPix;
- double alpha;
- XColor xcolor;
- Gulong lastPixel;
- GfxRGB rgb2;
- double r0, g0, b0, r1, g1, b1;
- Gulong pix;
- Guchar *p;
- int x, y, x1, y1, x2, y2;
- int n, m, i, j;
-
- // get CTM, check for singular matrix
- ctm = state->getCTM();
- if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
- error(-1, "Singular CTM in drawImage");
- if (inlineImg) {
- j = height * ((width + 7) / 8);
- str->reset();
- for (i = 0; i < j; ++i) {
- str->getChar();
- }
- str->close();
- }
- return;
- }
-
- // compute scale, shear, rotation, translation parameters
- rot = fabs(ctm[1]) > fabs(ctm[0]);
- if (rot) {
- xScale = -ctm[1];
- yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
- xShear = ctm[3] / yScale;
- yShear = -ctm[0] / ctm[1];
- } else {
- xScale = ctm[0];
- yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
- xShear = -ctm[2] / yScale;
- yShear = ctm[1] / ctm[0];
- }
- tx = xoutRound(ctm[2] + ctm[4]);
- ty = xoutRound(ctm[3] + ctm[5]);
- // use ceil() to avoid gaps between "striped" images
- scaledWidth = (int)ceil(fabs(xScale));
- xSign = (xScale < 0) ? -1 : 1;
- scaledHeight = (int)ceil(fabs(yScale));
- ySign = (yScale < 0) ? -1 : 1;
-
- // compute corners in device space
- ulx1 = 0;
- uly1 = 0;
- urx1 = xSign * (scaledWidth - 1);
- ury1 = xoutRound(yShear * urx1);
- llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
- lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
- lrx1 = xSign * (scaledWidth - 1) +
- xoutRound(xShear * ySign * (scaledHeight - 1));
- lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
- if (rot) {
- ulx = tx + uly1; uly = ty - ulx1;
- urx = tx + ury1; ury = ty - urx1;
- llx = tx + lly1; lly = ty - llx1;
- lrx = tx + lry1; lry = ty - lrx1;
- } else {
- ulx = tx + ulx1; uly = ty + uly1;
- urx = tx + urx1; ury = ty + ury1;
- llx = tx + llx1; lly = ty + lly1;
- lrx = tx + lrx1; lry = ty + lry1;
- }
-
- // bounding box:
- // (bx0, by0) = upper-left corner
- // (bx1, by1) = lower-right corner
- // (bw, bh) = size
- bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
- : (llx < lrx) ? llx : lrx
- : (urx < llx) ? (urx < lrx) ? urx : lrx
- : (llx < lrx) ? llx : lrx;
- bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
- : (llx > lrx) ? llx : lrx
- : (urx > llx) ? (urx > lrx) ? urx : lrx
- : (llx > lrx) ? llx : lrx;
- by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
- : (lly < lry) ? lly : lry
- : (ury < lly) ? (ury < lry) ? ury : lry
- : (lly < lry) ? lly : lry;
- by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
- : (lly > lry) ? lly : lry
- : (ury > lly) ? (ury > lry) ? ury : lry
- : (lly > lry) ? lly : lry;
- bw = bx1 - bx0 + 1;
- bh = by1 - by0 + 1;
-
- // Bounding box clipped to pixmap, i.e., "valid" rectangle:
- // (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
- // (cx1, cy1) = upper-left corner of valid rectangle in XImage
- // (cw, ch) = size of valid rectangle
- // These values will be used to transfer the XImage from/to the
- // Pixmap.
- cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
- if (bx0 < 0) {
- cx0 = 0;
- cx1 = -bx0;
- cw += bx0;
- } else {
- cx0 = bx0;
- cx1 = 0;
- }
- ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
- if (by0 < 0) {
- cy0 = 0;
- cy1 = -by0;
- ch += by0;
- } else {
- cy0 = by0;
- cy1 = 0;
- }
-
- // check for tiny (zero width or height) images
- // and off-page images
- if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
- if (inlineImg) {
- j = height * ((width + 7) / 8);
- str->reset();
- for (i = 0; i < j; ++i) {
- str->getChar();
- }
- str->close();
- }
- return;
- }
-
- // compute Bresenham parameters for x and y scaling
- yp = height / scaledHeight;
- yq = height % scaledHeight;
- xp = width / scaledWidth;
- xq = width % scaledWidth;
-
- // allocate pixel buffer
- pixBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
-
- // allocate XImage and read from page pixmap
- image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
- image->data = (char *)gmalloc(bh * image->bytes_per_line);
- XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
- image, cx1, cy1);
-
- // get mask color
- state->getFillRGB(&rgb);
- if (reverseVideo) {
- rgb.r = 1 - rgb.r;
- rgb.g = 1 - rgb.g;
- rgb.b = 1 - rgb.b;
- }
- r0 = rgb.r;
- g0 = rgb.g;
- b0 = rgb.b;
-
- // initialize background color
- // (the specific pixel value doesn't matter here, as long as
- // r1,g1,b1 correspond correctly to lastPixel)
- xcolor.pixel = lastPixel = 0;
- XQueryColor(display, colormap, &xcolor);
- r1 = (double)xcolor.red / 65535.0;
- g1 = (double)xcolor.green / 65535.0;
- b1 = (double)xcolor.blue / 65535.0;
-
- // initialize the image stream
- imgStr = new ImageStream(str, width, 1, 1);
- imgStr->reset();
-
- // init y scale Bresenham
- yt = 0;
- lastYStep = 1;
-
- for (y = 0; y < scaledHeight; ++y) {
-
- // y scale Bresenham
- yStep = yp;
- yt += yq;
- if (yt >= scaledHeight) {
- yt -= scaledHeight;
- ++yStep;
- }
-
- // read row(s) from image
- n = (yp > 0) ? yStep : lastYStep;
- if (n > 0) {
- p = pixBuf;
- for (i = 0; i < n; ++i) {
- memcpy(p, imgStr->getLine(), width);
- if (invert) {
- for (j = 0; j < width; ++j) {
- p[j] ^= 1;
- }
- }
- p += width;
- }
- }
- lastYStep = yStep;
-
- // init x scale Bresenham
- xt = 0;
- xSrc = 0;
-
- for (x = 0; x < scaledWidth; ++x) {
-
- // x scale Bresenham
- xStep = xp;
- xt += xq;
- if (xt >= scaledWidth) {
- xt -= scaledWidth;
- ++xStep;
- }
-
- // x shear
- x1 = xSign * x + xoutRound(xShear * ySign * y);
-
- // y shear
- y1 = ySign * y + xoutRound(yShear * x1);
-
- // rotation
- if (rot) {
- x2 = y1;
- y2 = -x1;
- } else {
- x2 = x1;
- y2 = y1;
- }
-
- // compute the filtered pixel at (x,y) after the
- // x and y scaling operations
- n = yStep > 0 ? yStep : 1;
- m = xStep > 0 ? xStep : 1;
- p = pixBuf + xSrc;
- imgPix = 0;
- for (i = 0; i < n; ++i) {
- for (j = 0; j < m; ++j) {
- imgPix += *p++;
- }
- p += width - m;
- }
-
- // x scale Bresenham
- xSrc += xStep;
-
- // blend image pixel with background
- alpha = (double)imgPix / (double)(n * m);
- xcolor.pixel = XGetPixel(image, tx + x2 - bx0, ty + y2 - by0);
- if (xcolor.pixel != lastPixel) {
- XQueryColor(display, colormap, &xcolor);
- r1 = (double)xcolor.red / 65535.0;
- g1 = (double)xcolor.green / 65535.0;
- b1 = (double)xcolor.blue / 65535.0;
- lastPixel = xcolor.pixel;
- }
- rgb2.r = r0 * (1 - alpha) + r1 * alpha;
- rgb2.g = g0 * (1 - alpha) + g1 * alpha;
- rgb2.b = b0 * (1 - alpha) + b1 * alpha;
- pix = findColor(&rgb2);
-
- // set pixel
- XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
- }
- }
-
- // blit the image into the pixmap
- XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);
-
- // free memory
- delete imgStr;
- gfree(pixBuf);
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
-}
-
-void XOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
- int width, int height, GfxImageColorMap *colorMap,
- int *maskColors, GBool inlineImg) {
- ImageStream *imgStr;
- XImage *image;
- int nComps, nVals, nBits;
- GBool dither;
- double *ctm;
- GBool rot;
- double xScale, yScale, xShear, yShear;
- int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
- int ulx, uly, llx, lly, urx, ury, lrx, lry;
- int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
- int bx0, by0, bx1, by1, bw, bh;
- int cx0, cy0, cx1, cy1, cw, ch;
- int yp, yq, yt, yStep, lastYStep;
- int xp, xq, xt, xStep, xSrc;
- GfxRGB *pixBuf;
- Guchar *alphaBuf;
- Guchar pixBuf2[gfxColorMaxComps];
- GfxRGB color2, err, errRight;
- GfxRGB *errDown;
- double r0, g0, b0, alpha, mul;
- Gulong pix;
- GfxRGB *p;
- Guchar *q, *p2;
- GBool oneBitMode;
- GfxRGB oneBitRGB[2];
- int x, y, x1, y1, x2, y2;
- int n, m, i, j, k;
-
- // image parameters
- nComps = colorMap->getNumPixelComps();
- nVals = width * nComps;
- nBits = colorMap->getBits();
- dither = nComps > 1 || nBits > 1;
-
- // get CTM, check for singular matrix
- ctm = state->getCTM();
- if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
- error(-1, "Singular CTM in drawImage");
- if (inlineImg) {
- str->reset();
- j = height * ((nVals * nBits + 7) / 8);
- for (i = 0; i < j; ++i) {
- str->getChar();
- }
- str->close();
- }
- return;
- }
-
- // compute scale, shear, rotation, translation parameters
- rot = fabs(ctm[1]) > fabs(ctm[0]);
- if (rot) {
- xScale = -ctm[1];
- yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
- xShear = ctm[3] / yScale;
- yShear = -ctm[0] / ctm[1];
- } else {
- xScale = ctm[0];
- yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
- xShear = -ctm[2] / yScale;
- yShear = ctm[1] / ctm[0];
- }
- tx = xoutRound(ctm[2] + ctm[4]);
- ty = xoutRound(ctm[3] + ctm[5]);
- if (xScale < 0) {
- // this is the right edge which needs to be (left + width - 1)
- --tx;
- }
- if (yScale < 0) {
- // this is the bottom edge which needs to be (top + height - 1)
- --ty;
- }
- // use ceil() to avoid gaps between "striped" images
- scaledWidth = (int)ceil(fabs(xScale));
- xSign = (xScale < 0) ? -1 : 1;
- scaledHeight = (int)ceil(fabs(yScale));
- ySign = (yScale < 0) ? -1 : 1;
-
- // compute corners in device space
- ulx1 = 0;
- uly1 = 0;
- urx1 = xSign * (scaledWidth - 1);
- ury1 = xoutRound(yShear * urx1);
- llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
- lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
- lrx1 = xSign * (scaledWidth - 1) +
- xoutRound(xShear * ySign * (scaledHeight - 1));
- lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
- if (rot) {
- ulx = tx + uly1; uly = ty - ulx1;
- urx = tx + ury1; ury = ty - urx1;
- llx = tx + lly1; lly = ty - llx1;
- lrx = tx + lry1; lry = ty - lrx1;
- } else {
- ulx = tx + ulx1; uly = ty + uly1;
- urx = tx + urx1; ury = ty + ury1;
- llx = tx + llx1; lly = ty + lly1;
- lrx = tx + lrx1; lry = ty + lry1;
- }
-
- // bounding box:
- // (bx0, by0) = upper-left corner
- // (bx1, by1) = lower-right corner
- // (bw, bh) = size
- bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
- : (llx < lrx) ? llx : lrx
- : (urx < llx) ? (urx < lrx) ? urx : lrx
- : (llx < lrx) ? llx : lrx;
- bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
- : (llx > lrx) ? llx : lrx
- : (urx > llx) ? (urx > lrx) ? urx : lrx
- : (llx > lrx) ? llx : lrx;
- by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
- : (lly < lry) ? lly : lry
- : (ury < lly) ? (ury < lry) ? ury : lry
- : (lly < lry) ? lly : lry;
- by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
- : (lly > lry) ? lly : lry
- : (ury > lly) ? (ury > lry) ? ury : lry
- : (lly > lry) ? lly : lry;
- bw = bx1 - bx0 + 1;
- bh = by1 - by0 + 1;
-
- // Bounding box clipped to pixmap, i.e., "valid" rectangle:
- // (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
- // (cx1, cy1) = upper-left corner of valid rectangle in XImage
- // (cw, ch) = size of valid rectangle
- // These values will be used to transfer the XImage from/to the
- // Pixmap.
- cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
- if (bx0 < 0) {
- cx0 = 0;
- cx1 = -bx0;
- cw += bx0;
- } else {
- cx0 = bx0;
- cx1 = 0;
- }
- ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
- if (by0 < 0) {
- cy0 = 0;
- cy1 = -by0;
- ch += by0;
- } else {
- cy0 = by0;
- cy1 = 0;
- }
-
- // check for tiny (zero width or height) images
- // and off-page images
- if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
- if (inlineImg) {
- str->reset();
- j = height * ((nVals * nBits + 7) / 8);
- for (i = 0; i < j; ++i)
- str->getChar();
- str->close();
- }
- return;
- }
-
- // compute Bresenham parameters for x and y scaling
- yp = height / scaledHeight;
- yq = height % scaledHeight;
- xp = width / scaledWidth;
- xq = width % scaledWidth;
-
- // allocate pixel buffer
- pixBuf = (GfxRGB *)gmalloc((yp + 1) * width * sizeof(GfxRGB));
- if (maskColors) {
- alphaBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
- } else {
- alphaBuf = NULL;
- }
-
- // allocate XImage
- image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
- image->data = (char *)gmalloc(bh * image->bytes_per_line);
-
- // if the transform is anything other than a 0/90/180/270 degree
- // rotation/flip, or if there is color key masking, read the
- // backgound pixmap to fill in the corners
- if (!((ulx == llx && uly == ury) ||
- (uly == lly && ulx == urx)) ||
- maskColors) {
- XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
- image, cx1, cy1);
- }
-
- // allocate error diffusion accumulators
- if (dither) {
- errDown = (GfxRGB *)gmalloc(bw * sizeof(GfxRGB));
- for (j = 0; j < bw; ++j) {
- errDown[j].r = errDown[j].g = errDown[j].b = 0;
- }
- } else {
- errDown = NULL;
- }
-
- // optimize the one-bit-deep image case
- if ((oneBitMode = nComps == 1 && nBits == 1)) {
- pixBuf2[0] = 0;
- colorMap->getRGB(pixBuf2, &oneBitRGB[0]);
- pixBuf2[0] = 1;
- colorMap->getRGB(pixBuf2, &oneBitRGB[1]);
- }
-
- // initialize the image stream
- imgStr = new ImageStream(str, width, nComps, nBits);
- imgStr->reset();
-
- // init y scale Bresenham
- yt = 0;
- lastYStep = 1;
-
- for (y = 0; y < scaledHeight; ++y) {
-
- // initialize error diffusion accumulator
- errRight.r = errRight.g = errRight.b = 0;
-
- // y scale Bresenham
- yStep = yp;
- yt += yq;
- if (yt >= scaledHeight) {
- yt -= scaledHeight;
- ++yStep;
- }
-
- // read row(s) from image
- n = (yp > 0) ? yStep : lastYStep;
- if (n > 0) {
- p = pixBuf;
- q = alphaBuf;
- for (i = 0; i < n; ++i) {
- p2 = imgStr->getLine();
- for (j = 0; j < width; ++j) {
- if (oneBitMode) {
- *p = oneBitRGB[*p2];
- } else {
- colorMap->getRGB(p2, p);
- }
- ++p;
- if (q) {
- *q = 1;
- for (k = 0; k < nComps; ++k) {
- if (p2[k] < maskColors[2*k] ||
- p2[k] > maskColors[2*k]) {
- *q = 0;
- break;
- }
- }
- ++q;
- }
- p2 += nComps;
- }
- }
- }
- lastYStep = yStep;
-
- // init x scale Bresenham
- xt = 0;
- xSrc = 0;
-
- for (x = 0; x < scaledWidth; ++x) {
-
- // x scale Bresenham
- xStep = xp;
- xt += xq;
- if (xt >= scaledWidth) {
- xt -= scaledWidth;
- ++xStep;
- }
-
- // x shear
- x1 = xSign * x + xoutRound(xShear * ySign * y);
-
- // y shear
- y1 = ySign * y + xoutRound(yShear * x1);
-
- // rotation
- if (rot) {
- x2 = y1;
- y2 = -x1;
- } else {
- x2 = x1;
- y2 = y1;
- }
-
- // compute the filtered pixel at (x,y) after the
- // x and y scaling operations
- n = yStep > 0 ? yStep : 1;
- m = xStep > 0 ? xStep : 1;
- p = pixBuf + xSrc;
- r0 = g0 = b0 = 0;
- q = alphaBuf ? alphaBuf + xSrc : (Guchar *)NULL;
- alpha = 0;
- for (i = 0; i < n; ++i) {
- for (j = 0; j < m; ++j) {
- r0 += p->r;
- g0 += p->g;
- b0 += p->b;
- ++p;
- if (q) {
- alpha += *q++;
- }
- }
- p += width - m;
- }
- mul = 1 / (double)(n * m);
- r0 *= mul;
- g0 *= mul;
- b0 *= mul;
- alpha *= mul;
-
- // x scale Bresenham
- xSrc += xStep;
-
- // compute pixel
- if (dither) {
- color2.r = r0 + errRight.r + errDown[tx + x2 - bx0].r;
- if (color2.r > 1) {
- color2.r = 1;
- } else if (color2.r < 0) {
- color2.r = 0;
- }
- color2.g = g0 + errRight.g + errDown[tx + x2 - bx0].g;
- if (color2.g > 1) {
- color2.g = 1;
- } else if (color2.g < 0) {
- color2.g = 0;
- }
- color2.b = b0 + errRight.b + errDown[tx + x2 - bx0].b;
- if (color2.b > 1) {
- color2.b = 1;
- } else if (color2.b < 0) {
- color2.b = 0;
- }
- pix = findColor(&color2, &err);
- errRight.r = errDown[tx + x2 - bx0].r = err.r / 2;
- errRight.g = errDown[tx + x2 - bx0].g = err.g / 2;
- errRight.b = errDown[tx + x2 - bx0].b = err.b / 2;
- } else {
- color2.r = r0;
- color2.g = g0;
- color2.b = b0;
- pix = findColor(&color2, &err);
- }
-
- // set pixel
- //~ this should do a blend when 0 < alpha < 1
- if (alpha < 0.75) {
- XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
- }
- }
- }
-
- // blit the image into the pixmap
- XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);
-
- // free memory
- delete imgStr;
- gfree(pixBuf);
- if (maskColors) {
- gfree(alphaBuf);
- }
- gfree(image->data);
- image->data = NULL;
- XDestroyImage(image);
- gfree(errDown);
-}
-
-GBool XOutputDev::findText(Unicode *s, int len, GBool top, GBool bottom,
- int *xMin, int *yMin, int *xMax, int *yMax) {
- double xMin1, yMin1, xMax1, yMax1;
-
- xMin1 = (double)*xMin;
- yMin1 = (double)*yMin;
- xMax1 = (double)*xMax;
- yMax1 = (double)*yMax;
- if (text->findText(s, len, top, bottom, &xMin1, &yMin1, &xMax1, &yMax1)) {
- *xMin = xoutRound(xMin1);
- *xMax = xoutRound(xMax1);
- *yMin = xoutRound(yMin1);
- *yMax = xoutRound(yMax1);
- return gTrue;
- }
- return gFalse;
-}
-
-GString *XOutputDev::getText(int xMin, int yMin, int xMax, int yMax) {
- return text->getText((double)xMin, (double)yMin,
- (double)xMax, (double)yMax);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/XOutputDev.cpp
new file mode 100644
index 000000000..e8acbf66a
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XOutputDev.cpp
@@ -0,0 +1,3690 @@
+//========================================================================
+//
+// XOutputDev.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <string.h>
+#include <ctype.h>
+#include <math.h>
+#include "gmem.h"
+#include "gfile.h"
+#include "GString.h"
+#include "GList.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Link.h"
+#include "GfxState.h"
+#include "GfxFont.h"
+#include "UnicodeMap.h"
+#include "CharCodeToUnicode.h"
+#include "FontFile.h"
+#include "Error.h"
+#include "TextOutputDev.h"
+#include "XOutputDev.h"
+#if HAVE_T1LIB_H
+#include "T1Font.h"
+#endif
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+#include "FTFont.h"
+#endif
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+#include "TTFont.h"
+#endif
+
+#ifdef VMS
+#if (__VMS_VER < 70000000)
+extern "C" int unlink(char *filename);
+#endif
+#endif
+
+#ifdef XlibSpecificationRelease
+#if XlibSpecificationRelease < 5
+typedef char *XPointer;
+#endif
+#else
+typedef char *XPointer;
+#endif
+
+//------------------------------------------------------------------------
+// Constants and macros
+//------------------------------------------------------------------------
+
+#define xoutRound(x) ((int)(x + 0.5))
+
+#define maxCurveSplits 6 // max number of splits when recursively
+ // drawing Bezier curves
+
+//------------------------------------------------------------------------
+// Font substitutions
+//------------------------------------------------------------------------
+
+struct XOutFontSubst {
+ char *name;
+ double mWidth;
+};
+
+// index: {symbolic:12, fixed:8, serif:4, sans-serif:0} + bold*2 + italic
+static XOutFontSubst xOutSubstFonts[16] = {
+ {"Helvetica", 0.833},
+ {"Helvetica-Oblique", 0.833},
+ {"Helvetica-Bold", 0.889},
+ {"Helvetica-BoldOblique", 0.889},
+ {"Times-Roman", 0.788},
+ {"Times-Italic", 0.722},
+ {"Times-Bold", 0.833},
+ {"Times-BoldItalic", 0.778},
+ {"Courier", 0.600},
+ {"Courier-Oblique", 0.600},
+ {"Courier-Bold", 0.600},
+ {"Courier-BoldOblique", 0.600},
+ {"Symbol", 0.576},
+ {"Symbol", 0.576},
+ {"Symbol", 0.576},
+ {"Symbol", 0.576}
+};
+
+//------------------------------------------------------------------------
+
+static void outputToFile(void *stream, char *data, int len) {
+ fwrite(data, 1, len, (FILE *)stream);
+}
+
+//------------------------------------------------------------------------
+// XOutputFont
+//------------------------------------------------------------------------
+
+XOutputFont::XOutputFont(Ref *idA, double m11OrigA, double m12OrigA,
+ double m21OrigA, double m22OrigA,
+ double m11A, double m12A, double m21A, double m22A,
+ Display *displayA, XOutputDev *xOutA) {
+ id = *idA;
+ display = displayA;
+ xOut = xOutA;
+ m11Orig = m11OrigA;
+ m12Orig = m12OrigA;
+ m21Orig = m21OrigA;
+ m22Orig = m22OrigA;
+ m11 = m11A;
+ m12 = m12A;
+ m21 = m21A;
+ m22 = m22A;
+}
+
+XOutputFont::~XOutputFont() {
+}
+
+void XOutputFont::getCharPath(GfxState *state,
+ CharCode c, Unicode *u, int ulen) {
+}
+
+#if HAVE_T1LIB_H
+//------------------------------------------------------------------------
+// XOutputT1Font
+//------------------------------------------------------------------------
+
+XOutputT1Font::XOutputT1Font(Ref *idA, T1FontFile *fontFileA,
+ double m11OrigA, double m12OrigA,
+ double m21OrigA, double m22OrigA,
+ double m11A, double m12A,
+ double m21A, double m22A,
+ Display *displayA, XOutputDev *xOutA):
+ XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
+ m11A, m12A, m21A, m22A, displayA, xOutA)
+{
+ double matrix[4];
+
+ fontFile = fontFileA;
+
+ // create the transformed instance
+ matrix[0] = m11;
+ matrix[1] = -m12;
+ matrix[2] = m21;
+ matrix[3] = -m22;
+ font = new T1Font(fontFile, matrix);
+}
+
+XOutputT1Font::~XOutputT1Font() {
+ if (font) {
+ delete font;
+ }
+}
+
+GBool XOutputT1Font::isOk() {
+ return font != NULL;
+}
+
+void XOutputT1Font::updateGC(GC gc) {
+}
+
+void XOutputT1Font::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
+ GC gc, GfxRGB *rgb,
+ double x, double y, double dx, double dy,
+ CharCode c, Unicode *u, int uLen) {
+ font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
+ (int)(rgb->r * 65535), (int)(rgb->g * 65535),
+ (int)(rgb->b * 65535), c, u[0]);
+}
+
+void XOutputT1Font::getCharPath(GfxState *state,
+ CharCode c, Unicode *u, int uLen) {
+ font->getCharPath(c, u[0], state);
+}
+#endif // HAVE_T1LIB_H
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+//------------------------------------------------------------------------
+// XOutputFTFont
+//------------------------------------------------------------------------
+
+XOutputFTFont::XOutputFTFont(Ref *idA, FTFontFile *fontFileA,
+ double m11OrigA, double m12OrigA,
+ double m21OrigA, double m22OrigA,
+ double m11A, double m12A,
+ double m21A, double m22A,
+ Display *displayA, XOutputDev *xOutA):
+ XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
+ m11A, m12A, m21A, m22A, displayA, xOutA)
+{
+ double matrix[4];
+
+ fontFile = fontFileA;
+
+ // create the transformed instance
+ matrix[0] = m11;
+ matrix[1] = -m12;
+ matrix[2] = m21;
+ matrix[3] = -m22;
+ font = new FTFont(fontFile, matrix);
+}
+
+XOutputFTFont::~XOutputFTFont() {
+ if (font) {
+ delete font;
+ }
+}
+
+GBool XOutputFTFont::isOk() {
+ return font != NULL;
+}
+
+void XOutputFTFont::updateGC(GC gc) {
+}
+
+void XOutputFTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
+ GC gc, GfxRGB *rgb,
+ double x, double y, double dx, double dy,
+ CharCode c, Unicode *u, int uLen) {
+ font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
+ (int)(rgb->r * 65535), (int)(rgb->g * 65535),
+ (int)(rgb->b * 65535), c, uLen > 0 ? u[0] : 0);
+}
+
+void XOutputFTFont::getCharPath(GfxState *state,
+ CharCode c, Unicode *u, int uLen) {
+ font->getCharPath(c, u[0], state);
+}
+#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+//------------------------------------------------------------------------
+// XOutputTTFont
+//------------------------------------------------------------------------
+
+XOutputTTFont::XOutputTTFont(Ref *idA, TTFontFile *fontFileA,
+ double m11OrigA, double m12OrigA,
+ double m21OrigA, double m22OrigA,
+ double m11A, double m12A,
+ double m21A, double m22A,
+ Display *displayA, XOutputDev *xOutA):
+ XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
+ m11A, m12A, m21A, m22A, displayA, xOutA)
+{
+ double matrix[4];
+
+ fontFile = fontFileA;
+
+ // create the transformed instance
+ matrix[0] = m11;
+ matrix[1] = -m12;
+ matrix[2] = m21;
+ matrix[3] = -m22;
+ font = new TTFont(fontFile, matrix);
+}
+
+XOutputTTFont::~XOutputTTFont() {
+ if (font) {
+ delete font;
+ }
+}
+
+GBool XOutputTTFont::isOk() {
+ return font != NULL;
+}
+
+void XOutputTTFont::updateGC(GC gc) {
+}
+
+void XOutputTTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
+ GC gc, GfxRGB *rgb,
+ double x, double y, double dx, double dy,
+ CharCode c, Unicode *u, int uLen) {
+ font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
+ (int)(rgb->r * 65535), (int)(rgb->g * 65535),
+ (int)(rgb->b * 65535), c, u[0]);
+}
+#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+//------------------------------------------------------------------------
+// XOutputServer8BitFont
+//------------------------------------------------------------------------
+
+// Copy <fmt>, substituting <val> for one occurrence of "%s", into
+// <buf>.
+static void stringSubst(char *buf, int bufSize, char *fmt, char *val) {
+ char *p, *q;
+ int i;
+
+ i = 0;
+ p = fmt;
+ while (*p) {
+ if (p[0] == '%' && p[1] == 's') {
+ q = val;
+ while (*q && i < bufSize - 1) {
+ buf[i++] = *q++;
+ }
+ p += 2;
+ } else {
+ if (i < bufSize - 1) {
+ buf[i++] = *p;
+ }
+ ++p;
+ }
+ }
+ buf[i] = '\0';
+}
+
+XOutputServer8BitFont::XOutputServer8BitFont(Ref *idA, GString *xlfdFmt,
+ UnicodeMap *xUMapA,
+ CharCodeToUnicode *fontUMap,
+ double m11OrigA, double m12OrigA,
+ double m21OrigA, double m22OrigA,
+ double m11A, double m12A,
+ double m21A, double m22A,
+ Display *displayA,
+ XOutputDev *xOutA):
+ XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
+ m11A, m12A, m21A, m22A, displayA, xOutA)
+{
+ double size, ntm11, ntm12, ntm21, ntm22;
+ GBool rotated;
+ int startSize, sz;
+ char fontName[500], fontSize[100];
+ Unicode u;
+ char buf;
+ int i;
+
+ // compute size and normalized transform matrix
+ size = sqrt(m21*m21 + m22*m22);
+ ntm11 = m11 / size;
+ ntm12 = -m12 / size;
+ ntm21 = m21 / size;
+ ntm22 = -m22 / size;
+
+ // try to get a rotated font?
+ rotated = !(ntm11 > 0 && ntm22 > 0 &&
+ fabs(ntm11 / ntm22 - 1) < 0.2 &&
+ fabs(ntm12) < 0.01 &&
+ fabs(ntm21) < 0.01);
+
+ // open X font -- if font is not found (which means the server can't
+ // scale fonts), try progressively smaller and then larger sizes
+ startSize = (int)size;
+ if (rotated) {
+ sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
+ ntm11<0 ? "~" : "", fabs(ntm11 * size),
+ ntm12<0 ? "~" : "", fabs(ntm12 * size),
+ ntm21<0 ? "~" : "", fabs(ntm21 * size),
+ ntm22<0 ? "~" : "", fabs(ntm22 * size));
+ } else {
+ sprintf(fontSize, "%d", startSize);
+ }
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
+ xFont = XLoadQueryFont(display, fontName);
+ if (!xFont) {
+ for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
+ sprintf(fontSize, "%d", sz);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
+ if ((xFont = XLoadQueryFont(display, fontName)))
+ break;
+ }
+ if (!xFont) {
+ for (sz = startSize + 1; sz < startSize + 10; ++sz) {
+ sprintf(fontSize, "%d", sz);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
+ fontSize);
+ if ((xFont = XLoadQueryFont(display, fontName))) {
+ break;
+ }
+ }
+ if (!xFont) {
+ sprintf(fontSize, "%d", startSize);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
+ fontSize);
+ error(-1, "Failed to open font: '%s'", fontName);
+ return;
+ }
+ }
+ }
+
+ // Construct char code map.
+ xUMap = xUMapA;
+ for (i = 0; i < 256; ++i) {
+ if (fontUMap->mapToUnicode((CID)i, &u, 1) == 1 &&
+ xUMap->mapUnicode(u, &buf, 1) == 1) {
+ map[i] = buf & 0xff;
+ } else {
+ map[i] = 0;
+ }
+ }
+}
+
+XOutputServer8BitFont::~XOutputServer8BitFont() {
+ if (xFont) {
+ XFreeFont(display, xFont);
+ }
+}
+
+GBool XOutputServer8BitFont::isOk() {
+ return xFont != NULL;
+}
+
+void XOutputServer8BitFont::updateGC(GC gc) {
+ XSetFont(display, gc, xFont->fid);
+}
+
+void XOutputServer8BitFont::drawChar(GfxState *state, Pixmap pixmap,
+ int w, int h, GC gc, GfxRGB *rgb,
+ double x, double y, double dx, double dy,
+ CharCode c, Unicode *u, int uLen) {
+ Gushort c1;
+ char buf[8];
+ double dx1, dy1;
+ int m, n, i, j, k;
+
+ c1 = map[c];
+ if (c1 > 0) {
+ buf[0] = (char)c1;
+ XDrawString(display, pixmap, gc, xoutRound(x), xoutRound(y), buf, 1);
+ } else {
+ // substituted character, using more than one character
+ n = 0;
+ for (i = 0; i < uLen; ++i) {
+ n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
+ }
+ if (n > 0) {
+ dx1 = dx / n;
+ dy1 = dy / n;
+ k = 0;
+ for (i = 0; i < uLen; ++i) {
+ m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
+ for (j = 0; j < m; ++j) {
+ XDrawString(display, pixmap, gc,
+ xoutRound(x + k*dx1), xoutRound(y + k*dy1),
+ buf + j, 1);
+ ++k;
+ }
+ }
+ }
+ }
+}
+
+//------------------------------------------------------------------------
+// XOutputServer16BitFont
+//------------------------------------------------------------------------
+
+XOutputServer16BitFont::XOutputServer16BitFont(Ref *idA, GString *xlfdFmt,
+ UnicodeMap *xUMapA,
+ CharCodeToUnicode *fontUMap,
+ double m11OrigA,
+ double m12OrigA,
+ double m21OrigA,
+ double m22OrigA,
+ double m11A, double m12A,
+ double m21A, double m22A,
+ Display *displayA,
+ XOutputDev *xOutA):
+ XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
+ m11A, m12A, m21A, m22A, displayA, xOutA)
+{
+ double size, ntm11, ntm12, ntm21, ntm22;
+ GBool rotated;
+ int startSize, sz;
+ char fontName[500], fontSize[100];
+
+ xUMap = xUMapA;
+ xUMap->incRefCnt();
+
+ // compute size and normalized transform matrix
+ size = sqrt(m21*m21 + m22*m22);
+ ntm11 = m11 / size;
+ ntm12 = -m12 / size;
+ ntm21 = m21 / size;
+ ntm22 = -m22 / size;
+
+ // try to get a rotated font?
+ rotated = !(ntm11 > 0 && ntm22 > 0 &&
+ fabs(ntm11 / ntm22 - 1) < 0.2 &&
+ fabs(ntm12) < 0.01 &&
+ fabs(ntm21) < 0.01);
+
+ // open X font -- if font is not found (which means the server can't
+ // scale fonts), try progressively smaller and then larger sizes
+ startSize = (int)size;
+ if (rotated) {
+ sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
+ ntm11<0 ? "~" : "", fabs(ntm11 * size),
+ ntm12<0 ? "~" : "", fabs(ntm12 * size),
+ ntm21<0 ? "~" : "", fabs(ntm21 * size),
+ ntm22<0 ? "~" : "", fabs(ntm22 * size));
+ } else {
+ sprintf(fontSize, "%d", startSize);
+ }
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
+ xFont = XLoadQueryFont(display, fontName);
+ if (!xFont) {
+ for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
+ sprintf(fontSize, "%d", sz);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
+ if ((xFont = XLoadQueryFont(display, fontName)))
+ break;
+ }
+ if (!xFont) {
+ for (sz = startSize + 1; sz < startSize + 10; ++sz) {
+ sprintf(fontSize, "%d", sz);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
+ fontSize);
+ if ((xFont = XLoadQueryFont(display, fontName))) {
+ break;
+ }
+ }
+ if (!xFont) {
+ sprintf(fontSize, "%d", startSize);
+ stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
+ fontSize);
+ error(-1, "Failed to open font: '%s'", fontName);
+ return;
+ }
+ }
+ }
+}
+
+XOutputServer16BitFont::~XOutputServer16BitFont() {
+ xUMap->decRefCnt();
+ if (xFont) {
+ XFreeFont(display, xFont);
+ }
+}
+
+GBool XOutputServer16BitFont::isOk() {
+ return xFont != NULL;
+}
+
+void XOutputServer16BitFont::updateGC(GC gc) {
+ XSetFont(display, gc, xFont->fid);
+}
+
+void XOutputServer16BitFont::drawChar(GfxState *state, Pixmap pixmap,
+ int w, int h, GC gc, GfxRGB *rgb,
+ double x, double y, double dx, double dy,
+ CharCode c, Unicode *u, int uLen) {
+ char buf[16];
+ XChar2b c1;
+ double dx1, dy1;
+ int m, n, i, j, k;
+
+ n = 0;
+ for (i = 0; i < uLen; ++i) {
+ n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
+ }
+ if (n > 0) {
+ dx1 = dx / n;
+ dy1 = dy / n;
+ k = 0;
+ for (i = 0; i < uLen; ++i) {
+ m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
+ for (j = 0; j+1 < m; j += 2) {
+ c1.byte1 = buf[j];
+ c1.byte2 = buf[j+1];
+ XDrawString16(display, pixmap, gc,
+ xoutRound(x + k*dx1), xoutRound(y + k*dy1),
+ &c1, 1);
+ ++k;
+ }
+ }
+ } else if (c != 0) {
+ // some PDF files use CID 0, which is .notdef, so just ignore it
+ error(-1, "Unknown character (CID=%d Unicode=%04x)",
+ c, uLen > 0 ? u[0] : (Unicode)0);
+ }
+}
+
+//------------------------------------------------------------------------
+// XOutputFontCache
+//------------------------------------------------------------------------
+
+#if HAVE_T1LIB_H
+XOutputT1FontFile::~XOutputT1FontFile() {
+ delete fontFile;
+ if (tmpFileName) {
+ unlink(tmpFileName->getCString());
+ delete tmpFileName;
+ }
+}
+#endif
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+XOutputFTFontFile::~XOutputFTFontFile() {
+ delete fontFile;
+ if (tmpFileName) {
+ unlink(tmpFileName->getCString());
+ delete tmpFileName;
+ }
+}
+#endif
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+XOutputTTFontFile::~XOutputTTFontFile() {
+ delete fontFile;
+ if (tmpFileName) {
+ unlink(tmpFileName->getCString());
+ delete tmpFileName;
+ }
+}
+#endif
+
+XOutputFontCache::XOutputFontCache(Display *displayA, Guint depthA,
+ XOutputDev *xOutA,
+ FontRastControl t1libControlA,
+ FontRastControl freetypeControlA) {
+ display = displayA;
+ depth = depthA;
+ xOut = xOutA;
+
+#if HAVE_T1LIB_H
+ t1Engine = NULL;
+ t1libControl = t1libControlA;
+#endif
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ ftEngine = NULL;
+#endif
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ ttEngine = NULL;
+#endif
+#if HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H
+ freetypeControl = freetypeControlA;
+#endif
+
+ clear();
+}
+
+XOutputFontCache::~XOutputFontCache() {
+ delFonts();
+}
+
+void XOutputFontCache::startDoc(int screenNum, Visual *visual,
+ Colormap colormap, GBool trueColor,
+ int rMul, int gMul, int bMul,
+ int rShift, int gShift, int bShift,
+ Gulong *colors, int numColors) {
+ delFonts();
+ clear();
+
+#if HAVE_T1LIB_H
+ if (t1libControl != fontRastNone) {
+ t1Engine = new T1FontEngine(display, visual, depth, colormap,
+ t1libControl == fontRastAALow ||
+ t1libControl == fontRastAAHigh,
+ t1libControl == fontRastAAHigh);
+ if (t1Engine->isOk()) {
+ if (trueColor) {
+ t1Engine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
+ } else {
+ t1Engine->useColorCube(colors, numColors);
+ }
+ } else {
+ delete t1Engine;
+ t1Engine = NULL;
+ }
+ }
+#endif // HAVE_T1LIB_H
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ ftEngine = new FTFontEngine(display, visual, depth, colormap,
+ freetypeControl == fontRastAALow ||
+ freetypeControl == fontRastAAHigh);
+ if (ftEngine->isOk()) {
+ if (trueColor) {
+ ftEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
+ } else {
+ ftEngine->useColorCube(colors, numColors);
+ }
+ } else {
+ delete ftEngine;
+ ftEngine = NULL;
+ }
+ }
+#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ ttEngine = new TTFontEngine(display, visual, depth, colormap,
+ freetypeControl == fontRastAALow ||
+ freetypeControl == fontRastAAHigh);
+ if (ttEngine->isOk()) {
+ if (trueColor) {
+ ttEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
+ } else {
+ ttEngine->useColorCube(colors, numColors);
+ }
+ } else {
+ delete ttEngine;
+ ttEngine = NULL;
+ }
+ }
+#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+}
+
+void XOutputFontCache::delFonts() {
+ int i;
+
+ for (i = 0; i < nFonts; ++i) {
+ delete fonts[i];
+ }
+
+#if HAVE_T1LIB_H
+ // delete Type 1 font files
+ deleteGList(t1FontFiles, XOutputT1FontFile);
+ if (t1Engine) {
+ delete t1Engine;
+ }
+#endif
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ // delete FreeType font files
+ deleteGList(ftFontFiles, XOutputFTFontFile);
+ if (ftEngine) {
+ delete ftEngine;
+ }
+#endif
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ // delete TrueType fonts
+ deleteGList(ttFontFiles, XOutputTTFontFile);
+ if (ttEngine) {
+ delete ttEngine;
+ }
+#endif
+}
+
+void XOutputFontCache::clear() {
+ int i;
+
+ for (i = 0; i < xOutFontCacheSize; ++i) {
+ fonts[i] = NULL;
+ }
+ nFonts = 0;
+
+#if HAVE_T1LIB_H
+ // clear Type 1 font files
+ t1FontFiles = new GList();
+#endif
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ // clear FreeType font cache
+ ftFontFiles = new GList();
+#endif
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ // clear TrueType font cache
+ ttFontFiles = new GList();
+#endif
+}
+
+XOutputFont *XOutputFontCache::getFont(XRef *xref, GfxFont *gfxFont,
+ double m11, double m12,
+ double m21, double m22) {
+ XOutputFont *font;
+ DisplayFontParam *dfp;
+ GString *substName;
+ double m11New, m12New, m21New, m22New;
+ double w1, w2, v;
+ double *fm;
+ char *name;
+ int index;
+ int code;
+ int i, j;
+
+ // is it the most recently used font?
+ if (nFonts > 0 && fonts[0]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
+ return fonts[0];
+ }
+
+ // is it in the cache?
+ for (i = 1; i < nFonts; ++i) {
+ if (fonts[i]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
+ font = fonts[i];
+ for (j = i; j > 0; --j) {
+ fonts[j] = fonts[j-1];
+ }
+ fonts[0] = font;
+ return font;
+ }
+ }
+
+ // try for a cached FontFile, an embedded font, or an external font
+ // file
+ font = NULL;
+ switch (gfxFont->getType()) {
+ case fontType1:
+ case fontType1C:
+#if HAVE_T1LIB_H
+ if (t1libControl != fontRastNone) {
+ font = tryGetT1Font(xref, gfxFont, m11, m12, m21, m22);
+ }
+#endif
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (!font) {
+ if (freetypeControl != fontRastNone) {
+ font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
+ }
+ }
+#endif
+ break;
+ case fontTrueType:
+ case fontCIDType2:
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
+ }
+#endif
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ font = tryGetTTFont(xref, gfxFont, m11, m12, m21, m22);
+ }
+#endif
+ break;
+ case fontCIDType0C:
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
+ }
+#endif
+ break;
+ default:
+ break;
+ }
+
+ if (!font) {
+
+ // search for a display font mapping
+ dfp = NULL;
+ if (gfxFont->isCIDFont()) {
+ if (((GfxCIDFont *)gfxFont)->getCollection()) {
+ dfp = globalParams->
+ getDisplayCIDFont(gfxFont->getName(),
+ ((GfxCIDFont *)gfxFont)->getCollection());
+ } else {
+ // this error (no CMap file) was already reported by GfxFont
+ return NULL;
+ }
+ } else {
+ if (gfxFont->getName()) {
+ dfp = globalParams->getDisplayFont(gfxFont->getName());
+ }
+ }
+ if (dfp) {
+ font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+ }
+
+ // substitute a font (8-bit fonts only)
+ if (!font && !gfxFont->isCIDFont()) {
+
+ // choose a substitute font
+ if (gfxFont->isFixedWidth()) {
+ index = 8;
+ } else if (gfxFont->isSerif()) {
+ index = 4;
+ } else {
+ index = 0;
+ }
+ if (gfxFont->isBold()) {
+ index += 2;
+ }
+ if (gfxFont->isItalic()) {
+ index += 1;
+ }
+ substName = new GString(xOutSubstFonts[index].name);
+
+ // adjust the font matrix -- compare the width of 'm' in the
+ // original font and the substituted font
+ m11New = m11;
+ m12New = m12;
+ m21New = m21;
+ m22New = m22;
+ for (code = 0; code < 256; ++code) {
+ if ((name = ((Gfx8BitFont *)gfxFont)->getCharName(code)) &&
+ name[0] == 'm' && name[1] == '\0') {
+ break;
+ }
+ }
+ if (code < 256) {
+ w1 = ((Gfx8BitFont *)gfxFont)->getWidth(code);
+ w2 = xOutSubstFonts[index].mWidth;
+ if (gfxFont->getType() == fontType3) {
+ // This is a hack which makes it possible to substitute for some
+ // Type 3 fonts. The problem is that it's impossible to know what
+ // the base coordinate system used in the font is without actually
+ // rendering the font. This code tries to guess by looking at the
+ // width of the character 'm' (which breaks if the font is a
+ // subset that doesn't contain 'm').
+ if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
+ w1 /= w2;
+ m11New *= w1;
+ m12New *= w1;
+ m21New *= w1;
+ m22New *= w1;
+ }
+ fm = gfxFont->getFontMatrix();
+ v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
+ m21New *= v;
+ m22New *= v;
+ } else if (!gfxFont->isSymbolic()) {
+ // if real font is substantially narrower than substituted
+ // font, reduce the font size accordingly
+ if (w1 > 0.01 && w1 < 0.9 * w2) {
+ w1 /= w2;
+ m11New *= w1;
+ m21New *= w1;
+ }
+ }
+ }
+
+ // get the font
+ dfp = globalParams->getDisplayFont(substName);
+ delete substName;
+ if (!dfp) {
+ // this should never happen since GlobalParams sets up default
+ // mappings for the Base-14 fonts
+ error(-1, "Couldn't find a font for '%s'",
+ gfxFont->getName()->getCString());
+ return NULL;
+ }
+ font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
+ m11New, m12New, m21New, m22New, gTrue);
+ }
+ }
+
+ // check for error
+ if (!font) {
+ // This will happen if the user specifies a bogus font in the
+ // config file (a non-existent font file or a font that requires a
+ // rasterizer that is disabled or wasn't built in), or if a CID
+ // font has no associated font in the config file.
+ if (gfxFont->isCIDFont()) {
+ error(-1, "Couldn't find a font for the '%s' character collection",
+ ((GfxCIDFont *)gfxFont)->getCollection()->getCString());
+ } else {
+ error(-1, "Couldn't find a font for '%s'",
+ gfxFont->getName() ?
+ gfxFont->getName()->getCString() : "[unnamed]");
+ }
+ return NULL;
+ }
+
+ // insert font in cache
+ if (nFonts == xOutFontCacheSize) {
+ --nFonts;
+ delete fonts[nFonts];
+ }
+ for (j = nFonts; j > 0; --j) {
+ fonts[j] = fonts[j-1];
+ }
+ fonts[0] = font;
+ ++nFonts;
+
+ return font;
+}
+
+XOutputFont *XOutputFontCache::tryGetFont(XRef *xref, DisplayFontParam *dfp,
+ GfxFont *gfxFont,
+ double m11Orig, double m12Orig,
+ double m21Orig, double m22Orig,
+ double m11, double m12,
+ double m21, double m22,
+ GBool subst) {
+ XOutputFont *font;
+
+ font = NULL;
+
+ // create the new font
+ switch (dfp->kind) {
+
+ case displayFontX:
+ font = tryGetServerFont(dfp->x.xlfd, dfp->x.encoding, gfxFont,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22);
+ break;
+
+ case displayFontT1:
+#if HAVE_T1LIB_H
+ if (t1libControl != fontRastNone) {
+ font = tryGetT1FontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, subst);
+ }
+#endif
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (!font) {
+ if (freetypeControl != fontRastNone) {
+ font = tryGetFTFontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, subst);
+ }
+ }
+#endif
+#if !((FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)) || defined(HAVE_T1LIB_H))
+ error(-1, "Config file specifies a Type 1 font,");
+ error(-1, "but xpdf was not built with t1lib or FreeType2 support");
+#endif
+ break;
+
+ case displayFontTT:
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ font = tryGetFTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, subst);
+ }
+#endif
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ if (freetypeControl != fontRastNone) {
+ font = tryGetTTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, subst);
+ }
+#endif
+#if !(HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+ error(-1, "Config file specifies a TrueType font,");
+ error(-1, "but xpdf was not built with FreeType support");
+ dfp = NULL;
+#endif
+ break;
+ }
+
+ return font;
+}
+
+#if HAVE_T1LIB_H
+XOutputFont *XOutputFontCache::tryGetT1Font(XRef *xref,
+ GfxFont *gfxFont,
+ double m11, double m12,
+ double m21, double m22) {
+ Ref *id;
+ XOutputT1FontFile *xFontFile;
+ XOutputFont *font;
+ Ref embRef;
+ GString *fileName;
+ FILE *f;
+ char *fontBuf;
+ int fontLen;
+ Type1CFontFile *ff;
+ Object refObj, strObj;
+ int c;
+ int i;
+
+ // check the already available font files
+ id = gfxFont->getID();
+ for (i = 0; i < t1FontFiles->getLength(); ++i) {
+ xFontFile = (XOutputT1FontFile *)t1FontFiles->get(i);
+ if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
+ !xFontFile->subst) {
+ font = new XOutputT1Font(id, xFontFile->fontFile,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+ }
+ }
+
+ // check for an embedded font
+ if (gfxFont->getEmbeddedFontID(&embRef)) {
+
+ // create the font file
+ fileName = NULL;
+ if (!openTempFile(&fileName, &f, "wb", NULL)) {
+ error(-1, "Couldn't create temporary Type 1 font file");
+ return NULL;
+ }
+ if (gfxFont->getType() == fontType1C) {
+ if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
+ fclose(f);
+ return NULL;
+ }
+ ff = new Type1CFontFile(fontBuf, fontLen);
+ ff->convertToType1(outputToFile, f);
+ delete ff;
+ gfree(fontBuf);
+ } else { // fontType1
+ refObj.initRef(embRef.num, embRef.gen);
+ refObj.fetch(xref, &strObj);
+ refObj.free();
+ strObj.streamReset();
+ while ((c = strObj.streamGetChar()) != EOF) {
+ fputc(c, f);
+ }
+ strObj.streamClose();
+ strObj.free();
+ }
+ fclose(f);
+
+ // create the Font
+ font = tryGetT1FontFromFile(xref, fileName, gTrue, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ // on systems with Unix hard link semantics, this will remove the
+ // last link to the temp file
+ unlink(fileName->getCString());
+
+ delete fileName;
+
+ // check for an external font file
+ } else if ((fileName = gfxFont->getExtFontFile())) {
+ font = tryGetT1FontFromFile(xref, fileName, gFalse, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ } else {
+ font = NULL;
+ }
+
+ return font;
+}
+
+XOutputFont *XOutputFontCache::tryGetT1FontFromFile(XRef *xref,
+ GString *fileName,
+ GBool deleteFile,
+ GfxFont *gfxFont,
+ double m11Orig,
+ double m12Orig,
+ double m21Orig,
+ double m22Orig,
+ double m11, double m12,
+ double m21, double m22,
+ GBool subst) {
+ Ref *id;
+ T1FontFile *fontFile;
+ XOutputFont *font;
+
+ // create the t1lib font file
+ fontFile = new T1FontFile(t1Engine, fileName->getCString(),
+ ((Gfx8BitFont *)gfxFont)->getEncoding(),
+ gfxFont->getFontBBox());
+ if (!fontFile->isOk()) {
+ error(-1, "Couldn't create t1lib font from '%s'",
+ fileName->getCString());
+ delete fontFile;
+ if (deleteFile) {
+ unlink(fileName->getCString());
+ }
+ return NULL;
+ }
+
+ // add to list
+ id = gfxFont->getID();
+ t1FontFiles->append(new XOutputT1FontFile(id->num, id->gen,
+ subst, fontFile,
+ deleteFile ? fileName->copy()
+ : (GString *)NULL));
+
+ // create the Font
+ font = new XOutputT1Font(gfxFont->getID(), fontFile,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+}
+#endif // HAVE_T1LIB_H
+
+#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+XOutputFont *XOutputFontCache::tryGetFTFont(XRef *xref,
+ GfxFont *gfxFont,
+ double m11, double m12,
+ double m21, double m22) {
+ Ref *id;
+ XOutputFTFontFile *xFontFile;
+ XOutputFont *font;
+ Ref embRef;
+ GString *fileName;
+ FILE *f;
+#if 1 //~ need this until FT can handle fonts with missing tables
+ char *fontBuf;
+ int fontLen;
+ TrueTypeFontFile *ff;
+#endif
+ Object refObj, strObj;
+ int c;
+ int i;
+
+ // check the already available font files
+ id = gfxFont->getID();
+ for (i = 0; i < ftFontFiles->getLength(); ++i) {
+ xFontFile = (XOutputFTFontFile *)ftFontFiles->get(i);
+ if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
+ !xFontFile->subst) {
+ font = new XOutputFTFont(id, xFontFile->fontFile,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+ }
+ }
+
+ // check for an embedded font
+ if (gfxFont->getEmbeddedFontID(&embRef)) {
+
+ // create the font file
+ fileName = NULL;
+ if (!openTempFile(&fileName, &f, "wb", NULL)) {
+ error(-1, "Couldn't create temporary TrueType font file");
+ return NULL;
+ }
+#if 1 //~ need this until FT can handle fonts with missing tables
+ if (gfxFont->getType() == fontTrueType ||
+ gfxFont->getType() == fontCIDType2) {
+ if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
+ fclose(f);
+ return NULL;
+ }
+ ff = new TrueTypeFontFile(fontBuf, fontLen);
+ ff->writeTTF(f);
+ delete ff;
+ gfree(fontBuf);
+ } else {
+ refObj.initRef(embRef.num, embRef.gen);
+ refObj.fetch(xref, &strObj);
+ refObj.free();
+ strObj.streamReset();
+ while ((c = strObj.streamGetChar()) != EOF) {
+ fputc(c, f);
+ }
+ strObj.streamClose();
+ strObj.free();
+ }
+#else
+ refObj.initRef(embRef.num, embRef.gen);
+ refObj.fetch(xref, &strObj);
+ refObj.free();
+ strObj.streamReset();
+ while ((c = strObj.streamGetChar()) != EOF) {
+ fputc(c, f);
+ }
+ strObj.streamClose();
+ strObj.free();
+#endif
+ fclose(f);
+
+ // create the Font
+ font = tryGetFTFontFromFile(xref, fileName, gTrue, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ // on systems with Unix hard link semantics, this will remove the
+ // last link to the temp file
+ unlink(fileName->getCString());
+
+ delete fileName;
+
+ // check for an external font file
+ } else if ((fileName = gfxFont->getExtFontFile())) {
+ font = tryGetFTFontFromFile(xref, fileName, gFalse, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ } else {
+ font = NULL;
+ }
+
+ return font;
+}
+
+XOutputFont *XOutputFontCache::tryGetFTFontFromFile(XRef *xref,
+ GString *fileName,
+ GBool deleteFile,
+ GfxFont *gfxFont,
+ double m11Orig,
+ double m12Orig,
+ double m21Orig,
+ double m22Orig,
+ double m11, double m12,
+ double m21, double m22,
+ GBool subst) {
+ Ref *id;
+ FTFontFile *fontFile;
+ XOutputFont *font;
+
+ // create the FreeType font file
+ if (gfxFont->isCIDFont()) {
+ if (gfxFont->getType() == fontCIDType2) {
+ fontFile = new FTFontFile(ftEngine, fileName->getCString(),
+ ((GfxCIDFont *)gfxFont)->getCIDToGID(),
+ ((GfxCIDFont *)gfxFont)->getCIDToGIDLen());
+ } else { // fontCIDType0C
+ fontFile = new FTFontFile(ftEngine, fileName->getCString());
+ }
+ } else {
+ fontFile = new FTFontFile(ftEngine, fileName->getCString(),
+ ((Gfx8BitFont *)gfxFont)->getEncoding(),
+ ((Gfx8BitFont *)gfxFont)->getHasEncoding());
+ }
+ if (!fontFile->isOk()) {
+ error(-1, "Couldn't create FreeType font from '%s'",
+ fileName->getCString());
+ delete fontFile;
+ if (deleteFile) {
+ unlink(fileName->getCString());
+ }
+ return NULL;
+ }
+
+ // add to list
+ id = gfxFont->getID();
+ ftFontFiles->append(new XOutputFTFontFile(id->num, id->gen,
+ subst, fontFile,
+ deleteFile ? fileName->copy()
+ : (GString *)NULL));
+
+ // create the Font
+ font = new XOutputFTFont(gfxFont->getID(), fontFile,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+}
+#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+XOutputFont *XOutputFontCache::tryGetTTFont(XRef *xref,
+ GfxFont *gfxFont,
+ double m11, double m12,
+ double m21, double m22) {
+ Ref *id;
+ XOutputTTFontFile *xFontFile;
+ XOutputFont *font;
+ Ref embRef;
+ GString *fileName;
+ FILE *f;
+ Object refObj, strObj;
+ int c;
+ int i;
+
+ // check the already available font files
+ id = gfxFont->getID();
+ xFontFile = NULL;
+ for (i = 0; i < ttFontFiles->getLength(); ++i) {
+ xFontFile = (XOutputTTFontFile *)ttFontFiles->get(i);
+ if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
+ !xFontFile->subst) {
+ font = new XOutputTTFont(id, xFontFile->fontFile,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+ }
+ }
+
+ // check for an embedded font
+ if (gfxFont->getEmbeddedFontID(&embRef)) {
+
+ // create the font file
+ fileName = NULL;
+ if (!openTempFile(&fileName, &f, "wb", NULL)) {
+ error(-1, "Couldn't create temporary TrueType font file");
+ return NULL;
+ }
+ refObj.initRef(embRef.num, embRef.gen);
+ refObj.fetch(xref, &strObj);
+ refObj.free();
+ strObj.streamReset();
+ while ((c = strObj.streamGetChar()) != EOF) {
+ fputc(c, f);
+ }
+ strObj.streamClose();
+ strObj.free();
+ fclose(f);
+
+ // create the Font
+ font = tryGetTTFontFromFile(xref, fileName, gTrue, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ // on systems with Unix hard link semantics, this will remove the
+ // last link to the temp file
+ unlink(fileName->getCString());
+
+ delete fileName;
+
+ } else if ((fileName = gfxFont->getExtFontFile())) {
+ font = tryGetTTFontFromFile(xref, fileName, gFalse, gfxFont,
+ m11, m12, m21, m22,
+ m11, m12, m21, m22, gFalse);
+
+ } else {
+ font = NULL;
+ }
+
+ return font;
+}
+
+XOutputFont *XOutputFontCache::tryGetTTFontFromFile(XRef *xref,
+ GString *fileName,
+ GBool deleteFile,
+ GfxFont *gfxFont,
+ double m11Orig,
+ double m12Orig,
+ double m21Orig,
+ double m22Orig,
+ double m11, double m12,
+ double m21, double m22,
+ GBool subst) {
+ Ref *id;
+ TTFontFile *fontFile;
+ XOutputFont *font;
+
+ // create the FreeType font file
+ if (gfxFont->isCIDFont()) {
+ // fontCIDType2
+ fontFile = new TTFontFile(ttEngine, fileName->getCString(),
+ ((GfxCIDFont *)gfxFont)->getCIDToGID(),
+ ((GfxCIDFont *)gfxFont)->getCIDToGIDLen());
+ } else {
+ fontFile = new TTFontFile(ttEngine, fileName->getCString(),
+ ((Gfx8BitFont *)gfxFont)->getEncoding(),
+ ((Gfx8BitFont *)gfxFont)->getHasEncoding());
+ }
+ if (!fontFile->isOk()) {
+ error(-1, "Couldn't create FreeType font from '%s'",
+ fileName->getCString());
+ delete fontFile;
+ if (deleteFile) {
+ unlink(fileName->getCString());
+ }
+ return NULL;
+ }
+
+ // add to list
+ id = gfxFont->getID();
+ ttFontFiles->append(new XOutputTTFontFile(id->num, id->gen,
+ subst, fontFile,
+ deleteFile ? fileName->copy()
+ : (GString *)NULL));
+
+ // create the Font
+ font = new XOutputTTFont(gfxFont->getID(), fontFile,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22, display, xOut);
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+}
+#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
+
+XOutputFont *XOutputFontCache::tryGetServerFont(GString *xlfd,
+ GString *encodingName,
+ GfxFont *gfxFont,
+ double m11Orig, double m12Orig,
+ double m21Orig, double m22Orig,
+ double m11, double m12,
+ double m21, double m22) {
+ XOutputFont *font;
+ UnicodeMap *uMap;
+ CharCodeToUnicode *ctu;
+
+ uMap = globalParams->getUnicodeMap(encodingName);
+ if (gfxFont->isCIDFont()) {
+ ctu = ((GfxCIDFont *)gfxFont)->getToUnicode();
+ font = new XOutputServer16BitFont(gfxFont->getID(), xlfd, uMap, ctu,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22,
+ display, xOut);
+ ctu->decRefCnt();
+ } else {
+ ctu = ((Gfx8BitFont *)gfxFont)->getToUnicode();
+ font = new XOutputServer8BitFont(gfxFont->getID(), xlfd, uMap, ctu,
+ m11Orig, m12Orig, m21Orig, m22Orig,
+ m11, m12, m21, m22,
+ display, xOut);
+ ctu->decRefCnt();
+ }
+ uMap->decRefCnt();
+ if (!font->isOk()) {
+ delete font;
+ return NULL;
+ }
+ return font;
+}
+
+//------------------------------------------------------------------------
+// T3FontCache
+//------------------------------------------------------------------------
+
+struct T3FontCacheTag {
+ Gushort code;
+ Gushort mru; // valid bit (0x8000) and MRU index
+ double wx, wy; // untransformed glyph metrics
+};
+
+class T3FontCache {
+public:
+
+ T3FontCache(Ref *fontID, double m11A, double m12A,
+ double m21A, double m22A,
+ int glyphXA, int glyphYA, int glyphWA, int glyphHA,
+ Display *displayA, Visual *visual, Guint depth,
+ Pixmap origPixmap);
+ ~T3FontCache();
+ GBool matches(Ref *idA, double m11A, double m12A,
+ double m21A, double m22A)
+ { return fontID.num == idA->num && fontID.gen == idA->gen &&
+ m11 == m11A && m12 == m12A && m21 == m21A && m22 == m22A; }
+
+ Ref fontID; // PDF font ID
+ double m11, m12, m21, m22; // transform matrix
+ int glyphX, glyphY; // pixel offset of glyph pixmaps
+ int glyphW, glyphH; // size of glyph pixmaps, in pixels
+ int glyphSize; // size of glyph pixmaps, in bytes
+ int cacheSets; // number of sets in cache
+ int cacheAssoc; // cache associativity (glyphs per set)
+ Guchar *cacheData; // glyph pixmap cache
+ T3FontCacheTag *cacheTags; // cache tags, i.e., char codes
+ Display *display;
+ Pixmap pixmap;
+ XImage *image;
+};
+
+T3FontCache::T3FontCache(Ref *fontIDA, double m11A, double m12A,
+ double m21A, double m22A,
+ int glyphXA, int glyphYA, int glyphWA, int glyphHA,
+ Display *displayA, Visual *visual, Guint depth,
+ Pixmap origPixmap) {
+ int i;
+
+ fontID = *fontIDA;
+ m11 = m11A;
+ m12 = m12A;
+ m21 = m21A;
+ m22 = m22A;
+ glyphX = glyphXA;
+ glyphY = glyphYA;
+ glyphW = glyphWA;
+ glyphH = glyphHA;
+ glyphSize = glyphW * glyphH;
+ cacheAssoc = 8;
+ if (glyphSize <= 256) {
+ cacheSets = 8;
+ } else if (glyphSize <= 512) {
+ cacheSets = 4;
+ } else if (glyphSize <= 1024) {
+ cacheSets = 2;
+ } else {
+ cacheSets = 1;
+ }
+ cacheData = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
+ cacheTags = (T3FontCacheTag *)gmalloc(cacheSets * cacheAssoc *
+ sizeof(T3FontCacheTag));
+ for (i = 0; i < cacheSets * cacheAssoc; ++i) {
+ cacheTags[i].mru = i & (cacheAssoc - 1);
+ }
+ display = displayA;
+ pixmap = XCreatePixmap(display, origPixmap, glyphW, glyphH, depth);
+ image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL,
+ glyphW, glyphH, 8, 0);
+ image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
+}
+
+T3FontCache::~T3FontCache() {
+ gfree(cacheData);
+ gfree(cacheTags);
+ XFreePixmap(display, pixmap);
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+}
+
+struct T3GlyphStack {
+ GBool cacheable;
+ Gushort code;
+ T3FontCache *cache;
+ int cacheIdx;
+ T3FontCacheTag *cacheTag;
+ Guchar *cacheData;
+ double x, y;
+ Unicode *u;
+ int uLen;
+ GfxRGB color;
+ int origPixmapW, origPixmapH;
+ Pixmap origPixmap;
+ GC origStrokeGC;
+ GC origFillGC;
+ Region origClipRegion;
+ double origCTM4, origCTM5;
+ double wx, wy; // untransformed glyph metrics
+ T3GlyphStack *next;
+};
+
+//------------------------------------------------------------------------
+// XOutputDev
+//------------------------------------------------------------------------
+
+XOutputDev::XOutputDev(Display *displayA, int screenNumA,
+ Visual *visualA, Colormap colormapA,
+ GBool reverseVideoA, unsigned long paperColorA,
+ GBool installCmap, int rgbCubeSize,
+ int forceDepth) {
+ XVisualInfo visualTempl;
+ XVisualInfo *visualList;
+ int nVisuals;
+ Gulong mask;
+ XColor xcolor;
+ XColor *xcolors;
+ int r, g, b, n, m;
+ GBool ok;
+
+ // no document yet
+ xref = NULL;
+
+ // display / screen / visual / colormap
+ display = displayA;
+ screenNum = screenNumA;
+ visual = visualA;
+ colormap = colormapA;
+
+ // no pixmap yet
+ pixmapW = pixmapH = 0;
+
+ // check for TrueColor visual
+ if (forceDepth != 0) {
+ depth = forceDepth;
+ trueColor = depth >= 16;
+ } else {
+ visualTempl.visualid = XVisualIDFromVisual(visual);
+ visualList = XGetVisualInfo(display, VisualIDMask,
+ &visualTempl, &nVisuals);
+ if (nVisuals < 1) {
+ // this shouldn't happen
+ XFree((XPointer)visualList);
+ visualList = XGetVisualInfo(display, VisualNoMask, &visualTempl,
+ &nVisuals);
+ }
+ depth = visualList->depth;
+ if (visualList->c_class == TrueColor) {
+ trueColor = gTrue;
+ for (mask = visualList->red_mask, rShift = 0;
+ mask && !(mask & 1);
+ mask >>= 1, ++rShift) ;
+ rMul = (int)mask;
+ for (mask = visualList->green_mask, gShift = 0;
+ mask && !(mask & 1);
+ mask >>= 1, ++gShift) ;
+ gMul = (int)mask;
+ for (mask = visualList->blue_mask, bShift = 0;
+ mask && !(mask & 1);
+ mask >>= 1, ++bShift) ;
+ bMul = (int)mask;
+ } else {
+ trueColor = gFalse;
+ }
+ XFree((XPointer)visualList);
+ }
+
+ // allocate a color cube
+ if (!trueColor) {
+ redMap[BlackPixel(display, screenNum) & 0xff] = 0;
+ redMap[WhitePixel(display, screenNum) & 0xff] = 1;
+
+ // set colors in private colormap
+ if (installCmap) {
+ for (numColors = 6; numColors >= 2; --numColors) {
+ m = numColors * numColors * numColors;
+ if (XAllocColorCells(display, colormap, False, NULL, 0, colors, m)) {
+ break;
+ }
+ }
+ if (numColors >= 2) {
+ m = numColors * numColors * numColors;
+ xcolors = (XColor *)gmalloc(m * sizeof(XColor));
+ n = 0;
+ for (r = 0; r < numColors; ++r) {
+ for (g = 0; g < numColors; ++g) {
+ for (b = 0; b < numColors; ++b) {
+ xcolors[n].pixel = colors[n];
+ xcolors[n].red = (r * 65535) / (numColors - 1);
+ xcolors[n].green = (g * 65535) / (numColors - 1);
+ xcolors[n].blue = (b * 65535) / (numColors - 1);
+ xcolors[n].flags = DoRed | DoGreen | DoBlue;
+ redMap[xcolors[n].pixel & 0xff] = xcolors[n].red / 65535.0;
+ ++n;
+ }
+ }
+ }
+ XStoreColors(display, colormap, xcolors, m);
+ gfree(xcolors);
+ } else {
+ numColors = 1;
+ colors[0] = BlackPixel(display, screenNum);
+ colors[1] = WhitePixel(display, screenNum);
+ }
+
+ // allocate colors in shared colormap
+ } else {
+ if (rgbCubeSize > maxRGBCube) {
+ rgbCubeSize = maxRGBCube;
+ }
+ ok = gFalse;
+ for (numColors = rgbCubeSize; numColors >= 2; --numColors) {
+ ok = gTrue;
+ n = 0;
+ for (r = 0; r < numColors && ok; ++r) {
+ for (g = 0; g < numColors && ok; ++g) {
+ for (b = 0; b < numColors && ok; ++b) {
+ if (n == 0) {
+ colors[n] = BlackPixel(display, screenNum);
+ redMap[colors[n] & 0xff] = 0;
+ ++n;
+ } else {
+ xcolor.red = (r * 65535) / (numColors - 1);
+ xcolor.green = (g * 65535) / (numColors - 1);
+ xcolor.blue = (b * 65535) / (numColors - 1);
+ if (XAllocColor(display, colormap, &xcolor)) {
+ colors[n++] = xcolor.pixel;
+ redMap[xcolor.pixel & 0xff] = xcolor.red / 65535.0;
+ } else {
+ ok = gFalse;
+ }
+ }
+ }
+ }
+ }
+ if (ok) {
+ break;
+ }
+ XFreeColors(display, colormap, &colors[1], n-1, 0);
+ }
+ if (!ok) {
+ numColors = 1;
+ colors[0] = BlackPixel(display, screenNum);
+ colors[1] = WhitePixel(display, screenNum);
+ }
+ }
+ }
+
+ // misc parameters
+ reverseVideo = reverseVideoA;
+ paperColor = paperColorA;
+
+ // set up the font cache and fonts
+ gfxFont = NULL;
+ font = NULL;
+ fontCache = new XOutputFontCache(display, depth, this,
+ globalParams->getT1libControl(),
+ globalParams->getFreeTypeControl());
+ nT3Fonts = 0;
+ t3GlyphStack = NULL;
+
+ // empty state stack
+ save = NULL;
+
+ // create text object
+ text = new TextPage(gFalse);
+}
+
+XOutputDev::~XOutputDev() {
+ int i;
+
+ delete fontCache;
+ for (i = 0; i < nT3Fonts; ++i) {
+ delete t3FontCache[i];
+ }
+ delete text;
+}
+
+void XOutputDev::startDoc(XRef *xrefA) {
+ int i;
+
+ xref = xrefA;
+ fontCache->startDoc(screenNum, visual, colormap, trueColor, rMul, gMul, bMul,
+ rShift, gShift, bShift, colors, numColors);
+ for (i = 0; i < nT3Fonts; ++i) {
+ delete t3FontCache[i];
+ }
+ nT3Fonts = 0;
+}
+
+void XOutputDev::startPage(int pageNum, GfxState *state) {
+ XGCValues gcValues;
+ XRectangle rect;
+
+ // default line flatness
+ flatness = 0;
+
+ // allocate GCs
+ gcValues.foreground = BlackPixel(display, screenNum);
+ gcValues.background = WhitePixel(display, screenNum);
+ gcValues.line_width = 0;
+ gcValues.line_style = LineSolid;
+ strokeGC = XCreateGC(display, pixmap,
+ GCForeground | GCBackground | GCLineWidth | GCLineStyle,
+ &gcValues);
+ fillGC = XCreateGC(display, pixmap,
+ GCForeground | GCBackground | GCLineWidth | GCLineStyle,
+ &gcValues);
+ gcValues.foreground = paperColor;
+ paperGC = XCreateGC(display, pixmap,
+ GCForeground | GCBackground | GCLineWidth | GCLineStyle,
+ &gcValues);
+
+ // initialize clip region
+ clipRegion = XCreateRegion();
+ rect.x = rect.y = 0;
+ rect.width = pixmapW;
+ rect.height = pixmapH;
+ XUnionRectWithRegion(&rect, clipRegion, clipRegion);
+ XSetRegion(display, strokeGC, clipRegion);
+ XSetRegion(display, fillGC, clipRegion);
+
+ // clear font
+ gfxFont = NULL;
+ font = NULL;
+
+ // clear window
+ XFillRectangle(display, pixmap, paperGC, 0, 0, pixmapW, pixmapH);
+
+ // clear text object
+ text->clear();
+}
+
+void XOutputDev::endPage() {
+ XOutputState *s;
+
+ text->coalesce();
+
+ // clear state stack, free all GCs, free the clip region
+ while (save) {
+ s = save;
+ save = save->next;
+ XFreeGC(display, s->strokeGC);
+ XFreeGC(display, s->fillGC);
+ XDestroyRegion(s->clipRegion);
+ delete s;
+ }
+ XFreeGC(display, strokeGC);
+ XFreeGC(display, fillGC);
+ XFreeGC(display, paperGC);
+ XDestroyRegion(clipRegion);
+}
+
+void XOutputDev::drawLink(Link *link, Catalog *catalog) {
+ double x1, y1, x2, y2, w;
+ GfxRGB rgb;
+ XPoint points[5];
+ int x, y;
+
+ link->getBorder(&x1, &y1, &x2, &y2, &w);
+ if (w > 0) {
+ rgb.r = 0;
+ rgb.g = 0;
+ rgb.b = 1;
+ XSetForeground(display, strokeGC, findColor(&rgb));
+ XSetLineAttributes(display, strokeGC, xoutRound(w),
+ LineSolid, CapRound, JoinRound);
+ cvtUserToDev(x1, y1, &x, &y);
+ points[0].x = points[4].x = x;
+ points[0].y = points[4].y = y;
+ cvtUserToDev(x2, y1, &x, &y);
+ points[1].x = x;
+ points[1].y = y;
+ cvtUserToDev(x2, y2, &x, &y);
+ points[2].x = x;
+ points[2].y = y;
+ cvtUserToDev(x1, y2, &x, &y);
+ points[3].x = x;
+ points[3].y = y;
+ XDrawLines(display, pixmap, strokeGC, points, 5, CoordModeOrigin);
+ }
+}
+
+void XOutputDev::saveState(GfxState *state) {
+ XOutputState *s;
+ XGCValues values;
+
+ // save current state
+ s = new XOutputState;
+ s->strokeGC = strokeGC;
+ s->fillGC = fillGC;
+ s->clipRegion = clipRegion;
+
+ // push onto state stack
+ s->next = save;
+ save = s;
+
+ // create a new current state by copying
+ strokeGC = XCreateGC(display, pixmap, 0, &values);
+ XCopyGC(display, s->strokeGC, 0xffffffff, strokeGC);
+ fillGC = XCreateGC(display, pixmap, 0, &values);
+ XCopyGC(display, s->fillGC, 0xffffffff, fillGC);
+ clipRegion = XCreateRegion();
+ XUnionRegion(s->clipRegion, clipRegion, clipRegion);
+ XSetRegion(display, strokeGC, clipRegion);
+ XSetRegion(display, fillGC, clipRegion);
+}
+
+void XOutputDev::restoreState(GfxState *state) {
+ XOutputState *s;
+
+ if (save) {
+ // kill current state
+ XFreeGC(display, strokeGC);
+ XFreeGC(display, fillGC);
+ XDestroyRegion(clipRegion);
+
+ // restore state
+ flatness = state->getFlatness();
+ strokeGC = save->strokeGC;
+ fillGC = save->fillGC;
+ clipRegion = save->clipRegion;
+ XSetRegion(display, strokeGC, clipRegion);
+ XSetRegion(display, fillGC, clipRegion);
+
+ // pop state stack
+ s = save;
+ save = save->next;
+ delete s;
+ }
+}
+
+void XOutputDev::updateAll(GfxState *state) {
+ updateLineAttrs(state, gTrue);
+ updateFlatness(state);
+ updateMiterLimit(state);
+ updateFillColor(state);
+ updateStrokeColor(state);
+ updateFont(state);
+}
+
+void XOutputDev::updateCTM(GfxState *state, double m11, double m12,
+ double m21, double m22, double m31, double m32) {
+ updateLineAttrs(state, gTrue);
+}
+
+void XOutputDev::updateLineDash(GfxState *state) {
+ updateLineAttrs(state, gTrue);
+}
+
+void XOutputDev::updateFlatness(GfxState *state) {
+ flatness = state->getFlatness();
+}
+
+void XOutputDev::updateLineJoin(GfxState *state) {
+ updateLineAttrs(state, gFalse);
+}
+
+void XOutputDev::updateLineCap(GfxState *state) {
+ updateLineAttrs(state, gFalse);
+}
+
+// unimplemented
+void XOutputDev::updateMiterLimit(GfxState *state) {
+}
+
+void XOutputDev::updateLineWidth(GfxState *state) {
+ updateLineAttrs(state, gFalse);
+}
+
+void XOutputDev::updateLineAttrs(GfxState *state, GBool updateDash) {
+ double width;
+ int cap, join;
+ double *dashPattern;
+ int dashLength;
+ double dashStart;
+ char dashList[20];
+ int i;
+
+ width = state->getTransformedLineWidth();
+ switch (state->getLineCap()) {
+ case 0: cap = CapButt; break;
+ case 1: cap = CapRound; break;
+ case 2: cap = CapProjecting; break;
+ default:
+ error(-1, "Bad line cap style (%d)", state->getLineCap());
+ cap = CapButt;
+ break;
+ }
+ switch (state->getLineJoin()) {
+ case 0: join = JoinMiter; break;
+ case 1: join = JoinRound; break;
+ case 2: join = JoinBevel; break;
+ default:
+ error(-1, "Bad line join style (%d)", state->getLineJoin());
+ join = JoinMiter;
+ break;
+ }
+ state->getLineDash(&dashPattern, &dashLength, &dashStart);
+#if 1 //~ work around a bug in XFree86 (???)
+ if (dashLength > 0 && cap == CapProjecting) {
+ cap = CapButt;
+ }
+#endif
+ XSetLineAttributes(display, strokeGC, xoutRound(width),
+ dashLength > 0 ? LineOnOffDash : LineSolid,
+ cap, join);
+ if (updateDash && dashLength > 0) {
+ if (dashLength > 20)
+ dashLength = 20;
+ for (i = 0; i < dashLength; ++i) {
+ dashList[i] = xoutRound(state->transformWidth(dashPattern[i]));
+ if (dashList[i] == 0)
+ dashList[i] = 1;
+ }
+ XSetDashes(display, strokeGC, xoutRound(dashStart), dashList, dashLength);
+ }
+}
+
+void XOutputDev::updateFillColor(GfxState *state) {
+ GfxRGB rgb;
+
+ state->getFillRGB(&rgb);
+ if (reverseVideo) {
+ rgb.r = 1 - rgb.r;
+ rgb.g = 1 - rgb.g;
+ rgb.b = 1 - rgb.b;
+ }
+ XSetForeground(display, fillGC, findColor(&rgb));
+}
+
+void XOutputDev::updateStrokeColor(GfxState *state) {
+ GfxRGB rgb;
+
+ state->getStrokeRGB(&rgb);
+ if (reverseVideo) {
+ rgb.r = 1 - rgb.r;
+ rgb.g = 1 - rgb.g;
+ rgb.b = 1 - rgb.b;
+ }
+ XSetForeground(display, strokeGC, findColor(&rgb));
+}
+
+void XOutputDev::updateFont(GfxState *state) {
+ double m11, m12, m21, m22;
+
+ text->updateFont(state);
+
+ if (!(gfxFont = state->getFont())) {
+ font = NULL;
+ return;
+ }
+ if (gfxFont->getType() == fontType3) {
+ font = NULL;
+ return;
+ }
+ state->getFontTransMat(&m11, &m12, &m21, &m22);
+ m11 *= state->getHorizScaling();
+ m12 *= state->getHorizScaling();
+ font = fontCache->getFont(xref, gfxFont, m11, m12, m21, m22);
+ if (font) {
+ font->updateGC(fillGC);
+ font->updateGC(strokeGC);
+ }
+}
+
+void XOutputDev::stroke(GfxState *state) {
+ XPoint *points;
+ int *lengths;
+ int n, size, numPoints, i, j;
+
+ // transform points
+ n = convertPath(state, &points, &size, &numPoints, &lengths, gFalse);
+
+ // draw each subpath
+ j = 0;
+ for (i = 0; i < n; ++i) {
+ XDrawLines(display, pixmap, strokeGC, points + j, lengths[i],
+ CoordModeOrigin);
+ j += lengths[i];
+ }
+
+ // free points and lengths arrays
+ if (points != tmpPoints)
+ gfree(points);
+ if (lengths != tmpLengths)
+ gfree(lengths);
+}
+
+void XOutputDev::fill(GfxState *state) {
+ doFill(state, WindingRule);
+}
+
+void XOutputDev::eoFill(GfxState *state) {
+ doFill(state, EvenOddRule);
+}
+
+//
+// X doesn't color the pixels on the right-most and bottom-most
+// borders of a polygon. This means that one-pixel-thick polygons
+// are not colored at all. I think this is supposed to be a
+// feature, but I can't figure out why. So after it fills a
+// polygon, it also draws lines around the border. This is done
+// only for single-component polygons, since it's not very
+// compatible with the compound polygon kludge (see convertPath()).
+//
+void XOutputDev::doFill(GfxState *state, int rule) {
+ XPoint *points;
+ int *lengths;
+ int n, size, numPoints, i, j;
+
+ // set fill rule
+ XSetFillRule(display, fillGC, rule);
+
+ // transform points, build separate polygons
+ n = convertPath(state, &points, &size, &numPoints, &lengths, gTrue);
+
+ // fill them
+ j = 0;
+ for (i = 0; i < n; ++i) {
+ XFillPolygon(display, pixmap, fillGC, points + j, lengths[i],
+ Complex, CoordModeOrigin);
+ if (state->getPath()->getNumSubpaths() == 1) {
+ XDrawLines(display, pixmap, fillGC, points + j, lengths[i],
+ CoordModeOrigin);
+ }
+ j += lengths[i] + 1;
+ }
+
+ // free points and lengths arrays
+ if (points != tmpPoints)
+ gfree(points);
+ if (lengths != tmpLengths)
+ gfree(lengths);
+}
+
+void XOutputDev::clip(GfxState *state) {
+ doClip(state, WindingRule);
+}
+
+void XOutputDev::eoClip(GfxState *state) {
+ doClip(state, EvenOddRule);
+}
+
+void XOutputDev::doClip(GfxState *state, int rule) {
+ Region region, region2;
+ XPoint *points;
+ int *lengths;
+ int n, size, numPoints, i, j;
+
+ // transform points, build separate polygons
+ n = convertPath(state, &points, &size, &numPoints, &lengths, gTrue);
+
+ // construct union of subpath regions
+ // (XPolygonRegion chokes if there aren't at least three points --
+ // this happens if the PDF file does moveto/closepath/clip, which
+ // sets an empty clipping region)
+ if (lengths[0] > 2) {
+ region = XPolygonRegion(points, lengths[0], rule);
+ } else {
+ region = XCreateRegion();
+ }
+ j = lengths[0] + 1;
+ for (i = 1; i < n; ++i) {
+ if (lengths[i] > 2) {
+ region2 = XPolygonRegion(points + j, lengths[i], rule);
+ } else {
+ region2 = XCreateRegion();
+ }
+ XUnionRegion(region2, region, region);
+ XDestroyRegion(region2);
+ j += lengths[i] + 1;
+ }
+
+ // intersect region with clipping region
+ XIntersectRegion(region, clipRegion, clipRegion);
+ XDestroyRegion(region);
+ XSetRegion(display, strokeGC, clipRegion);
+ XSetRegion(display, fillGC, clipRegion);
+
+ // free points and lengths arrays
+ if (points != tmpPoints)
+ gfree(points);
+ if (lengths != tmpLengths)
+ gfree(lengths);
+}
+
+//
+// Transform points in the path and convert curves to line segments.
+// Builds a set of subpaths and returns the number of subpaths.
+// If <fillHack> is set, close any unclosed subpaths and activate a
+// kludge for polygon fills: First, it divides up the subpaths into
+// non-overlapping polygons by simply comparing bounding rectangles.
+// Then it connects subaths within a single compound polygon to a single
+// point so that X can fill the polygon (sort of).
+//
+int XOutputDev::convertPath(GfxState *state, XPoint **points, int *size,
+ int *numPoints, int **lengths, GBool fillHack) {
+ GfxPath *path;
+ BoundingRect *rects;
+ BoundingRect rect;
+ int n, i, ii, j, k, k0;
+
+ // get path and number of subpaths
+ path = state->getPath();
+ n = path->getNumSubpaths();
+
+ // allocate lengths array
+ if (n < numTmpSubpaths)
+ *lengths = tmpLengths;
+ else
+ *lengths = (int *)gmalloc(n * sizeof(int));
+
+ // allocate bounding rectangles array
+ if (fillHack) {
+ if (n < numTmpSubpaths)
+ rects = tmpRects;
+ else
+ rects = (BoundingRect *)gmalloc(n * sizeof(BoundingRect));
+ } else {
+ rects = NULL;
+ }
+
+ // do each subpath
+ *points = tmpPoints;
+ *size = numTmpPoints;
+ *numPoints = 0;
+ for (i = 0; i < n; ++i) {
+
+ // transform the points
+ j = *numPoints;
+ convertSubpath(state, path->getSubpath(i), points, size, numPoints);
+
+ // construct bounding rectangle
+ if (fillHack) {
+ rects[i].xMin = rects[i].xMax = (*points)[j].x;
+ rects[i].yMin = rects[i].yMax = (*points)[j].y;
+ for (k = j + 1; k < *numPoints; ++k) {
+ if ((*points)[k].x < rects[i].xMin)
+ rects[i].xMin = (*points)[k].x;
+ else if ((*points)[k].x > rects[i].xMax)
+ rects[i].xMax = (*points)[k].x;
+ if ((*points)[k].y < rects[i].yMin)
+ rects[i].yMin = (*points)[k].y;
+ else if ((*points)[k].y > rects[i].yMax)
+ rects[i].yMax = (*points)[k].y;
+ }
+ }
+
+ // close subpath if necessary
+ if (fillHack && ((*points)[*numPoints-1].x != (*points)[j].x ||
+ (*points)[*numPoints-1].y != (*points)[j].y)) {
+ addPoint(points, size, numPoints, (*points)[j].x, (*points)[j].y);
+ }
+
+ // length of this subpath
+ (*lengths)[i] = *numPoints - j;
+
+ // leave an extra point for compound fill hack
+ if (fillHack)
+ addPoint(points, size, numPoints, 0, 0);
+ }
+
+ // kludge: munge any points that are *way* out of bounds - these can
+ // crash certain (buggy) X servers
+ for (i = 0; i < *numPoints; ++i) {
+ if ((*points)[i].x < -pixmapW) {
+ (*points)[i].x = -pixmapW;
+ } else if ((*points)[i].x > 2 * pixmapW) {
+ (*points)[i].x = 2 * pixmapW;
+ }
+ if ((*points)[i].y < -pixmapH) {
+ (*points)[i].y = -pixmapH;
+ } else if ((*points)[i].y > 2 * pixmapH) {
+ (*points)[i].y = 2 * pixmapH;
+ }
+ }
+
+ // combine compound polygons
+ if (fillHack) {
+ i = j = k = 0;
+ while (i < n) {
+
+ // start with subpath i
+ rect = rects[i];
+ (*lengths)[j] = (*lengths)[i];
+ k0 = k;
+ (*points)[k + (*lengths)[i]] = (*points)[k0];
+ k += (*lengths)[i] + 1;
+ ++i;
+
+ // combine overlapping polygons
+ do {
+
+ // look for the first subsequent subpath, if any, which overlaps
+ for (ii = i; ii < n; ++ii) {
+ if (rects[ii].xMax > rects[i].xMin &&
+ rects[ii].xMin < rects[i].xMax &&
+ rects[ii].yMax > rects[i].yMin &&
+ rects[ii].yMin < rects[i].yMax) {
+ break;
+ }
+ }
+
+ // if there is an overlap, combine the polygons
+ if (ii < n) {
+ for (; i <= ii; ++i) {
+ if (rects[i].xMin < rect.xMin)
+ rect.xMin = rects[j].xMin;
+ if (rects[i].xMax > rect.xMax)
+ rect.xMax = rects[j].xMax;
+ if (rects[i].yMin < rect.yMin)
+ rect.yMin = rects[j].yMin;
+ if (rects[i].yMax > rect.yMax)
+ rect.yMax = rects[j].yMax;
+ (*lengths)[j] += (*lengths)[i] + 1;
+ (*points)[k + (*lengths)[i]] = (*points)[k0];
+ k += (*lengths)[i] + 1;
+ }
+ }
+ } while (ii < n && i < n);
+
+ ++j;
+ }
+
+ // free bounding rectangles
+ if (rects != tmpRects)
+ gfree(rects);
+
+ n = j;
+ }
+
+ return n;
+}
+
+//
+// Transform points in a single subpath and convert curves to line
+// segments.
+//
+void XOutputDev::convertSubpath(GfxState *state, GfxSubpath *subpath,
+ XPoint **points, int *size, int *n) {
+ double x0, y0, x1, y1, x2, y2, x3, y3;
+ int m, i;
+
+ m = subpath->getNumPoints();
+ i = 0;
+ while (i < m) {
+ if (i >= 1 && subpath->getCurve(i)) {
+ state->transform(subpath->getX(i-1), subpath->getY(i-1), &x0, &y0);
+ state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
+ state->transform(subpath->getX(i+1), subpath->getY(i+1), &x2, &y2);
+ state->transform(subpath->getX(i+2), subpath->getY(i+2), &x3, &y3);
+ doCurve(points, size, n, x0, y0, x1, y1, x2, y2, x3, y3);
+ i += 3;
+ } else {
+ state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
+ addPoint(points, size, n, xoutRound(x1), xoutRound(y1));
+ ++i;
+ }
+ }
+}
+
+//
+// Subdivide a Bezier curve. This uses floating point to avoid
+// propagating rounding errors. (The curves look noticeably more
+// jagged with integer arithmetic.)
+//
+void XOutputDev::doCurve(XPoint **points, int *size, int *n,
+ double x0, double y0, double x1, double y1,
+ double x2, double y2, double x3, double y3) {
+ double x[(1<<maxCurveSplits)+1][3];
+ double y[(1<<maxCurveSplits)+1][3];
+ int next[1<<maxCurveSplits];
+ int p1, p2, p3;
+ double xx1, yy1, xx2, yy2;
+ double dx, dy, mx, my, d1, d2;
+ double xl0, yl0, xl1, yl1, xl2, yl2;
+ double xr0, yr0, xr1, yr1, xr2, yr2, xr3, yr3;
+ double xh, yh;
+ double flat;
+
+ flat = (double)(flatness * flatness);
+ if (flat < 1)
+ flat = 1;
+
+ // initial segment
+ p1 = 0;
+ p2 = 1<<maxCurveSplits;
+ x[p1][0] = x0; y[p1][0] = y0;
+ x[p1][1] = x1; y[p1][1] = y1;
+ x[p1][2] = x2; y[p1][2] = y2;
+ x[p2][0] = x3; y[p2][0] = y3;
+ next[p1] = p2;
+
+ while (p1 < (1<<maxCurveSplits)) {
+
+ // get next segment
+ xl0 = x[p1][0]; yl0 = y[p1][0];
+ xx1 = x[p1][1]; yy1 = y[p1][1];
+ xx2 = x[p1][2]; yy2 = y[p1][2];
+ p2 = next[p1];
+ xr3 = x[p2][0]; yr3 = y[p2][0];
+
+ // compute distances from control points to midpoint of the
+ // straight line (this is a bit of a hack, but it's much faster
+ // than computing the actual distances to the line)
+ mx = (xl0 + xr3) * 0.5;
+ my = (yl0 + yr3) * 0.5;
+ dx = xx1 - mx;
+ dy = yy1 - my;
+ d1 = dx*dx + dy*dy;
+ dx = xx2 - mx;
+ dy = yy2 - my;
+ d2 = dx*dx + dy*dy;
+
+ // if curve is flat enough, or no more divisions allowed then
+ // add the straight line segment
+ if (p2 - p1 <= 1 || (d1 <= flat && d2 <= flat)) {
+ addPoint(points, size, n, xoutRound(xr3), xoutRound(yr3));
+ p1 = p2;
+
+ // otherwise, subdivide the curve
+ } else {
+ xl1 = (xl0 + xx1) * 0.5;
+ yl1 = (yl0 + yy1) * 0.5;
+ xh = (xx1 + xx2) * 0.5;
+ yh = (yy1 + yy2) * 0.5;
+ xl2 = (xl1 + xh) * 0.5;
+ yl2 = (yl1 + yh) * 0.5;
+ xr2 = (xx2 + xr3) * 0.5;
+ yr2 = (yy2 + yr3) * 0.5;
+ xr1 = (xh + xr2) * 0.5;
+ yr1 = (yh + yr2) * 0.5;
+ xr0 = (xl2 + xr1) * 0.5;
+ yr0 = (yl2 + yr1) * 0.5;
+
+ // add the new subdivision points
+ p3 = (p1 + p2) / 2;
+ x[p1][1] = xl1; y[p1][1] = yl1;
+ x[p1][2] = xl2; y[p1][2] = yl2;
+ next[p1] = p3;
+ x[p3][0] = xr0; y[p3][0] = yr0;
+ x[p3][1] = xr1; y[p3][1] = yr1;
+ x[p3][2] = xr2; y[p3][2] = yr2;
+ next[p3] = p2;
+ }
+ }
+}
+
+//
+// Add a point to the points array. (This would use a generic resizable
+// array type if C++ supported parameterized types in some reasonable
+// way -- templates are a disgusting kludge.)
+//
+void XOutputDev::addPoint(XPoint **points, int *size, int *k, int x, int y) {
+ if (*k >= *size) {
+ *size += 32;
+ if (*points == tmpPoints) {
+ *points = (XPoint *)gmalloc(*size * sizeof(XPoint));
+ memcpy(*points, tmpPoints, *k * sizeof(XPoint));
+ } else {
+ *points = (XPoint *)grealloc(*points, *size * sizeof(XPoint));
+ }
+ }
+ (*points)[*k].x = x;
+ (*points)[*k].y = y;
+ ++(*k);
+}
+
+void XOutputDev::beginString(GfxState *state, GString *s) {
+ text->beginString(state, state->getCurX(), state->getCurY());
+}
+
+void XOutputDev::endString(GfxState *state) {
+ text->endString();
+}
+
+void XOutputDev::drawChar(GfxState *state, double x, double y,
+ double dx, double dy,
+ double originX, double originY,
+ CharCode code, Unicode *u, int uLen) {
+ int render;
+ double x1, y1, dx1, dy1;
+ GfxRGB rgb;
+ double saveCurX, saveCurY;
+ double *ctm;
+ double saveCTM[6];
+
+ text->addChar(state, x, y, dx, dy, u, uLen);
+
+ if (!font) {
+ return;
+ }
+
+ // check for invisible text -- this is used by Acrobat Capture
+ render = state->getRender();
+ if ((render & 3) == 3) {
+ return;
+ }
+
+ x -= originX;
+ y -= originY;
+ state->transform(x, y, &x1, &y1);
+ state->transformDelta(dx, dy, &dx1, &dy1);
+
+ // fill
+ if (!(render & 1)) {
+ state->getFillRGB(&rgb);
+ if (reverseVideo) {
+ rgb.r = 1 - rgb.r;
+ rgb.g = 1 - rgb.g;
+ rgb.b = 1 - rgb.b;
+ }
+ font->drawChar(state, pixmap, pixmapW, pixmapH, fillGC, &rgb,
+ x1, y1, dx1, dy1, code, u, uLen);
+ }
+
+ // stroke
+ if ((render & 3) == 1 || (render & 3) == 2) {
+ if (font->hasGetCharPath()) {
+ saveCurX = state->getCurX();
+ saveCurY = state->getCurY();
+ ctm = state->getCTM();
+ memcpy(saveCTM, ctm, 6 * sizeof(double));
+ state->setCTM(1, 0, 0, 1, x1, y1);
+ font->getCharPath(state, code, u, uLen);
+ stroke(state);
+ state->clearPath();
+ state->setCTM(saveCTM[0], saveCTM[1], saveCTM[2], saveCTM[3],
+ saveCTM[4], saveCTM[5]);
+ state->moveTo(saveCurX, saveCurY);
+ } else {
+ // can't stroke the outline, so just fill it using the stroke
+ // color
+ state->getStrokeRGB(&rgb);
+ if (reverseVideo) {
+ rgb.r = 1 - rgb.r;
+ rgb.g = 1 - rgb.g;
+ rgb.b = 1 - rgb.b;
+ }
+ font->drawChar(state, pixmap, pixmapW, pixmapH, strokeGC, &rgb,
+ x1, y1, dx1, dy1, code, u, uLen);
+ }
+ }
+
+#if 0 //~ unimplemented: clipping to char path
+ // clip
+ if (render & 4) {
+ }
+#endif
+}
+
+GBool XOutputDev::beginType3Char(GfxState *state,
+ CharCode code, Unicode *u, int uLen) {
+ Ref *fontID;
+ double *ctm, *bbox;
+ GfxRGB color;
+ T3FontCache *t3Font;
+ T3GlyphStack *t3gs;
+ double x1, y1, xMin, yMin, xMax, yMax, xt, yt;
+ int i, j;
+
+ if (!gfxFont) {
+ return gFalse;
+ }
+ fontID = gfxFont->getID();
+ ctm = state->getCTM();
+ state->transform(0, 0, &xt, &yt);
+
+ // is it the first (MRU) font in the cache?
+ if (!(nT3Fonts > 0 &&
+ t3FontCache[0]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3]))) {
+
+ // is the font elsewhere in the cache?
+ for (i = 1; i < nT3Fonts; ++i) {
+ if (t3FontCache[i]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3])) {
+ t3Font = t3FontCache[i];
+ for (j = i; j > 0; --j) {
+ t3FontCache[j] = t3FontCache[j - 1];
+ }
+ t3FontCache[0] = t3Font;
+ break;
+ }
+ }
+ if (i >= nT3Fonts) {
+
+ // create new entry in the font cache
+ if (nT3Fonts == xOutT3FontCacheSize) {
+ delete t3FontCache[nT3Fonts - 1];
+ --nT3Fonts;
+ }
+ for (j = nT3Fonts; j > 0; --j) {
+ t3FontCache[j] = t3FontCache[j - 1];
+ }
+ ++nT3Fonts;
+ bbox = gfxFont->getFontBBox();
+ if (bbox[0] == 0 && bbox[1] == 0 && bbox[2] == 0 && bbox[3] == 0) {
+ // broken bounding box -- just take a guess
+ xMin = xt - 5;
+ xMax = xMin + 30;
+ yMax = yt + 15;
+ yMin = yMax - 45;
+ } else {
+ state->transform(bbox[0], bbox[1], &x1, &y1);
+ xMin = xMax = x1;
+ yMin = yMax = y1;
+ state->transform(bbox[0], bbox[3], &x1, &y1);
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+ state->transform(bbox[2], bbox[1], &x1, &y1);
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+ state->transform(bbox[2], bbox[3], &x1, &y1);
+ if (x1 < xMin) {
+ xMin = x1;
+ } else if (x1 > xMax) {
+ xMax = x1;
+ }
+ if (y1 < yMin) {
+ yMin = y1;
+ } else if (y1 > yMax) {
+ yMax = y1;
+ }
+ }
+ t3FontCache[0] = new T3FontCache(fontID, ctm[0], ctm[1], ctm[2], ctm[3],
+ (int)floor(xMin - xt),
+ (int)floor(yMin - yt),
+ (int)ceil(xMax) - (int)floor(xMin) + 3,
+ (int)ceil(yMax) - (int)floor(yMin) + 3,
+ display, visual, depth, pixmap);
+ }
+ }
+ t3Font = t3FontCache[0];
+
+ // is the glyph in the cache?
+ i = (code & (t3Font->cacheSets - 1)) * t3Font->cacheAssoc;
+ for (j = 0; j < t3Font->cacheAssoc; ++j) {
+ if ((t3Font->cacheTags[i+j].mru & 0x8000) &&
+ t3Font->cacheTags[i+j].code == code) {
+ state->getFillRGB(&color);
+ if (reverseVideo) {
+ color.r = 1 - color.r;
+ color.g = 1 - color.g;
+ color.b = 1 - color.b;
+ }
+ text->addChar(state, 0, 0,
+ t3Font->cacheTags[i+j].wx, t3Font->cacheTags[i+j].wy,
+ u, uLen);
+ drawType3Glyph(t3Font, &t3Font->cacheTags[i+j],
+ t3Font->cacheData + (i+j) * t3Font->glyphSize,
+ xt, yt, &color);
+ return gTrue;
+ }
+ }
+
+ // push a new Type 3 glyph record
+ t3gs = new T3GlyphStack();
+ t3gs->next = t3GlyphStack;
+ t3GlyphStack = t3gs;
+ t3GlyphStack->cacheable = gFalse;
+ t3GlyphStack->code = code;
+ t3GlyphStack->cache = t3Font;
+ t3GlyphStack->cacheIdx = i;
+ t3GlyphStack->x = xt;
+ t3GlyphStack->y = yt;
+ t3GlyphStack->u = u;
+ t3GlyphStack->uLen = uLen;
+
+ return gFalse;
+}
+
+void XOutputDev::endType3Char(GfxState *state) {
+ XImage *image;
+ Guchar *p;
+ int x, y;
+ Gulong pixel;
+ double alpha;
+ T3GlyphStack *t3gs;
+ double *ctm;
+
+ if (t3GlyphStack->cacheable) {
+ image = t3GlyphStack->cache->image;
+ XGetSubImage(display, pixmap, 0, 0,
+ t3GlyphStack->cache->glyphW, t3GlyphStack->cache->glyphH,
+ (1 << depth) - 1, ZPixmap, image, 0, 0);
+ p = t3GlyphStack->cacheData;
+ for (y = 0; y < t3GlyphStack->cache->glyphH; ++y) {
+ for (x = 0; x < t3GlyphStack->cache->glyphW; ++x) {
+ pixel = XGetPixel(image, x, y);
+ if (trueColor) {
+ alpha = (double)((pixel >> rShift) & rMul) / (double)rMul;
+ } else {
+ alpha = redMap[pixel & 0xff];
+ }
+ if (alpha <= 0.2) {
+ *p++ = 4;
+ } else if (alpha <= 0.4) {
+ *p++ = 3;
+ } else if (alpha <= 0.6) {
+ *p++ = 2;
+ } else if (alpha <= 0.8) {
+ *p++ = 1;
+ } else {
+ *p++ = 0;
+ }
+ }
+ }
+ XDestroyRegion(clipRegion);
+ XFreeGC(display, strokeGC);
+ XFreeGC(display, fillGC);
+ pixmapW = t3GlyphStack->origPixmapW;
+ pixmapH = t3GlyphStack->origPixmapH;
+ pixmap = t3GlyphStack->origPixmap;
+ strokeGC = t3GlyphStack->origStrokeGC;
+ fillGC = t3GlyphStack->origFillGC;
+ clipRegion = t3GlyphStack->origClipRegion;
+ drawType3Glyph(t3GlyphStack->cache,
+ t3GlyphStack->cacheTag, t3GlyphStack->cacheData,
+ t3GlyphStack->x, t3GlyphStack->y, &t3GlyphStack->color);
+ // the CTM must be restored here in order for TextPage::addChar to
+ // work correctly
+ ctm = state->getCTM();
+ state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3],
+ t3GlyphStack->origCTM4, t3GlyphStack->origCTM5);
+ }
+ text->addChar(state, 0, 0, t3GlyphStack->wx, t3GlyphStack->wy,
+ t3GlyphStack->u, t3GlyphStack->uLen);
+ t3gs = t3GlyphStack;
+ t3GlyphStack = t3gs->next;
+ delete t3gs;
+}
+
+void XOutputDev::drawType3Glyph(T3FontCache *t3Font,
+ T3FontCacheTag *tag, Guchar *data,
+ double x, double y, GfxRGB *color) {
+ XImage *image;
+ XColor xcolor;
+ GfxRGB bg, rgb;
+ Gulong map[5];
+ Gulong pixel;
+ Guchar *p;
+ int x0, y0, w0, h0, x1, y1;
+ int ix, iy;
+
+ // compute: (x0,y0) = position in destination pixmap
+ // (x1,y1) = position in the XImage
+ // (w0,h0) = size of XImage transfer
+ x0 = xoutRound(x + t3Font->glyphX);
+ y0 = xoutRound(y + t3Font->glyphY);
+ x1 = 0;
+ y1 = 0;
+ w0 = t3Font->glyphW;
+ h0 = t3Font->glyphH;
+ if (x0 < 0) {
+ x1 = -x0;
+ w0 += x0;
+ x0 = 0;
+ }
+ if (x0 + w0 > pixmapW) {
+ w0 = pixmapW - x0;
+ }
+ if (w0 <= 0) {
+ return;
+ }
+ if (y0 < 0) {
+ y1 = -y0;
+ h0 += y0;
+ y0 = 0;
+ }
+ if (y0 + h0 > pixmapH) {
+ h0 = pixmapH - y0;
+ }
+ if (h0 <= 0) {
+ return;
+ }
+
+ image = t3Font->image;
+ XGetSubImage(display, pixmap, x0, y0, w0, h0,
+ (1 << depth) - 1, ZPixmap, image, x1, y1);
+ xcolor.pixel = XGetPixel(image, t3Font->glyphW / 2, t3Font->glyphH / 2);
+ XQueryColor(display, colormap, &xcolor);
+ bg.r = xcolor.red / 65535.0;
+ bg.g = xcolor.green / 65535.0;
+ bg.b = xcolor.blue / 65535.0;
+ rgb.r = 0.25 * (color->r + 3 * bg.r);
+ rgb.g = 0.25 * (color->g + 3 * bg.g);
+ rgb.b = 0.25 * (color->b + 3 * bg.b);
+ map[1] = findColor(&rgb);
+ rgb.r = 0.5 * (color->r + bg.r);
+ rgb.g = 0.5 * (color->g + bg.g);
+ rgb.b = 0.5 * (color->b + bg.b);
+ map[2] = findColor(&rgb);
+ rgb.r = 0.25 * (3 * color->r + bg.r);
+ rgb.g = 0.25 * (3 * color->g + bg.g);
+ rgb.b = 0.25 * (3 * color->b + bg.b);
+ map[3] = findColor(&rgb);
+ map[4] = findColor(color);
+ p = data;
+ for (iy = 0; iy < t3Font->glyphH; ++iy) {
+ for (ix = 0; ix < t3Font->glyphW; ++ix) {
+ pixel = *p++;
+ if (pixel > 0) {
+ XPutPixel(image, ix, iy, map[pixel]);
+ }
+ }
+ }
+ XPutImage(display, pixmap, fillGC, image, x1, y1, x0, y0, w0, h0);
+}
+
+void XOutputDev::type3D0(GfxState *state, double wx, double wy) {
+ t3GlyphStack->wx = wx;
+ t3GlyphStack->wy = wy;
+}
+
+void XOutputDev::type3D1(GfxState *state, double wx, double wy,
+ double llx, double lly, double urx, double ury) {
+ GfxColor fgColor;
+ XGCValues gcValues;
+ XRectangle rect;
+ double *ctm;
+ T3FontCache *t3Font;
+ int i, j;
+
+ // allocate a cache entry
+ t3GlyphStack->cacheable = gTrue;
+ t3Font = t3GlyphStack->cache;
+ i = t3GlyphStack->cacheIdx;
+ for (j = 0; j < t3Font->cacheAssoc; ++j) {
+ if ((t3Font->cacheTags[i+j].mru & 0x7fff) == t3Font->cacheAssoc - 1) {
+ t3Font->cacheTags[i+j].mru = 0x8000;
+ t3Font->cacheTags[i+j].code = t3GlyphStack->code;
+ t3GlyphStack->cacheTag = &t3Font->cacheTags[i+j];
+ t3GlyphStack->cacheData = t3Font->cacheData + (i+j) * t3Font->glyphSize;
+ } else {
+ ++t3Font->cacheTags[i+j].mru;
+ }
+ }
+ t3GlyphStack->wx = wx;
+ t3GlyphStack->wy = wy;
+ t3GlyphStack->cacheTag->wx = wx;
+ t3GlyphStack->cacheTag->wy = wy;
+
+ // prepare to rasterize the glyph
+ //~ do we need to handle both fill and stroke color?
+ state->getFillRGB(&t3GlyphStack->color);
+ if (reverseVideo) {
+ t3GlyphStack->color.r = 1 - t3GlyphStack->color.r;
+ t3GlyphStack->color.g = 1 - t3GlyphStack->color.g;
+ t3GlyphStack->color.b = 1 - t3GlyphStack->color.b;
+ }
+ fgColor.c[0] = reverseVideo ? 1 : 0;
+ state->setFillColorSpace(new GfxDeviceGrayColorSpace());
+ state->setFillColor(&fgColor);
+ state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
+ state->setStrokeColor(&fgColor);
+ t3GlyphStack->origPixmapW = pixmapW;
+ t3GlyphStack->origPixmapH = pixmapH;
+ t3GlyphStack->origPixmap = pixmap;
+ t3GlyphStack->origStrokeGC = strokeGC;
+ t3GlyphStack->origFillGC = fillGC;
+ t3GlyphStack->origClipRegion = clipRegion;
+ pixmapW = t3GlyphStack->cache->glyphW;
+ pixmapH = t3GlyphStack->cache->glyphH;
+ pixmap = t3GlyphStack->cache->pixmap;
+ gcValues.foreground = BlackPixel(display, screenNum);
+ gcValues.background = WhitePixel(display, screenNum);
+ gcValues.line_width = 0;
+ gcValues.line_style = LineSolid;
+ strokeGC = XCreateGC(display, pixmap,
+ GCForeground | GCBackground | GCLineWidth | GCLineStyle,
+ &gcValues);
+ updateLineAttrs(state, gTrue);
+ gcValues.foreground = WhitePixel(display, screenNum);
+ fillGC = XCreateGC(display, pixmap,
+ GCForeground | GCBackground | GCLineWidth | GCLineStyle,
+ &gcValues);
+ XFillRectangle(display, pixmap, fillGC, 0, 0, pixmapW, pixmapH);
+ XSetForeground(display, fillGC, BlackPixel(display, screenNum));
+ clipRegion = XCreateRegion();
+ rect.x = rect.y = 0;
+ rect.width = pixmapW;
+ rect.height = pixmapH;
+ XUnionRectWithRegion(&rect, clipRegion, clipRegion);
+ XSetRegion(display, strokeGC, clipRegion);
+ XSetRegion(display, fillGC, clipRegion);
+ ctm = state->getCTM();
+ t3GlyphStack->origCTM4 = ctm[4];
+ t3GlyphStack->origCTM5 = ctm[5];
+ state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3],
+ -t3GlyphStack->cache->glyphX, -t3GlyphStack->cache->glyphY);
+}
+
+inline Gulong XOutputDev::findColor(GfxRGB *x, GfxRGB *err) {
+ double gray;
+ int r, g, b;
+ Gulong pixel;
+
+ if (trueColor) {
+ r = xoutRound(x->r * rMul);
+ g = xoutRound(x->g * gMul);
+ b = xoutRound(x->b * bMul);
+ pixel = ((Gulong)r << rShift) +
+ ((Gulong)g << gShift) +
+ ((Gulong)b << bShift);
+ err->r = x->r - (double)r / rMul;
+ err->g = x->g - (double)g / gMul;
+ err->b = x->b - (double)b / bMul;
+ } else if (numColors == 1) {
+ gray = 0.299 * x->r + 0.587 * x->g + 0.114 * x->b;
+ if (gray < 0.5) {
+ pixel = colors[0];
+ err->r = x->r;
+ err->g = x->g;
+ err->b = x->b;
+ } else {
+ pixel = colors[1];
+ err->r = x->r - 1;
+ err->g = x->g - 1;
+ err->b = x->b - 1;
+ }
+ } else {
+ r = xoutRound(x->r * (numColors - 1));
+ g = xoutRound(x->g * (numColors - 1));
+ b = xoutRound(x->b * (numColors - 1));
+ pixel = colors[(r * numColors + g) * numColors + b];
+ err->r = x->r - (double)r / (numColors - 1);
+ err->g = x->g - (double)g / (numColors - 1);
+ err->b = x->b - (double)b / (numColors - 1);
+ }
+ return pixel;
+}
+
+Gulong XOutputDev::findColor(GfxRGB *rgb) {
+ int r, g, b;
+ double gray;
+ Gulong pixel;
+
+ if (trueColor) {
+ r = xoutRound(rgb->r * rMul);
+ g = xoutRound(rgb->g * gMul);
+ b = xoutRound(rgb->b * bMul);
+ pixel = ((Gulong)r << rShift) +
+ ((Gulong)g << gShift) +
+ ((Gulong)b << bShift);
+ } else if (numColors == 1) {
+ gray = 0.299 * rgb->r + 0.587 * rgb->g + 0.114 * rgb->b;
+ if (gray < 0.5)
+ pixel = colors[0];
+ else
+ pixel = colors[1];
+ } else {
+ r = xoutRound(rgb->r * (numColors - 1));
+ g = xoutRound(rgb->g * (numColors - 1));
+ b = xoutRound(rgb->b * (numColors - 1));
+#if 0 // this makes things worse as often as better
+ // even a very light color shouldn't map to white
+ if (r == numColors - 1 && g == numColors - 1 && b == numColors - 1) {
+ if (color->getR() < 0.95)
+ --r;
+ if (color->getG() < 0.95)
+ --g;
+ if (color->getB() < 0.95)
+ --b;
+ }
+#endif
+ pixel = colors[(r * numColors + g) * numColors + b];
+ }
+ return pixel;
+}
+
+void XOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
+ int width, int height, GBool invert,
+ GBool inlineImg) {
+ ImageStream *imgStr;
+ XImage *image;
+ double *ctm;
+ GBool rot;
+ double xScale, yScale, xShear, yShear;
+ int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
+ int ulx, uly, llx, lly, urx, ury, lrx, lry;
+ int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
+ int bx0, by0, bx1, by1, bw, bh;
+ int cx0, cy0, cx1, cy1, cw, ch;
+ int yp, yq, yt, yStep, lastYStep;
+ int xp, xq, xt, xStep, xSrc;
+ GfxRGB rgb;
+ Guchar *pixBuf;
+ int imgPix;
+ double alpha;
+ XColor xcolor;
+ Gulong lastPixel;
+ GfxRGB rgb2;
+ double r0, g0, b0, r1, g1, b1;
+ Gulong pix;
+ Guchar *p;
+ int x, y, x1, y1, x2, y2;
+ int n, m, i, j;
+
+ // get CTM, check for singular matrix
+ ctm = state->getCTM();
+ if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
+ error(-1, "Singular CTM in drawImage");
+ if (inlineImg) {
+ j = height * ((width + 7) / 8);
+ str->reset();
+ for (i = 0; i < j; ++i) {
+ str->getChar();
+ }
+ str->close();
+ }
+ return;
+ }
+
+ // compute scale, shear, rotation, translation parameters
+ rot = fabs(ctm[1]) > fabs(ctm[0]);
+ if (rot) {
+ xScale = -ctm[1];
+ yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
+ xShear = ctm[3] / yScale;
+ yShear = -ctm[0] / ctm[1];
+ } else {
+ xScale = ctm[0];
+ yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
+ xShear = -ctm[2] / yScale;
+ yShear = ctm[1] / ctm[0];
+ }
+ tx = xoutRound(ctm[2] + ctm[4]);
+ ty = xoutRound(ctm[3] + ctm[5]);
+ // use ceil() to avoid gaps between "striped" images
+ scaledWidth = (int)ceil(fabs(xScale));
+ xSign = (xScale < 0) ? -1 : 1;
+ scaledHeight = (int)ceil(fabs(yScale));
+ ySign = (yScale < 0) ? -1 : 1;
+
+ // compute corners in device space
+ ulx1 = 0;
+ uly1 = 0;
+ urx1 = xSign * (scaledWidth - 1);
+ ury1 = xoutRound(yShear * urx1);
+ llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
+ lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
+ lrx1 = xSign * (scaledWidth - 1) +
+ xoutRound(xShear * ySign * (scaledHeight - 1));
+ lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
+ if (rot) {
+ ulx = tx + uly1; uly = ty - ulx1;
+ urx = tx + ury1; ury = ty - urx1;
+ llx = tx + lly1; lly = ty - llx1;
+ lrx = tx + lry1; lry = ty - lrx1;
+ } else {
+ ulx = tx + ulx1; uly = ty + uly1;
+ urx = tx + urx1; ury = ty + ury1;
+ llx = tx + llx1; lly = ty + lly1;
+ lrx = tx + lrx1; lry = ty + lry1;
+ }
+
+ // bounding box:
+ // (bx0, by0) = upper-left corner
+ // (bx1, by1) = lower-right corner
+ // (bw, bh) = size
+ bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
+ : (llx < lrx) ? llx : lrx
+ : (urx < llx) ? (urx < lrx) ? urx : lrx
+ : (llx < lrx) ? llx : lrx;
+ bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
+ : (llx > lrx) ? llx : lrx
+ : (urx > llx) ? (urx > lrx) ? urx : lrx
+ : (llx > lrx) ? llx : lrx;
+ by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
+ : (lly < lry) ? lly : lry
+ : (ury < lly) ? (ury < lry) ? ury : lry
+ : (lly < lry) ? lly : lry;
+ by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
+ : (lly > lry) ? lly : lry
+ : (ury > lly) ? (ury > lry) ? ury : lry
+ : (lly > lry) ? lly : lry;
+ bw = bx1 - bx0 + 1;
+ bh = by1 - by0 + 1;
+
+ // Bounding box clipped to pixmap, i.e., "valid" rectangle:
+ // (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
+ // (cx1, cy1) = upper-left corner of valid rectangle in XImage
+ // (cw, ch) = size of valid rectangle
+ // These values will be used to transfer the XImage from/to the
+ // Pixmap.
+ cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
+ if (bx0 < 0) {
+ cx0 = 0;
+ cx1 = -bx0;
+ cw += bx0;
+ } else {
+ cx0 = bx0;
+ cx1 = 0;
+ }
+ ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
+ if (by0 < 0) {
+ cy0 = 0;
+ cy1 = -by0;
+ ch += by0;
+ } else {
+ cy0 = by0;
+ cy1 = 0;
+ }
+
+ // check for tiny (zero width or height) images
+ // and off-page images
+ if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
+ if (inlineImg) {
+ j = height * ((width + 7) / 8);
+ str->reset();
+ for (i = 0; i < j; ++i) {
+ str->getChar();
+ }
+ str->close();
+ }
+ return;
+ }
+
+ // compute Bresenham parameters for x and y scaling
+ yp = height / scaledHeight;
+ yq = height % scaledHeight;
+ xp = width / scaledWidth;
+ xq = width % scaledWidth;
+
+ // allocate pixel buffer
+ pixBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
+
+ // allocate XImage and read from page pixmap
+ image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
+ image->data = (char *)gmalloc(bh * image->bytes_per_line);
+ XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
+ image, cx1, cy1);
+
+ // get mask color
+ state->getFillRGB(&rgb);
+ if (reverseVideo) {
+ rgb.r = 1 - rgb.r;
+ rgb.g = 1 - rgb.g;
+ rgb.b = 1 - rgb.b;
+ }
+ r0 = rgb.r;
+ g0 = rgb.g;
+ b0 = rgb.b;
+
+ // initialize background color
+ // (the specific pixel value doesn't matter here, as long as
+ // r1,g1,b1 correspond correctly to lastPixel)
+ xcolor.pixel = lastPixel = 0;
+ XQueryColor(display, colormap, &xcolor);
+ r1 = (double)xcolor.red / 65535.0;
+ g1 = (double)xcolor.green / 65535.0;
+ b1 = (double)xcolor.blue / 65535.0;
+
+ // initialize the image stream
+ imgStr = new ImageStream(str, width, 1, 1);
+ imgStr->reset();
+
+ // init y scale Bresenham
+ yt = 0;
+ lastYStep = 1;
+
+ for (y = 0; y < scaledHeight; ++y) {
+
+ // y scale Bresenham
+ yStep = yp;
+ yt += yq;
+ if (yt >= scaledHeight) {
+ yt -= scaledHeight;
+ ++yStep;
+ }
+
+ // read row(s) from image
+ n = (yp > 0) ? yStep : lastYStep;
+ if (n > 0) {
+ p = pixBuf;
+ for (i = 0; i < n; ++i) {
+ memcpy(p, imgStr->getLine(), width);
+ if (invert) {
+ for (j = 0; j < width; ++j) {
+ p[j] ^= 1;
+ }
+ }
+ p += width;
+ }
+ }
+ lastYStep = yStep;
+
+ // init x scale Bresenham
+ xt = 0;
+ xSrc = 0;
+
+ for (x = 0; x < scaledWidth; ++x) {
+
+ // x scale Bresenham
+ xStep = xp;
+ xt += xq;
+ if (xt >= scaledWidth) {
+ xt -= scaledWidth;
+ ++xStep;
+ }
+
+ // x shear
+ x1 = xSign * x + xoutRound(xShear * ySign * y);
+
+ // y shear
+ y1 = ySign * y + xoutRound(yShear * x1);
+
+ // rotation
+ if (rot) {
+ x2 = y1;
+ y2 = -x1;
+ } else {
+ x2 = x1;
+ y2 = y1;
+ }
+
+ // compute the filtered pixel at (x,y) after the
+ // x and y scaling operations
+ n = yStep > 0 ? yStep : 1;
+ m = xStep > 0 ? xStep : 1;
+ p = pixBuf + xSrc;
+ imgPix = 0;
+ for (i = 0; i < n; ++i) {
+ for (j = 0; j < m; ++j) {
+ imgPix += *p++;
+ }
+ p += width - m;
+ }
+
+ // x scale Bresenham
+ xSrc += xStep;
+
+ // blend image pixel with background
+ alpha = (double)imgPix / (double)(n * m);
+ xcolor.pixel = XGetPixel(image, tx + x2 - bx0, ty + y2 - by0);
+ if (xcolor.pixel != lastPixel) {
+ XQueryColor(display, colormap, &xcolor);
+ r1 = (double)xcolor.red / 65535.0;
+ g1 = (double)xcolor.green / 65535.0;
+ b1 = (double)xcolor.blue / 65535.0;
+ lastPixel = xcolor.pixel;
+ }
+ rgb2.r = r0 * (1 - alpha) + r1 * alpha;
+ rgb2.g = g0 * (1 - alpha) + g1 * alpha;
+ rgb2.b = b0 * (1 - alpha) + b1 * alpha;
+ pix = findColor(&rgb2);
+
+ // set pixel
+ XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
+ }
+ }
+
+ // blit the image into the pixmap
+ XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);
+
+ // free memory
+ delete imgStr;
+ gfree(pixBuf);
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+}
+
+void XOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
+ int width, int height, GfxImageColorMap *colorMap,
+ int *maskColors, GBool inlineImg) {
+ ImageStream *imgStr;
+ XImage *image;
+ int nComps, nVals, nBits;
+ GBool dither;
+ double *ctm;
+ GBool rot;
+ double xScale, yScale, xShear, yShear;
+ int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
+ int ulx, uly, llx, lly, urx, ury, lrx, lry;
+ int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
+ int bx0, by0, bx1, by1, bw, bh;
+ int cx0, cy0, cx1, cy1, cw, ch;
+ int yp, yq, yt, yStep, lastYStep;
+ int xp, xq, xt, xStep, xSrc;
+ GfxRGB *pixBuf;
+ Guchar *alphaBuf;
+ Guchar pixBuf2[gfxColorMaxComps];
+ GfxRGB color2, err, errRight;
+ GfxRGB *errDown;
+ double r0, g0, b0, alpha, mul;
+ Gulong pix;
+ GfxRGB *p;
+ Guchar *q, *p2;
+ GBool oneBitMode;
+ GfxRGB oneBitRGB[2];
+ int x, y, x1, y1, x2, y2;
+ int n, m, i, j, k;
+
+ // image parameters
+ nComps = colorMap->getNumPixelComps();
+ nVals = width * nComps;
+ nBits = colorMap->getBits();
+ dither = nComps > 1 || nBits > 1;
+
+ // get CTM, check for singular matrix
+ ctm = state->getCTM();
+ if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
+ error(-1, "Singular CTM in drawImage");
+ if (inlineImg) {
+ str->reset();
+ j = height * ((nVals * nBits + 7) / 8);
+ for (i = 0; i < j; ++i) {
+ str->getChar();
+ }
+ str->close();
+ }
+ return;
+ }
+
+ // compute scale, shear, rotation, translation parameters
+ rot = fabs(ctm[1]) > fabs(ctm[0]);
+ if (rot) {
+ xScale = -ctm[1];
+ yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
+ xShear = ctm[3] / yScale;
+ yShear = -ctm[0] / ctm[1];
+ } else {
+ xScale = ctm[0];
+ yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
+ xShear = -ctm[2] / yScale;
+ yShear = ctm[1] / ctm[0];
+ }
+ tx = xoutRound(ctm[2] + ctm[4]);
+ ty = xoutRound(ctm[3] + ctm[5]);
+ if (xScale < 0) {
+ // this is the right edge which needs to be (left + width - 1)
+ --tx;
+ }
+ if (yScale < 0) {
+ // this is the bottom edge which needs to be (top + height - 1)
+ --ty;
+ }
+ // use ceil() to avoid gaps between "striped" images
+ scaledWidth = (int)ceil(fabs(xScale));
+ xSign = (xScale < 0) ? -1 : 1;
+ scaledHeight = (int)ceil(fabs(yScale));
+ ySign = (yScale < 0) ? -1 : 1;
+
+ // compute corners in device space
+ ulx1 = 0;
+ uly1 = 0;
+ urx1 = xSign * (scaledWidth - 1);
+ ury1 = xoutRound(yShear * urx1);
+ llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
+ lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
+ lrx1 = xSign * (scaledWidth - 1) +
+ xoutRound(xShear * ySign * (scaledHeight - 1));
+ lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
+ if (rot) {
+ ulx = tx + uly1; uly = ty - ulx1;
+ urx = tx + ury1; ury = ty - urx1;
+ llx = tx + lly1; lly = ty - llx1;
+ lrx = tx + lry1; lry = ty - lrx1;
+ } else {
+ ulx = tx + ulx1; uly = ty + uly1;
+ urx = tx + urx1; ury = ty + ury1;
+ llx = tx + llx1; lly = ty + lly1;
+ lrx = tx + lrx1; lry = ty + lry1;
+ }
+
+ // bounding box:
+ // (bx0, by0) = upper-left corner
+ // (bx1, by1) = lower-right corner
+ // (bw, bh) = size
+ bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
+ : (llx < lrx) ? llx : lrx
+ : (urx < llx) ? (urx < lrx) ? urx : lrx
+ : (llx < lrx) ? llx : lrx;
+ bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
+ : (llx > lrx) ? llx : lrx
+ : (urx > llx) ? (urx > lrx) ? urx : lrx
+ : (llx > lrx) ? llx : lrx;
+ by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
+ : (lly < lry) ? lly : lry
+ : (ury < lly) ? (ury < lry) ? ury : lry
+ : (lly < lry) ? lly : lry;
+ by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
+ : (lly > lry) ? lly : lry
+ : (ury > lly) ? (ury > lry) ? ury : lry
+ : (lly > lry) ? lly : lry;
+ bw = bx1 - bx0 + 1;
+ bh = by1 - by0 + 1;
+
+ // Bounding box clipped to pixmap, i.e., "valid" rectangle:
+ // (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
+ // (cx1, cy1) = upper-left corner of valid rectangle in XImage
+ // (cw, ch) = size of valid rectangle
+ // These values will be used to transfer the XImage from/to the
+ // Pixmap.
+ cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
+ if (bx0 < 0) {
+ cx0 = 0;
+ cx1 = -bx0;
+ cw += bx0;
+ } else {
+ cx0 = bx0;
+ cx1 = 0;
+ }
+ ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
+ if (by0 < 0) {
+ cy0 = 0;
+ cy1 = -by0;
+ ch += by0;
+ } else {
+ cy0 = by0;
+ cy1 = 0;
+ }
+
+ // check for tiny (zero width or height) images
+ // and off-page images
+ if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
+ if (inlineImg) {
+ str->reset();
+ j = height * ((nVals * nBits + 7) / 8);
+ for (i = 0; i < j; ++i)
+ str->getChar();
+ str->close();
+ }
+ return;
+ }
+
+ // compute Bresenham parameters for x and y scaling
+ yp = height / scaledHeight;
+ yq = height % scaledHeight;
+ xp = width / scaledWidth;
+ xq = width % scaledWidth;
+
+ // allocate pixel buffer
+ pixBuf = (GfxRGB *)gmalloc((yp + 1) * width * sizeof(GfxRGB));
+ if (maskColors) {
+ alphaBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
+ } else {
+ alphaBuf = NULL;
+ }
+
+ // allocate XImage
+ image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
+ image->data = (char *)gmalloc(bh * image->bytes_per_line);
+
+ // if the transform is anything other than a 0/90/180/270 degree
+ // rotation/flip, or if there is color key masking, read the
+ // backgound pixmap to fill in the corners
+ if (!((ulx == llx && uly == ury) ||
+ (uly == lly && ulx == urx)) ||
+ maskColors) {
+ XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
+ image, cx1, cy1);
+ }
+
+ // allocate error diffusion accumulators
+ if (dither) {
+ errDown = (GfxRGB *)gmalloc(bw * sizeof(GfxRGB));
+ for (j = 0; j < bw; ++j) {
+ errDown[j].r = errDown[j].g = errDown[j].b = 0;
+ }
+ } else {
+ errDown = NULL;
+ }
+
+ // optimize the one-bit-deep image case
+ if ((oneBitMode = nComps == 1 && nBits == 1)) {
+ pixBuf2[0] = 0;
+ colorMap->getRGB(pixBuf2, &oneBitRGB[0]);
+ pixBuf2[0] = 1;
+ colorMap->getRGB(pixBuf2, &oneBitRGB[1]);
+ }
+
+ // initialize the image stream
+ imgStr = new ImageStream(str, width, nComps, nBits);
+ imgStr->reset();
+
+ // init y scale Bresenham
+ yt = 0;
+ lastYStep = 1;
+
+ for (y = 0; y < scaledHeight; ++y) {
+
+ // initialize error diffusion accumulator
+ errRight.r = errRight.g = errRight.b = 0;
+
+ // y scale Bresenham
+ yStep = yp;
+ yt += yq;
+ if (yt >= scaledHeight) {
+ yt -= scaledHeight;
+ ++yStep;
+ }
+
+ // read row(s) from image
+ n = (yp > 0) ? yStep : lastYStep;
+ if (n > 0) {
+ p = pixBuf;
+ q = alphaBuf;
+ for (i = 0; i < n; ++i) {
+ p2 = imgStr->getLine();
+ for (j = 0; j < width; ++j) {
+ if (oneBitMode) {
+ *p = oneBitRGB[*p2];
+ } else {
+ colorMap->getRGB(p2, p);
+ }
+ ++p;
+ if (q) {
+ *q = 1;
+ for (k = 0; k < nComps; ++k) {
+ if (p2[k] < maskColors[2*k] ||
+ p2[k] > maskColors[2*k]) {
+ *q = 0;
+ break;
+ }
+ }
+ ++q;
+ }
+ p2 += nComps;
+ }
+ }
+ }
+ lastYStep = yStep;
+
+ // init x scale Bresenham
+ xt = 0;
+ xSrc = 0;
+
+ for (x = 0; x < scaledWidth; ++x) {
+
+ // x scale Bresenham
+ xStep = xp;
+ xt += xq;
+ if (xt >= scaledWidth) {
+ xt -= scaledWidth;
+ ++xStep;
+ }
+
+ // x shear
+ x1 = xSign * x + xoutRound(xShear * ySign * y);
+
+ // y shear
+ y1 = ySign * y + xoutRound(yShear * x1);
+
+ // rotation
+ if (rot) {
+ x2 = y1;
+ y2 = -x1;
+ } else {
+ x2 = x1;
+ y2 = y1;
+ }
+
+ // compute the filtered pixel at (x,y) after the
+ // x and y scaling operations
+ n = yStep > 0 ? yStep : 1;
+ m = xStep > 0 ? xStep : 1;
+ p = pixBuf + xSrc;
+ r0 = g0 = b0 = 0;
+ q = alphaBuf ? alphaBuf + xSrc : (Guchar *)NULL;
+ alpha = 0;
+ for (i = 0; i < n; ++i) {
+ for (j = 0; j < m; ++j) {
+ r0 += p->r;
+ g0 += p->g;
+ b0 += p->b;
+ ++p;
+ if (q) {
+ alpha += *q++;
+ }
+ }
+ p += width - m;
+ }
+ mul = 1 / (double)(n * m);
+ r0 *= mul;
+ g0 *= mul;
+ b0 *= mul;
+ alpha *= mul;
+
+ // x scale Bresenham
+ xSrc += xStep;
+
+ // compute pixel
+ if (dither) {
+ color2.r = r0 + errRight.r + errDown[tx + x2 - bx0].r;
+ if (color2.r > 1) {
+ color2.r = 1;
+ } else if (color2.r < 0) {
+ color2.r = 0;
+ }
+ color2.g = g0 + errRight.g + errDown[tx + x2 - bx0].g;
+ if (color2.g > 1) {
+ color2.g = 1;
+ } else if (color2.g < 0) {
+ color2.g = 0;
+ }
+ color2.b = b0 + errRight.b + errDown[tx + x2 - bx0].b;
+ if (color2.b > 1) {
+ color2.b = 1;
+ } else if (color2.b < 0) {
+ color2.b = 0;
+ }
+ pix = findColor(&color2, &err);
+ errRight.r = errDown[tx + x2 - bx0].r = err.r / 2;
+ errRight.g = errDown[tx + x2 - bx0].g = err.g / 2;
+ errRight.b = errDown[tx + x2 - bx0].b = err.b / 2;
+ } else {
+ color2.r = r0;
+ color2.g = g0;
+ color2.b = b0;
+ pix = findColor(&color2, &err);
+ }
+
+ // set pixel
+ //~ this should do a blend when 0 < alpha < 1
+ if (alpha < 0.75) {
+ XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
+ }
+ }
+ }
+
+ // blit the image into the pixmap
+ XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);
+
+ // free memory
+ delete imgStr;
+ gfree(pixBuf);
+ if (maskColors) {
+ gfree(alphaBuf);
+ }
+ gfree(image->data);
+ image->data = NULL;
+ XDestroyImage(image);
+ gfree(errDown);
+}
+
+GBool XOutputDev::findText(Unicode *s, int len, GBool top, GBool bottom,
+ int *xMin, int *yMin, int *xMax, int *yMax) {
+ double xMin1, yMin1, xMax1, yMax1;
+
+ xMin1 = (double)*xMin;
+ yMin1 = (double)*yMin;
+ xMax1 = (double)*xMax;
+ yMax1 = (double)*yMax;
+ if (text->findText(s, len, top, bottom, &xMin1, &yMin1, &xMax1, &yMax1)) {
+ *xMin = xoutRound(xMin1);
+ *xMax = xoutRound(xMax1);
+ *yMin = xoutRound(yMin1);
+ *yMax = xoutRound(yMax1);
+ return gTrue;
+ }
+ return gFalse;
+}
+
+GString *XOutputDev::getText(int xMin, int yMin, int xMax, int yMax) {
+ return text->getText((double)xMin, (double)yMin,
+ (double)xMax, (double)yMax);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFApp.cc b/filters/kword/pdf/xpdf/xpdf/XPDFApp.cc
deleted file mode 100644
index e456310b6..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XPDFApp.cc
+++ /dev/null
@@ -1,386 +0,0 @@
-//========================================================================
-//
-// XPDFApp.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "GString.h"
-#include "GList.h"
-#include "Error.h"
-#include "XPDFViewer.h"
-#include "XPDFApp.h"
-#include "config.h"
-
-// these macro defns conflict with xpdf's Object class
-#ifdef LESSTIF_VERSION
-#undef XtDisplay
-#undef XtScreen
-#undef XtWindow
-#undef XtParent
-#undef XtIsRealized
-#endif
-
-//------------------------------------------------------------------------
-
-#define remoteCmdSize 512
-
-//------------------------------------------------------------------------
-
-static String fallbackResources[] = {
- "*XmTextField.fontList: -*-courier-medium-r-normal--12-*-*-*-*-*-iso8859-1",
- "*.fontList: -*-helvetica-medium-r-normal--12-*-*-*-*-*-iso8859-1",
- "*XmTextField.translations: #override\\n"
- " Ctrl<Key>a:beginning-of-line()\\n"
- " Ctrl<Key>b:backward-character()\\n"
- " Ctrl<Key>d:delete-next-character()\\n"
- " Ctrl<Key>e:end-of-line()\\n"
- " Ctrl<Key>f:forward-character()\\n"
- " Ctrl<Key>u:beginning-of-line()delete-to-end-of-line()\\n"
- " Ctrl<Key>k:delete-to-end-of-line()\\n",
- NULL
-};
-
-static XrmOptionDescRec xOpts[] = {
- {"-display", ".display", XrmoptionSepArg, NULL},
- {"-foreground", "*Foreground", XrmoptionSepArg, NULL},
- {"-fg", "*Foreground", XrmoptionSepArg, NULL},
- {"-background", "*Background", XrmoptionSepArg, NULL},
- {"-bg", "*Background", XrmoptionSepArg, NULL},
- {"-geometry", ".geometry", XrmoptionSepArg, NULL},
- {"-g", ".geometry", XrmoptionSepArg, NULL},
- {"-font", "*.fontList", XrmoptionSepArg, NULL},
- {"-fn", "*.fontList", XrmoptionSepArg, NULL},
- {"-title", ".title", XrmoptionSepArg, NULL},
- {"-cmap", ".installCmap", XrmoptionNoArg, (XPointer)"on"},
- {"-rgb", ".rgbCubeSize", XrmoptionSepArg, NULL},
- {"-rv", ".reverseVideo", XrmoptionNoArg, (XPointer)"true"},
- {"-papercolor", ".paperColor", XrmoptionSepArg, NULL},
- {"-z", ".initialZoom", XrmoptionSepArg, NULL}
-};
-
-#define nXOpts (sizeof(xOpts) / sizeof(XrmOptionDescRec))
-
-struct XPDFAppResources {
- String geometry;
- String title;
- Bool installCmap;
- int rgbCubeSize;
- Bool reverseVideo;
- String paperColor;
- String initialZoom;
- Bool viKeys;
-};
-
-static Bool defInstallCmap = False;
-static int defRGBCubeSize = defaultRGBCube;
-static Bool defReverseVideo = False;
-static Bool defViKeys = False;
-
-static XtResource xResources[] = {
- { "geometry", "Geometry", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, geometry), XtRString, (XtPointer)NULL },
- { "title", "Title", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, title), XtRString, (XtPointer)NULL },
- { "installCmap", "InstallCmap", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, installCmap), XtRBool, (XtPointer)&defInstallCmap },
- { "rgbCubeSize", "RgbCubeSize", XtRInt, sizeof(int), XtOffsetOf(XPDFAppResources, rgbCubeSize), XtRInt, (XtPointer)&defRGBCubeSize },
- { "reverseVideo", "ReverseVideo", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, reverseVideo), XtRBool, (XtPointer)&defReverseVideo },
- { "paperColor", "PaperColor", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, paperColor), XtRString, (XtPointer)NULL },
- { "initialZoom", "InitialZoom", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, initialZoom), XtRString, (XtPointer)NULL },
- { "viKeys", "ViKeys", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, viKeys), XtRBool, (XtPointer)&defViKeys }
-};
-
-#define nXResources (sizeof(xResources) / sizeof(XtResource))
-
-//------------------------------------------------------------------------
-// XPDFApp
-//------------------------------------------------------------------------
-
-#if 0 //~ for debugging
-static int xErrorHandler(Display *display, XErrorEvent *ev) {
- printf("X error:\n");
- printf(" resource ID = %08lx\n", ev->resourceid);
- printf(" serial = %lu\n", ev->serial);
- printf(" error_code = %d\n", ev->error_code);
- printf(" request_code = %d\n", ev->request_code);
- printf(" minor_code = %d\n", ev->minor_code);
- fflush(stdout);
- abort();
-}
-#endif
-
-XPDFApp::XPDFApp(int *argc, char *argv[]) {
- appShell = XtAppInitialize(&appContext, xpdfAppName, xOpts, nXOpts,
- argc, argv, fallbackResources, NULL, 0);
- display = XtDisplay(appShell);
- screenNum = XScreenNumberOfScreen(XtScreen(appShell));
-#if XmVERSION > 1
- XtVaSetValues(XmGetXmDisplay(XtDisplay(appShell)),
- XmNenableButtonTab, True, NULL);
-#endif
-#if XmVERSION > 1
- // Drag-and-drop appears to be buggy -- I'm seeing weird crashes
- // deep in the Motif code when I destroy widgets in the XpdfForms
- // code. Xpdf doesn't use it, so just turn it off.
- XtVaSetValues(XmGetXmDisplay(XtDisplay(appShell)),
- XmNdragInitiatorProtocolStyle, XmDRAG_NONE,
- XmNdragReceiverProtocolStyle, XmDRAG_NONE,
- NULL);
-#endif
-
-#if 0 //~ for debugging
- XSynchronize(display, True);
- XSetErrorHandler(&xErrorHandler);
-#endif
-
- fullScreen = gFalse;
- remoteAtom = None;
- remoteViewer = NULL;
- remoteWin = None;
-
- getResources();
-
- viewers = new GList();
-
-}
-
-void XPDFApp::getResources() {
- XPDFAppResources resources;
- XColor xcol, xcol2;
- Colormap colormap;
-
- XtGetApplicationResources(appShell, &resources, xResources, nXResources,
- NULL, 0);
- geometry = resources.geometry ? new GString(resources.geometry)
- : (GString *)NULL;
- title = resources.title ? new GString(resources.title) : (GString *)NULL;
- installCmap = (GBool)resources.installCmap;
- rgbCubeSize = resources.rgbCubeSize;
- reverseVideo = (GBool)resources.reverseVideo;
- paperColor = reverseVideo ? BlackPixel(display, screenNum) :
- WhitePixel(display, screenNum);
- if (resources.paperColor) {
- XtVaGetValues(appShell, XmNcolormap, &colormap, NULL);
- if (XAllocNamedColor(display, colormap, resources.paperColor,
- &xcol, &xcol2)) {
- paperColor = xcol.pixel;
- } else {
- error(-1, "Couldn't allocate color '%s'", resources.paperColor);
- }
- }
- initialZoom = resources.initialZoom ? new GString(resources.initialZoom)
- : (GString *)NULL;
- viKeys = (GBool)resources.viKeys;
-}
-
-XPDFApp::~XPDFApp() {
- deleteGList(viewers, XPDFViewer);
- if (geometry) {
- delete geometry;
- }
- if (title) {
- delete title;
- }
- if (initialZoom) {
- delete initialZoom;
- }
-}
-
-XPDFViewer *XPDFApp::open(GString *fileName, int page,
- GString *ownerPassword, GString *userPassword) {
- XPDFViewer *viewer;
-
- viewer = new XPDFViewer(this, fileName, page, NULL,
- ownerPassword, userPassword);
- if (!viewer->isOk()) {
- delete viewer;
- return NULL;
- }
- if (remoteAtom != None) {
- remoteViewer = viewer;
- remoteWin = viewer->getWindow();
- XtAddEventHandler(remoteWin, PropertyChangeMask, False,
- &remoteMsgCbk, this);
- XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin), CurrentTime);
- }
- viewers->append(viewer);
- return viewer;
-}
-
-XPDFViewer *XPDFApp::openAtDest(GString *fileName, GString *dest,
- GString *ownerPassword,
- GString *userPassword) {
- XPDFViewer *viewer;
-
- viewer = new XPDFViewer(this, fileName, 1, dest,
- ownerPassword, userPassword);
- if (!viewer->isOk()) {
- delete viewer;
- return NULL;
- }
- if (remoteAtom != None) {
- remoteViewer = viewer;
- remoteWin = viewer->getWindow();
- XtAddEventHandler(remoteWin, PropertyChangeMask, False,
- &remoteMsgCbk, this);
- XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin), CurrentTime);
- }
- viewers->append(viewer);
- return viewer;
-}
-
-void XPDFApp::close(XPDFViewer *viewer, GBool closeLast) {
- int i;
-
- if (viewers->getLength() == 1) {
- if (viewer != (XPDFViewer *)viewers->get(0)) {
- return;
- }
- if (closeLast) {
- quit();
- } else {
- viewer->clear();
- }
- } else {
- for (i = 0; i < viewers->getLength(); ++i) {
- if (((XPDFViewer *)viewers->get(i)) == viewer) {
- viewers->del(i);
- if (remoteAtom != None && remoteViewer == viewer) {
- remoteViewer = (XPDFViewer *)viewers->get(viewers->getLength() - 1);
- remoteWin = remoteViewer->getWindow();
- XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin),
- CurrentTime);
- }
- delete viewer;
- return;
- }
- }
- }
-}
-
-void XPDFApp::quit() {
- if (remoteAtom != None) {
- XSetSelectionOwner(display, remoteAtom, None, CurrentTime);
- }
- while (viewers->getLength() > 0) {
- delete (XPDFViewer *)viewers->del(0);
- }
- XtAppSetExitFlag(appContext);
-}
-
-void XPDFApp::run() {
- XtAppMainLoop(appContext);
-}
-
-void XPDFApp::setRemoteName(char *remoteName) {
- remoteAtom = XInternAtom(display, remoteName, False);
- remoteXWin = XGetSelectionOwner(display, remoteAtom);
-}
-
-GBool XPDFApp::remoteServerRunning() {
- return remoteXWin != None;
-}
-
-void XPDFApp::remoteOpen(GString *fileName, int page, GBool raise) {
- char cmd[remoteCmdSize];
-
- sprintf(cmd, "%c %d %.200s",
- raise ? 'D' : 'd', page, fileName->getCString());
- XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
- PropModeReplace, (Guchar *)cmd, strlen(cmd) + 1);
- XFlush(display);
-}
-
-void XPDFApp::remoteOpenAtDest(GString *fileName, GString *dest, GBool raise) {
- char cmd[remoteCmdSize];
-
- sprintf(cmd, "%c +%.256s %.200s",
- raise ? 'D' : 'd', dest->getCString(), fileName->getCString());
- XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
- PropModeReplace, (Guchar *)cmd, strlen(cmd) + 1);
- XFlush(display);
-}
-
-void XPDFApp::remoteRaise() {
- XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
- PropModeReplace, (Guchar *)"r", 2);
- XFlush(display);
-}
-
-void XPDFApp::remoteQuit() {
- XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
- PropModeReplace, (Guchar *)"q", 2);
- XFlush(display);
-}
-
-void XPDFApp::remoteMsgCbk(Widget widget, XtPointer ptr,
- XEvent *event, Boolean *cont) {
- XPDFApp *app = (XPDFApp *)ptr;
- char *cmd;
- Atom type;
- int format;
- Gulong size, remain;
- char *p, *q;
- GString *fileName;
- int page;
- GString *destName;
-
- if (event->xproperty.atom != app->remoteAtom) {
- *cont = True;
- return;
- }
- *cont = False;
-
- // get command
- if (XGetWindowProperty(app->display, XtWindow(app->remoteWin),
- app->remoteAtom, 0, remoteCmdSize/4,
- True, app->remoteAtom,
- &type, &format, &size, &remain,
- (Guchar **)&cmd) != Success) {
- return;
- }
- if (size == 0) {
- return;
- }
-
- // raise window
- if (cmd[0] == 'D' || cmd[0] == 'r'){
- XMapRaised(app->display, XtWindow(app->remoteWin));
- XFlush(app->display);
- }
-
- // display file / page
- if (cmd[0] == 'd' || cmd[0] == 'D') {
- p = cmd + 2;
- q = strchr(p, ' ');
- if (!q) {
- return;
- }
- *q++ = '\0';
- page = 1;
- destName = NULL;
- if (*p == '+') {
- destName = new GString(p + 1);
- } else {
- page = atoi(p);
- }
- if (q) {
- fileName = new GString(q);
- app->remoteViewer->open(fileName, page, destName);
- delete fileName;
- }
- XFree((XPointer)cmd);
- if (destName) {
- delete destName;
- }
-
- // quit
- } else if (cmd[0] == 'q') {
- app->quit();
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFApp.cpp b/filters/kword/pdf/xpdf/xpdf/XPDFApp.cpp
new file mode 100644
index 000000000..b64f17c7f
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XPDFApp.cpp
@@ -0,0 +1,386 @@
+//========================================================================
+//
+// XPDFApp.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "GString.h"
+#include "GList.h"
+#include "Error.h"
+#include "XPDFViewer.h"
+#include "XPDFApp.h"
+#include "config.h"
+
+// these macro defns conflict with xpdf's Object class
+#ifdef LESSTIF_VERSION
+#undef XtDisplay
+#undef XtScreen
+#undef XtWindow
+#undef XtParent
+#undef XtIsRealized
+#endif
+
+//------------------------------------------------------------------------
+
+#define remoteCmdSize 512
+
+//------------------------------------------------------------------------
+
+static String fallbackResources[] = {
+ "*XmTextField.fontList: -*-courier-medium-r-normal--12-*-*-*-*-*-iso8859-1",
+ "*.fontList: -*-helvetica-medium-r-normal--12-*-*-*-*-*-iso8859-1",
+ "*XmTextField.translations: #override\\n"
+ " Ctrl<Key>a:beginning-of-line()\\n"
+ " Ctrl<Key>b:backward-character()\\n"
+ " Ctrl<Key>d:delete-next-character()\\n"
+ " Ctrl<Key>e:end-of-line()\\n"
+ " Ctrl<Key>f:forward-character()\\n"
+ " Ctrl<Key>u:beginning-of-line()delete-to-end-of-line()\\n"
+ " Ctrl<Key>k:delete-to-end-of-line()\\n",
+ NULL
+};
+
+static XrmOptionDescRec xOpts[] = {
+ {"-display", ".display", XrmoptionSepArg, NULL},
+ {"-foreground", "*Foreground", XrmoptionSepArg, NULL},
+ {"-fg", "*Foreground", XrmoptionSepArg, NULL},
+ {"-background", "*Background", XrmoptionSepArg, NULL},
+ {"-bg", "*Background", XrmoptionSepArg, NULL},
+ {"-geometry", ".geometry", XrmoptionSepArg, NULL},
+ {"-g", ".geometry", XrmoptionSepArg, NULL},
+ {"-font", "*.fontList", XrmoptionSepArg, NULL},
+ {"-fn", "*.fontList", XrmoptionSepArg, NULL},
+ {"-title", ".title", XrmoptionSepArg, NULL},
+ {"-cmap", ".installCmap", XrmoptionNoArg, (XPointer)"on"},
+ {"-rgb", ".rgbCubeSize", XrmoptionSepArg, NULL},
+ {"-rv", ".reverseVideo", XrmoptionNoArg, (XPointer)"true"},
+ {"-papercolor", ".paperColor", XrmoptionSepArg, NULL},
+ {"-z", ".initialZoom", XrmoptionSepArg, NULL}
+};
+
+#define nXOpts (sizeof(xOpts) / sizeof(XrmOptionDescRec))
+
+struct XPDFAppResources {
+ String geometry;
+ String title;
+ Bool installCmap;
+ int rgbCubeSize;
+ Bool reverseVideo;
+ String paperColor;
+ String initialZoom;
+ Bool viKeys;
+};
+
+static Bool defInstallCmap = False;
+static int defRGBCubeSize = defaultRGBCube;
+static Bool defReverseVideo = False;
+static Bool defViKeys = False;
+
+static XtResource xResources[] = {
+ { "geometry", "Geometry", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, geometry), XtRString, (XtPointer)NULL },
+ { "title", "Title", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, title), XtRString, (XtPointer)NULL },
+ { "installCmap", "InstallCmap", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, installCmap), XtRBool, (XtPointer)&defInstallCmap },
+ { "rgbCubeSize", "RgbCubeSize", XtRInt, sizeof(int), XtOffsetOf(XPDFAppResources, rgbCubeSize), XtRInt, (XtPointer)&defRGBCubeSize },
+ { "reverseVideo", "ReverseVideo", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, reverseVideo), XtRBool, (XtPointer)&defReverseVideo },
+ { "paperColor", "PaperColor", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, paperColor), XtRString, (XtPointer)NULL },
+ { "initialZoom", "InitialZoom", XtRString, sizeof(String), XtOffsetOf(XPDFAppResources, initialZoom), XtRString, (XtPointer)NULL },
+ { "viKeys", "ViKeys", XtRBool, sizeof(Bool), XtOffsetOf(XPDFAppResources, viKeys), XtRBool, (XtPointer)&defViKeys }
+};
+
+#define nXResources (sizeof(xResources) / sizeof(XtResource))
+
+//------------------------------------------------------------------------
+// XPDFApp
+//------------------------------------------------------------------------
+
+#if 0 //~ for debugging
+static int xErrorHandler(Display *display, XErrorEvent *ev) {
+ printf("X error:\n");
+ printf(" resource ID = %08lx\n", ev->resourceid);
+ printf(" serial = %lu\n", ev->serial);
+ printf(" error_code = %d\n", ev->error_code);
+ printf(" request_code = %d\n", ev->request_code);
+ printf(" minor_code = %d\n", ev->minor_code);
+ fflush(stdout);
+ abort();
+}
+#endif
+
+XPDFApp::XPDFApp(int *argc, char *argv[]) {
+ appShell = XtAppInitialize(&appContext, xpdfAppName, xOpts, nXOpts,
+ argc, argv, fallbackResources, NULL, 0);
+ display = XtDisplay(appShell);
+ screenNum = XScreenNumberOfScreen(XtScreen(appShell));
+#if XmVERSION > 1
+ XtVaSetValues(XmGetXmDisplay(XtDisplay(appShell)),
+ XmNenableButtonTab, True, NULL);
+#endif
+#if XmVERSION > 1
+ // Drag-and-drop appears to be buggy -- I'm seeing weird crashes
+ // deep in the Motif code when I destroy widgets in the XpdfForms
+ // code. Xpdf doesn't use it, so just turn it off.
+ XtVaSetValues(XmGetXmDisplay(XtDisplay(appShell)),
+ XmNdragInitiatorProtocolStyle, XmDRAG_NONE,
+ XmNdragReceiverProtocolStyle, XmDRAG_NONE,
+ NULL);
+#endif
+
+#if 0 //~ for debugging
+ XSynchronize(display, True);
+ XSetErrorHandler(&xErrorHandler);
+#endif
+
+ fullScreen = gFalse;
+ remoteAtom = None;
+ remoteViewer = NULL;
+ remoteWin = None;
+
+ getResources();
+
+ viewers = new GList();
+
+}
+
+void XPDFApp::getResources() {
+ XPDFAppResources resources;
+ XColor xcol, xcol2;
+ Colormap colormap;
+
+ XtGetApplicationResources(appShell, &resources, xResources, nXResources,
+ NULL, 0);
+ geometry = resources.geometry ? new GString(resources.geometry)
+ : (GString *)NULL;
+ title = resources.title ? new GString(resources.title) : (GString *)NULL;
+ installCmap = (GBool)resources.installCmap;
+ rgbCubeSize = resources.rgbCubeSize;
+ reverseVideo = (GBool)resources.reverseVideo;
+ paperColor = reverseVideo ? BlackPixel(display, screenNum) :
+ WhitePixel(display, screenNum);
+ if (resources.paperColor) {
+ XtVaGetValues(appShell, XmNcolormap, &colormap, NULL);
+ if (XAllocNamedColor(display, colormap, resources.paperColor,
+ &xcol, &xcol2)) {
+ paperColor = xcol.pixel;
+ } else {
+ error(-1, "Couldn't allocate color '%s'", resources.paperColor);
+ }
+ }
+ initialZoom = resources.initialZoom ? new GString(resources.initialZoom)
+ : (GString *)NULL;
+ viKeys = (GBool)resources.viKeys;
+}
+
+XPDFApp::~XPDFApp() {
+ deleteGList(viewers, XPDFViewer);
+ if (geometry) {
+ delete geometry;
+ }
+ if (title) {
+ delete title;
+ }
+ if (initialZoom) {
+ delete initialZoom;
+ }
+}
+
+XPDFViewer *XPDFApp::open(GString *fileName, int page,
+ GString *ownerPassword, GString *userPassword) {
+ XPDFViewer *viewer;
+
+ viewer = new XPDFViewer(this, fileName, page, NULL,
+ ownerPassword, userPassword);
+ if (!viewer->isOk()) {
+ delete viewer;
+ return NULL;
+ }
+ if (remoteAtom != None) {
+ remoteViewer = viewer;
+ remoteWin = viewer->getWindow();
+ XtAddEventHandler(remoteWin, PropertyChangeMask, False,
+ &remoteMsgCbk, this);
+ XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin), CurrentTime);
+ }
+ viewers->append(viewer);
+ return viewer;
+}
+
+XPDFViewer *XPDFApp::openAtDest(GString *fileName, GString *dest,
+ GString *ownerPassword,
+ GString *userPassword) {
+ XPDFViewer *viewer;
+
+ viewer = new XPDFViewer(this, fileName, 1, dest,
+ ownerPassword, userPassword);
+ if (!viewer->isOk()) {
+ delete viewer;
+ return NULL;
+ }
+ if (remoteAtom != None) {
+ remoteViewer = viewer;
+ remoteWin = viewer->getWindow();
+ XtAddEventHandler(remoteWin, PropertyChangeMask, False,
+ &remoteMsgCbk, this);
+ XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin), CurrentTime);
+ }
+ viewers->append(viewer);
+ return viewer;
+}
+
+void XPDFApp::close(XPDFViewer *viewer, GBool closeLast) {
+ int i;
+
+ if (viewers->getLength() == 1) {
+ if (viewer != (XPDFViewer *)viewers->get(0)) {
+ return;
+ }
+ if (closeLast) {
+ quit();
+ } else {
+ viewer->clear();
+ }
+ } else {
+ for (i = 0; i < viewers->getLength(); ++i) {
+ if (((XPDFViewer *)viewers->get(i)) == viewer) {
+ viewers->del(i);
+ if (remoteAtom != None && remoteViewer == viewer) {
+ remoteViewer = (XPDFViewer *)viewers->get(viewers->getLength() - 1);
+ remoteWin = remoteViewer->getWindow();
+ XSetSelectionOwner(display, remoteAtom, XtWindow(remoteWin),
+ CurrentTime);
+ }
+ delete viewer;
+ return;
+ }
+ }
+ }
+}
+
+void XPDFApp::quit() {
+ if (remoteAtom != None) {
+ XSetSelectionOwner(display, remoteAtom, None, CurrentTime);
+ }
+ while (viewers->getLength() > 0) {
+ delete (XPDFViewer *)viewers->del(0);
+ }
+ XtAppSetExitFlag(appContext);
+}
+
+void XPDFApp::run() {
+ XtAppMainLoop(appContext);
+}
+
+void XPDFApp::setRemoteName(char *remoteName) {
+ remoteAtom = XInternAtom(display, remoteName, False);
+ remoteXWin = XGetSelectionOwner(display, remoteAtom);
+}
+
+GBool XPDFApp::remoteServerRunning() {
+ return remoteXWin != None;
+}
+
+void XPDFApp::remoteOpen(GString *fileName, int page, GBool raise) {
+ char cmd[remoteCmdSize];
+
+ sprintf(cmd, "%c %d %.200s",
+ raise ? 'D' : 'd', page, fileName->getCString());
+ XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
+ PropModeReplace, (Guchar *)cmd, strlen(cmd) + 1);
+ XFlush(display);
+}
+
+void XPDFApp::remoteOpenAtDest(GString *fileName, GString *dest, GBool raise) {
+ char cmd[remoteCmdSize];
+
+ sprintf(cmd, "%c +%.256s %.200s",
+ raise ? 'D' : 'd', dest->getCString(), fileName->getCString());
+ XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
+ PropModeReplace, (Guchar *)cmd, strlen(cmd) + 1);
+ XFlush(display);
+}
+
+void XPDFApp::remoteRaise() {
+ XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
+ PropModeReplace, (Guchar *)"r", 2);
+ XFlush(display);
+}
+
+void XPDFApp::remoteQuit() {
+ XChangeProperty(display, remoteXWin, remoteAtom, remoteAtom, 8,
+ PropModeReplace, (Guchar *)"q", 2);
+ XFlush(display);
+}
+
+void XPDFApp::remoteMsgCbk(Widget widget, XtPointer ptr,
+ XEvent *event, Boolean *cont) {
+ XPDFApp *app = (XPDFApp *)ptr;
+ char *cmd;
+ Atom type;
+ int format;
+ Gulong size, remain;
+ char *p, *q;
+ GString *fileName;
+ int page;
+ GString *destName;
+
+ if (event->xproperty.atom != app->remoteAtom) {
+ *cont = True;
+ return;
+ }
+ *cont = False;
+
+ // get command
+ if (XGetWindowProperty(app->display, XtWindow(app->remoteWin),
+ app->remoteAtom, 0, remoteCmdSize/4,
+ True, app->remoteAtom,
+ &type, &format, &size, &remain,
+ (Guchar **)&cmd) != Success) {
+ return;
+ }
+ if (size == 0) {
+ return;
+ }
+
+ // raise window
+ if (cmd[0] == 'D' || cmd[0] == 'r'){
+ XMapRaised(app->display, XtWindow(app->remoteWin));
+ XFlush(app->display);
+ }
+
+ // display file / page
+ if (cmd[0] == 'd' || cmd[0] == 'D') {
+ p = cmd + 2;
+ q = strchr(p, ' ');
+ if (!q) {
+ return;
+ }
+ *q++ = '\0';
+ page = 1;
+ destName = NULL;
+ if (*p == '+') {
+ destName = new GString(p + 1);
+ } else {
+ page = atoi(p);
+ }
+ if (q) {
+ fileName = new GString(q);
+ app->remoteViewer->open(fileName, page, destName);
+ delete fileName;
+ }
+ XFree((XPointer)cmd);
+ if (destName) {
+ delete destName;
+ }
+
+ // quit
+ } else if (cmd[0] == 'q') {
+ app->quit();
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFCore.cc b/filters/kword/pdf/xpdf/xpdf/XPDFCore.cc
deleted file mode 100644
index 8376ce97d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XPDFCore.cc
+++ /dev/null
@@ -1,1913 +0,0 @@
-//========================================================================
-//
-// XPDFCore.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <X11/keysym.h>
-#include <X11/cursorfont.h>
-#include "gmem.h"
-#include "GString.h"
-#include "GList.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "PDFDoc.h"
-#include "ErrorCodes.h"
-#include "GfxState.h"
-#include "PSOutputDev.h"
-#include "TextOutputDev.h"
-#include "XPixmapOutputDev.h"
-#include "XPDFCore.h"
-
-// these macro defns conflict with xpdf's Object class
-#ifdef LESSTIF_VERSION
-#undef XtDisplay
-#undef XtScreen
-#undef XtWindow
-#undef XtParent
-#undef XtIsRealized
-#endif
-
-// hack around old X includes which are missing these symbols
-#ifndef XK_Page_Up
-#define XK_Page_Up 0xFF55
-#endif
-#ifndef XK_Page_Down
-#define XK_Page_Down 0xFF56
-#endif
-#ifndef XK_KP_Home
-#define XK_KP_Home 0xFF95
-#endif
-#ifndef XK_KP_Left
-#define XK_KP_Left 0xFF96
-#endif
-#ifndef XK_KP_Up
-#define XK_KP_Up 0xFF97
-#endif
-#ifndef XK_KP_Right
-#define XK_KP_Right 0xFF98
-#endif
-#ifndef XK_KP_Down
-#define XK_KP_Down 0xFF99
-#endif
-#ifndef XK_KP_Prior
-#define XK_KP_Prior 0xFF9A
-#endif
-#ifndef XK_KP_Page_Up
-#define XK_KP_Page_Up 0xFF9A
-#endif
-#ifndef XK_KP_Next
-#define XK_KP_Next 0xFF9B
-#endif
-#ifndef XK_KP_Page_Down
-#define XK_KP_Page_Down 0xFF9B
-#endif
-#ifndef XK_KP_End
-#define XK_KP_End 0xFF9C
-#endif
-#ifndef XK_KP_Begin
-#define XK_KP_Begin 0xFF9D
-#endif
-#ifndef XK_KP_Insert
-#define XK_KP_Insert 0xFF9E
-#endif
-#ifndef XK_KP_Delete
-#define XK_KP_Delete 0xFF9F
-#endif
-
-//------------------------------------------------------------------------
-
-#define highlightNone 0
-#define highlightNormal 1
-#define highlightSelected 2
-
-//------------------------------------------------------------------------
-
-static int zoomDPI[maxZoom - minZoom + 1] = {
- 29, 35, 42, 50, 60,
- 72,
- 86, 104, 124, 149, 179
-};
-
-//------------------------------------------------------------------------
-
-GString *XPDFCore::currentSelection = NULL;
-XPDFCore *XPDFCore::currentSelectionOwner = NULL;
-
-//------------------------------------------------------------------------
-// XPDFCore
-//------------------------------------------------------------------------
-
-XPDFCore::XPDFCore(Widget shellA, Widget parentWidgetA,
- Gulong paperColorA, GBool fullScreenA, GBool reverseVideo,
- GBool installCmap, int rgbCubeSize) {
- GString *initialZoom;
- int i;
-
- shell = shellA;
- parentWidget = parentWidgetA;
- display = XtDisplay(parentWidget);
- screenNum = XScreenNumberOfScreen(XtScreen(parentWidget));
-
- paperColor = paperColorA;
- fullScreen = fullScreenA;
-
- // for some reason, querying XmNvisual doesn't work (even if done
- // after the window is mapped)
- visual = DefaultVisual(display, screenNum);
- XtVaGetValues(shell, XmNcolormap, &colormap, NULL);
-
- scrolledWin = NULL;
- hScrollBar = NULL;
- vScrollBar = NULL;
- drawAreaFrame = NULL;
- drawArea = NULL;
- out = NULL;
-
- doc = NULL;
- page = 0;
- rotate = 0;
-
- // get the initial zoom value
- initialZoom = globalParams->getInitialZoom();
- if (!initialZoom->cmp("page")) {
- zoom = zoomPage;
- } else if (!initialZoom->cmp("width")) {
- zoom = zoomWidth;
- } else {
- zoom = atoi(initialZoom->getCString());
- if (zoom < minZoom) {
- zoom = minZoom;
- } else if (zoom > maxZoom) {
- zoom = maxZoom;
- }
- }
-
- scrollX = 0;
- scrollY = 0;
- linkAction = NULL;
- selectXMin = selectXMax = 0;
- selectYMin = selectYMax = 0;
- dragging = gFalse;
- lastDragLeft = lastDragTop = gTrue;
-
- panning = gFalse;
-
-
- updateCbk = NULL;
- actionCbk = NULL;
- keyPressCbk = NULL;
- mouseCbk = NULL;
- reqPasswordCbk = NULL;
-
- // no history yet
- historyCur = xpdfHistorySize - 1;
- historyBLen = historyFLen = 0;
- for (i = 0; i < xpdfHistorySize; ++i) {
- history[i].fileName = NULL;
- }
-
- // optional features default to on
- hyperlinksEnabled = gTrue;
- selectEnabled = gTrue;
-
- // do X-specific initialization and create the widgets
- initWindow();
-
- // create the OutputDev
- out = new XPixmapOutputDev(display, screenNum, visual, colormap,
- reverseVideo, paperColor,
- installCmap, rgbCubeSize, gTrue,
- &outputDevRedrawCbk, this);
- out->startDoc(NULL);
-}
-
-XPDFCore::~XPDFCore() {
- int i;
-
- if (out) {
- delete out;
- }
- if (doc) {
- delete doc;
- }
- if (currentSelectionOwner == this && currentSelection) {
- delete currentSelection;
- currentSelection = NULL;
- currentSelectionOwner = NULL;
- }
- for (i = 0; i < xpdfHistorySize; ++i) {
- if (history[i].fileName) {
- delete history[i].fileName;
- }
- }
- if (selectGC) {
- XFreeGC(display, selectGC);
- XFreeGC(display, highlightGC);
- }
- if (drawAreaGC) {
- XFreeGC(display, drawAreaGC);
- }
- if (drawArea) {
- XtDestroyWidget(drawArea);
- }
- if (drawAreaFrame) {
- XtDestroyWidget(drawAreaFrame);
- }
- if (vScrollBar) {
- XtDestroyWidget(vScrollBar);
- }
- if (hScrollBar) {
- XtDestroyWidget(hScrollBar);
- }
- if (scrolledWin) {
- XtDestroyWidget(scrolledWin);
- }
- if (busyCursor) {
- XFreeCursor(display, busyCursor);
- }
- if (linkCursor) {
- XFreeCursor(display, linkCursor);
- }
- if (selectCursor) {
- XFreeCursor(display, selectCursor);
- }
-}
-
-//------------------------------------------------------------------------
-// loadFile / displayPage / displayDest
-//------------------------------------------------------------------------
-
-int XPDFCore::loadFile(GString *fileName, GString *ownerPassword,
- GString *userPassword) {
- PDFDoc *newDoc;
- GString *password;
- GBool again;
- int err;
-
- // busy cursor
- setCursor(busyCursor);
-
- // open the PDF file
- newDoc = new PDFDoc(fileName->copy(), ownerPassword, userPassword);
- if (!newDoc->isOk()) {
- err = newDoc->getErrorCode();
- delete newDoc;
- if (err != errEncrypted || !reqPasswordCbk) {
- setCursor(None);
- return err;
- }
-
- // try requesting a password
- again = ownerPassword != NULL || userPassword != NULL;
- while (1) {
- if (!(password = (*reqPasswordCbk)(reqPasswordCbkData, again))) {
- setCursor(None);
- return errEncrypted;
- }
- newDoc = new PDFDoc(fileName->copy(), password, password);
- if (newDoc->isOk()) {
- break;
- }
- err = newDoc->getErrorCode();
- delete newDoc;
- if (err != errEncrypted) {
- setCursor(None);
- return err;
- }
- again = gTrue;
- }
- }
-
- // replace old document
- if (doc) {
- delete doc;
- }
- doc = newDoc;
- if (out) {
- out->startDoc(doc->getXRef());
- }
-
- // nothing displayed yet
- page = -99;
-
- // save the modification time
- modTime = getModTime(doc->getFileName()->getCString());
-
- // update the parent window
- if (updateCbk) {
- (*updateCbk)(updateCbkData, doc->getFileName(), -1,
- doc->getNumPages(), NULL);
- }
-
- // back to regular cursor
- setCursor(None);
-
- return errNone;
-}
-
-void XPDFCore::resizeToPage(int pg) {
- Dimension width, height;
- double width1, height1;
- Dimension topW, topH, topBorder, daW, daH;
- Dimension displayW, displayH;
-
- displayW = DisplayWidth(display, screenNum);
- displayH = DisplayHeight(display, screenNum);
- if (fullScreen) {
- width = displayW;
- height = displayH;
- } else {
- if (pg < 0 || pg > doc->getNumPages()) {
- width1 = 612;
- height1 = 792;
- } else if (doc->getPageRotate(pg) == 90 ||
- doc->getPageRotate(pg) == 270) {
- width1 = doc->getPageHeight(pg);
- height1 = doc->getPageWidth(pg);
- } else {
- width1 = doc->getPageWidth(pg);
- height1 = doc->getPageHeight(pg);
- }
- if (zoom == zoomPage || zoom == zoomWidth) {
- width = (Dimension)((width1 * zoomDPI[defZoom - minZoom]) / 72 + 0.5);
- height = (Dimension)((height1 * zoomDPI[defZoom - minZoom]) / 72 + 0.5);
- } else {
- width = (Dimension)((width1 * zoomDPI[zoom - minZoom]) / 72 + 0.5);
- height = (Dimension)((height1 * zoomDPI[zoom - minZoom]) / 72 + 0.5);
- }
- if (width > displayW - 100) {
- width = displayW - 100;
- }
- if (height > displayH - 150) {
- height = displayH - 150;
- }
- }
-
- if (XtIsRealized(shell)) {
- XtVaGetValues(shell, XmNwidth, &topW, XmNheight, &topH,
- XmNborderWidth, &topBorder, NULL);
- XtVaGetValues(drawArea, XmNwidth, &daW, XmNheight, &daH, NULL);
- XtVaSetValues(shell, XmNwidth, width + (topW - daW),
- XmNheight, height + (topH - daH), NULL);
- } else {
- XtVaSetValues(drawArea, XmNwidth, width, XmNheight, height, NULL);
- }
-}
-
-void XPDFCore::clear() {
- if (!doc) {
- return;
- }
-
- // no document
- delete doc;
- doc = NULL;
- out->clear();
-
- // no page displayed
- page = -99;
-
- // redraw
- scrollX = scrollY = 0;
- updateScrollBars();
- redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
-}
-
-void XPDFCore::displayPage(int pageA, int zoomA, int rotateA,
- GBool scrollToTop, GBool addToHist) {
- double hDPI, vDPI;
- int rot;
- XPDFHistory *h;
- GBool newZoom;
- XGCValues gcValues;
- time_t newModTime;
- int oldScrollX, oldScrollY;
-
- // update the zoom and rotate values
- newZoom = zoomA != zoom;
- zoom = zoomA;
- rotate = rotateA;
-
- // check for document and valid page number
- if (!doc || pageA <= 0 || pageA > doc->getNumPages()) {
- return;
- }
-
- // busy cursor
- setCursor(busyCursor);
-
-
- // check for changes to the file
- newModTime = getModTime(doc->getFileName()->getCString());
- if (newModTime != modTime) {
- if (loadFile(doc->getFileName()) == errNone) {
- if (pageA > doc->getNumPages()) {
- pageA = doc->getNumPages();
- }
- }
- modTime = newModTime;
- }
-
- // free the old GCs
- if (selectGC) {
- XFreeGC(display, selectGC);
- XFreeGC(display, highlightGC);
- }
-
- // new page number
- page = pageA;
-
- // scroll to top
- if (scrollToTop) {
- scrollY = 0;
- }
-
- // if zoom level changed, scroll to the top-left corner
- if (newZoom) {
- scrollX = scrollY = 0;
- }
-
- // initialize mouse-related stuff
- linkAction = NULL;
- selectXMin = selectXMax = 0;
- selectYMin = selectYMax = 0;
- dragging = gFalse;
- lastDragLeft = lastDragTop = gTrue;
-
- // draw the page
- rot = rotate + doc->getPageRotate(page);
- if (rot >= 360) {
- rot -= 360;
- } else if (rotate < 0) {
- rot += 360;
- }
- if (zoom == zoomPage) {
- if (rot == 90 || rot == 270) {
- hDPI = (drawAreaWidth / doc->getPageHeight(page)) * 72;
- vDPI = (drawAreaHeight / doc->getPageWidth(page)) * 72;
- } else {
- hDPI = (drawAreaWidth / doc->getPageWidth(page)) * 72;
- vDPI = (drawAreaHeight / doc->getPageHeight(page)) * 72;
- }
- dpi = (hDPI < vDPI) ? hDPI : vDPI;
- } else if (zoom == zoomWidth) {
- if (rot == 90 || rot == 270) {
- dpi = (drawAreaWidth / doc->getPageHeight(page)) * 72;
- } else {
- dpi = (drawAreaWidth / doc->getPageWidth(page)) * 72;
- }
- } else {
- dpi = zoomDPI[zoom - minZoom];
- }
- out->setWindow(XtWindow(drawArea));
- doc->displayPage(out, page, dpi, rotate, gTrue);
- oldScrollX = scrollX;
- oldScrollY = scrollY;
- updateScrollBars();
- if (scrollX != oldScrollX || scrollY != oldScrollY) {
- redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
- }
-
-
- // add to history
- if (addToHist) {
- if (++historyCur == xpdfHistorySize) {
- historyCur = 0;
- }
- h = &history[historyCur];
- if (h->fileName) {
- delete h->fileName;
- }
- h->fileName = doc->getFileName()->copy();
- h->page = page;
- if (historyBLen < xpdfHistorySize) {
- ++historyBLen;
- }
- historyFLen = 0;
- }
-
- // update the parent window
- if (updateCbk) {
- (*updateCbk)(updateCbkData, NULL, page, -1, "");
- }
-
- // allocate new GCs
- gcValues.foreground = BlackPixel(display, screenNum) ^
- WhitePixel(display, screenNum);
- gcValues.function = GXxor;
- selectGC = XCreateGC(display, out->getPixmap(),
- GCForeground | GCFunction, &gcValues);
- highlightGC = XCreateGC(display, out->getPixmap(),
- GCForeground | GCFunction, &gcValues);
-
- // back to regular cursor
- setCursor(None);
-}
-
-void XPDFCore::displayDest(LinkDest *dest, int zoomA, int rotateA,
- GBool addToHist) {
- Ref pageRef;
- int pg;
- int dx, dy;
-
- if (dest->isPageRef()) {
- pageRef = dest->getPageRef();
- pg = doc->findPage(pageRef.num, pageRef.gen);
- } else {
- pg = dest->getPageNum();
- }
- if (pg <= 0 || pg > doc->getNumPages()) {
- pg = 1;
- }
- if (pg != page) {
- displayPage(pg, zoomA, rotateA, gTrue, addToHist);
- }
-
- if (fullScreen) {
- return;
- }
- switch (dest->getKind()) {
- case destXYZ:
- out->cvtUserToDev(dest->getLeft(), dest->getTop(), &dx, &dy);
- if (dest->getChangeLeft() || dest->getChangeTop()) {
- scrollTo(dest->getChangeLeft() ? dx : scrollX,
- dest->getChangeTop() ? dy : scrollY);
- }
- //~ what is the zoom parameter?
- break;
- case destFit:
- case destFitB:
- //~ do fit
- scrollTo(0, 0);
- break;
- case destFitH:
- case destFitBH:
- //~ do fit
- out->cvtUserToDev(0, dest->getTop(), &dx, &dy);
- scrollTo(0, dy);
- break;
- case destFitV:
- case destFitBV:
- //~ do fit
- out->cvtUserToDev(dest->getLeft(), 0, &dx, &dy);
- scrollTo(dx, 0);
- break;
- case destFitR:
- //~ do fit
- out->cvtUserToDev(dest->getLeft(), dest->getTop(), &dx, &dy);
- scrollTo(dx, dy);
- break;
- }
-}
-
-//------------------------------------------------------------------------
-// page/position changes
-//------------------------------------------------------------------------
-
-void XPDFCore::gotoNextPage(int inc, GBool top) {
- int pg;
-
- if (!doc || doc->getNumPages() == 0) {
- return;
- }
- if (page < doc->getNumPages()) {
- if ((pg = page + inc) > doc->getNumPages()) {
- pg = doc->getNumPages();
- }
- displayPage(pg, zoom, rotate, top, gTrue);
- } else {
- XBell(display, 0);
- }
-}
-
-void XPDFCore::gotoPrevPage(int dec, GBool top, GBool bottom) {
- int pg;
-
- if (!doc || doc->getNumPages() == 0) {
- return;
- }
- if (page > 1) {
- if (!fullScreen && bottom) {
- scrollY = out->getPixmapHeight() - drawAreaHeight;
- if (scrollY < 0) {
- scrollY = 0;
- }
- // displayPage will call updateScrollBars()
- }
- if ((pg = page - dec) < 1) {
- pg = 1;
- }
- displayPage(pg, zoom, rotate, top, gTrue);
- } else {
- XBell(display, 0);
- }
-}
-
-void XPDFCore::goForward() {
- if (historyFLen == 0) {
- XBell(display, 0);
- return;
- }
- if (++historyCur == xpdfHistorySize) {
- historyCur = 0;
- }
- --historyFLen;
- ++historyBLen;
- if (history[historyCur].fileName->cmp(doc->getFileName()) != 0) {
- if (loadFile(history[historyCur].fileName) != errNone) {
- XBell(display, 0);
- return;
- }
- }
- displayPage(history[historyCur].page, zoom, rotate, gFalse, gFalse);
-}
-
-void XPDFCore::goBackward() {
- if (historyBLen <= 1) {
- XBell(display, 0);
- return;
- }
- if (--historyCur < 0) {
- historyCur = xpdfHistorySize - 1;
- }
- --historyBLen;
- ++historyFLen;
- if (history[historyCur].fileName->cmp(doc->getFileName()) != 0) {
- if (loadFile(history[historyCur].fileName) != errNone) {
- XBell(display, 0);
- return;
- }
- }
- displayPage(history[historyCur].page, zoom, rotate, gFalse, gFalse);
-}
-
-void XPDFCore::scrollLeft(int nCols) {
- scrollTo(scrollX - nCols * 16, scrollY);
-}
-
-void XPDFCore::scrollRight(int nCols) {
- scrollTo(scrollX + nCols * 16, scrollY);
-}
-
-void XPDFCore::scrollUp(int nLines) {
- scrollTo(scrollX, scrollY - nLines * 16);
-}
-
-void XPDFCore::scrollDown(int nLines) {
- scrollTo(scrollX, scrollY + nLines * 16);
-}
-
-void XPDFCore::scrollPageUp() {
- if (scrollY == 0) {
- gotoPrevPage(1, gFalse, gTrue);
- } else {
- scrollTo(scrollX, scrollY - drawAreaHeight);
- }
-}
-
-void XPDFCore::scrollPageDown() {
- if (scrollY >= out->getPixmapHeight() - drawAreaHeight) {
- gotoNextPage(1, gTrue);
- } else {
- scrollTo(scrollX, scrollY + drawAreaHeight);
- }
-}
-
-void XPDFCore::scrollTo(int x, int y) {
- GBool needRedraw;
- int maxPos, pos;
-
- needRedraw = gFalse;
-
- maxPos = out ? out->getPixmapWidth() : 1;
- if (maxPos < drawAreaWidth) {
- maxPos = drawAreaWidth;
- }
- if (x < 0) {
- pos = 0;
- } else if (x > maxPos - drawAreaWidth) {
- pos = maxPos - drawAreaWidth;
- } else {
- pos = x;
- }
- if (scrollX != pos) {
- scrollX = pos;
- XmScrollBarSetValues(hScrollBar, scrollX, drawAreaWidth, 16,
- drawAreaWidth, False);
- needRedraw = gTrue;
- }
-
- maxPos = out ? out->getPixmapHeight() : 1;
- if (maxPos < drawAreaHeight) {
- maxPos = drawAreaHeight;
- }
- if (y < 0) {
- pos = 0;
- } else if (y > maxPos - drawAreaHeight) {
- pos = maxPos - drawAreaHeight;
- } else {
- pos = y;
- }
- if (scrollY != pos) {
- scrollY = pos;
- XmScrollBarSetValues(vScrollBar, scrollY, drawAreaHeight, 16,
- drawAreaHeight, False);
- needRedraw = gTrue;
- }
-
- if (needRedraw) {
- redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
- }
-}
-
-//------------------------------------------------------------------------
-// selection
-//------------------------------------------------------------------------
-
-void XPDFCore::setSelection(int newXMin, int newYMin,
- int newXMax, int newYMax) {
- Pixmap pixmap;
- int x, y;
- GBool needRedraw, needScroll;
- GBool moveLeft, moveRight, moveTop, moveBottom;
-
- pixmap = out->getPixmap();
-
-
- // erase old selection on off-screen bitmap
- needRedraw = gFalse;
- if (selectXMin < selectXMax && selectYMin < selectYMax) {
- XFillRectangle(display, pixmap,
- selectGC, selectXMin, selectYMin,
- selectXMax - selectXMin, selectYMax - selectYMin);
- needRedraw = gTrue;
- }
-
- // draw new selection on off-screen bitmap
- if (newXMin < newXMax && newYMin < newYMax) {
- XFillRectangle(display, pixmap,
- selectGC, newXMin, newYMin,
- newXMax - newXMin, newYMax - newYMin);
- needRedraw = gTrue;
- }
-
- // check which edges moved
- moveLeft = newXMin != selectXMin;
- moveTop = newYMin != selectYMin;
- moveRight = newXMax != selectXMax;
- moveBottom = newYMax != selectYMax;
-
- // redraw currently visible part of bitmap
- if (needRedraw) {
- if (moveLeft) {
- redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
- (newYMin < selectYMin) ? newYMin : selectYMin,
- (newXMin > selectXMin) ? newXMin : selectXMin,
- (newYMax > selectYMax) ? newYMax : selectYMax);
- }
- if (moveRight) {
- redrawRectangle((newXMax < selectXMax) ? newXMax : selectXMax,
- (newYMin < selectYMin) ? newYMin : selectYMin,
- (newXMax > selectXMax) ? newXMax : selectXMax,
- (newYMax > selectYMax) ? newYMax : selectYMax);
- }
- if (moveTop) {
- redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
- (newYMin < selectYMin) ? newYMin : selectYMin,
- (newXMax > selectXMax) ? newXMax : selectXMax,
- (newYMin > selectYMin) ? newYMin : selectYMin);
- }
- if (moveBottom) {
- redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
- (newYMax < selectYMax) ? newYMax : selectYMax,
- (newXMax > selectXMax) ? newXMax : selectXMax,
- (newYMax > selectYMax) ? newYMax : selectYMax);
- }
- }
-
- // switch to new selection coords
- selectXMin = newXMin;
- selectXMax = newXMax;
- selectYMin = newYMin;
- selectYMax = newYMax;
-
- // scroll if necessary
- if (fullScreen) {
- return;
- }
- needScroll = gFalse;
- x = scrollX;
- y = scrollY;
- if (moveLeft && selectXMin < x) {
- x = selectXMin;
- needScroll = gTrue;
- } else if (moveRight && selectXMax >= x + drawAreaWidth) {
- x = selectXMax - drawAreaWidth;
- needScroll = gTrue;
- } else if (moveLeft && selectXMin >= x + drawAreaWidth) {
- x = selectXMin - drawAreaWidth;
- needScroll = gTrue;
- } else if (moveRight && selectXMax < x) {
- x = selectXMax;
- needScroll = gTrue;
- }
- if (moveTop && selectYMin < y) {
- y = selectYMin;
- needScroll = gTrue;
- } else if (moveBottom && selectYMax >= y + drawAreaHeight) {
- y = selectYMax - drawAreaHeight;
- needScroll = gTrue;
- } else if (moveTop && selectYMin >= y + drawAreaHeight) {
- y = selectYMin - drawAreaHeight;
- needScroll = gTrue;
- } else if (moveBottom && selectYMax < y) {
- y = selectYMax;
- needScroll = gTrue;
- }
- if (needScroll) {
- scrollTo(x, y);
- }
-}
-
-void XPDFCore::moveSelection(int mx, int my) {
- int xMin, yMin, xMax, yMax;
-
- // clip mouse coords
- if (mx < 0) {
- mx = 0;
- } else if (mx >= out->getPixmapWidth()) {
- mx = out->getPixmapWidth() - 1;
- }
- if (my < 0) {
- my = 0;
- } else if (my >= out->getPixmapHeight()) {
- my = out->getPixmapHeight() - 1;
- }
-
- // move appropriate edges of selection
- if (lastDragLeft) {
- if (mx < selectXMax) {
- xMin = mx;
- xMax = selectXMax;
- } else {
- xMin = selectXMax;
- xMax = mx;
- lastDragLeft = gFalse;
- }
- } else {
- if (mx > selectXMin) {
- xMin = selectXMin;
- xMax = mx;
- } else {
- xMin = mx;
- xMax = selectXMin;
- lastDragLeft = gTrue;
- }
- }
- if (lastDragTop) {
- if (my < selectYMax) {
- yMin = my;
- yMax = selectYMax;
- } else {
- yMin = selectYMax;
- yMax = my;
- lastDragTop = gFalse;
- }
- } else {
- if (my > selectYMin) {
- yMin = selectYMin;
- yMax = my;
- } else {
- yMin = my;
- yMax = selectYMin;
- lastDragTop = gTrue;
- }
- }
-
- // redraw the selection
- setSelection(xMin, yMin, xMax, yMax);
-}
-
-// X's copy-and-paste mechanism is brain damaged. Xt doesn't help
-// any, but doesn't make it too much worse, either. Motif, on the
-// other hand, adds significant complexity to the mess. So here we
-// blow off the Motif junk and stick to plain old Xt. The next two
-// functions (copySelection and convertSelectionCbk) implement the
-// magic needed to deal with Xt's mechanism. Note that this requires
-// global variables (currentSelection and currentSelectionOwner).
-
-void XPDFCore::copySelection() {
- if (!doc->okToCopy()) {
- return;
- }
- if (currentSelection) {
- delete currentSelection;
- }
- //~ for multithreading: need a mutex here
- currentSelection = out->getText(selectXMin, selectYMin,
- selectXMax, selectYMax);
- currentSelectionOwner = this;
- XtOwnSelection(drawArea, XA_PRIMARY, XtLastTimestampProcessed(display),
- &convertSelectionCbk, NULL, NULL);
-}
-
-Boolean XPDFCore::convertSelectionCbk(Widget widget, Atom *selection,
- Atom *target, Atom *type,
- XtPointer *value, unsigned long *length,
- int *format) {
- if (*target != XA_STRING) {
- return False;
- }
- //~ for multithreading: need a mutex here
- *value = XtNewString(currentSelection->getCString());
- *length = currentSelection->getLength();
- *type = XA_STRING;
- *format = 8; // 8-bit elements
- return True;
-}
-
-GBool XPDFCore::getSelection(int *xMin, int *yMin, int *xMax, int *yMax) {
- if (selectXMin >= selectXMax || selectYMin >= selectYMax) {
- return gFalse;
- }
- *xMin = selectXMin;
- *yMin = selectYMin;
- *xMax = selectXMax;
- *yMax = selectYMax;
- return gTrue;
-}
-
-GString *XPDFCore::extractText(int xMin, int yMin, int xMax, int yMax) {
- if (!doc->okToCopy()) {
- return NULL;
- }
- return out->getText(xMin, yMin, xMax, yMax);
-}
-
-GString *XPDFCore::extractText(int pageNum,
- int xMin, int yMin, int xMax, int yMax) {
- TextOutputDev *textOut;
- GString *s;
-
- if (!doc->okToCopy()) {
- return NULL;
- }
- textOut = new TextOutputDev(NULL, gFalse, gFalse);
- if (!textOut->isOk()) {
- delete textOut;
- return NULL;
- }
- doc->displayPage(textOut, pageNum, dpi, rotate, gFalse);
- s = textOut->getText(xMin, yMin, xMax, yMax);
- delete textOut;
- return s;
-}
-
-//------------------------------------------------------------------------
-// hyperlinks
-//------------------------------------------------------------------------
-
-void XPDFCore::doLink(int mx, int my) {
- double x, y;
- LinkAction *action;
-
- // look for a link
- out->cvtDevToUser(mx, my, &x, &y);
- if ((action = doc->findLink(x, y))) {
- doAction(action);
- }
-}
-
-void XPDFCore::doAction(LinkAction *action) {
- LinkActionKind kind;
- LinkDest *dest;
- GString *namedDest;
- char *s;
- GString *fileName, *fileName2;
- GString *cmd;
- GString *actionName;
- Object movieAnnot, obj1, obj2;
- GString *msg;
- int i;
-
- switch (kind = action->getKind()) {
-
- // GoTo / GoToR action
- case actionGoTo:
- case actionGoToR:
- if (kind == actionGoTo) {
- dest = NULL;
- namedDest = NULL;
- if ((dest = ((LinkGoTo *)action)->getDest())) {
- dest = dest->copy();
- } else if ((namedDest = ((LinkGoTo *)action)->getNamedDest())) {
- namedDest = namedDest->copy();
- }
- } else {
- dest = NULL;
- namedDest = NULL;
- if ((dest = ((LinkGoToR *)action)->getDest())) {
- dest = dest->copy();
- } else if ((namedDest = ((LinkGoToR *)action)->getNamedDest())) {
- namedDest = namedDest->copy();
- }
- s = ((LinkGoToR *)action)->getFileName()->getCString();
- //~ translate path name for VMS (deal with '/')
- if (isAbsolutePath(s)) {
- fileName = new GString(s);
- } else {
- fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
- }
- if (loadFile(fileName) != errNone) {
- if (dest) {
- delete dest;
- }
- if (namedDest) {
- delete namedDest;
- }
- delete fileName;
- return;
- }
- delete fileName;
- }
- if (namedDest) {
- dest = doc->findDest(namedDest);
- delete namedDest;
- }
- if (dest) {
- displayDest(dest, zoom, rotate, gTrue);
- delete dest;
- } else {
- if (kind == actionGoToR) {
- displayPage(1, zoom, 0, gFalse, gTrue);
- }
- }
- break;
-
- // Launch action
- case actionLaunch:
- fileName = ((LinkLaunch *)action)->getFileName();
- s = fileName->getCString();
- if (!strcmp(s + fileName->getLength() - 4, ".pdf") ||
- !strcmp(s + fileName->getLength() - 4, ".PDF")) {
- //~ translate path name for VMS (deal with '/')
- if (isAbsolutePath(s)) {
- fileName = fileName->copy();
- } else {
- fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
- }
- if (loadFile(fileName) != errNone) {
- delete fileName;
- return;
- }
- delete fileName;
- displayPage(1, zoom, rotate, gFalse, gTrue);
- } else {
- fileName = fileName->copy();
- if (((LinkLaunch *)action)->getParams()) {
- fileName->append(' ');
- fileName->append(((LinkLaunch *)action)->getParams());
- }
-#ifdef VMS
- fileName->insert(0, "spawn/nowait ");
-#elif defined(__EMX__)
- fileName->insert(0, "start /min /n ");
-#else
- fileName->append(" &");
-#endif
- msg = new GString("About to execute the command:\n");
- msg->append(fileName);
- if (doQuestionDialog("Launching external application", msg)) {
- system(fileName->getCString());
- }
- delete fileName;
- delete msg;
- }
- break;
-
- // URI action
- case actionURI:
- if (!(cmd = globalParams->getURLCommand())) {
- error(-1, "No urlCommand defined in config file");
- break;
- }
- runCommand(cmd, ((LinkURI *)action)->getURI());
- break;
-
- // Named action
- case actionNamed:
- actionName = ((LinkNamed *)action)->getName();
- if (!actionName->cmp("NextPage")) {
- gotoNextPage(1, gTrue);
- } else if (!actionName->cmp("PrevPage")) {
- gotoPrevPage(1, gTrue, gFalse);
- } else if (!actionName->cmp("FirstPage")) {
- if (page != 1) {
- displayPage(1, zoom, rotate, gTrue, gTrue);
- }
- } else if (!actionName->cmp("LastPage")) {
- if (page != doc->getNumPages()) {
- displayPage(doc->getNumPages(), zoom, rotate, gTrue, gTrue);
- }
- } else if (!actionName->cmp("GoBack")) {
- goBackward();
- } else if (!actionName->cmp("GoForward")) {
- goForward();
- } else if (!actionName->cmp("Quit")) {
- if (actionCbk) {
- (*actionCbk)(actionCbkData, "Quit");
- }
- } else {
- error(-1, "Unknown named action: '%s'", actionName->getCString());
- }
- break;
-
- // Movie action
- case actionMovie:
- if (!(cmd = globalParams->getMovieCommand())) {
- error(-1, "No movieCommand defined in config file");
- break;
- }
- if (((LinkMovie *)action)->hasAnnotRef()) {
- doc->getXRef()->fetch(((LinkMovie *)action)->getAnnotRef()->num,
- ((LinkMovie *)action)->getAnnotRef()->gen,
- &movieAnnot);
- } else {
- doc->getCatalog()->getPage(page)->getAnnots(&obj1);
- if (obj1.isArray()) {
- for (i = 0; i < obj1.arrayGetLength(); ++i) {
- if (obj1.arrayGet(i, &movieAnnot)->isDict()) {
- if (movieAnnot.dictLookup("Subtype", &obj2)->isName("Movie")) {
- obj2.free();
- break;
- }
- obj2.free();
- }
- movieAnnot.free();
- }
- obj1.free();
- }
- }
- if (movieAnnot.isDict()) {
- if (movieAnnot.dictLookup("Movie", &obj1)->isDict()) {
- if (obj1.dictLookup("F", &obj2)) {
- if ((fileName = LinkAction::getFileSpecName(&obj2))) {
- if (!isAbsolutePath(fileName->getCString())) {
- fileName2 = appendToPath(
- grabPath(doc->getFileName()->getCString()),
- fileName->getCString());
- delete fileName;
- fileName = fileName2;
- }
- runCommand(cmd, fileName);
- delete fileName;
- }
- obj2.free();
- }
- obj1.free();
- }
- }
- movieAnnot.free();
- break;
-
- // unknown action type
- case actionUnknown:
- error(-1, "Unknown link action type: '%s'",
- ((LinkUnknown *)action)->getAction()->getCString());
- break;
- }
-}
-
-// Run a command, given a <cmdFmt> string with one '%s' in it, and an
-// <arg> string to insert in place of the '%s'.
-void XPDFCore::runCommand(GString *cmdFmt, GString *arg) {
- GString *cmd;
- char *s;
- int i;
-
- if ((s = strstr(cmdFmt->getCString(), "%s"))) {
- cmd = arg->copy();
- // filter out any quote marks (' or ") to avoid a potential
- // security hole
- i = 0;
- while (i < cmd->getLength()) {
- if (cmd->getChar(i) == '"') {
- cmd->del(i);
- cmd->insert(i, "%22");
- i += 3;
- } else if (cmd->getChar(i) == '\'') {
- cmd->del(i);
- cmd->insert(i, "%27");
- i += 3;
- } else {
- ++i;
- }
- }
- cmd->insert(0, cmdFmt->getCString(),
- s - cmdFmt->getCString());
- cmd->append(s + 2);
- } else {
- cmd = cmdFmt->copy();
- }
-#ifdef VMS
- cmd->insert(0, "spawn/nowait ");
-#elif defined(__EMX__)
- cmd->insert(0, "start /min /n ");
-#else
- cmd->append(" &");
-#endif
- system(cmd->getCString());
- delete cmd;
-}
-
-
-//------------------------------------------------------------------------
-// find
-//------------------------------------------------------------------------
-
-void XPDFCore::find(char *s) {
- Unicode *u;
- TextOutputDev *textOut;
- int xMin, yMin, xMax, yMax;
- double xMin1, yMin1, xMax1, yMax1;
- int pg;
- GBool top;
- int len, i;
-
- // check for zero-length string
- if (!s[0]) {
- XBell(display, 0);
- return;
- }
-
- // set cursor to watch
- setCursor(busyCursor);
-
- // convert to Unicode
-#if 1 //~ should do something more intelligent here
- len = strlen(s);
- u = (Unicode *)gmalloc(len * sizeof(Unicode));
- for (i = 0; i < len; ++i) {
- u[i] = (Unicode)(s[i] & 0xff);
- }
-#endif
-
- // search current page starting at current selection or top of page
- xMin = yMin = xMax = yMax = 0;
- if (selectXMin < selectXMax && selectYMin < selectYMax) {
- xMin = selectXMax;
- yMin = (selectYMin + selectYMax) / 2;
- top = gFalse;
- } else {
- top = gTrue;
- }
- if (out->findText(u, len, top, gTrue, &xMin, &yMin, &xMax, &yMax)) {
- goto found;
- }
-
- // search following pages
- textOut = new TextOutputDev(NULL, gFalse, gFalse);
- if (!textOut->isOk()) {
- delete textOut;
- goto done;
- }
- for (pg = page+1; pg <= doc->getNumPages(); ++pg) {
- doc->displayPage(textOut, pg, 72, 0, gFalse);
- if (textOut->findText(u, len, gTrue, gTrue,
- &xMin1, &yMin1, &xMax1, &yMax1)) {
- goto foundPage;
- }
- }
-
- // search previous pages
- for (pg = 1; pg < page; ++pg) {
- doc->displayPage(textOut, pg, 72, 0, gFalse);
- if (textOut->findText(u, len, gTrue, gTrue,
- &xMin1, &yMin1, &xMax1, &yMax1)) {
- goto foundPage;
- }
- }
- delete textOut;
-
- // search current page ending at current selection
- if (selectXMin < selectXMax && selectYMin < selectYMax) {
- xMax = selectXMin;
- yMax = (selectYMin + selectYMax) / 2;
- if (out->findText(u, len, gTrue, gFalse, &xMin, &yMin, &xMax, &yMax)) {
- goto found;
- }
- }
-
- // not found
- XBell(display, 0);
- goto done;
-
- // found on a different page
- foundPage:
- delete textOut;
- displayPage(pg, zoom, rotate, gTrue, gTrue);
- if (!out->findText(u, len, gTrue, gTrue, &xMin, &yMin, &xMax, &yMax)) {
- // this can happen if coalescing is bad
- goto done;
- }
-
- // found: change the selection
- found:
- setSelection(xMin, yMin, xMax, yMax);
-#ifndef NO_TEXT_SELECT
- copySelection();
-#endif
-
- done:
- gfree(u);
-
- // reset cursors to normal
- setCursor(None);
-}
-
-//------------------------------------------------------------------------
-// misc access
-//------------------------------------------------------------------------
-
-void XPDFCore::setBusyCursor(GBool busy) {
- setCursor(busy ? busyCursor : None);
-}
-
-void XPDFCore::takeFocus() {
- XmProcessTraversal(drawArea, XmTRAVERSE_CURRENT);
-}
-
-//------------------------------------------------------------------------
-// GUI code
-//------------------------------------------------------------------------
-
-void XPDFCore::initWindow() {
- Arg args[20];
- int n;
-
- // create the cursors
- busyCursor = XCreateFontCursor(display, XC_watch);
- linkCursor = XCreateFontCursor(display, XC_hand2);
- selectCursor = XCreateFontCursor(display, XC_cross);
- currentCursor = 0;
-
- // create the scrolled window and scrollbars
- n = 0;
- XtSetArg(args[n], XmNscrollingPolicy, XmAPPLICATION_DEFINED); ++n;
- XtSetArg(args[n], XmNvisualPolicy, XmVARIABLE); ++n;
- scrolledWin = XmCreateScrolledWindow(parentWidget, "scroll", args, n);
- XtManageChild(scrolledWin);
- n = 0;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- XtSetArg(args[n], XmNminimum, 0); ++n;
- XtSetArg(args[n], XmNmaximum, 1); ++n;
- XtSetArg(args[n], XmNsliderSize, 1); ++n;
- XtSetArg(args[n], XmNvalue, 0); ++n;
- XtSetArg(args[n], XmNincrement, 1); ++n;
- XtSetArg(args[n], XmNpageIncrement, 1); ++n;
- hScrollBar = XmCreateScrollBar(scrolledWin, "hScrollBar", args, n);
- XtManageChild(hScrollBar);
- XtAddCallback(hScrollBar, XmNvalueChangedCallback,
- &hScrollChangeCbk, (XtPointer)this);
-#ifndef DISABLE_SMOOTH_SCROLL
- XtAddCallback(hScrollBar, XmNdragCallback,
- &hScrollDragCbk, (XtPointer)this);
-#endif
- n = 0;
- XtSetArg(args[n], XmNorientation, XmVERTICAL); ++n;
- XtSetArg(args[n], XmNminimum, 0); ++n;
- XtSetArg(args[n], XmNmaximum, 1); ++n;
- XtSetArg(args[n], XmNsliderSize, 1); ++n;
- XtSetArg(args[n], XmNvalue, 0); ++n;
- XtSetArg(args[n], XmNincrement, 1); ++n;
- XtSetArg(args[n], XmNpageIncrement, 1); ++n;
- vScrollBar = XmCreateScrollBar(scrolledWin, "vScrollBar", args, n);
- XtManageChild(vScrollBar);
- XtAddCallback(vScrollBar, XmNvalueChangedCallback,
- &vScrollChangeCbk, (XtPointer)this);
-#ifndef DISABLE_SMOOTH_SCROLL
- XtAddCallback(vScrollBar, XmNdragCallback,
- &vScrollDragCbk, (XtPointer)this);
-#endif
-
- // create the drawing area
- n = 0;
- XtSetArg(args[n], XmNshadowType, XmSHADOW_IN); ++n;
- XtSetArg(args[n], XmNmarginWidth, 0); ++n;
- XtSetArg(args[n], XmNmarginHeight, 0); ++n;
- if (fullScreen) {
- XtSetArg(args[n], XmNshadowThickness, 0); ++n;
- }
- drawAreaFrame = XmCreateFrame(scrolledWin, "drawAreaFrame", args, n);
- XtManageChild(drawAreaFrame);
- n = 0;
- XtSetArg(args[n], XmNresizePolicy, XmRESIZE_ANY); ++n;
- XtSetArg(args[n], XmNbackground, paperColor); ++n;
- XtSetArg(args[n], XmNwidth, 700); ++n;
- XtSetArg(args[n], XmNheight, 500); ++n;
- drawArea = XmCreateDrawingArea(drawAreaFrame, "drawArea", args, n);
- XtManageChild(drawArea);
- XtAddCallback(drawArea, XmNresizeCallback, &resizeCbk, (XtPointer)this);
- XtAddCallback(drawArea, XmNexposeCallback, &redrawCbk, (XtPointer)this);
- XtAddCallback(drawArea, XmNinputCallback, &inputCbk, (XtPointer)this);
- resizeCbk(drawArea, this, NULL);
-
- // set up mouse motion translations
- XtOverrideTranslations(drawArea, XtParseTranslationTable(
- "<Btn1Down>:DrawingAreaInput()\n"
- "<Btn1Up>:DrawingAreaInput()\n"
- "<Btn1Motion>:DrawingAreaInput()\n"
- "<Motion>:DrawingAreaInput()"));
-
- // can't create a GC until the window gets mapped
- drawAreaGC = NULL;
- selectGC = NULL;
- highlightGC = NULL;
-}
-
-void XPDFCore::hScrollChangeCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
-
- core->scrollTo(data->value, core->scrollY);
-}
-
-void XPDFCore::hScrollDragCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
-
- core->scrollTo(data->value, core->scrollY);
-}
-
-void XPDFCore::vScrollChangeCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
-
- core->scrollTo(core->scrollX, data->value);
-}
-
-void XPDFCore::vScrollDragCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
-
- core->scrollTo(core->scrollX, data->value);
-}
-
-void XPDFCore::resizeCbk(Widget widget, XtPointer ptr, XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- Arg args[2];
- int n;
- Dimension w, h;
-
- n = 0;
- XtSetArg(args[n], XmNwidth, &w); ++n;
- XtSetArg(args[n], XmNheight, &h); ++n;
- XtGetValues(core->drawArea, args, n);
- core->drawAreaWidth = (int)w;
- core->drawAreaHeight = (int)h;
- if (core->page >= 0 &&
- (core->zoom == zoomPage || core->zoom == zoomWidth)) {
- core->displayPage(core->page, core->zoom, core->rotate,
- gFalse, gFalse);
- } else {
- core->updateScrollBars();
- }
-}
-
-void XPDFCore::redrawCbk(Widget widget, XtPointer ptr, XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmDrawingAreaCallbackStruct *data = (XmDrawingAreaCallbackStruct *)callData;
- int x, y, w, h;
-
- if (data->reason == XmCR_EXPOSE) {
- x = core->scrollX + data->event->xexpose.x;
- y = core->scrollY + data->event->xexpose.y;
- w = data->event->xexpose.width;
- h = data->event->xexpose.height;
- } else {
- x = core->scrollX;
- y = core->scrollY;
- w = core->drawAreaWidth;
- h = core->drawAreaHeight;
- }
- core->redrawRectangle(x, y, w, h);
-}
-
-void XPDFCore::outputDevRedrawCbk(void *data) {
- XPDFCore *core = (XPDFCore *)data;
-
- core->redrawRectangle(core->scrollX, core->scrollY,
- core->drawAreaWidth, core->drawAreaHeight);
-}
-
-void XPDFCore::inputCbk(Widget widget, XtPointer ptr, XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
- XmDrawingAreaCallbackStruct *data = (XmDrawingAreaCallbackStruct *)callData;
- LinkAction *action;
- int mx, my;
- double x, y;
- char *s;
- KeySym key;
- char buf[20];
- int n;
-
- switch (data->event->type) {
- case ButtonPress:
- if (data->event->xbutton.button == 1) {
- core->takeFocus();
- if (core->doc && core->doc->getNumPages() > 0) {
- if (core->selectEnabled) {
- mx = core->scrollX + data->event->xbutton.x;
- my = core->scrollY + data->event->xbutton.y;
- core->setSelection(mx, my, mx, my);
- core->setCursor(core->selectCursor);
- core->dragging = gTrue;
- }
- }
- } else if (data->event->xbutton.button == 2) {
- if (!core->fullScreen) {
- core->panning = gTrue;
- core->panMX = data->event->xbutton.x;
- core->panMY = data->event->xbutton.y;
- }
- } else if (data->event->xbutton.button == 4) { // mouse wheel up
- if (core->fullScreen) {
- core->gotoPrevPage(1, gTrue, gFalse);
- } else if (core->scrollY == 0) {
- core->gotoPrevPage(1, gFalse, gTrue);
- } else {
- core->scrollUp(1);
- }
- } else if (data->event->xbutton.button == 5) { // mouse wheel down
- if (core->fullScreen ||
- core->scrollY >=
- core->out->getPixmapHeight() - core->drawAreaHeight) {
- core->gotoNextPage(1, gTrue);
- } else {
- core->scrollDown(1);
- }
- } else if (data->event->xbutton.button == 6) { // second mouse wheel right
- if (!core->fullScreen) {
- core->scrollRight(1);
- }
- } else if (data->event->xbutton.button == 7) { // second mouse wheel left
- if (!core->fullScreen) {
- core->scrollLeft(1);
- }
- } else {
- if (*core->mouseCbk) {
- (*core->mouseCbk)(core->mouseCbkData, data->event);
- }
- }
- break;
- case ButtonRelease:
- if (data->event->xbutton.button == 1) {
- if (core->doc && core->doc->getNumPages() > 0) {
- mx = core->scrollX + data->event->xbutton.x;
- my = core->scrollY + data->event->xbutton.y;
- if (core->dragging) {
- core->dragging = gFalse;
- core->setCursor(None);
- core->moveSelection(mx, my);
-#ifndef NO_TEXT_SELECT
- if (core->selectXMin != core->selectXMax &&
- core->selectYMin != core->selectYMax) {
- if (core->doc->okToCopy()) {
- core->copySelection();
- } else {
- error(-1, "Copying of text from this document is not allowed.");
- }
- }
-#endif
- }
- if (core->hyperlinksEnabled) {
- if (core->selectXMin == core->selectXMax ||
- core->selectYMin == core->selectYMax) {
- core->doLink(mx, my);
- }
- }
- }
- } else if (data->event->xbutton.button == 2) {
- core->panning = gFalse;
- } else {
- if (*core->mouseCbk) {
- (*core->mouseCbk)(core->mouseCbkData, data->event);
- }
- }
- break;
- case MotionNotify:
- if (core->doc && core->doc->getNumPages() > 0) {
- mx = core->scrollX + data->event->xbutton.x;
- my = core->scrollY + data->event->xbutton.y;
- if (core->dragging) {
- core->moveSelection(mx, my);
- } else if (core->hyperlinksEnabled) {
- core->out->cvtDevToUser(mx, my, &x, &y);
- if ((action = core->doc->findLink(x, y))) {
- core->setCursor(core->linkCursor);
- if (action != core->linkAction) {
- core->linkAction = action;
- if (core->updateCbk) {
- s = "";
- switch (action->getKind()) {
- case actionGoTo:
- s = "[internal link]";
- break;
- case actionGoToR:
- s = ((LinkGoToR *)action)->getFileName()->getCString();
- break;
- case actionLaunch:
- s = ((LinkLaunch *)action)->getFileName()->getCString();
- break;
- case actionURI:
- s = ((LinkURI *)action)->getURI()->getCString();
- break;
- case actionNamed:
- s = ((LinkNamed *)action)->getName()->getCString();
- break;
- case actionMovie:
- s = "[movie]";
- break;
- case actionUnknown:
- s = "[unknown link]";
- break;
- }
- (*core->updateCbk)(core->updateCbkData, NULL, -1, -1, s);
- }
- }
- } else {
- core->setCursor(None);
- if (core->linkAction) {
- core->linkAction = NULL;
- if (core->updateCbk) {
- (*core->updateCbk)(core->updateCbkData, NULL, -1, -1, "");
- }
- }
- }
- }
- }
- if (core->panning) {
- core->scrollTo(core->scrollX - (data->event->xbutton.x - core->panMX),
- core->scrollY - (data->event->xbutton.y - core->panMY));
- core->panMX = data->event->xbutton.x;
- core->panMY = data->event->xbutton.y;
- }
- break;
- case KeyPress:
- n = XLookupString(&data->event->xkey, buf, sizeof(buf) - 1,
- &key, NULL);
- core->keyPress(buf, key, data->event->xkey.state);
- break;
- }
-}
-
-void XPDFCore::keyPress(char *s, KeySym key, Guint modifiers) {
- switch (key) {
- case XK_Home:
- case XK_KP_Home:
- if (modifiers & ControlMask) {
- displayPage(1, zoom, rotate, gTrue, gTrue);
- } else if (!fullScreen) {
- scrollTo(0, 0);
- }
- return;
- case XK_End:
- case XK_KP_End:
- if (modifiers & ControlMask) {
- displayPage(doc->getNumPages(), zoom, rotate, gTrue, gTrue);
- } else if (!fullScreen) {
- scrollTo(out->getPixmapWidth() - drawAreaWidth,
- out->getPixmapHeight() - drawAreaHeight);
- }
- return;
- case XK_Page_Up:
- case XK_KP_Page_Up:
- if (fullScreen) {
- gotoPrevPage(1, gTrue, gFalse);
- } else {
- scrollPageUp();
- }
- return;
- case XK_Page_Down:
- case XK_KP_Page_Down:
- if (fullScreen) {
- gotoNextPage(1, gTrue);
- } else {
- scrollPageDown();
- }
- return;
- case XK_Left:
- case XK_KP_Left:
- if (!fullScreen) {
- scrollLeft();
- }
- return;
- case XK_Right:
- case XK_KP_Right:
- if (!fullScreen) {
- scrollRight();
- }
- return;
- case XK_Up:
- case XK_KP_Up:
- if (!fullScreen) {
- scrollUp();
- }
- return;
- case XK_Down:
- case XK_KP_Down:
- if (!fullScreen) {
- scrollDown();
- }
- return;
- }
-
- if (*keyPressCbk) {
- (*keyPressCbk)(keyPressCbkData, s, key, modifiers);
- }
-}
-
-void XPDFCore::redrawRectangle(int x, int y, int w, int h) {
- XGCValues gcValues;
- Window drawAreaWin;
-
- // clip to window
- if (x < scrollX) {
- w -= scrollX - x;
- x = scrollX;
- }
- if (x + w > scrollX + drawAreaWidth) {
- w = scrollX + drawAreaWidth - x;
- }
- if (y < scrollY) {
- h -= scrollY - y;
- y = scrollY;
- }
- if (y + h > scrollY + drawAreaHeight) {
- h = scrollY + drawAreaHeight - y;
- }
-
- // create a GC for the drawing area
- drawAreaWin = XtWindow(drawArea);
- if (!drawAreaGC) {
- gcValues.foreground = paperColor;
- drawAreaGC = XCreateGC(display, drawAreaWin, GCForeground, &gcValues);
- }
-
- // draw white background past the edges of the document
- if (x + w > out->getPixmapWidth()) {
- XFillRectangle(display, drawAreaWin, drawAreaGC,
- out->getPixmapWidth() - scrollX, y - scrollY,
- x + w - out->getPixmapWidth(), h);
- w = out->getPixmapWidth() - x;
- }
- if (y + h > out->getPixmapHeight()) {
- XFillRectangle(display, drawAreaWin, drawAreaGC,
- x - scrollX, out->getPixmapHeight() - scrollY,
- w, y + h - out->getPixmapHeight());
- h = out->getPixmapHeight() - y;
- }
-
- // redraw (checking to see if pixmap has been allocated yet)
- if (out->getPixmapWidth() > 0) {
- XCopyArea(display, out->getPixmap(), drawAreaWin, drawAreaGC,
- x, y, w, h, x - scrollX, y - scrollY);
- }
-}
-
-void XPDFCore::updateScrollBars() {
- Arg args[20];
- int n;
- int maxPos;
-
- maxPos = out ? out->getPixmapWidth() : 1;
- if (maxPos < drawAreaWidth) {
- maxPos = drawAreaWidth;
- }
- if (scrollX > maxPos - drawAreaWidth) {
- scrollX = maxPos - drawAreaWidth;
- }
- n = 0;
- XtSetArg(args[n], XmNvalue, scrollX); ++n;
- XtSetArg(args[n], XmNmaximum, maxPos); ++n;
- XtSetArg(args[n], XmNsliderSize, drawAreaWidth); ++n;
- XtSetArg(args[n], XmNincrement, 16); ++n;
- XtSetArg(args[n], XmNpageIncrement, drawAreaWidth); ++n;
- XtSetValues(hScrollBar, args, n);
-
- maxPos = out ? out->getPixmapHeight() : 1;
- if (maxPos < drawAreaHeight) {
- maxPos = drawAreaHeight;
- }
- if (scrollY > maxPos - drawAreaHeight) {
- scrollY = maxPos - drawAreaHeight;
- }
- n = 0;
- XtSetArg(args[n], XmNvalue, scrollY); ++n;
- XtSetArg(args[n], XmNmaximum, maxPos); ++n;
- XtSetArg(args[n], XmNsliderSize, drawAreaHeight); ++n;
- XtSetArg(args[n], XmNincrement, 16); ++n;
- XtSetArg(args[n], XmNpageIncrement, drawAreaHeight); ++n;
- XtSetValues(vScrollBar, args, n);
-}
-
-void XPDFCore::setCursor(Cursor cursor) {
- Window topWin;
-
- if (cursor == currentCursor) {
- return;
- }
- if (!(topWin = XtWindow(shell))) {
- return;
- }
- if (cursor == None) {
- XUndefineCursor(display, topWin);
- } else {
- XDefineCursor(display, topWin, cursor);
- }
- XFlush(display);
- currentCursor = cursor;
-}
-
-GBool XPDFCore::doQuestionDialog(char *title, GString *msg) {
- return doDialog(XmDIALOG_QUESTION, gTrue, title, msg);
-}
-
-void XPDFCore::doInfoDialog(char *title, GString *msg) {
- doDialog(XmDIALOG_INFORMATION, gFalse, title, msg);
-}
-
-void XPDFCore::doErrorDialog(char *title, GString *msg) {
- doDialog(XmDIALOG_ERROR, gFalse, title, msg);
-}
-
-GBool XPDFCore::doDialog(int type, GBool hasCancel,
- char *title, GString *msg) {
- Widget dialog;
- XtAppContext appContext;
- Arg args[20];
- int n;
- XmString s1, s2;
- XEvent event;
-
- n = 0;
- XtSetArg(args[n], XmNdialogType, type); ++n;
- XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
- s1 = XmStringCreateLocalized(title);
- XtSetArg(args[n], XmNdialogTitle, s1); ++n;
- s2 = XmStringCreateLocalized(msg->getCString());
- XtSetArg(args[n], XmNmessageString, s2); ++n;
- dialog = XmCreateMessageDialog(drawArea, "questionDialog", args, n);
- XmStringFree(s1);
- XmStringFree(s2);
- XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_HELP_BUTTON));
- XtAddCallback(dialog, XmNokCallback,
- &dialogOkCbk, (XtPointer)this);
- if (hasCancel) {
- XtAddCallback(dialog, XmNcancelCallback,
- &dialogCancelCbk, (XtPointer)this);
- } else {
- XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON));
- }
-
- XtManageChild(dialog);
-
- appContext = XtWidgetToApplicationContext(dialog);
- dialogDone = 0;
- do {
- XtAppNextEvent(appContext, &event);
- XtDispatchEvent(&event);
- } while (!dialogDone);
-
- XtUnmanageChild(dialog);
- XtDestroyWidget(dialog);
-
- return dialogDone > 0;
-}
-
-void XPDFCore::dialogOkCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
-
- core->dialogDone = 1;
-}
-
-void XPDFCore::dialogCancelCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFCore *core = (XPDFCore *)ptr;
-
- core->dialogDone = -1;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFCore.cpp b/filters/kword/pdf/xpdf/xpdf/XPDFCore.cpp
new file mode 100644
index 000000000..517b99700
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XPDFCore.cpp
@@ -0,0 +1,1913 @@
+//========================================================================
+//
+// XPDFCore.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <X11/keysym.h>
+#include <X11/cursorfont.h>
+#include "gmem.h"
+#include "GString.h"
+#include "GList.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "PDFDoc.h"
+#include "ErrorCodes.h"
+#include "GfxState.h"
+#include "PSOutputDev.h"
+#include "TextOutputDev.h"
+#include "XPixmapOutputDev.h"
+#include "XPDFCore.h"
+
+// these macro defns conflict with xpdf's Object class
+#ifdef LESSTIF_VERSION
+#undef XtDisplay
+#undef XtScreen
+#undef XtWindow
+#undef XtParent
+#undef XtIsRealized
+#endif
+
+// hack around old X includes which are missing these symbols
+#ifndef XK_Page_Up
+#define XK_Page_Up 0xFF55
+#endif
+#ifndef XK_Page_Down
+#define XK_Page_Down 0xFF56
+#endif
+#ifndef XK_KP_Home
+#define XK_KP_Home 0xFF95
+#endif
+#ifndef XK_KP_Left
+#define XK_KP_Left 0xFF96
+#endif
+#ifndef XK_KP_Up
+#define XK_KP_Up 0xFF97
+#endif
+#ifndef XK_KP_Right
+#define XK_KP_Right 0xFF98
+#endif
+#ifndef XK_KP_Down
+#define XK_KP_Down 0xFF99
+#endif
+#ifndef XK_KP_Prior
+#define XK_KP_Prior 0xFF9A
+#endif
+#ifndef XK_KP_Page_Up
+#define XK_KP_Page_Up 0xFF9A
+#endif
+#ifndef XK_KP_Next
+#define XK_KP_Next 0xFF9B
+#endif
+#ifndef XK_KP_Page_Down
+#define XK_KP_Page_Down 0xFF9B
+#endif
+#ifndef XK_KP_End
+#define XK_KP_End 0xFF9C
+#endif
+#ifndef XK_KP_Begin
+#define XK_KP_Begin 0xFF9D
+#endif
+#ifndef XK_KP_Insert
+#define XK_KP_Insert 0xFF9E
+#endif
+#ifndef XK_KP_Delete
+#define XK_KP_Delete 0xFF9F
+#endif
+
+//------------------------------------------------------------------------
+
+#define highlightNone 0
+#define highlightNormal 1
+#define highlightSelected 2
+
+//------------------------------------------------------------------------
+
+static int zoomDPI[maxZoom - minZoom + 1] = {
+ 29, 35, 42, 50, 60,
+ 72,
+ 86, 104, 124, 149, 179
+};
+
+//------------------------------------------------------------------------
+
+GString *XPDFCore::currentSelection = NULL;
+XPDFCore *XPDFCore::currentSelectionOwner = NULL;
+
+//------------------------------------------------------------------------
+// XPDFCore
+//------------------------------------------------------------------------
+
+XPDFCore::XPDFCore(Widget shellA, Widget parentWidgetA,
+ Gulong paperColorA, GBool fullScreenA, GBool reverseVideo,
+ GBool installCmap, int rgbCubeSize) {
+ GString *initialZoom;
+ int i;
+
+ shell = shellA;
+ parentWidget = parentWidgetA;
+ display = XtDisplay(parentWidget);
+ screenNum = XScreenNumberOfScreen(XtScreen(parentWidget));
+
+ paperColor = paperColorA;
+ fullScreen = fullScreenA;
+
+ // for some reason, querying XmNvisual doesn't work (even if done
+ // after the window is mapped)
+ visual = DefaultVisual(display, screenNum);
+ XtVaGetValues(shell, XmNcolormap, &colormap, NULL);
+
+ scrolledWin = NULL;
+ hScrollBar = NULL;
+ vScrollBar = NULL;
+ drawAreaFrame = NULL;
+ drawArea = NULL;
+ out = NULL;
+
+ doc = NULL;
+ page = 0;
+ rotate = 0;
+
+ // get the initial zoom value
+ initialZoom = globalParams->getInitialZoom();
+ if (!initialZoom->cmp("page")) {
+ zoom = zoomPage;
+ } else if (!initialZoom->cmp("width")) {
+ zoom = zoomWidth;
+ } else {
+ zoom = atoi(initialZoom->getCString());
+ if (zoom < minZoom) {
+ zoom = minZoom;
+ } else if (zoom > maxZoom) {
+ zoom = maxZoom;
+ }
+ }
+
+ scrollX = 0;
+ scrollY = 0;
+ linkAction = NULL;
+ selectXMin = selectXMax = 0;
+ selectYMin = selectYMax = 0;
+ dragging = gFalse;
+ lastDragLeft = lastDragTop = gTrue;
+
+ panning = gFalse;
+
+
+ updateCbk = NULL;
+ actionCbk = NULL;
+ keyPressCbk = NULL;
+ mouseCbk = NULL;
+ reqPasswordCbk = NULL;
+
+ // no history yet
+ historyCur = xpdfHistorySize - 1;
+ historyBLen = historyFLen = 0;
+ for (i = 0; i < xpdfHistorySize; ++i) {
+ history[i].fileName = NULL;
+ }
+
+ // optional features default to on
+ hyperlinksEnabled = gTrue;
+ selectEnabled = gTrue;
+
+ // do X-specific initialization and create the widgets
+ initWindow();
+
+ // create the OutputDev
+ out = new XPixmapOutputDev(display, screenNum, visual, colormap,
+ reverseVideo, paperColor,
+ installCmap, rgbCubeSize, gTrue,
+ &outputDevRedrawCbk, this);
+ out->startDoc(NULL);
+}
+
+XPDFCore::~XPDFCore() {
+ int i;
+
+ if (out) {
+ delete out;
+ }
+ if (doc) {
+ delete doc;
+ }
+ if (currentSelectionOwner == this && currentSelection) {
+ delete currentSelection;
+ currentSelection = NULL;
+ currentSelectionOwner = NULL;
+ }
+ for (i = 0; i < xpdfHistorySize; ++i) {
+ if (history[i].fileName) {
+ delete history[i].fileName;
+ }
+ }
+ if (selectGC) {
+ XFreeGC(display, selectGC);
+ XFreeGC(display, highlightGC);
+ }
+ if (drawAreaGC) {
+ XFreeGC(display, drawAreaGC);
+ }
+ if (drawArea) {
+ XtDestroyWidget(drawArea);
+ }
+ if (drawAreaFrame) {
+ XtDestroyWidget(drawAreaFrame);
+ }
+ if (vScrollBar) {
+ XtDestroyWidget(vScrollBar);
+ }
+ if (hScrollBar) {
+ XtDestroyWidget(hScrollBar);
+ }
+ if (scrolledWin) {
+ XtDestroyWidget(scrolledWin);
+ }
+ if (busyCursor) {
+ XFreeCursor(display, busyCursor);
+ }
+ if (linkCursor) {
+ XFreeCursor(display, linkCursor);
+ }
+ if (selectCursor) {
+ XFreeCursor(display, selectCursor);
+ }
+}
+
+//------------------------------------------------------------------------
+// loadFile / displayPage / displayDest
+//------------------------------------------------------------------------
+
+int XPDFCore::loadFile(GString *fileName, GString *ownerPassword,
+ GString *userPassword) {
+ PDFDoc *newDoc;
+ GString *password;
+ GBool again;
+ int err;
+
+ // busy cursor
+ setCursor(busyCursor);
+
+ // open the PDF file
+ newDoc = new PDFDoc(fileName->copy(), ownerPassword, userPassword);
+ if (!newDoc->isOk()) {
+ err = newDoc->getErrorCode();
+ delete newDoc;
+ if (err != errEncrypted || !reqPasswordCbk) {
+ setCursor(None);
+ return err;
+ }
+
+ // try requesting a password
+ again = ownerPassword != NULL || userPassword != NULL;
+ while (1) {
+ if (!(password = (*reqPasswordCbk)(reqPasswordCbkData, again))) {
+ setCursor(None);
+ return errEncrypted;
+ }
+ newDoc = new PDFDoc(fileName->copy(), password, password);
+ if (newDoc->isOk()) {
+ break;
+ }
+ err = newDoc->getErrorCode();
+ delete newDoc;
+ if (err != errEncrypted) {
+ setCursor(None);
+ return err;
+ }
+ again = gTrue;
+ }
+ }
+
+ // replace old document
+ if (doc) {
+ delete doc;
+ }
+ doc = newDoc;
+ if (out) {
+ out->startDoc(doc->getXRef());
+ }
+
+ // nothing displayed yet
+ page = -99;
+
+ // save the modification time
+ modTime = getModTime(doc->getFileName()->getCString());
+
+ // update the parent window
+ if (updateCbk) {
+ (*updateCbk)(updateCbkData, doc->getFileName(), -1,
+ doc->getNumPages(), NULL);
+ }
+
+ // back to regular cursor
+ setCursor(None);
+
+ return errNone;
+}
+
+void XPDFCore::resizeToPage(int pg) {
+ Dimension width, height;
+ double width1, height1;
+ Dimension topW, topH, topBorder, daW, daH;
+ Dimension displayW, displayH;
+
+ displayW = DisplayWidth(display, screenNum);
+ displayH = DisplayHeight(display, screenNum);
+ if (fullScreen) {
+ width = displayW;
+ height = displayH;
+ } else {
+ if (pg < 0 || pg > doc->getNumPages()) {
+ width1 = 612;
+ height1 = 792;
+ } else if (doc->getPageRotate(pg) == 90 ||
+ doc->getPageRotate(pg) == 270) {
+ width1 = doc->getPageHeight(pg);
+ height1 = doc->getPageWidth(pg);
+ } else {
+ width1 = doc->getPageWidth(pg);
+ height1 = doc->getPageHeight(pg);
+ }
+ if (zoom == zoomPage || zoom == zoomWidth) {
+ width = (Dimension)((width1 * zoomDPI[defZoom - minZoom]) / 72 + 0.5);
+ height = (Dimension)((height1 * zoomDPI[defZoom - minZoom]) / 72 + 0.5);
+ } else {
+ width = (Dimension)((width1 * zoomDPI[zoom - minZoom]) / 72 + 0.5);
+ height = (Dimension)((height1 * zoomDPI[zoom - minZoom]) / 72 + 0.5);
+ }
+ if (width > displayW - 100) {
+ width = displayW - 100;
+ }
+ if (height > displayH - 150) {
+ height = displayH - 150;
+ }
+ }
+
+ if (XtIsRealized(shell)) {
+ XtVaGetValues(shell, XmNwidth, &topW, XmNheight, &topH,
+ XmNborderWidth, &topBorder, NULL);
+ XtVaGetValues(drawArea, XmNwidth, &daW, XmNheight, &daH, NULL);
+ XtVaSetValues(shell, XmNwidth, width + (topW - daW),
+ XmNheight, height + (topH - daH), NULL);
+ } else {
+ XtVaSetValues(drawArea, XmNwidth, width, XmNheight, height, NULL);
+ }
+}
+
+void XPDFCore::clear() {
+ if (!doc) {
+ return;
+ }
+
+ // no document
+ delete doc;
+ doc = NULL;
+ out->clear();
+
+ // no page displayed
+ page = -99;
+
+ // redraw
+ scrollX = scrollY = 0;
+ updateScrollBars();
+ redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
+}
+
+void XPDFCore::displayPage(int pageA, int zoomA, int rotateA,
+ GBool scrollToTop, GBool addToHist) {
+ double hDPI, vDPI;
+ int rot;
+ XPDFHistory *h;
+ GBool newZoom;
+ XGCValues gcValues;
+ time_t newModTime;
+ int oldScrollX, oldScrollY;
+
+ // update the zoom and rotate values
+ newZoom = zoomA != zoom;
+ zoom = zoomA;
+ rotate = rotateA;
+
+ // check for document and valid page number
+ if (!doc || pageA <= 0 || pageA > doc->getNumPages()) {
+ return;
+ }
+
+ // busy cursor
+ setCursor(busyCursor);
+
+
+ // check for changes to the file
+ newModTime = getModTime(doc->getFileName()->getCString());
+ if (newModTime != modTime) {
+ if (loadFile(doc->getFileName()) == errNone) {
+ if (pageA > doc->getNumPages()) {
+ pageA = doc->getNumPages();
+ }
+ }
+ modTime = newModTime;
+ }
+
+ // free the old GCs
+ if (selectGC) {
+ XFreeGC(display, selectGC);
+ XFreeGC(display, highlightGC);
+ }
+
+ // new page number
+ page = pageA;
+
+ // scroll to top
+ if (scrollToTop) {
+ scrollY = 0;
+ }
+
+ // if zoom level changed, scroll to the top-left corner
+ if (newZoom) {
+ scrollX = scrollY = 0;
+ }
+
+ // initialize mouse-related stuff
+ linkAction = NULL;
+ selectXMin = selectXMax = 0;
+ selectYMin = selectYMax = 0;
+ dragging = gFalse;
+ lastDragLeft = lastDragTop = gTrue;
+
+ // draw the page
+ rot = rotate + doc->getPageRotate(page);
+ if (rot >= 360) {
+ rot -= 360;
+ } else if (rotate < 0) {
+ rot += 360;
+ }
+ if (zoom == zoomPage) {
+ if (rot == 90 || rot == 270) {
+ hDPI = (drawAreaWidth / doc->getPageHeight(page)) * 72;
+ vDPI = (drawAreaHeight / doc->getPageWidth(page)) * 72;
+ } else {
+ hDPI = (drawAreaWidth / doc->getPageWidth(page)) * 72;
+ vDPI = (drawAreaHeight / doc->getPageHeight(page)) * 72;
+ }
+ dpi = (hDPI < vDPI) ? hDPI : vDPI;
+ } else if (zoom == zoomWidth) {
+ if (rot == 90 || rot == 270) {
+ dpi = (drawAreaWidth / doc->getPageHeight(page)) * 72;
+ } else {
+ dpi = (drawAreaWidth / doc->getPageWidth(page)) * 72;
+ }
+ } else {
+ dpi = zoomDPI[zoom - minZoom];
+ }
+ out->setWindow(XtWindow(drawArea));
+ doc->displayPage(out, page, dpi, rotate, gTrue);
+ oldScrollX = scrollX;
+ oldScrollY = scrollY;
+ updateScrollBars();
+ if (scrollX != oldScrollX || scrollY != oldScrollY) {
+ redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
+ }
+
+
+ // add to history
+ if (addToHist) {
+ if (++historyCur == xpdfHistorySize) {
+ historyCur = 0;
+ }
+ h = &history[historyCur];
+ if (h->fileName) {
+ delete h->fileName;
+ }
+ h->fileName = doc->getFileName()->copy();
+ h->page = page;
+ if (historyBLen < xpdfHistorySize) {
+ ++historyBLen;
+ }
+ historyFLen = 0;
+ }
+
+ // update the parent window
+ if (updateCbk) {
+ (*updateCbk)(updateCbkData, NULL, page, -1, "");
+ }
+
+ // allocate new GCs
+ gcValues.foreground = BlackPixel(display, screenNum) ^
+ WhitePixel(display, screenNum);
+ gcValues.function = GXxor;
+ selectGC = XCreateGC(display, out->getPixmap(),
+ GCForeground | GCFunction, &gcValues);
+ highlightGC = XCreateGC(display, out->getPixmap(),
+ GCForeground | GCFunction, &gcValues);
+
+ // back to regular cursor
+ setCursor(None);
+}
+
+void XPDFCore::displayDest(LinkDest *dest, int zoomA, int rotateA,
+ GBool addToHist) {
+ Ref pageRef;
+ int pg;
+ int dx, dy;
+
+ if (dest->isPageRef()) {
+ pageRef = dest->getPageRef();
+ pg = doc->findPage(pageRef.num, pageRef.gen);
+ } else {
+ pg = dest->getPageNum();
+ }
+ if (pg <= 0 || pg > doc->getNumPages()) {
+ pg = 1;
+ }
+ if (pg != page) {
+ displayPage(pg, zoomA, rotateA, gTrue, addToHist);
+ }
+
+ if (fullScreen) {
+ return;
+ }
+ switch (dest->getKind()) {
+ case destXYZ:
+ out->cvtUserToDev(dest->getLeft(), dest->getTop(), &dx, &dy);
+ if (dest->getChangeLeft() || dest->getChangeTop()) {
+ scrollTo(dest->getChangeLeft() ? dx : scrollX,
+ dest->getChangeTop() ? dy : scrollY);
+ }
+ //~ what is the zoom parameter?
+ break;
+ case destFit:
+ case destFitB:
+ //~ do fit
+ scrollTo(0, 0);
+ break;
+ case destFitH:
+ case destFitBH:
+ //~ do fit
+ out->cvtUserToDev(0, dest->getTop(), &dx, &dy);
+ scrollTo(0, dy);
+ break;
+ case destFitV:
+ case destFitBV:
+ //~ do fit
+ out->cvtUserToDev(dest->getLeft(), 0, &dx, &dy);
+ scrollTo(dx, 0);
+ break;
+ case destFitR:
+ //~ do fit
+ out->cvtUserToDev(dest->getLeft(), dest->getTop(), &dx, &dy);
+ scrollTo(dx, dy);
+ break;
+ }
+}
+
+//------------------------------------------------------------------------
+// page/position changes
+//------------------------------------------------------------------------
+
+void XPDFCore::gotoNextPage(int inc, GBool top) {
+ int pg;
+
+ if (!doc || doc->getNumPages() == 0) {
+ return;
+ }
+ if (page < doc->getNumPages()) {
+ if ((pg = page + inc) > doc->getNumPages()) {
+ pg = doc->getNumPages();
+ }
+ displayPage(pg, zoom, rotate, top, gTrue);
+ } else {
+ XBell(display, 0);
+ }
+}
+
+void XPDFCore::gotoPrevPage(int dec, GBool top, GBool bottom) {
+ int pg;
+
+ if (!doc || doc->getNumPages() == 0) {
+ return;
+ }
+ if (page > 1) {
+ if (!fullScreen && bottom) {
+ scrollY = out->getPixmapHeight() - drawAreaHeight;
+ if (scrollY < 0) {
+ scrollY = 0;
+ }
+ // displayPage will call updateScrollBars()
+ }
+ if ((pg = page - dec) < 1) {
+ pg = 1;
+ }
+ displayPage(pg, zoom, rotate, top, gTrue);
+ } else {
+ XBell(display, 0);
+ }
+}
+
+void XPDFCore::goForward() {
+ if (historyFLen == 0) {
+ XBell(display, 0);
+ return;
+ }
+ if (++historyCur == xpdfHistorySize) {
+ historyCur = 0;
+ }
+ --historyFLen;
+ ++historyBLen;
+ if (history[historyCur].fileName->cmp(doc->getFileName()) != 0) {
+ if (loadFile(history[historyCur].fileName) != errNone) {
+ XBell(display, 0);
+ return;
+ }
+ }
+ displayPage(history[historyCur].page, zoom, rotate, gFalse, gFalse);
+}
+
+void XPDFCore::goBackward() {
+ if (historyBLen <= 1) {
+ XBell(display, 0);
+ return;
+ }
+ if (--historyCur < 0) {
+ historyCur = xpdfHistorySize - 1;
+ }
+ --historyBLen;
+ ++historyFLen;
+ if (history[historyCur].fileName->cmp(doc->getFileName()) != 0) {
+ if (loadFile(history[historyCur].fileName) != errNone) {
+ XBell(display, 0);
+ return;
+ }
+ }
+ displayPage(history[historyCur].page, zoom, rotate, gFalse, gFalse);
+}
+
+void XPDFCore::scrollLeft(int nCols) {
+ scrollTo(scrollX - nCols * 16, scrollY);
+}
+
+void XPDFCore::scrollRight(int nCols) {
+ scrollTo(scrollX + nCols * 16, scrollY);
+}
+
+void XPDFCore::scrollUp(int nLines) {
+ scrollTo(scrollX, scrollY - nLines * 16);
+}
+
+void XPDFCore::scrollDown(int nLines) {
+ scrollTo(scrollX, scrollY + nLines * 16);
+}
+
+void XPDFCore::scrollPageUp() {
+ if (scrollY == 0) {
+ gotoPrevPage(1, gFalse, gTrue);
+ } else {
+ scrollTo(scrollX, scrollY - drawAreaHeight);
+ }
+}
+
+void XPDFCore::scrollPageDown() {
+ if (scrollY >= out->getPixmapHeight() - drawAreaHeight) {
+ gotoNextPage(1, gTrue);
+ } else {
+ scrollTo(scrollX, scrollY + drawAreaHeight);
+ }
+}
+
+void XPDFCore::scrollTo(int x, int y) {
+ GBool needRedraw;
+ int maxPos, pos;
+
+ needRedraw = gFalse;
+
+ maxPos = out ? out->getPixmapWidth() : 1;
+ if (maxPos < drawAreaWidth) {
+ maxPos = drawAreaWidth;
+ }
+ if (x < 0) {
+ pos = 0;
+ } else if (x > maxPos - drawAreaWidth) {
+ pos = maxPos - drawAreaWidth;
+ } else {
+ pos = x;
+ }
+ if (scrollX != pos) {
+ scrollX = pos;
+ XmScrollBarSetValues(hScrollBar, scrollX, drawAreaWidth, 16,
+ drawAreaWidth, False);
+ needRedraw = gTrue;
+ }
+
+ maxPos = out ? out->getPixmapHeight() : 1;
+ if (maxPos < drawAreaHeight) {
+ maxPos = drawAreaHeight;
+ }
+ if (y < 0) {
+ pos = 0;
+ } else if (y > maxPos - drawAreaHeight) {
+ pos = maxPos - drawAreaHeight;
+ } else {
+ pos = y;
+ }
+ if (scrollY != pos) {
+ scrollY = pos;
+ XmScrollBarSetValues(vScrollBar, scrollY, drawAreaHeight, 16,
+ drawAreaHeight, False);
+ needRedraw = gTrue;
+ }
+
+ if (needRedraw) {
+ redrawRectangle(scrollX, scrollY, drawAreaWidth, drawAreaHeight);
+ }
+}
+
+//------------------------------------------------------------------------
+// selection
+//------------------------------------------------------------------------
+
+void XPDFCore::setSelection(int newXMin, int newYMin,
+ int newXMax, int newYMax) {
+ Pixmap pixmap;
+ int x, y;
+ GBool needRedraw, needScroll;
+ GBool moveLeft, moveRight, moveTop, moveBottom;
+
+ pixmap = out->getPixmap();
+
+
+ // erase old selection on off-screen bitmap
+ needRedraw = gFalse;
+ if (selectXMin < selectXMax && selectYMin < selectYMax) {
+ XFillRectangle(display, pixmap,
+ selectGC, selectXMin, selectYMin,
+ selectXMax - selectXMin, selectYMax - selectYMin);
+ needRedraw = gTrue;
+ }
+
+ // draw new selection on off-screen bitmap
+ if (newXMin < newXMax && newYMin < newYMax) {
+ XFillRectangle(display, pixmap,
+ selectGC, newXMin, newYMin,
+ newXMax - newXMin, newYMax - newYMin);
+ needRedraw = gTrue;
+ }
+
+ // check which edges moved
+ moveLeft = newXMin != selectXMin;
+ moveTop = newYMin != selectYMin;
+ moveRight = newXMax != selectXMax;
+ moveBottom = newYMax != selectYMax;
+
+ // redraw currently visible part of bitmap
+ if (needRedraw) {
+ if (moveLeft) {
+ redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
+ (newYMin < selectYMin) ? newYMin : selectYMin,
+ (newXMin > selectXMin) ? newXMin : selectXMin,
+ (newYMax > selectYMax) ? newYMax : selectYMax);
+ }
+ if (moveRight) {
+ redrawRectangle((newXMax < selectXMax) ? newXMax : selectXMax,
+ (newYMin < selectYMin) ? newYMin : selectYMin,
+ (newXMax > selectXMax) ? newXMax : selectXMax,
+ (newYMax > selectYMax) ? newYMax : selectYMax);
+ }
+ if (moveTop) {
+ redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
+ (newYMin < selectYMin) ? newYMin : selectYMin,
+ (newXMax > selectXMax) ? newXMax : selectXMax,
+ (newYMin > selectYMin) ? newYMin : selectYMin);
+ }
+ if (moveBottom) {
+ redrawRectangle((newXMin < selectXMin) ? newXMin : selectXMin,
+ (newYMax < selectYMax) ? newYMax : selectYMax,
+ (newXMax > selectXMax) ? newXMax : selectXMax,
+ (newYMax > selectYMax) ? newYMax : selectYMax);
+ }
+ }
+
+ // switch to new selection coords
+ selectXMin = newXMin;
+ selectXMax = newXMax;
+ selectYMin = newYMin;
+ selectYMax = newYMax;
+
+ // scroll if necessary
+ if (fullScreen) {
+ return;
+ }
+ needScroll = gFalse;
+ x = scrollX;
+ y = scrollY;
+ if (moveLeft && selectXMin < x) {
+ x = selectXMin;
+ needScroll = gTrue;
+ } else if (moveRight && selectXMax >= x + drawAreaWidth) {
+ x = selectXMax - drawAreaWidth;
+ needScroll = gTrue;
+ } else if (moveLeft && selectXMin >= x + drawAreaWidth) {
+ x = selectXMin - drawAreaWidth;
+ needScroll = gTrue;
+ } else if (moveRight && selectXMax < x) {
+ x = selectXMax;
+ needScroll = gTrue;
+ }
+ if (moveTop && selectYMin < y) {
+ y = selectYMin;
+ needScroll = gTrue;
+ } else if (moveBottom && selectYMax >= y + drawAreaHeight) {
+ y = selectYMax - drawAreaHeight;
+ needScroll = gTrue;
+ } else if (moveTop && selectYMin >= y + drawAreaHeight) {
+ y = selectYMin - drawAreaHeight;
+ needScroll = gTrue;
+ } else if (moveBottom && selectYMax < y) {
+ y = selectYMax;
+ needScroll = gTrue;
+ }
+ if (needScroll) {
+ scrollTo(x, y);
+ }
+}
+
+void XPDFCore::moveSelection(int mx, int my) {
+ int xMin, yMin, xMax, yMax;
+
+ // clip mouse coords
+ if (mx < 0) {
+ mx = 0;
+ } else if (mx >= out->getPixmapWidth()) {
+ mx = out->getPixmapWidth() - 1;
+ }
+ if (my < 0) {
+ my = 0;
+ } else if (my >= out->getPixmapHeight()) {
+ my = out->getPixmapHeight() - 1;
+ }
+
+ // move appropriate edges of selection
+ if (lastDragLeft) {
+ if (mx < selectXMax) {
+ xMin = mx;
+ xMax = selectXMax;
+ } else {
+ xMin = selectXMax;
+ xMax = mx;
+ lastDragLeft = gFalse;
+ }
+ } else {
+ if (mx > selectXMin) {
+ xMin = selectXMin;
+ xMax = mx;
+ } else {
+ xMin = mx;
+ xMax = selectXMin;
+ lastDragLeft = gTrue;
+ }
+ }
+ if (lastDragTop) {
+ if (my < selectYMax) {
+ yMin = my;
+ yMax = selectYMax;
+ } else {
+ yMin = selectYMax;
+ yMax = my;
+ lastDragTop = gFalse;
+ }
+ } else {
+ if (my > selectYMin) {
+ yMin = selectYMin;
+ yMax = my;
+ } else {
+ yMin = my;
+ yMax = selectYMin;
+ lastDragTop = gTrue;
+ }
+ }
+
+ // redraw the selection
+ setSelection(xMin, yMin, xMax, yMax);
+}
+
+// X's copy-and-paste mechanism is brain damaged. Xt doesn't help
+// any, but doesn't make it too much worse, either. Motif, on the
+// other hand, adds significant complexity to the mess. So here we
+// blow off the Motif junk and stick to plain old Xt. The next two
+// functions (copySelection and convertSelectionCbk) implement the
+// magic needed to deal with Xt's mechanism. Note that this requires
+// global variables (currentSelection and currentSelectionOwner).
+
+void XPDFCore::copySelection() {
+ if (!doc->okToCopy()) {
+ return;
+ }
+ if (currentSelection) {
+ delete currentSelection;
+ }
+ //~ for multithreading: need a mutex here
+ currentSelection = out->getText(selectXMin, selectYMin,
+ selectXMax, selectYMax);
+ currentSelectionOwner = this;
+ XtOwnSelection(drawArea, XA_PRIMARY, XtLastTimestampProcessed(display),
+ &convertSelectionCbk, NULL, NULL);
+}
+
+Boolean XPDFCore::convertSelectionCbk(Widget widget, Atom *selection,
+ Atom *target, Atom *type,
+ XtPointer *value, unsigned long *length,
+ int *format) {
+ if (*target != XA_STRING) {
+ return False;
+ }
+ //~ for multithreading: need a mutex here
+ *value = XtNewString(currentSelection->getCString());
+ *length = currentSelection->getLength();
+ *type = XA_STRING;
+ *format = 8; // 8-bit elements
+ return True;
+}
+
+GBool XPDFCore::getSelection(int *xMin, int *yMin, int *xMax, int *yMax) {
+ if (selectXMin >= selectXMax || selectYMin >= selectYMax) {
+ return gFalse;
+ }
+ *xMin = selectXMin;
+ *yMin = selectYMin;
+ *xMax = selectXMax;
+ *yMax = selectYMax;
+ return gTrue;
+}
+
+GString *XPDFCore::extractText(int xMin, int yMin, int xMax, int yMax) {
+ if (!doc->okToCopy()) {
+ return NULL;
+ }
+ return out->getText(xMin, yMin, xMax, yMax);
+}
+
+GString *XPDFCore::extractText(int pageNum,
+ int xMin, int yMin, int xMax, int yMax) {
+ TextOutputDev *textOut;
+ GString *s;
+
+ if (!doc->okToCopy()) {
+ return NULL;
+ }
+ textOut = new TextOutputDev(NULL, gFalse, gFalse);
+ if (!textOut->isOk()) {
+ delete textOut;
+ return NULL;
+ }
+ doc->displayPage(textOut, pageNum, dpi, rotate, gFalse);
+ s = textOut->getText(xMin, yMin, xMax, yMax);
+ delete textOut;
+ return s;
+}
+
+//------------------------------------------------------------------------
+// hyperlinks
+//------------------------------------------------------------------------
+
+void XPDFCore::doLink(int mx, int my) {
+ double x, y;
+ LinkAction *action;
+
+ // look for a link
+ out->cvtDevToUser(mx, my, &x, &y);
+ if ((action = doc->findLink(x, y))) {
+ doAction(action);
+ }
+}
+
+void XPDFCore::doAction(LinkAction *action) {
+ LinkActionKind kind;
+ LinkDest *dest;
+ GString *namedDest;
+ char *s;
+ GString *fileName, *fileName2;
+ GString *cmd;
+ GString *actionName;
+ Object movieAnnot, obj1, obj2;
+ GString *msg;
+ int i;
+
+ switch (kind = action->getKind()) {
+
+ // GoTo / GoToR action
+ case actionGoTo:
+ case actionGoToR:
+ if (kind == actionGoTo) {
+ dest = NULL;
+ namedDest = NULL;
+ if ((dest = ((LinkGoTo *)action)->getDest())) {
+ dest = dest->copy();
+ } else if ((namedDest = ((LinkGoTo *)action)->getNamedDest())) {
+ namedDest = namedDest->copy();
+ }
+ } else {
+ dest = NULL;
+ namedDest = NULL;
+ if ((dest = ((LinkGoToR *)action)->getDest())) {
+ dest = dest->copy();
+ } else if ((namedDest = ((LinkGoToR *)action)->getNamedDest())) {
+ namedDest = namedDest->copy();
+ }
+ s = ((LinkGoToR *)action)->getFileName()->getCString();
+ //~ translate path name for VMS (deal with '/')
+ if (isAbsolutePath(s)) {
+ fileName = new GString(s);
+ } else {
+ fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
+ }
+ if (loadFile(fileName) != errNone) {
+ if (dest) {
+ delete dest;
+ }
+ if (namedDest) {
+ delete namedDest;
+ }
+ delete fileName;
+ return;
+ }
+ delete fileName;
+ }
+ if (namedDest) {
+ dest = doc->findDest(namedDest);
+ delete namedDest;
+ }
+ if (dest) {
+ displayDest(dest, zoom, rotate, gTrue);
+ delete dest;
+ } else {
+ if (kind == actionGoToR) {
+ displayPage(1, zoom, 0, gFalse, gTrue);
+ }
+ }
+ break;
+
+ // Launch action
+ case actionLaunch:
+ fileName = ((LinkLaunch *)action)->getFileName();
+ s = fileName->getCString();
+ if (!strcmp(s + fileName->getLength() - 4, ".pdf") ||
+ !strcmp(s + fileName->getLength() - 4, ".PDF")) {
+ //~ translate path name for VMS (deal with '/')
+ if (isAbsolutePath(s)) {
+ fileName = fileName->copy();
+ } else {
+ fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
+ }
+ if (loadFile(fileName) != errNone) {
+ delete fileName;
+ return;
+ }
+ delete fileName;
+ displayPage(1, zoom, rotate, gFalse, gTrue);
+ } else {
+ fileName = fileName->copy();
+ if (((LinkLaunch *)action)->getParams()) {
+ fileName->append(' ');
+ fileName->append(((LinkLaunch *)action)->getParams());
+ }
+#ifdef VMS
+ fileName->insert(0, "spawn/nowait ");
+#elif defined(__EMX__)
+ fileName->insert(0, "start /min /n ");
+#else
+ fileName->append(" &");
+#endif
+ msg = new GString("About to execute the command:\n");
+ msg->append(fileName);
+ if (doQuestionDialog("Launching external application", msg)) {
+ system(fileName->getCString());
+ }
+ delete fileName;
+ delete msg;
+ }
+ break;
+
+ // URI action
+ case actionURI:
+ if (!(cmd = globalParams->getURLCommand())) {
+ error(-1, "No urlCommand defined in config file");
+ break;
+ }
+ runCommand(cmd, ((LinkURI *)action)->getURI());
+ break;
+
+ // Named action
+ case actionNamed:
+ actionName = ((LinkNamed *)action)->getName();
+ if (!actionName->cmp("NextPage")) {
+ gotoNextPage(1, gTrue);
+ } else if (!actionName->cmp("PrevPage")) {
+ gotoPrevPage(1, gTrue, gFalse);
+ } else if (!actionName->cmp("FirstPage")) {
+ if (page != 1) {
+ displayPage(1, zoom, rotate, gTrue, gTrue);
+ }
+ } else if (!actionName->cmp("LastPage")) {
+ if (page != doc->getNumPages()) {
+ displayPage(doc->getNumPages(), zoom, rotate, gTrue, gTrue);
+ }
+ } else if (!actionName->cmp("GoBack")) {
+ goBackward();
+ } else if (!actionName->cmp("GoForward")) {
+ goForward();
+ } else if (!actionName->cmp("Quit")) {
+ if (actionCbk) {
+ (*actionCbk)(actionCbkData, "Quit");
+ }
+ } else {
+ error(-1, "Unknown named action: '%s'", actionName->getCString());
+ }
+ break;
+
+ // Movie action
+ case actionMovie:
+ if (!(cmd = globalParams->getMovieCommand())) {
+ error(-1, "No movieCommand defined in config file");
+ break;
+ }
+ if (((LinkMovie *)action)->hasAnnotRef()) {
+ doc->getXRef()->fetch(((LinkMovie *)action)->getAnnotRef()->num,
+ ((LinkMovie *)action)->getAnnotRef()->gen,
+ &movieAnnot);
+ } else {
+ doc->getCatalog()->getPage(page)->getAnnots(&obj1);
+ if (obj1.isArray()) {
+ for (i = 0; i < obj1.arrayGetLength(); ++i) {
+ if (obj1.arrayGet(i, &movieAnnot)->isDict()) {
+ if (movieAnnot.dictLookup("Subtype", &obj2)->isName("Movie")) {
+ obj2.free();
+ break;
+ }
+ obj2.free();
+ }
+ movieAnnot.free();
+ }
+ obj1.free();
+ }
+ }
+ if (movieAnnot.isDict()) {
+ if (movieAnnot.dictLookup("Movie", &obj1)->isDict()) {
+ if (obj1.dictLookup("F", &obj2)) {
+ if ((fileName = LinkAction::getFileSpecName(&obj2))) {
+ if (!isAbsolutePath(fileName->getCString())) {
+ fileName2 = appendToPath(
+ grabPath(doc->getFileName()->getCString()),
+ fileName->getCString());
+ delete fileName;
+ fileName = fileName2;
+ }
+ runCommand(cmd, fileName);
+ delete fileName;
+ }
+ obj2.free();
+ }
+ obj1.free();
+ }
+ }
+ movieAnnot.free();
+ break;
+
+ // unknown action type
+ case actionUnknown:
+ error(-1, "Unknown link action type: '%s'",
+ ((LinkUnknown *)action)->getAction()->getCString());
+ break;
+ }
+}
+
+// Run a command, given a <cmdFmt> string with one '%s' in it, and an
+// <arg> string to insert in place of the '%s'.
+void XPDFCore::runCommand(GString *cmdFmt, GString *arg) {
+ GString *cmd;
+ char *s;
+ int i;
+
+ if ((s = strstr(cmdFmt->getCString(), "%s"))) {
+ cmd = arg->copy();
+ // filter out any quote marks (' or ") to avoid a potential
+ // security hole
+ i = 0;
+ while (i < cmd->getLength()) {
+ if (cmd->getChar(i) == '"') {
+ cmd->del(i);
+ cmd->insert(i, "%22");
+ i += 3;
+ } else if (cmd->getChar(i) == '\'') {
+ cmd->del(i);
+ cmd->insert(i, "%27");
+ i += 3;
+ } else {
+ ++i;
+ }
+ }
+ cmd->insert(0, cmdFmt->getCString(),
+ s - cmdFmt->getCString());
+ cmd->append(s + 2);
+ } else {
+ cmd = cmdFmt->copy();
+ }
+#ifdef VMS
+ cmd->insert(0, "spawn/nowait ");
+#elif defined(__EMX__)
+ cmd->insert(0, "start /min /n ");
+#else
+ cmd->append(" &");
+#endif
+ system(cmd->getCString());
+ delete cmd;
+}
+
+
+//------------------------------------------------------------------------
+// find
+//------------------------------------------------------------------------
+
+void XPDFCore::find(char *s) {
+ Unicode *u;
+ TextOutputDev *textOut;
+ int xMin, yMin, xMax, yMax;
+ double xMin1, yMin1, xMax1, yMax1;
+ int pg;
+ GBool top;
+ int len, i;
+
+ // check for zero-length string
+ if (!s[0]) {
+ XBell(display, 0);
+ return;
+ }
+
+ // set cursor to watch
+ setCursor(busyCursor);
+
+ // convert to Unicode
+#if 1 //~ should do something more intelligent here
+ len = strlen(s);
+ u = (Unicode *)gmalloc(len * sizeof(Unicode));
+ for (i = 0; i < len; ++i) {
+ u[i] = (Unicode)(s[i] & 0xff);
+ }
+#endif
+
+ // search current page starting at current selection or top of page
+ xMin = yMin = xMax = yMax = 0;
+ if (selectXMin < selectXMax && selectYMin < selectYMax) {
+ xMin = selectXMax;
+ yMin = (selectYMin + selectYMax) / 2;
+ top = gFalse;
+ } else {
+ top = gTrue;
+ }
+ if (out->findText(u, len, top, gTrue, &xMin, &yMin, &xMax, &yMax)) {
+ goto found;
+ }
+
+ // search following pages
+ textOut = new TextOutputDev(NULL, gFalse, gFalse);
+ if (!textOut->isOk()) {
+ delete textOut;
+ goto done;
+ }
+ for (pg = page+1; pg <= doc->getNumPages(); ++pg) {
+ doc->displayPage(textOut, pg, 72, 0, gFalse);
+ if (textOut->findText(u, len, gTrue, gTrue,
+ &xMin1, &yMin1, &xMax1, &yMax1)) {
+ goto foundPage;
+ }
+ }
+
+ // search previous pages
+ for (pg = 1; pg < page; ++pg) {
+ doc->displayPage(textOut, pg, 72, 0, gFalse);
+ if (textOut->findText(u, len, gTrue, gTrue,
+ &xMin1, &yMin1, &xMax1, &yMax1)) {
+ goto foundPage;
+ }
+ }
+ delete textOut;
+
+ // search current page ending at current selection
+ if (selectXMin < selectXMax && selectYMin < selectYMax) {
+ xMax = selectXMin;
+ yMax = (selectYMin + selectYMax) / 2;
+ if (out->findText(u, len, gTrue, gFalse, &xMin, &yMin, &xMax, &yMax)) {
+ goto found;
+ }
+ }
+
+ // not found
+ XBell(display, 0);
+ goto done;
+
+ // found on a different page
+ foundPage:
+ delete textOut;
+ displayPage(pg, zoom, rotate, gTrue, gTrue);
+ if (!out->findText(u, len, gTrue, gTrue, &xMin, &yMin, &xMax, &yMax)) {
+ // this can happen if coalescing is bad
+ goto done;
+ }
+
+ // found: change the selection
+ found:
+ setSelection(xMin, yMin, xMax, yMax);
+#ifndef NO_TEXT_SELECT
+ copySelection();
+#endif
+
+ done:
+ gfree(u);
+
+ // reset cursors to normal
+ setCursor(None);
+}
+
+//------------------------------------------------------------------------
+// misc access
+//------------------------------------------------------------------------
+
+void XPDFCore::setBusyCursor(GBool busy) {
+ setCursor(busy ? busyCursor : None);
+}
+
+void XPDFCore::takeFocus() {
+ XmProcessTraversal(drawArea, XmTRAVERSE_CURRENT);
+}
+
+//------------------------------------------------------------------------
+// GUI code
+//------------------------------------------------------------------------
+
+void XPDFCore::initWindow() {
+ Arg args[20];
+ int n;
+
+ // create the cursors
+ busyCursor = XCreateFontCursor(display, XC_watch);
+ linkCursor = XCreateFontCursor(display, XC_hand2);
+ selectCursor = XCreateFontCursor(display, XC_cross);
+ currentCursor = 0;
+
+ // create the scrolled window and scrollbars
+ n = 0;
+ XtSetArg(args[n], XmNscrollingPolicy, XmAPPLICATION_DEFINED); ++n;
+ XtSetArg(args[n], XmNvisualPolicy, XmVARIABLE); ++n;
+ scrolledWin = XmCreateScrolledWindow(parentWidget, "scroll", args, n);
+ XtManageChild(scrolledWin);
+ n = 0;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ XtSetArg(args[n], XmNminimum, 0); ++n;
+ XtSetArg(args[n], XmNmaximum, 1); ++n;
+ XtSetArg(args[n], XmNsliderSize, 1); ++n;
+ XtSetArg(args[n], XmNvalue, 0); ++n;
+ XtSetArg(args[n], XmNincrement, 1); ++n;
+ XtSetArg(args[n], XmNpageIncrement, 1); ++n;
+ hScrollBar = XmCreateScrollBar(scrolledWin, "hScrollBar", args, n);
+ XtManageChild(hScrollBar);
+ XtAddCallback(hScrollBar, XmNvalueChangedCallback,
+ &hScrollChangeCbk, (XtPointer)this);
+#ifndef DISABLE_SMOOTH_SCROLL
+ XtAddCallback(hScrollBar, XmNdragCallback,
+ &hScrollDragCbk, (XtPointer)this);
+#endif
+ n = 0;
+ XtSetArg(args[n], XmNorientation, XmVERTICAL); ++n;
+ XtSetArg(args[n], XmNminimum, 0); ++n;
+ XtSetArg(args[n], XmNmaximum, 1); ++n;
+ XtSetArg(args[n], XmNsliderSize, 1); ++n;
+ XtSetArg(args[n], XmNvalue, 0); ++n;
+ XtSetArg(args[n], XmNincrement, 1); ++n;
+ XtSetArg(args[n], XmNpageIncrement, 1); ++n;
+ vScrollBar = XmCreateScrollBar(scrolledWin, "vScrollBar", args, n);
+ XtManageChild(vScrollBar);
+ XtAddCallback(vScrollBar, XmNvalueChangedCallback,
+ &vScrollChangeCbk, (XtPointer)this);
+#ifndef DISABLE_SMOOTH_SCROLL
+ XtAddCallback(vScrollBar, XmNdragCallback,
+ &vScrollDragCbk, (XtPointer)this);
+#endif
+
+ // create the drawing area
+ n = 0;
+ XtSetArg(args[n], XmNshadowType, XmSHADOW_IN); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 0); ++n;
+ XtSetArg(args[n], XmNmarginHeight, 0); ++n;
+ if (fullScreen) {
+ XtSetArg(args[n], XmNshadowThickness, 0); ++n;
+ }
+ drawAreaFrame = XmCreateFrame(scrolledWin, "drawAreaFrame", args, n);
+ XtManageChild(drawAreaFrame);
+ n = 0;
+ XtSetArg(args[n], XmNresizePolicy, XmRESIZE_ANY); ++n;
+ XtSetArg(args[n], XmNbackground, paperColor); ++n;
+ XtSetArg(args[n], XmNwidth, 700); ++n;
+ XtSetArg(args[n], XmNheight, 500); ++n;
+ drawArea = XmCreateDrawingArea(drawAreaFrame, "drawArea", args, n);
+ XtManageChild(drawArea);
+ XtAddCallback(drawArea, XmNresizeCallback, &resizeCbk, (XtPointer)this);
+ XtAddCallback(drawArea, XmNexposeCallback, &redrawCbk, (XtPointer)this);
+ XtAddCallback(drawArea, XmNinputCallback, &inputCbk, (XtPointer)this);
+ resizeCbk(drawArea, this, NULL);
+
+ // set up mouse motion translations
+ XtOverrideTranslations(drawArea, XtParseTranslationTable(
+ "<Btn1Down>:DrawingAreaInput()\n"
+ "<Btn1Up>:DrawingAreaInput()\n"
+ "<Btn1Motion>:DrawingAreaInput()\n"
+ "<Motion>:DrawingAreaInput()"));
+
+ // can't create a GC until the window gets mapped
+ drawAreaGC = NULL;
+ selectGC = NULL;
+ highlightGC = NULL;
+}
+
+void XPDFCore::hScrollChangeCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
+
+ core->scrollTo(data->value, core->scrollY);
+}
+
+void XPDFCore::hScrollDragCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
+
+ core->scrollTo(data->value, core->scrollY);
+}
+
+void XPDFCore::vScrollChangeCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
+
+ core->scrollTo(core->scrollX, data->value);
+}
+
+void XPDFCore::vScrollDragCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmScrollBarCallbackStruct *data = (XmScrollBarCallbackStruct *)callData;
+
+ core->scrollTo(core->scrollX, data->value);
+}
+
+void XPDFCore::resizeCbk(Widget widget, XtPointer ptr, XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ Arg args[2];
+ int n;
+ Dimension w, h;
+
+ n = 0;
+ XtSetArg(args[n], XmNwidth, &w); ++n;
+ XtSetArg(args[n], XmNheight, &h); ++n;
+ XtGetValues(core->drawArea, args, n);
+ core->drawAreaWidth = (int)w;
+ core->drawAreaHeight = (int)h;
+ if (core->page >= 0 &&
+ (core->zoom == zoomPage || core->zoom == zoomWidth)) {
+ core->displayPage(core->page, core->zoom, core->rotate,
+ gFalse, gFalse);
+ } else {
+ core->updateScrollBars();
+ }
+}
+
+void XPDFCore::redrawCbk(Widget widget, XtPointer ptr, XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmDrawingAreaCallbackStruct *data = (XmDrawingAreaCallbackStruct *)callData;
+ int x, y, w, h;
+
+ if (data->reason == XmCR_EXPOSE) {
+ x = core->scrollX + data->event->xexpose.x;
+ y = core->scrollY + data->event->xexpose.y;
+ w = data->event->xexpose.width;
+ h = data->event->xexpose.height;
+ } else {
+ x = core->scrollX;
+ y = core->scrollY;
+ w = core->drawAreaWidth;
+ h = core->drawAreaHeight;
+ }
+ core->redrawRectangle(x, y, w, h);
+}
+
+void XPDFCore::outputDevRedrawCbk(void *data) {
+ XPDFCore *core = (XPDFCore *)data;
+
+ core->redrawRectangle(core->scrollX, core->scrollY,
+ core->drawAreaWidth, core->drawAreaHeight);
+}
+
+void XPDFCore::inputCbk(Widget widget, XtPointer ptr, XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+ XmDrawingAreaCallbackStruct *data = (XmDrawingAreaCallbackStruct *)callData;
+ LinkAction *action;
+ int mx, my;
+ double x, y;
+ char *s;
+ KeySym key;
+ char buf[20];
+ int n;
+
+ switch (data->event->type) {
+ case ButtonPress:
+ if (data->event->xbutton.button == 1) {
+ core->takeFocus();
+ if (core->doc && core->doc->getNumPages() > 0) {
+ if (core->selectEnabled) {
+ mx = core->scrollX + data->event->xbutton.x;
+ my = core->scrollY + data->event->xbutton.y;
+ core->setSelection(mx, my, mx, my);
+ core->setCursor(core->selectCursor);
+ core->dragging = gTrue;
+ }
+ }
+ } else if (data->event->xbutton.button == 2) {
+ if (!core->fullScreen) {
+ core->panning = gTrue;
+ core->panMX = data->event->xbutton.x;
+ core->panMY = data->event->xbutton.y;
+ }
+ } else if (data->event->xbutton.button == 4) { // mouse wheel up
+ if (core->fullScreen) {
+ core->gotoPrevPage(1, gTrue, gFalse);
+ } else if (core->scrollY == 0) {
+ core->gotoPrevPage(1, gFalse, gTrue);
+ } else {
+ core->scrollUp(1);
+ }
+ } else if (data->event->xbutton.button == 5) { // mouse wheel down
+ if (core->fullScreen ||
+ core->scrollY >=
+ core->out->getPixmapHeight() - core->drawAreaHeight) {
+ core->gotoNextPage(1, gTrue);
+ } else {
+ core->scrollDown(1);
+ }
+ } else if (data->event->xbutton.button == 6) { // second mouse wheel right
+ if (!core->fullScreen) {
+ core->scrollRight(1);
+ }
+ } else if (data->event->xbutton.button == 7) { // second mouse wheel left
+ if (!core->fullScreen) {
+ core->scrollLeft(1);
+ }
+ } else {
+ if (*core->mouseCbk) {
+ (*core->mouseCbk)(core->mouseCbkData, data->event);
+ }
+ }
+ break;
+ case ButtonRelease:
+ if (data->event->xbutton.button == 1) {
+ if (core->doc && core->doc->getNumPages() > 0) {
+ mx = core->scrollX + data->event->xbutton.x;
+ my = core->scrollY + data->event->xbutton.y;
+ if (core->dragging) {
+ core->dragging = gFalse;
+ core->setCursor(None);
+ core->moveSelection(mx, my);
+#ifndef NO_TEXT_SELECT
+ if (core->selectXMin != core->selectXMax &&
+ core->selectYMin != core->selectYMax) {
+ if (core->doc->okToCopy()) {
+ core->copySelection();
+ } else {
+ error(-1, "Copying of text from this document is not allowed.");
+ }
+ }
+#endif
+ }
+ if (core->hyperlinksEnabled) {
+ if (core->selectXMin == core->selectXMax ||
+ core->selectYMin == core->selectYMax) {
+ core->doLink(mx, my);
+ }
+ }
+ }
+ } else if (data->event->xbutton.button == 2) {
+ core->panning = gFalse;
+ } else {
+ if (*core->mouseCbk) {
+ (*core->mouseCbk)(core->mouseCbkData, data->event);
+ }
+ }
+ break;
+ case MotionNotify:
+ if (core->doc && core->doc->getNumPages() > 0) {
+ mx = core->scrollX + data->event->xbutton.x;
+ my = core->scrollY + data->event->xbutton.y;
+ if (core->dragging) {
+ core->moveSelection(mx, my);
+ } else if (core->hyperlinksEnabled) {
+ core->out->cvtDevToUser(mx, my, &x, &y);
+ if ((action = core->doc->findLink(x, y))) {
+ core->setCursor(core->linkCursor);
+ if (action != core->linkAction) {
+ core->linkAction = action;
+ if (core->updateCbk) {
+ s = "";
+ switch (action->getKind()) {
+ case actionGoTo:
+ s = "[internal link]";
+ break;
+ case actionGoToR:
+ s = ((LinkGoToR *)action)->getFileName()->getCString();
+ break;
+ case actionLaunch:
+ s = ((LinkLaunch *)action)->getFileName()->getCString();
+ break;
+ case actionURI:
+ s = ((LinkURI *)action)->getURI()->getCString();
+ break;
+ case actionNamed:
+ s = ((LinkNamed *)action)->getName()->getCString();
+ break;
+ case actionMovie:
+ s = "[movie]";
+ break;
+ case actionUnknown:
+ s = "[unknown link]";
+ break;
+ }
+ (*core->updateCbk)(core->updateCbkData, NULL, -1, -1, s);
+ }
+ }
+ } else {
+ core->setCursor(None);
+ if (core->linkAction) {
+ core->linkAction = NULL;
+ if (core->updateCbk) {
+ (*core->updateCbk)(core->updateCbkData, NULL, -1, -1, "");
+ }
+ }
+ }
+ }
+ }
+ if (core->panning) {
+ core->scrollTo(core->scrollX - (data->event->xbutton.x - core->panMX),
+ core->scrollY - (data->event->xbutton.y - core->panMY));
+ core->panMX = data->event->xbutton.x;
+ core->panMY = data->event->xbutton.y;
+ }
+ break;
+ case KeyPress:
+ n = XLookupString(&data->event->xkey, buf, sizeof(buf) - 1,
+ &key, NULL);
+ core->keyPress(buf, key, data->event->xkey.state);
+ break;
+ }
+}
+
+void XPDFCore::keyPress(char *s, KeySym key, Guint modifiers) {
+ switch (key) {
+ case XK_Home:
+ case XK_KP_Home:
+ if (modifiers & ControlMask) {
+ displayPage(1, zoom, rotate, gTrue, gTrue);
+ } else if (!fullScreen) {
+ scrollTo(0, 0);
+ }
+ return;
+ case XK_End:
+ case XK_KP_End:
+ if (modifiers & ControlMask) {
+ displayPage(doc->getNumPages(), zoom, rotate, gTrue, gTrue);
+ } else if (!fullScreen) {
+ scrollTo(out->getPixmapWidth() - drawAreaWidth,
+ out->getPixmapHeight() - drawAreaHeight);
+ }
+ return;
+ case XK_Page_Up:
+ case XK_KP_Page_Up:
+ if (fullScreen) {
+ gotoPrevPage(1, gTrue, gFalse);
+ } else {
+ scrollPageUp();
+ }
+ return;
+ case XK_Page_Down:
+ case XK_KP_Page_Down:
+ if (fullScreen) {
+ gotoNextPage(1, gTrue);
+ } else {
+ scrollPageDown();
+ }
+ return;
+ case XK_Left:
+ case XK_KP_Left:
+ if (!fullScreen) {
+ scrollLeft();
+ }
+ return;
+ case XK_Right:
+ case XK_KP_Right:
+ if (!fullScreen) {
+ scrollRight();
+ }
+ return;
+ case XK_Up:
+ case XK_KP_Up:
+ if (!fullScreen) {
+ scrollUp();
+ }
+ return;
+ case XK_Down:
+ case XK_KP_Down:
+ if (!fullScreen) {
+ scrollDown();
+ }
+ return;
+ }
+
+ if (*keyPressCbk) {
+ (*keyPressCbk)(keyPressCbkData, s, key, modifiers);
+ }
+}
+
+void XPDFCore::redrawRectangle(int x, int y, int w, int h) {
+ XGCValues gcValues;
+ Window drawAreaWin;
+
+ // clip to window
+ if (x < scrollX) {
+ w -= scrollX - x;
+ x = scrollX;
+ }
+ if (x + w > scrollX + drawAreaWidth) {
+ w = scrollX + drawAreaWidth - x;
+ }
+ if (y < scrollY) {
+ h -= scrollY - y;
+ y = scrollY;
+ }
+ if (y + h > scrollY + drawAreaHeight) {
+ h = scrollY + drawAreaHeight - y;
+ }
+
+ // create a GC for the drawing area
+ drawAreaWin = XtWindow(drawArea);
+ if (!drawAreaGC) {
+ gcValues.foreground = paperColor;
+ drawAreaGC = XCreateGC(display, drawAreaWin, GCForeground, &gcValues);
+ }
+
+ // draw white background past the edges of the document
+ if (x + w > out->getPixmapWidth()) {
+ XFillRectangle(display, drawAreaWin, drawAreaGC,
+ out->getPixmapWidth() - scrollX, y - scrollY,
+ x + w - out->getPixmapWidth(), h);
+ w = out->getPixmapWidth() - x;
+ }
+ if (y + h > out->getPixmapHeight()) {
+ XFillRectangle(display, drawAreaWin, drawAreaGC,
+ x - scrollX, out->getPixmapHeight() - scrollY,
+ w, y + h - out->getPixmapHeight());
+ h = out->getPixmapHeight() - y;
+ }
+
+ // redraw (checking to see if pixmap has been allocated yet)
+ if (out->getPixmapWidth() > 0) {
+ XCopyArea(display, out->getPixmap(), drawAreaWin, drawAreaGC,
+ x, y, w, h, x - scrollX, y - scrollY);
+ }
+}
+
+void XPDFCore::updateScrollBars() {
+ Arg args[20];
+ int n;
+ int maxPos;
+
+ maxPos = out ? out->getPixmapWidth() : 1;
+ if (maxPos < drawAreaWidth) {
+ maxPos = drawAreaWidth;
+ }
+ if (scrollX > maxPos - drawAreaWidth) {
+ scrollX = maxPos - drawAreaWidth;
+ }
+ n = 0;
+ XtSetArg(args[n], XmNvalue, scrollX); ++n;
+ XtSetArg(args[n], XmNmaximum, maxPos); ++n;
+ XtSetArg(args[n], XmNsliderSize, drawAreaWidth); ++n;
+ XtSetArg(args[n], XmNincrement, 16); ++n;
+ XtSetArg(args[n], XmNpageIncrement, drawAreaWidth); ++n;
+ XtSetValues(hScrollBar, args, n);
+
+ maxPos = out ? out->getPixmapHeight() : 1;
+ if (maxPos < drawAreaHeight) {
+ maxPos = drawAreaHeight;
+ }
+ if (scrollY > maxPos - drawAreaHeight) {
+ scrollY = maxPos - drawAreaHeight;
+ }
+ n = 0;
+ XtSetArg(args[n], XmNvalue, scrollY); ++n;
+ XtSetArg(args[n], XmNmaximum, maxPos); ++n;
+ XtSetArg(args[n], XmNsliderSize, drawAreaHeight); ++n;
+ XtSetArg(args[n], XmNincrement, 16); ++n;
+ XtSetArg(args[n], XmNpageIncrement, drawAreaHeight); ++n;
+ XtSetValues(vScrollBar, args, n);
+}
+
+void XPDFCore::setCursor(Cursor cursor) {
+ Window topWin;
+
+ if (cursor == currentCursor) {
+ return;
+ }
+ if (!(topWin = XtWindow(shell))) {
+ return;
+ }
+ if (cursor == None) {
+ XUndefineCursor(display, topWin);
+ } else {
+ XDefineCursor(display, topWin, cursor);
+ }
+ XFlush(display);
+ currentCursor = cursor;
+}
+
+GBool XPDFCore::doQuestionDialog(char *title, GString *msg) {
+ return doDialog(XmDIALOG_QUESTION, gTrue, title, msg);
+}
+
+void XPDFCore::doInfoDialog(char *title, GString *msg) {
+ doDialog(XmDIALOG_INFORMATION, gFalse, title, msg);
+}
+
+void XPDFCore::doErrorDialog(char *title, GString *msg) {
+ doDialog(XmDIALOG_ERROR, gFalse, title, msg);
+}
+
+GBool XPDFCore::doDialog(int type, GBool hasCancel,
+ char *title, GString *msg) {
+ Widget dialog;
+ XtAppContext appContext;
+ Arg args[20];
+ int n;
+ XmString s1, s2;
+ XEvent event;
+
+ n = 0;
+ XtSetArg(args[n], XmNdialogType, type); ++n;
+ XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
+ s1 = XmStringCreateLocalized(title);
+ XtSetArg(args[n], XmNdialogTitle, s1); ++n;
+ s2 = XmStringCreateLocalized(msg->getCString());
+ XtSetArg(args[n], XmNmessageString, s2); ++n;
+ dialog = XmCreateMessageDialog(drawArea, "questionDialog", args, n);
+ XmStringFree(s1);
+ XmStringFree(s2);
+ XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_HELP_BUTTON));
+ XtAddCallback(dialog, XmNokCallback,
+ &dialogOkCbk, (XtPointer)this);
+ if (hasCancel) {
+ XtAddCallback(dialog, XmNcancelCallback,
+ &dialogCancelCbk, (XtPointer)this);
+ } else {
+ XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON));
+ }
+
+ XtManageChild(dialog);
+
+ appContext = XtWidgetToApplicationContext(dialog);
+ dialogDone = 0;
+ do {
+ XtAppNextEvent(appContext, &event);
+ XtDispatchEvent(&event);
+ } while (!dialogDone);
+
+ XtUnmanageChild(dialog);
+ XtDestroyWidget(dialog);
+
+ return dialogDone > 0;
+}
+
+void XPDFCore::dialogOkCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+
+ core->dialogDone = 1;
+}
+
+void XPDFCore::dialogCancelCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFCore *core = (XPDFCore *)ptr;
+
+ core->dialogDone = -1;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFTree.cc b/filters/kword/pdf/xpdf/xpdf/XPDFTree.cc
deleted file mode 100644
index 46e5466c5..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XPDFTree.cc
+++ /dev/null
@@ -1,929 +0,0 @@
-//========================================================================
-//
-// XPDFTree.cc
-//
-//========================================================================
-
-#include <stdlib.h>
-#include "gmem.h"
-#include "XPDFTreeP.h"
-
-//------------------------------------------------------------------------
-
-#define xpdfTreeIndent 16
-
-//------------------------------------------------------------------------
-
-struct _XPDFTreeEntry {
- Widget widget;
- XPDFTreeEntry *children;
- XPDFTreeEntry *next;
-};
-
-//------------------------------------------------------------------------
-
-static void classPartInitialize(WidgetClass widgetClass);
-static void initialize(Widget requestWidget, Widget newWidget,
- ArgList args, Cardinal *numArgs);
-static void destroy(Widget widget);
-static void destroySubtree(XPDFTreeEntry *e);
-static void resize(Widget widget);
-static void redisplay(Widget widget, XEvent *event, Region region);
-static void redisplaySubtree(XPDFTreeWidget w, XPDFTreeEntry *e,
- XEvent *event, Region region);
-static void drawExpandedIcon(XPDFTreeWidget w, Position x, Position y);
-static void drawCollapsedIcon(XPDFTreeWidget w, Position x, Position y);
-static Boolean setValues(Widget oldWidget, Widget requestWidget,
- Widget newWidget, ArgList args, Cardinal *numArgs);
-static void setValuesAlmost(Widget oldWidget, Widget newWidget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply);
-static XtGeometryResult queryGeometry(Widget widget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply);
-static XtGeometryResult geometryManager(Widget widget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply);
-static void changeManaged(Widget widget);
-static void initConstraint(Widget requestWidget, Widget newWidget,
- ArgList args, Cardinal *numArgs);
-static void destroyConstraint(Widget widget);
-static void deleteSubtree(Widget widget);
-static Boolean constraintSetValues(Widget oldWidget, Widget requestWidget,
- Widget newWidget,
- ArgList args, Cardinal *numArgs);
-static void insertChildOnList(XPDFTreeEntry *e, XPDFTreeEntry **listHead);
-static void deleteChildFromList(XPDFTreeEntry *e, XPDFTreeEntry **listHead);
-static void createGC(Widget widget);
-static void destroyGC(Widget widget);
-static void layout(Widget widget, Widget instigator);
-static int layoutSubtree(XPDFTreeWidget w, Widget instigator,
- XPDFTreeEntry *e, Position x, Position y,
- Boolean visible);
-static void calcSize(Widget widget, Widget instigator,
- Dimension *totalWidth,
- Dimension *totalHeight);
-static void calcSubtreeSize(XPDFTreeWidget w, Widget instigator,
- XPDFTreeEntry *e,
- Dimension *width, Dimension *height);
-static Boolean needRelayout(Widget oldWidget, Widget newWidget);
-static void click(Widget widget, XEvent *event,
- String *params, Cardinal *numParams);
-static Boolean findPosition(XPDFTreeWidget w, int x, int y,
- XPDFTreeEntry **e, Boolean *onExpandIcon);
-static Boolean findPositionInSubtree(XPDFTreeWidget w, int x, int y,
- XPDFTreeEntry **e,
- Boolean *onExpandIcon);
-
-//------------------------------------------------------------------------
-
-static XtResource resources[] = {
- { XmNmarginWidth, XmCMarginWidth, XmRHorizontalDimension,
- sizeof(Dimension), XtOffsetOf(XPDFTreeRec, tree.marginWidth),
- XmRImmediate, (XtPointer)0 },
- { XmNmarginHeight, XmCMarginHeight, XmRVerticalDimension,
- sizeof(Dimension), XtOffsetOf(XPDFTreeRec, tree.marginHeight),
- XmRImmediate, (XtPointer)0 },
- { XPDFNselectionCallback, XmCCallback, XmRCallback,
- sizeof(XtCallbackList), XtOffsetOf(XPDFTreeRec, tree.selectCallback),
- XmRImmediate, (XtPointer)NULL }
-};
-
-static XmSyntheticResource synResources[] = {
- { XmNmarginWidth, sizeof(Dimension),
- XtOffsetOf(XPDFTreeRec, tree.marginWidth),
-#if XmVERSION > 1
- XmeFromHorizontalPixels, XmeToHorizontalPixels
-#else
- _XmFromHorizontalPixels, _XmToHorizontalPixels
-#endif
- },
- { XmNmarginHeight, sizeof(Dimension),
- XtOffsetOf(XPDFTreeRec, tree.marginHeight),
-#if XmVERSION > 1
- XmeFromVerticalPixels, XmeToVerticalPixels
-#else
- _XmFromVerticalPixels, _XmToVerticalPixels
-#endif
- }
-};
-
-static XtResource constraints[] = {
- { XPDFNentryParent, XPDFCentryParent, XmRWidget,
- sizeof(Widget), XtOffsetOf(XPDFTreeConstraintRec, tree.entryParent),
- XmRImmediate, (XtPointer)NULL },
- { XPDFNentryExpanded, XPDFCentryExpanded, XmRBoolean,
- sizeof(Boolean), XtOffsetOf(XPDFTreeConstraintRec, tree.entryExpanded),
- XmRImmediate, (XtPointer)False },
- { XPDFNentryPosition, XPDFCentryPosition, XmRInt,
- sizeof(int), XtOffsetOf(XPDFTreeConstraintRec, tree.entryPosition),
- XmRImmediate, (XtPointer)0 }
-};
-
-static char defaultTranslations[] =
- "<Btn1Down>: XPDFTreeClick()";
-
-static XtActionsRec actions[] = {
- { "XPDFTreeClick", click }
-};
-
-externaldef(xpdftreeclassrec) XPDFTreeClassRec xpdfTreeClassRec = {
- { // Core
- (WidgetClass)&xmManagerClassRec, // superclass
- "XPDFTree", // class_name
- sizeof(XPDFTreeRec), // widget_size
- NULL, // class_initialize
- &classPartInitialize, // class_part_initialize
- FALSE, // class_inited
- &initialize, // initialize
- NULL, // initialize_hook
- XtInheritRealize, // realize
- actions, // actions
- XtNumber(actions), // num_actions
- resources, // resources
- XtNumber(resources), // num_resources
- NULLQUARK, // xrm_class
- TRUE, // compress_motion
- XtExposeCompressMaximal, // compress_exposure
- TRUE, // compress_enterleave
- FALSE, // visible_interest
- &destroy, // destroy
- &resize, // resize
- &redisplay, // expose
- &setValues, // set_values
- NULL, // set_values_hook
- &setValuesAlmost, // set_values_almost
- NULL, // get_values_hook
- NULL, // accept_focus
- XtVersion, // version
- NULL, // callback_private
- defaultTranslations, // tm_table
- &queryGeometry, // query_geometry
- NULL, // display_accelerator
- NULL // extension
- },
- { // Composite
- &geometryManager, // geometry_manager
- &changeManaged, // change_managed
- XtInheritInsertChild, // insert_child
- XtInheritDeleteChild, // delete_child
- NULL // extension
- },
- { // Constraint
- constraints, // constraint_resources
- XtNumber(constraints), // constraint_num_resources
- sizeof(XPDFTreeConstraintRec), // constraint_size
- &initConstraint, // constraint_initialize
- &destroyConstraint, // constraint_destroy
- &constraintSetValues, // constraint_set_values
- NULL // extension
- },
- { // XmManager
- XtInheritTranslations, // translations
-#if XmVERSION > 1
- synResources, // syn_resources
- XtNumber(synResources), // num_syn_resources
-#else
- NULL, // syn_resources
- 0, // num_syn_resources
-#endif
- NULL, // syn_constraint_resources
- 0, // num_syn_constraint_res's
- XmInheritParentProcess, // parent_process
- NULL // extension
- },
- { // XPDFTree
- &createGC, // createGC
- &destroyGC, // destroyGC
- &layout, // layout
- &calcSize, // calcSize
- &needRelayout, // needRelayout
- NULL // extension
- }
-};
-
-externaldef(xpdftreewidgetclass) WidgetClass xpdfTreeWidgetClass =
- (WidgetClass)&xpdfTreeClassRec;
-
-//------------------------------------------------------------------------
-
-static void classPartInitialize(WidgetClass widgetCls) {
- XPDFTreeWidgetClass wc = (XPDFTreeWidgetClass)widgetCls;
- XPDFTreeWidgetClass sc = (XPDFTreeWidgetClass)wc->coreClass.superclass;
-
- // method inheritance
- if (wc->treeClass.createGC == XPDFInheritCreateGC) {
- wc->treeClass.createGC = sc->treeClass.createGC;
- }
- if (wc->treeClass.destroyGC == XPDFInheritDestroyGC) {
- wc->treeClass.destroyGC = sc->treeClass.destroyGC;
- }
- if (wc->treeClass.layout == XPDFInheritLayout) {
- wc->treeClass.layout = sc->treeClass.layout;
- }
- if (wc->treeClass.calcSize == XPDFInheritCalcSize) {
- wc->treeClass.calcSize = sc->treeClass.calcSize;
- }
- if (wc->treeClass.needRelayout == XPDFInheritNeedRelayout) {
- wc->treeClass.needRelayout = sc->treeClass.needRelayout;
- }
-}
-
-static void initialize(Widget requestWidget, Widget newWidget,
- ArgList args, Cardinal *numArgs) {
- XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(newWidget);
-
- nw->tree.root = NULL;
- nw->tree.redrawY = -1;
- if (cls->treeClass.createGC) {
- (*cls->treeClass.createGC)(newWidget);
- } else {
- createGC(newWidget);
- }
-}
-
-static void destroy(Widget widget) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
-
- if (w->tree.root) {
- destroySubtree(w->tree.root);
- w->tree.root = NULL;
- }
- if (cls->treeClass.destroyGC) {
- (*cls->treeClass.destroyGC)(widget);
- } else {
- destroyGC(widget);
- }
-}
-
-static void destroySubtree(XPDFTreeEntry *e) {
- if (e->children) {
- destroySubtree(e->children);
- }
- if (e->next) {
- destroySubtree(e->next);
- }
-}
-
-static void resize(Widget widget) {
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
-
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)(widget, NULL);
- } else {
- layout(widget, NULL);
- }
-}
-
-static void redisplay(Widget widget, XEvent *event, Region region) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XPDFTreeEntry *e;
-
- if (w->tree.redrawY >= 0) {
- XClearArea(XtDisplay((Widget)w), XtWindow((Widget)w),
- 0, w->tree.redrawY, w->core.width, w->core.height, False);
- w->tree.redrawY = -1;
- }
- for (e = w->tree.root; e; e = e->next) {
- redisplaySubtree(w, e, event, region);
- }
-}
-
-static void redisplaySubtree(XPDFTreeWidget w, XPDFTreeEntry *e,
- XEvent *event, Region region) {
- XPDFTreeConstraint c;
- Position x, y, y2;
- XPDFTreeEntry *child;
-
- (*XtClass(e->widget)->core_class.expose)(e->widget, event, region);
- c = XPDFTreeCPart(e->widget);
- x = e->widget->core.x;
- y = e->widget->core.y + e->widget->core.height / 2;
- if (e->children) {
- if (c->entryExpanded) {
- drawExpandedIcon(w, x - 8, y);
- y2 = y; // make gcc happy
- for (child = e->children; child; child = child->next) {
- y2 = child->widget->core.y + child->widget->core.height / 2;
- XDrawLine(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.dottedGC,
- x - 8, y2, x + 6, y2);
- redisplaySubtree(w, child, event, region);
- }
- XDrawLine(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.dottedGC,
- x - 8, y + 2, x - 8, y2);
- } else {
- drawCollapsedIcon(w, x - 8, y);
- }
- }
-}
-
-static void drawExpandedIcon(XPDFTreeWidget w, Position x, Position y) {
- XPoint pts[4];
-
- pts[0].x = x - 4; pts[0].y = y - 2;
- pts[1].x = x + 4; pts[1].y = y - 2;
- pts[2].x = x; pts[2].y = y + 2;
- pts[3].x = x - 4; pts[3].y = y - 2;
- XDrawLines(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.plainGC,
- pts, 4, CoordModeOrigin);
-}
-
-static void drawCollapsedIcon(XPDFTreeWidget w, Position x, Position y) {
- XPoint pts[4];
-
- pts[0].x = x - 2; pts[0].y = y - 4;
- pts[1].x = x - 2; pts[1].y = y + 4;
- pts[2].x = x + 2; pts[2].y = y;
- pts[3].x = x - 2; pts[3].y = y - 4;
- XDrawLines(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.plainGC,
- pts, 4, CoordModeOrigin);
-}
-
-static Boolean setValues(Widget oldWidget, Widget requestWidget,
- Widget newWidget, ArgList args, Cardinal *numArgs) {
- XPDFTreeWidget ow = (XPDFTreeWidget)oldWidget;
- XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(nw);
- Boolean relayout, redisp;
-
- // check to see if layout-affecting resources have changed
- if (cls->treeClass.needRelayout) {
- relayout = (*cls->treeClass.needRelayout)((Widget)ow, (Widget)nw);
- } else {
- relayout = needRelayout((Widget)ow, (Widget)nw);
- }
- redisp = False;
- if (relayout) {
-
- // calculate a new ideal size (reset the widget size first so
- // calcSize will compute a new one)
- if (nw->core.width == ow->core.width) {
- nw->core.width = 0;
- }
- if (nw->core.height == ow->core.height) {
- nw->core.height = 0;
- }
- if (cls->treeClass.calcSize) {
- (*cls->treeClass.calcSize)((Widget)nw, NULL,
- &nw->core.width, &nw->core.height);
- } else {
- calcSize((Widget)nw, NULL, &nw->core.width, &nw->core.height);
- }
-
- // if resources have changed but size hasn't, layout manually
- // (because Xt just looks at the size)
- if (nw->core.width == ow->core.width &&
- nw->core.height == ow->core.height) {
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)((Widget)nw, NULL);
- } else {
- layout((Widget)nw, NULL);
- }
- redisp = True;
- }
- }
-
- return redisp;
-}
-
-static void setValuesAlmost(Widget oldWidget, Widget newWidget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply) {
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(newWidget);
-
- // our parent rejected a geometry request, so accept the compromise
- // and relayout
- if (!reply->request_mode) {
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)(newWidget, NULL);
- } else {
- layout(newWidget, NULL);
- }
- }
- *request = *reply;
-}
-
-static XtGeometryResult queryGeometry(Widget widget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply) {
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
-
- if (!XtIsRealized(widget)) {
- reply->width = XtWidth(widget);
- reply->height = XtHeight(widget);
- } else {
- reply->width = 0;
- reply->height = 0;
- }
- if (cls->treeClass.calcSize) {
- (*cls->treeClass.calcSize)(widget, NULL, &reply->width, &reply->height);
- } else {
- calcSize(widget, NULL, &reply->width, &reply->height);
- }
-#if XmVERSION > 1
- return XmeReplyToQueryGeometry(widget, request, reply);
-#else
- if ((request->request_mode & CWWidth) &&
- (request->request_mode & CWHeight) &&
- request->width == reply->width &&
- request->height == reply->height) {
- return XtGeometryYes;
- }
- if (reply->width == XtWidth(widget) &&
- reply->height == XtHeight(widget)) {
- return XtGeometryNo;
- }
- reply->request_mode = CWWidth | CWHeight;
- return XtGeometryAlmost;
-#endif
-}
-
-static XtGeometryResult geometryManager(Widget widget,
- XtWidgetGeometry *request,
- XtWidgetGeometry *reply) {
- XPDFTreeWidget w = (XPDFTreeWidget)XtParent(widget);
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(w);
- Dimension curWidth, curHeight, curBW;
- XtWidgetGeometry parentReq;
- XtGeometryResult result;
-
- // deny any requests for a new position
- if ((request->request_mode & CWX) || (request->request_mode & CWY)) {
- return XtGeometryNo;
- }
-
- // save the current geometry
- curWidth = w->core.width;
- curHeight = w->core.height;
- curBW = w->core.border_width;
-
- // make the requested changes
- if (request->request_mode & CWWidth) {
- w->core.width = request->width;
- }
- if (request->request_mode & CWHeight) {
- w->core.height = request->height;
- }
- if (request->request_mode & CWBorderWidth) {
- w->core.border_width = request->border_width;
- }
-
- // calculate the new ideal size
- parentReq.width = 0;
- parentReq.height = 0;
- if (cls->treeClass.calcSize) {
- (*cls->treeClass.calcSize)((Widget)w, widget,
- &parentReq.width, &reply->height);
- } else {
- calcSize((Widget)w, widget, &parentReq.width, &reply->height);
- }
-
- // send geometry request to our parent
- parentReq.request_mode = CWWidth | CWHeight;
- if (request->request_mode & XtCWQueryOnly) {
- parentReq.request_mode |= XtCWQueryOnly;
- }
- result = XtMakeGeometryRequest((Widget)w, &parentReq, NULL);
- if (result == XtGeometryAlmost) {
- result = XtGeometryNo;
- }
-
- if (result == XtGeometryNo || (request->request_mode & XtCWQueryOnly)) {
- // restore the original geometry
- w->core.width = curWidth;
- w->core.height = curHeight;
- w->core.border_width = curBW;
- } else {
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)((Widget)w, widget);
- } else {
- layout((Widget)w, widget);
- }
- }
-
- return result;
-}
-
-static void changeManaged(Widget widget) {
- Dimension width, height;
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
-
- // compute the ideal size
- if (!XtIsRealized(widget)) {
- width = XtWidth(widget);
- height = XtHeight(widget);
- } else {
- width = 0;
- height = 0;
- }
- if (cls->treeClass.calcSize) {
- (*cls->treeClass.calcSize)(widget, NULL, &width, &height);
- } else {
- calcSize(widget, NULL, &width, &height);
- }
-
- // make resize request to parent -- keep asking until we get a yes
- // or no
- while (XtMakeResizeRequest(widget, width, height, &width, &height)
- == XtGeometryAlmost) ;
-
- // relayout
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)(widget, NULL);
- } else {
- layout(widget, NULL);
- }
-
-#if XmVERSION > 1
- // update keyboard traversal
- XmeNavigChangeManaged(widget);
-#else
- _XmNavigChangeManaged(widget);
-#endif
-}
-
-static void initConstraint(Widget requestWidget, Widget newWidget,
- ArgList args, Cardinal *numArgs) {
- XPDFTreeWidget w = (XPDFTreeWidget)XtParent(newWidget);
- XPDFTreeConstraint c;
-
- c = XPDFTreeCPart(newWidget);
- c->e = (XPDFTreeEntry *)gmalloc(sizeof(XPDFTreeEntry));
- c->e->widget = newWidget;
- c->e->children = NULL;
- c->e->next = NULL;
- if (c->entryParent) {
- insertChildOnList(c->e, &XPDFTreeCPart(c->entryParent)->e->children);
- } else {
- insertChildOnList(c->e, &w->tree.root);
- }
-}
-
-static void destroyConstraint(Widget widget) {
- deleteSubtree(widget);
-}
-
-static void deleteSubtree(Widget widget) {
- XPDFTreeWidget w = (XPDFTreeWidget)XtParent(widget);
- XPDFTreeConstraint c;
-
- c = XPDFTreeCPart(widget);
- if (!c->e) {
- return;
- }
- while (c->e->children) {
- deleteSubtree(c->e->children->widget);
- }
- if (c->entryParent) {
- deleteChildFromList(c->e, &XPDFTreeCPart(c->entryParent)->e->children);
- } else {
- deleteChildFromList(c->e, &w->tree.root);
- }
- gfree(c->e);
- c->e = NULL;
-}
-
-static Boolean constraintSetValues(Widget oldWidget, Widget requestWidget,
- Widget newWidget,
- ArgList args, Cardinal *numArgs) {
- XPDFTreeWidget w = (XPDFTreeWidget)XtParent(newWidget);
- XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass((Widget)w);
- XPDFTreeConstraint oc, nc;
- Boolean relayout;
- Dimension width, height;
-
- if (!XtIsManaged(newWidget)) {
- return False;
- }
- oc = XPDFTreeCPart(oldWidget);
- nc = XPDFTreeCPart(newWidget);
- relayout = False;
- if (nc->entryParent != oc->entryParent ||
- nc->entryPosition != oc->entryPosition) {
- if (oc->entryParent) {
- deleteChildFromList(oc->e, &XPDFTreeCPart(oc->entryParent)->e->children);
- } else {
- deleteChildFromList(oc->e, &w->tree.root);
- }
- if (nc->entryParent) {
- insertChildOnList(nc->e, &XPDFTreeCPart(nc->entryParent)->e->children);
- } else {
- insertChildOnList(nc->e, &w->tree.root);
- }
- relayout = True;
- } else if (nc->entryExpanded != oc->entryExpanded) {
- relayout = True;
- }
-
- if (relayout) {
-
- // calculate a new ideal size (reset the widget size first so
- // calcSize will compute a new one)
- width = 0;
- height = 0;
- if (cls->treeClass.calcSize) {
- (*cls->treeClass.calcSize)((Widget)w, NULL, &width, &height);
- } else {
- calcSize((Widget)w, NULL, &width, &height);
- }
-
- // make resize request to parent -- keep asking until we get a yes
- // or no
- while (XtMakeResizeRequest((Widget)w, width, height, &width, &height)
- == XtGeometryAlmost) ;
-
- // relayout the widget
- if (cls->treeClass.layout) {
- (*cls->treeClass.layout)((Widget)w, NULL);
- } else {
- layout((Widget)w, NULL);
- }
- }
-
- return relayout;
-}
-
-static void insertChildOnList(XPDFTreeEntry *e, XPDFTreeEntry **listHead) {
- int pos;
- XPDFTreeEntry *e2;
-
- pos = XPDFTreeCPart(e->widget)->entryPosition;
- if (!*listHead || pos < XPDFTreeCPart((*listHead)->widget)->entryPosition) {
- e->next = *listHead;
- *listHead = e;
- } else {
- for (e2 = *listHead;
- e2->next && pos >= XPDFTreeCPart(e2->next->widget)->entryPosition;
- e2 = e2->next) ;
- e->next = e2->next;
- e2->next = e;
- }
-}
-
-static void deleteChildFromList(XPDFTreeEntry *e, XPDFTreeEntry **listHead) {
- XPDFTreeEntry **p;
-
- for (p = listHead; *p; p = &(*p)->next) {
- if (*p == e) {
- *p = e->next;
- e->next = NULL;
- return;
- }
- }
-}
-
-static void createGC(Widget widget) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XGCValues gcValues;
-
- gcValues.foreground = w->manager.foreground;
- gcValues.line_width = 0;
- gcValues.line_style = LineSolid;
- w->tree.plainGC = XtGetGC(widget,
- GCForeground | GCLineWidth | GCLineStyle,
- &gcValues);
-
- gcValues.line_style = LineOnOffDash;
- gcValues.dashes = 1;
- gcValues.dash_offset = 0;
- w->tree.dottedGC = XtGetGC(widget,
- GCForeground | GCLineWidth | GCLineStyle |
- GCDashList | GCDashOffset,
- &gcValues);
-}
-
-static void destroyGC(Widget widget) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
-
- XtReleaseGC(widget, w->tree.plainGC);
- XtReleaseGC(widget, w->tree.dottedGC);
-}
-
-static void layout(Widget widget, Widget instigator) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XPDFTreeEntry *e;
- Position x, y;
-
- x = w->tree.marginWidth + xpdfTreeIndent;
- y = w->tree.marginHeight;
- for (e = w->tree.root; e; e = e->next) {
- y = layoutSubtree(w, instigator, e, x, y, True);
- }
-}
-
-static int layoutSubtree(XPDFTreeWidget w, Widget instigator,
- XPDFTreeEntry *e, Position x, Position y,
- Boolean visible) {
- Widget ew;
- XPDFTreeEntry *child;
- XPDFTreeConstraint c;
-
- ew = e->widget;
- if (!XtIsManaged(ew)) {
- return y;
- }
- c = XPDFTreeCPart(ew);
-
- // place this entry
- if (ew) {
- if (visible) {
- if (ew == instigator) {
- ew->core.x = x;
- ew->core.y = y;
- } else {
-#if XmVERSION > 1
- XmeConfigureObject(ew, x, y, ew->core.width, ew->core.height,
- ew->core.border_width);
-#else
- _XmConfigureObject(ew, x, y, ew->core.width, ew->core.height,
- ew->core.border_width);
-#endif
- }
- y += ew->core.height + 2 * ew->core.border_width;
- }
- }
-
- // place this entry's children
- x += xpdfTreeIndent;
- for (child = e->children; child; child = child->next) {
- y = layoutSubtree(w, instigator, child, x, y,
- visible && (!c || c->entryExpanded));
- }
-
- return y;
-}
-
-static void calcSize(Widget widget, Widget instigator,
- Dimension *totalWidth,
- Dimension *totalHeight) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XPDFTreeEntry *e;
- Dimension w1, h1, w2, h2;
-
- w1 = h1 = 0;
- for (e = w->tree.root; e; e = e->next) {
- calcSubtreeSize(w, instigator, e, &w2, &h2);
- if (w2 > w1) {
- w1 = w2;
- }
- h1 += h2;
- }
- w1 += xpdfTreeIndent + 2 * w->tree.marginWidth;
- h1 += 2 * w->tree.marginHeight;
- if (h1 == 0) {
- h1 = 1;
- }
- if (!*totalWidth) {
- *totalWidth = w1;
- }
- if (!*totalHeight) {
- *totalHeight = h1;
- }
-}
-
-static void calcSubtreeSize(XPDFTreeWidget w, Widget instigator,
- XPDFTreeEntry *e,
- Dimension *width, Dimension *height) {
- Widget ew;
- XPDFTreeEntry *child;
- XPDFTreeConstraint c;
- XtWidgetGeometry geom;
- Dimension w1, h1, w2, h2;
-
- ew = e->widget;
- if (!XtIsManaged(ew)) {
- *width = *height = 0;
- return;
- }
- c = XPDFTreeCPart(ew);
-
- // get size of this entry
- if (ew) {
- if (!XtIsManaged(ew)) {
- *width = *height = 0;
- return;
- }
- if (ew == instigator) {
- w1 = ew->core.width;
- h1 = ew->core.height;
- } else {
- XtQueryGeometry(ew, NULL, &geom);
- w1 = (geom.request_mode & CWWidth) ? geom.width : ew->core.width;
- h1 = (geom.request_mode & CWHeight) ? geom.height : ew->core.height;
- }
- h1 += 2 * ew->core.border_width;
- } else {
- // root of tree
- w1 = 0;
- h1 = 0;
- }
-
- // if this entry is expanded, get size of all of its children
- if (c->entryExpanded) {
- for (child = e->children; child; child = child->next) {
- calcSubtreeSize(w, instigator, child, &w2, &h2);
- w2 += xpdfTreeIndent;
- if (w2 > w1) {
- w1 = w2;
- }
- h1 += h2;
- }
- }
-
- *width = w1;
- *height = h1;
-}
-
-static Boolean needRelayout(Widget oldWidget, Widget newWidget) {
- XPDFTreeWidget ow = (XPDFTreeWidget)oldWidget;
- XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
-
- if (nw->tree.marginWidth != ow->tree.marginWidth ||
- nw->tree.marginHeight != ow->tree.marginHeight) {
- return True;
- }
- return False;
-}
-
-static void click(Widget widget, XEvent *event,
- String *params, Cardinal *numParams) {
- XPDFTreeWidget w = (XPDFTreeWidget)widget;
- XButtonPressedEvent *bpe;
- XPDFTreeEntry *e;
- Boolean onExpandIcon;
- XPDFTreeConstraint c;
- XPDFTreeSelectCallbackStruct cbs;
-
- if (event->type != ButtonPress) {
- return;
- }
- bpe = (XButtonPressedEvent *)event;
- if (findPosition(w, bpe->x, bpe->y, &e, &onExpandIcon)) {
- if (onExpandIcon) {
- c = XPDFTreeCPart(e->widget);
- w->tree.redrawY = e->widget->core.y;
- XtVaSetValues(e->widget, XPDFNentryExpanded, !c->entryExpanded, NULL);
- } else {
- XmProcessTraversal(e->widget, XmTRAVERSE_CURRENT);
- XtCallActionProc(widget, "ManagerGadgetActivate", event, NULL, 0);
- cbs.reason = XmCR_ACTIVATE;
- cbs.event = event;
- cbs.selectedItem = e->widget;
- XtCallCallbackList(widget, w->tree.selectCallback, &cbs);
- }
- }
-}
-
-static Boolean findPosition(XPDFTreeWidget w, int x, int y,
- XPDFTreeEntry **e, Boolean *onExpandIcon) {
- XPDFTreeEntry *e2;
-
- for (e2 = w->tree.root; e2; e2 = e2->next) {
- *e = e2;
- if (findPositionInSubtree(w, x, y, e, onExpandIcon)) {
- return True;
- }
- }
- return False;
-}
-
-// If (x,y) falls on either an expand/collapse icon or a label gadget,
-// set *<e> and *<onExpandIcon> and return true.
-static Boolean findPositionInSubtree(XPDFTreeWidget w, int x, int y,
- XPDFTreeEntry **e,
- Boolean *onExpandIcon) {
- Widget child;
- XPDFTreeConstraint c;
- XPDFTreeEntry *e2;
- int y1;
-
- child = (*e)->widget;
- y1 = child->core.y + child->core.height / 2;
- if (x >= child->core.x && x < child->core.x + child->core.width &&
- y >= child->core.y && y < child->core.y + child->core.height) {
- *onExpandIcon = False;
- return True;
- } else if (x >= child->core.x - 16 && x < child->core.x - 4 &&
- y >= y1 - 6 && y < y1 + 6 &&
- (*e)->children) {
- *onExpandIcon = True;
- return True;
- }
- c = XPDFTreeCPart(child);
- if (!c || c->entryExpanded) {
- for (e2 = (*e)->children; e2; e2 = e2->next) {
- *e = e2;
- if (findPositionInSubtree(w, x, y, e, onExpandIcon)) {
- return True;
- }
- }
- }
- return False;
-}
-
-Widget XPDFCreateTree(Widget parent, char *name,
- ArgList argList, Cardinal numArgs) {
- return XtCreateWidget(name, xpdfTreeWidgetClass, parent, argList, numArgs);
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFTree.cpp b/filters/kword/pdf/xpdf/xpdf/XPDFTree.cpp
new file mode 100644
index 000000000..edc7fb8fc
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XPDFTree.cpp
@@ -0,0 +1,929 @@
+//========================================================================
+//
+// XPDFTree.cpp
+//
+//========================================================================
+
+#include <stdlib.h>
+#include "gmem.h"
+#include "XPDFTreeP.h"
+
+//------------------------------------------------------------------------
+
+#define xpdfTreeIndent 16
+
+//------------------------------------------------------------------------
+
+struct _XPDFTreeEntry {
+ Widget widget;
+ XPDFTreeEntry *children;
+ XPDFTreeEntry *next;
+};
+
+//------------------------------------------------------------------------
+
+static void classPartInitialize(WidgetClass widgetClass);
+static void initialize(Widget requestWidget, Widget newWidget,
+ ArgList args, Cardinal *numArgs);
+static void destroy(Widget widget);
+static void destroySubtree(XPDFTreeEntry *e);
+static void resize(Widget widget);
+static void redisplay(Widget widget, XEvent *event, Region region);
+static void redisplaySubtree(XPDFTreeWidget w, XPDFTreeEntry *e,
+ XEvent *event, Region region);
+static void drawExpandedIcon(XPDFTreeWidget w, Position x, Position y);
+static void drawCollapsedIcon(XPDFTreeWidget w, Position x, Position y);
+static Boolean setValues(Widget oldWidget, Widget requestWidget,
+ Widget newWidget, ArgList args, Cardinal *numArgs);
+static void setValuesAlmost(Widget oldWidget, Widget newWidget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply);
+static XtGeometryResult queryGeometry(Widget widget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply);
+static XtGeometryResult geometryManager(Widget widget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply);
+static void changeManaged(Widget widget);
+static void initConstraint(Widget requestWidget, Widget newWidget,
+ ArgList args, Cardinal *numArgs);
+static void destroyConstraint(Widget widget);
+static void deleteSubtree(Widget widget);
+static Boolean constraintSetValues(Widget oldWidget, Widget requestWidget,
+ Widget newWidget,
+ ArgList args, Cardinal *numArgs);
+static void insertChildOnList(XPDFTreeEntry *e, XPDFTreeEntry **listHead);
+static void deleteChildFromList(XPDFTreeEntry *e, XPDFTreeEntry **listHead);
+static void createGC(Widget widget);
+static void destroyGC(Widget widget);
+static void layout(Widget widget, Widget instigator);
+static int layoutSubtree(XPDFTreeWidget w, Widget instigator,
+ XPDFTreeEntry *e, Position x, Position y,
+ Boolean visible);
+static void calcSize(Widget widget, Widget instigator,
+ Dimension *totalWidth,
+ Dimension *totalHeight);
+static void calcSubtreeSize(XPDFTreeWidget w, Widget instigator,
+ XPDFTreeEntry *e,
+ Dimension *width, Dimension *height);
+static Boolean needRelayout(Widget oldWidget, Widget newWidget);
+static void click(Widget widget, XEvent *event,
+ String *params, Cardinal *numParams);
+static Boolean findPosition(XPDFTreeWidget w, int x, int y,
+ XPDFTreeEntry **e, Boolean *onExpandIcon);
+static Boolean findPositionInSubtree(XPDFTreeWidget w, int x, int y,
+ XPDFTreeEntry **e,
+ Boolean *onExpandIcon);
+
+//------------------------------------------------------------------------
+
+static XtResource resources[] = {
+ { XmNmarginWidth, XmCMarginWidth, XmRHorizontalDimension,
+ sizeof(Dimension), XtOffsetOf(XPDFTreeRec, tree.marginWidth),
+ XmRImmediate, (XtPointer)0 },
+ { XmNmarginHeight, XmCMarginHeight, XmRVerticalDimension,
+ sizeof(Dimension), XtOffsetOf(XPDFTreeRec, tree.marginHeight),
+ XmRImmediate, (XtPointer)0 },
+ { XPDFNselectionCallback, XmCCallback, XmRCallback,
+ sizeof(XtCallbackList), XtOffsetOf(XPDFTreeRec, tree.selectCallback),
+ XmRImmediate, (XtPointer)NULL }
+};
+
+static XmSyntheticResource synResources[] = {
+ { XmNmarginWidth, sizeof(Dimension),
+ XtOffsetOf(XPDFTreeRec, tree.marginWidth),
+#if XmVERSION > 1
+ XmeFromHorizontalPixels, XmeToHorizontalPixels
+#else
+ _XmFromHorizontalPixels, _XmToHorizontalPixels
+#endif
+ },
+ { XmNmarginHeight, sizeof(Dimension),
+ XtOffsetOf(XPDFTreeRec, tree.marginHeight),
+#if XmVERSION > 1
+ XmeFromVerticalPixels, XmeToVerticalPixels
+#else
+ _XmFromVerticalPixels, _XmToVerticalPixels
+#endif
+ }
+};
+
+static XtResource constraints[] = {
+ { XPDFNentryParent, XPDFCentryParent, XmRWidget,
+ sizeof(Widget), XtOffsetOf(XPDFTreeConstraintRec, tree.entryParent),
+ XmRImmediate, (XtPointer)NULL },
+ { XPDFNentryExpanded, XPDFCentryExpanded, XmRBoolean,
+ sizeof(Boolean), XtOffsetOf(XPDFTreeConstraintRec, tree.entryExpanded),
+ XmRImmediate, (XtPointer)False },
+ { XPDFNentryPosition, XPDFCentryPosition, XmRInt,
+ sizeof(int), XtOffsetOf(XPDFTreeConstraintRec, tree.entryPosition),
+ XmRImmediate, (XtPointer)0 }
+};
+
+static char defaultTranslations[] =
+ "<Btn1Down>: XPDFTreeClick()";
+
+static XtActionsRec actions[] = {
+ { "XPDFTreeClick", click }
+};
+
+externaldef(xpdftreeclassrec) XPDFTreeClassRec xpdfTreeClassRec = {
+ { // Core
+ (WidgetClass)&xmManagerClassRec, // superclass
+ "XPDFTree", // class_name
+ sizeof(XPDFTreeRec), // widget_size
+ NULL, // class_initialize
+ &classPartInitialize, // class_part_initialize
+ FALSE, // class_inited
+ &initialize, // initialize
+ NULL, // initialize_hook
+ XtInheritRealize, // realize
+ actions, // actions
+ XtNumber(actions), // num_actions
+ resources, // resources
+ XtNumber(resources), // num_resources
+ NULLQUARK, // xrm_class
+ TRUE, // compress_motion
+ XtExposeCompressMaximal, // compress_exposure
+ TRUE, // compress_enterleave
+ FALSE, // visible_interest
+ &destroy, // destroy
+ &resize, // resize
+ &redisplay, // expose
+ &setValues, // set_values
+ NULL, // set_values_hook
+ &setValuesAlmost, // set_values_almost
+ NULL, // get_values_hook
+ NULL, // accept_focus
+ XtVersion, // version
+ NULL, // callback_private
+ defaultTranslations, // tm_table
+ &queryGeometry, // query_geometry
+ NULL, // display_accelerator
+ NULL // extension
+ },
+ { // Composite
+ &geometryManager, // geometry_manager
+ &changeManaged, // change_managed
+ XtInheritInsertChild, // insert_child
+ XtInheritDeleteChild, // delete_child
+ NULL // extension
+ },
+ { // Constraint
+ constraints, // constraint_resources
+ XtNumber(constraints), // constraint_num_resources
+ sizeof(XPDFTreeConstraintRec), // constraint_size
+ &initConstraint, // constraint_initialize
+ &destroyConstraint, // constraint_destroy
+ &constraintSetValues, // constraint_set_values
+ NULL // extension
+ },
+ { // XmManager
+ XtInheritTranslations, // translations
+#if XmVERSION > 1
+ synResources, // syn_resources
+ XtNumber(synResources), // num_syn_resources
+#else
+ NULL, // syn_resources
+ 0, // num_syn_resources
+#endif
+ NULL, // syn_constraint_resources
+ 0, // num_syn_constraint_res's
+ XmInheritParentProcess, // parent_process
+ NULL // extension
+ },
+ { // XPDFTree
+ &createGC, // createGC
+ &destroyGC, // destroyGC
+ &layout, // layout
+ &calcSize, // calcSize
+ &needRelayout, // needRelayout
+ NULL // extension
+ }
+};
+
+externaldef(xpdftreewidgetclass) WidgetClass xpdfTreeWidgetClass =
+ (WidgetClass)&xpdfTreeClassRec;
+
+//------------------------------------------------------------------------
+
+static void classPartInitialize(WidgetClass widgetCls) {
+ XPDFTreeWidgetClass wc = (XPDFTreeWidgetClass)widgetCls;
+ XPDFTreeWidgetClass sc = (XPDFTreeWidgetClass)wc->coreClass.superclass;
+
+ // method inheritance
+ if (wc->treeClass.createGC == XPDFInheritCreateGC) {
+ wc->treeClass.createGC = sc->treeClass.createGC;
+ }
+ if (wc->treeClass.destroyGC == XPDFInheritDestroyGC) {
+ wc->treeClass.destroyGC = sc->treeClass.destroyGC;
+ }
+ if (wc->treeClass.layout == XPDFInheritLayout) {
+ wc->treeClass.layout = sc->treeClass.layout;
+ }
+ if (wc->treeClass.calcSize == XPDFInheritCalcSize) {
+ wc->treeClass.calcSize = sc->treeClass.calcSize;
+ }
+ if (wc->treeClass.needRelayout == XPDFInheritNeedRelayout) {
+ wc->treeClass.needRelayout = sc->treeClass.needRelayout;
+ }
+}
+
+static void initialize(Widget requestWidget, Widget newWidget,
+ ArgList args, Cardinal *numArgs) {
+ XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(newWidget);
+
+ nw->tree.root = NULL;
+ nw->tree.redrawY = -1;
+ if (cls->treeClass.createGC) {
+ (*cls->treeClass.createGC)(newWidget);
+ } else {
+ createGC(newWidget);
+ }
+}
+
+static void destroy(Widget widget) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
+
+ if (w->tree.root) {
+ destroySubtree(w->tree.root);
+ w->tree.root = NULL;
+ }
+ if (cls->treeClass.destroyGC) {
+ (*cls->treeClass.destroyGC)(widget);
+ } else {
+ destroyGC(widget);
+ }
+}
+
+static void destroySubtree(XPDFTreeEntry *e) {
+ if (e->children) {
+ destroySubtree(e->children);
+ }
+ if (e->next) {
+ destroySubtree(e->next);
+ }
+}
+
+static void resize(Widget widget) {
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
+
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)(widget, NULL);
+ } else {
+ layout(widget, NULL);
+ }
+}
+
+static void redisplay(Widget widget, XEvent *event, Region region) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XPDFTreeEntry *e;
+
+ if (w->tree.redrawY >= 0) {
+ XClearArea(XtDisplay((Widget)w), XtWindow((Widget)w),
+ 0, w->tree.redrawY, w->core.width, w->core.height, False);
+ w->tree.redrawY = -1;
+ }
+ for (e = w->tree.root; e; e = e->next) {
+ redisplaySubtree(w, e, event, region);
+ }
+}
+
+static void redisplaySubtree(XPDFTreeWidget w, XPDFTreeEntry *e,
+ XEvent *event, Region region) {
+ XPDFTreeConstraint c;
+ Position x, y, y2;
+ XPDFTreeEntry *child;
+
+ (*XtClass(e->widget)->core_class.expose)(e->widget, event, region);
+ c = XPDFTreeCPart(e->widget);
+ x = e->widget->core.x;
+ y = e->widget->core.y + e->widget->core.height / 2;
+ if (e->children) {
+ if (c->entryExpanded) {
+ drawExpandedIcon(w, x - 8, y);
+ y2 = y; // make gcc happy
+ for (child = e->children; child; child = child->next) {
+ y2 = child->widget->core.y + child->widget->core.height / 2;
+ XDrawLine(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.dottedGC,
+ x - 8, y2, x + 6, y2);
+ redisplaySubtree(w, child, event, region);
+ }
+ XDrawLine(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.dottedGC,
+ x - 8, y + 2, x - 8, y2);
+ } else {
+ drawCollapsedIcon(w, x - 8, y);
+ }
+ }
+}
+
+static void drawExpandedIcon(XPDFTreeWidget w, Position x, Position y) {
+ XPoint pts[4];
+
+ pts[0].x = x - 4; pts[0].y = y - 2;
+ pts[1].x = x + 4; pts[1].y = y - 2;
+ pts[2].x = x; pts[2].y = y + 2;
+ pts[3].x = x - 4; pts[3].y = y - 2;
+ XDrawLines(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.plainGC,
+ pts, 4, CoordModeOrigin);
+}
+
+static void drawCollapsedIcon(XPDFTreeWidget w, Position x, Position y) {
+ XPoint pts[4];
+
+ pts[0].x = x - 2; pts[0].y = y - 4;
+ pts[1].x = x - 2; pts[1].y = y + 4;
+ pts[2].x = x + 2; pts[2].y = y;
+ pts[3].x = x - 2; pts[3].y = y - 4;
+ XDrawLines(XtDisplay((Widget)w), XtWindow((Widget)w), w->tree.plainGC,
+ pts, 4, CoordModeOrigin);
+}
+
+static Boolean setValues(Widget oldWidget, Widget requestWidget,
+ Widget newWidget, ArgList args, Cardinal *numArgs) {
+ XPDFTreeWidget ow = (XPDFTreeWidget)oldWidget;
+ XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(nw);
+ Boolean relayout, redisp;
+
+ // check to see if layout-affecting resources have changed
+ if (cls->treeClass.needRelayout) {
+ relayout = (*cls->treeClass.needRelayout)((Widget)ow, (Widget)nw);
+ } else {
+ relayout = needRelayout((Widget)ow, (Widget)nw);
+ }
+ redisp = False;
+ if (relayout) {
+
+ // calculate a new ideal size (reset the widget size first so
+ // calcSize will compute a new one)
+ if (nw->core.width == ow->core.width) {
+ nw->core.width = 0;
+ }
+ if (nw->core.height == ow->core.height) {
+ nw->core.height = 0;
+ }
+ if (cls->treeClass.calcSize) {
+ (*cls->treeClass.calcSize)((Widget)nw, NULL,
+ &nw->core.width, &nw->core.height);
+ } else {
+ calcSize((Widget)nw, NULL, &nw->core.width, &nw->core.height);
+ }
+
+ // if resources have changed but size hasn't, layout manually
+ // (because Xt just looks at the size)
+ if (nw->core.width == ow->core.width &&
+ nw->core.height == ow->core.height) {
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)((Widget)nw, NULL);
+ } else {
+ layout((Widget)nw, NULL);
+ }
+ redisp = True;
+ }
+ }
+
+ return redisp;
+}
+
+static void setValuesAlmost(Widget oldWidget, Widget newWidget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply) {
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(newWidget);
+
+ // our parent rejected a geometry request, so accept the compromise
+ // and relayout
+ if (!reply->request_mode) {
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)(newWidget, NULL);
+ } else {
+ layout(newWidget, NULL);
+ }
+ }
+ *request = *reply;
+}
+
+static XtGeometryResult queryGeometry(Widget widget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply) {
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
+
+ if (!XtIsRealized(widget)) {
+ reply->width = XtWidth(widget);
+ reply->height = XtHeight(widget);
+ } else {
+ reply->width = 0;
+ reply->height = 0;
+ }
+ if (cls->treeClass.calcSize) {
+ (*cls->treeClass.calcSize)(widget, NULL, &reply->width, &reply->height);
+ } else {
+ calcSize(widget, NULL, &reply->width, &reply->height);
+ }
+#if XmVERSION > 1
+ return XmeReplyToQueryGeometry(widget, request, reply);
+#else
+ if ((request->request_mode & CWWidth) &&
+ (request->request_mode & CWHeight) &&
+ request->width == reply->width &&
+ request->height == reply->height) {
+ return XtGeometryYes;
+ }
+ if (reply->width == XtWidth(widget) &&
+ reply->height == XtHeight(widget)) {
+ return XtGeometryNo;
+ }
+ reply->request_mode = CWWidth | CWHeight;
+ return XtGeometryAlmost;
+#endif
+}
+
+static XtGeometryResult geometryManager(Widget widget,
+ XtWidgetGeometry *request,
+ XtWidgetGeometry *reply) {
+ XPDFTreeWidget w = (XPDFTreeWidget)XtParent(widget);
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(w);
+ Dimension curWidth, curHeight, curBW;
+ XtWidgetGeometry parentReq;
+ XtGeometryResult result;
+
+ // deny any requests for a new position
+ if ((request->request_mode & CWX) || (request->request_mode & CWY)) {
+ return XtGeometryNo;
+ }
+
+ // save the current geometry
+ curWidth = w->core.width;
+ curHeight = w->core.height;
+ curBW = w->core.border_width;
+
+ // make the requested changes
+ if (request->request_mode & CWWidth) {
+ w->core.width = request->width;
+ }
+ if (request->request_mode & CWHeight) {
+ w->core.height = request->height;
+ }
+ if (request->request_mode & CWBorderWidth) {
+ w->core.border_width = request->border_width;
+ }
+
+ // calculate the new ideal size
+ parentReq.width = 0;
+ parentReq.height = 0;
+ if (cls->treeClass.calcSize) {
+ (*cls->treeClass.calcSize)((Widget)w, widget,
+ &parentReq.width, &reply->height);
+ } else {
+ calcSize((Widget)w, widget, &parentReq.width, &reply->height);
+ }
+
+ // send geometry request to our parent
+ parentReq.request_mode = CWWidth | CWHeight;
+ if (request->request_mode & XtCWQueryOnly) {
+ parentReq.request_mode |= XtCWQueryOnly;
+ }
+ result = XtMakeGeometryRequest((Widget)w, &parentReq, NULL);
+ if (result == XtGeometryAlmost) {
+ result = XtGeometryNo;
+ }
+
+ if (result == XtGeometryNo || (request->request_mode & XtCWQueryOnly)) {
+ // restore the original geometry
+ w->core.width = curWidth;
+ w->core.height = curHeight;
+ w->core.border_width = curBW;
+ } else {
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)((Widget)w, widget);
+ } else {
+ layout((Widget)w, widget);
+ }
+ }
+
+ return result;
+}
+
+static void changeManaged(Widget widget) {
+ Dimension width, height;
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass(widget);
+
+ // compute the ideal size
+ if (!XtIsRealized(widget)) {
+ width = XtWidth(widget);
+ height = XtHeight(widget);
+ } else {
+ width = 0;
+ height = 0;
+ }
+ if (cls->treeClass.calcSize) {
+ (*cls->treeClass.calcSize)(widget, NULL, &width, &height);
+ } else {
+ calcSize(widget, NULL, &width, &height);
+ }
+
+ // make resize request to parent -- keep asking until we get a yes
+ // or no
+ while (XtMakeResizeRequest(widget, width, height, &width, &height)
+ == XtGeometryAlmost) ;
+
+ // relayout
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)(widget, NULL);
+ } else {
+ layout(widget, NULL);
+ }
+
+#if XmVERSION > 1
+ // update keyboard traversal
+ XmeNavigChangeManaged(widget);
+#else
+ _XmNavigChangeManaged(widget);
+#endif
+}
+
+static void initConstraint(Widget requestWidget, Widget newWidget,
+ ArgList args, Cardinal *numArgs) {
+ XPDFTreeWidget w = (XPDFTreeWidget)XtParent(newWidget);
+ XPDFTreeConstraint c;
+
+ c = XPDFTreeCPart(newWidget);
+ c->e = (XPDFTreeEntry *)gmalloc(sizeof(XPDFTreeEntry));
+ c->e->widget = newWidget;
+ c->e->children = NULL;
+ c->e->next = NULL;
+ if (c->entryParent) {
+ insertChildOnList(c->e, &XPDFTreeCPart(c->entryParent)->e->children);
+ } else {
+ insertChildOnList(c->e, &w->tree.root);
+ }
+}
+
+static void destroyConstraint(Widget widget) {
+ deleteSubtree(widget);
+}
+
+static void deleteSubtree(Widget widget) {
+ XPDFTreeWidget w = (XPDFTreeWidget)XtParent(widget);
+ XPDFTreeConstraint c;
+
+ c = XPDFTreeCPart(widget);
+ if (!c->e) {
+ return;
+ }
+ while (c->e->children) {
+ deleteSubtree(c->e->children->widget);
+ }
+ if (c->entryParent) {
+ deleteChildFromList(c->e, &XPDFTreeCPart(c->entryParent)->e->children);
+ } else {
+ deleteChildFromList(c->e, &w->tree.root);
+ }
+ gfree(c->e);
+ c->e = NULL;
+}
+
+static Boolean constraintSetValues(Widget oldWidget, Widget requestWidget,
+ Widget newWidget,
+ ArgList args, Cardinal *numArgs) {
+ XPDFTreeWidget w = (XPDFTreeWidget)XtParent(newWidget);
+ XPDFTreeWidgetClass cls = (XPDFTreeWidgetClass)XtClass((Widget)w);
+ XPDFTreeConstraint oc, nc;
+ Boolean relayout;
+ Dimension width, height;
+
+ if (!XtIsManaged(newWidget)) {
+ return False;
+ }
+ oc = XPDFTreeCPart(oldWidget);
+ nc = XPDFTreeCPart(newWidget);
+ relayout = False;
+ if (nc->entryParent != oc->entryParent ||
+ nc->entryPosition != oc->entryPosition) {
+ if (oc->entryParent) {
+ deleteChildFromList(oc->e, &XPDFTreeCPart(oc->entryParent)->e->children);
+ } else {
+ deleteChildFromList(oc->e, &w->tree.root);
+ }
+ if (nc->entryParent) {
+ insertChildOnList(nc->e, &XPDFTreeCPart(nc->entryParent)->e->children);
+ } else {
+ insertChildOnList(nc->e, &w->tree.root);
+ }
+ relayout = True;
+ } else if (nc->entryExpanded != oc->entryExpanded) {
+ relayout = True;
+ }
+
+ if (relayout) {
+
+ // calculate a new ideal size (reset the widget size first so
+ // calcSize will compute a new one)
+ width = 0;
+ height = 0;
+ if (cls->treeClass.calcSize) {
+ (*cls->treeClass.calcSize)((Widget)w, NULL, &width, &height);
+ } else {
+ calcSize((Widget)w, NULL, &width, &height);
+ }
+
+ // make resize request to parent -- keep asking until we get a yes
+ // or no
+ while (XtMakeResizeRequest((Widget)w, width, height, &width, &height)
+ == XtGeometryAlmost) ;
+
+ // relayout the widget
+ if (cls->treeClass.layout) {
+ (*cls->treeClass.layout)((Widget)w, NULL);
+ } else {
+ layout((Widget)w, NULL);
+ }
+ }
+
+ return relayout;
+}
+
+static void insertChildOnList(XPDFTreeEntry *e, XPDFTreeEntry **listHead) {
+ int pos;
+ XPDFTreeEntry *e2;
+
+ pos = XPDFTreeCPart(e->widget)->entryPosition;
+ if (!*listHead || pos < XPDFTreeCPart((*listHead)->widget)->entryPosition) {
+ e->next = *listHead;
+ *listHead = e;
+ } else {
+ for (e2 = *listHead;
+ e2->next && pos >= XPDFTreeCPart(e2->next->widget)->entryPosition;
+ e2 = e2->next) ;
+ e->next = e2->next;
+ e2->next = e;
+ }
+}
+
+static void deleteChildFromList(XPDFTreeEntry *e, XPDFTreeEntry **listHead) {
+ XPDFTreeEntry **p;
+
+ for (p = listHead; *p; p = &(*p)->next) {
+ if (*p == e) {
+ *p = e->next;
+ e->next = NULL;
+ return;
+ }
+ }
+}
+
+static void createGC(Widget widget) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XGCValues gcValues;
+
+ gcValues.foreground = w->manager.foreground;
+ gcValues.line_width = 0;
+ gcValues.line_style = LineSolid;
+ w->tree.plainGC = XtGetGC(widget,
+ GCForeground | GCLineWidth | GCLineStyle,
+ &gcValues);
+
+ gcValues.line_style = LineOnOffDash;
+ gcValues.dashes = 1;
+ gcValues.dash_offset = 0;
+ w->tree.dottedGC = XtGetGC(widget,
+ GCForeground | GCLineWidth | GCLineStyle |
+ GCDashList | GCDashOffset,
+ &gcValues);
+}
+
+static void destroyGC(Widget widget) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+
+ XtReleaseGC(widget, w->tree.plainGC);
+ XtReleaseGC(widget, w->tree.dottedGC);
+}
+
+static void layout(Widget widget, Widget instigator) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XPDFTreeEntry *e;
+ Position x, y;
+
+ x = w->tree.marginWidth + xpdfTreeIndent;
+ y = w->tree.marginHeight;
+ for (e = w->tree.root; e; e = e->next) {
+ y = layoutSubtree(w, instigator, e, x, y, True);
+ }
+}
+
+static int layoutSubtree(XPDFTreeWidget w, Widget instigator,
+ XPDFTreeEntry *e, Position x, Position y,
+ Boolean visible) {
+ Widget ew;
+ XPDFTreeEntry *child;
+ XPDFTreeConstraint c;
+
+ ew = e->widget;
+ if (!XtIsManaged(ew)) {
+ return y;
+ }
+ c = XPDFTreeCPart(ew);
+
+ // place this entry
+ if (ew) {
+ if (visible) {
+ if (ew == instigator) {
+ ew->core.x = x;
+ ew->core.y = y;
+ } else {
+#if XmVERSION > 1
+ XmeConfigureObject(ew, x, y, ew->core.width, ew->core.height,
+ ew->core.border_width);
+#else
+ _XmConfigureObject(ew, x, y, ew->core.width, ew->core.height,
+ ew->core.border_width);
+#endif
+ }
+ y += ew->core.height + 2 * ew->core.border_width;
+ }
+ }
+
+ // place this entry's children
+ x += xpdfTreeIndent;
+ for (child = e->children; child; child = child->next) {
+ y = layoutSubtree(w, instigator, child, x, y,
+ visible && (!c || c->entryExpanded));
+ }
+
+ return y;
+}
+
+static void calcSize(Widget widget, Widget instigator,
+ Dimension *totalWidth,
+ Dimension *totalHeight) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XPDFTreeEntry *e;
+ Dimension w1, h1, w2, h2;
+
+ w1 = h1 = 0;
+ for (e = w->tree.root; e; e = e->next) {
+ calcSubtreeSize(w, instigator, e, &w2, &h2);
+ if (w2 > w1) {
+ w1 = w2;
+ }
+ h1 += h2;
+ }
+ w1 += xpdfTreeIndent + 2 * w->tree.marginWidth;
+ h1 += 2 * w->tree.marginHeight;
+ if (h1 == 0) {
+ h1 = 1;
+ }
+ if (!*totalWidth) {
+ *totalWidth = w1;
+ }
+ if (!*totalHeight) {
+ *totalHeight = h1;
+ }
+}
+
+static void calcSubtreeSize(XPDFTreeWidget w, Widget instigator,
+ XPDFTreeEntry *e,
+ Dimension *width, Dimension *height) {
+ Widget ew;
+ XPDFTreeEntry *child;
+ XPDFTreeConstraint c;
+ XtWidgetGeometry geom;
+ Dimension w1, h1, w2, h2;
+
+ ew = e->widget;
+ if (!XtIsManaged(ew)) {
+ *width = *height = 0;
+ return;
+ }
+ c = XPDFTreeCPart(ew);
+
+ // get size of this entry
+ if (ew) {
+ if (!XtIsManaged(ew)) {
+ *width = *height = 0;
+ return;
+ }
+ if (ew == instigator) {
+ w1 = ew->core.width;
+ h1 = ew->core.height;
+ } else {
+ XtQueryGeometry(ew, NULL, &geom);
+ w1 = (geom.request_mode & CWWidth) ? geom.width : ew->core.width;
+ h1 = (geom.request_mode & CWHeight) ? geom.height : ew->core.height;
+ }
+ h1 += 2 * ew->core.border_width;
+ } else {
+ // root of tree
+ w1 = 0;
+ h1 = 0;
+ }
+
+ // if this entry is expanded, get size of all of its children
+ if (c->entryExpanded) {
+ for (child = e->children; child; child = child->next) {
+ calcSubtreeSize(w, instigator, child, &w2, &h2);
+ w2 += xpdfTreeIndent;
+ if (w2 > w1) {
+ w1 = w2;
+ }
+ h1 += h2;
+ }
+ }
+
+ *width = w1;
+ *height = h1;
+}
+
+static Boolean needRelayout(Widget oldWidget, Widget newWidget) {
+ XPDFTreeWidget ow = (XPDFTreeWidget)oldWidget;
+ XPDFTreeWidget nw = (XPDFTreeWidget)newWidget;
+
+ if (nw->tree.marginWidth != ow->tree.marginWidth ||
+ nw->tree.marginHeight != ow->tree.marginHeight) {
+ return True;
+ }
+ return False;
+}
+
+static void click(Widget widget, XEvent *event,
+ String *params, Cardinal *numParams) {
+ XPDFTreeWidget w = (XPDFTreeWidget)widget;
+ XButtonPressedEvent *bpe;
+ XPDFTreeEntry *e;
+ Boolean onExpandIcon;
+ XPDFTreeConstraint c;
+ XPDFTreeSelectCallbackStruct cbs;
+
+ if (event->type != ButtonPress) {
+ return;
+ }
+ bpe = (XButtonPressedEvent *)event;
+ if (findPosition(w, bpe->x, bpe->y, &e, &onExpandIcon)) {
+ if (onExpandIcon) {
+ c = XPDFTreeCPart(e->widget);
+ w->tree.redrawY = e->widget->core.y;
+ XtVaSetValues(e->widget, XPDFNentryExpanded, !c->entryExpanded, NULL);
+ } else {
+ XmProcessTraversal(e->widget, XmTRAVERSE_CURRENT);
+ XtCallActionProc(widget, "ManagerGadgetActivate", event, NULL, 0);
+ cbs.reason = XmCR_ACTIVATE;
+ cbs.event = event;
+ cbs.selectedItem = e->widget;
+ XtCallCallbackList(widget, w->tree.selectCallback, &cbs);
+ }
+ }
+}
+
+static Boolean findPosition(XPDFTreeWidget w, int x, int y,
+ XPDFTreeEntry **e, Boolean *onExpandIcon) {
+ XPDFTreeEntry *e2;
+
+ for (e2 = w->tree.root; e2; e2 = e2->next) {
+ *e = e2;
+ if (findPositionInSubtree(w, x, y, e, onExpandIcon)) {
+ return True;
+ }
+ }
+ return False;
+}
+
+// If (x,y) falls on either an expand/collapse icon or a label gadget,
+// set *<e> and *<onExpandIcon> and return true.
+static Boolean findPositionInSubtree(XPDFTreeWidget w, int x, int y,
+ XPDFTreeEntry **e,
+ Boolean *onExpandIcon) {
+ Widget child;
+ XPDFTreeConstraint c;
+ XPDFTreeEntry *e2;
+ int y1;
+
+ child = (*e)->widget;
+ y1 = child->core.y + child->core.height / 2;
+ if (x >= child->core.x && x < child->core.x + child->core.width &&
+ y >= child->core.y && y < child->core.y + child->core.height) {
+ *onExpandIcon = False;
+ return True;
+ } else if (x >= child->core.x - 16 && x < child->core.x - 4 &&
+ y >= y1 - 6 && y < y1 + 6 &&
+ (*e)->children) {
+ *onExpandIcon = True;
+ return True;
+ }
+ c = XPDFTreeCPart(child);
+ if (!c || c->entryExpanded) {
+ for (e2 = (*e)->children; e2; e2 = e2->next) {
+ *e = e2;
+ if (findPositionInSubtree(w, x, y, e, onExpandIcon)) {
+ return True;
+ }
+ }
+ }
+ return False;
+}
+
+Widget XPDFCreateTree(Widget parent, char *name,
+ ArgList argList, Cardinal numArgs) {
+ return XtCreateWidget(name, xpdfTreeWidgetClass, parent, argList, numArgs);
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cc b/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cc
deleted file mode 100644
index a8c8f8f0f..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cc
+++ /dev/null
@@ -1,2318 +0,0 @@
-//========================================================================
-//
-// XPDFViewer.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <X11/cursorfont.h>
-#ifdef HAVE_X11_XPM_H
-#include <X11/xpm.h>
-#endif
-#include "gmem.h"
-#include "gfile.h"
-#include "GString.h"
-#include "GList.h"
-#include "Error.h"
-#include "GlobalParams.h"
-#include "PDFDoc.h"
-#include "ErrorCodes.h"
-#include "Outline.h"
-#include "UnicodeMap.h"
-#ifndef DISABLE_OUTLINE
-#define Object XtObject
-#include "XPDFTree.h"
-#undef Object
-#endif
-#include "XPDFApp.h"
-#include "XPDFViewer.h"
-#include "XPixmapOutputDev.h"
-#include "PSOutputDev.h"
-#include "config.h"
-
-// these macro defns conflict with xpdf's Object class
-#ifdef LESSTIF_VERSION
-#undef XtDisplay
-#undef XtScreen
-#undef XtWindow
-#undef XtParent
-#undef XtIsRealized
-#endif
-
-#if XmVERSION <= 1
-#define XmSET True
-#define XmUNSET False
-#endif
-
-//------------------------------------------------------------------------
-// GUI includes
-//------------------------------------------------------------------------
-
-#include "xpdfIcon.xpm"
-#include "leftArrow.xbm"
-#include "leftArrowDis.xbm"
-#include "dblLeftArrow.xbm"
-#include "dblLeftArrowDis.xbm"
-#include "rightArrow.xbm"
-#include "rightArrowDis.xbm"
-#include "dblRightArrow.xbm"
-#include "dblRightArrowDis.xbm"
-#include "backArrow.xbm"
-#include "backArrowDis.xbm"
-#include "forwardArrow.xbm"
-#include "forwardArrowDis.xbm"
-#include "find.xbm"
-#include "findDis.xbm"
-#include "print.xbm"
-#include "printDis.xbm"
-#include "about.xbm"
-#include "about-text.h"
-
-//------------------------------------------------------------------------
-
-XPDFViewer::XPDFViewer(XPDFApp *appA, GString *fileName,
- int pageA, GString *destName,
- GString *ownerPassword, GString *userPassword) {
- LinkDest *dest;
- int pg, z;
- GString *dir;
-
- app = appA;
- win = NULL;
- core = NULL;
- password = NULL;
- ok = gFalse;
-#ifndef DISABLE_OUTLINE
- outlineLabels = NULL;
- outlineLabelsLength = outlineLabelsSize = 0;
-#endif
-
- // do Motif-specific initialization and create the window;
- // this also creates the core object
- initWindow();
- initAboutDialog();
- initOpenDialog();
- initFindDialog();
- initSaveAsDialog();
- initPrintDialog();
- initPasswordDialog();
-
- dest = NULL; // make gcc happy
- pg = pageA; // make gcc happy
-
- if (fileName) {
- if (loadFile(fileName, ownerPassword, userPassword)) {
- getPageAndDest(pageA, destName, &pg, &dest);
- if (pg > 0) {
- core->resizeToPage(pg);
- }
- dir = makePathAbsolute(grabPath(fileName->getCString()));
- setOpenDialogDir(dir->getCString());
- setSaveAsDialogDir(dir->getCString());
- delete dir;
- } else {
- return;
- }
- }
-
- // map the window -- we do this after calling resizeToPage to avoid
- // an annoying on-screen resize
- mapWindow();
-
- // display the first page
- z = app->getFullScreen() ? zoomPage : core->getZoom();
- if (dest) {
- displayDest(dest, z, core->getRotate(), gTrue);
- delete dest;
- } else {
- displayPage(pg, z, core->getRotate(), gTrue, gTrue);
- }
-
- ok = gTrue;
-}
-
-XPDFViewer::~XPDFViewer() {
- delete core;
- XmFontListFree(aboutBigFont);
- XmFontListFree(aboutVersionFont);
- XmFontListFree(aboutFixedFont);
- closeWindow();
-#ifndef DISABLE_OUTLINE
- if (outlineLabels) {
- gfree(outlineLabels);
- }
-#endif
- if (password) {
- delete password;
- }
-}
-
-void XPDFViewer::open(GString *fileName, int pageA, GString *destName) {
- LinkDest *dest;
- int pg, z;
-
- if (!core->getDoc() || fileName->cmp(core->getDoc()->getFileName())) {
- if (!loadFile(fileName, NULL, NULL)) {
- return;
- }
- }
- getPageAndDest(pageA, destName, &pg, &dest);
- z = app->getFullScreen() ? zoomPage : core->getZoom();
- if (dest) {
- displayDest(dest, z, core->getRotate(), gTrue);
- delete dest;
- } else {
- displayPage(pg, z, core->getRotate(), gTrue, gTrue);
- }
-}
-
-void XPDFViewer::clear() {
- char *title;
- XmString s;
-
- core->clear();
-
- // set up title, number-of-pages display
- title = app->getTitle() ? app->getTitle()->getCString()
- : (char *)xpdfAppName;
- XtVaSetValues(win, XmNtitle, title, XmNiconName, title, NULL);
- s = XmStringCreateLocalized("");
- XtVaSetValues(pageNumText, XmNlabelString, s, NULL);
- XmStringFree(s);
- s = XmStringCreateLocalized(" of 0");
- XtVaSetValues(pageCountLabel, XmNlabelString, s, NULL);
- XmStringFree(s);
-
- // disable buttons
- XtVaSetValues(prevTenPageBtn, XmNsensitive, False, NULL);
- XtVaSetValues(prevPageBtn, XmNsensitive, False, NULL);
- XtVaSetValues(nextTenPageBtn, XmNsensitive, False, NULL);
- XtVaSetValues(nextPageBtn, XmNsensitive, False, NULL);
-}
-
-//------------------------------------------------------------------------
-// load / display
-//------------------------------------------------------------------------
-
-GBool XPDFViewer::loadFile(GString *fileName, GString *ownerPassword,
- GString *userPassword) {
- return core->loadFile(fileName, ownerPassword, userPassword) == errNone;
-}
-
-void XPDFViewer::reloadFile() {
- int pg;
-
- if (!core->getDoc()) {
- return;
- }
- pg = core->getPageNum();
- loadFile(core->getDoc()->getFileName());
- if (pg > core->getDoc()->getNumPages()) {
- pg = core->getDoc()->getNumPages();
- }
- displayPage(pg, core->getZoom(), core->getRotate(), gFalse, gFalse);
-}
-
-void XPDFViewer::displayPage(int pageA, int zoomA, int rotateA,
- GBool scrollToTop, GBool addToHist) {
- core->displayPage(pageA, zoomA, rotateA, scrollToTop, addToHist);
-}
-
-void XPDFViewer::displayDest(LinkDest *dest, int zoomA, int rotateA,
- GBool addToHist) {
- core->displayDest(dest, zoomA, rotateA, addToHist);
-}
-
-void XPDFViewer::getPageAndDest(int pageA, GString *destName,
- int *pageOut, LinkDest **destOut) {
- Ref pageRef;
-
- // find the page number for a named destination
- *pageOut = pageA;
- *destOut = NULL;
- if (destName && (*destOut = core->getDoc()->findDest(destName))) {
- if ((*destOut)->isPageRef()) {
- pageRef = (*destOut)->getPageRef();
- *pageOut = core->getDoc()->findPage(pageRef.num, pageRef.gen);
- } else {
- *pageOut = (*destOut)->getPageNum();
- }
- }
-
- if (*pageOut <= 0) {
- *pageOut = 1;
- }
- if (*pageOut > core->getDoc()->getNumPages()) {
- *pageOut = core->getDoc()->getNumPages();
- }
-}
-
-//------------------------------------------------------------------------
-// password dialog
-//------------------------------------------------------------------------
-
-GString *XPDFViewer::reqPasswordCbk(void *data, GBool again) {
- XPDFViewer *viewer = (XPDFViewer *)data;
-
- viewer->getPassword(again);
- return viewer->password;
-}
-
-//------------------------------------------------------------------------
-// actions
-//------------------------------------------------------------------------
-
-void XPDFViewer::actionCbk(void *data, char *action) {
- XPDFViewer *viewer = (XPDFViewer *)data;
-
- if (!strcmp(action, "Quit")) {
- viewer->app->quit();
- }
-}
-
-//------------------------------------------------------------------------
-// keyboard/mouse input
-//------------------------------------------------------------------------
-
-void XPDFViewer::keyPressCbk(void *data, char *s, KeySym key,
- Guint modifiers) {
- XPDFViewer *viewer = (XPDFViewer *)data;
- int z;
-
- if (s[0]) {
- switch (s[0]) {
- case 'O':
- case 'o':
- viewer->mapOpenDialog(gFalse);
- break;
- case 'R':
- case 'r':
- viewer->reloadFile();
- break;
- case 'F':
- case 'f':
- case '\006': // ctrl-F
- if (viewer->core->getDoc()) {
- XtManageChild(viewer->findDialog);
- }
- break;
- case '\007': // ctrl-G
- if (viewer->core->getDoc()) {
- XPDFViewer::findFindCbk(None, viewer, NULL);
- }
- break;
- case '\020': // ctrl-P
- if (viewer->core->getDoc()) {
- XtManageChild(viewer->printDialog);
- }
- break;
- case 'N':
- case 'n':
- viewer->core->gotoNextPage(1, !(modifiers & Mod5Mask));
- break;
- case 'P':
- case 'p':
- viewer->core->gotoPrevPage(1, !(modifiers & Mod5Mask), gFalse);
- break;
- case ' ':
- if (viewer->app->getFullScreen()) {
- viewer->core->gotoNextPage(1, gTrue);
- } else {
- viewer->core->scrollPageDown();
- }
- break;
- case '\b': // bs
- case '\177': // del
- if (viewer->app->getFullScreen()) {
- viewer->core->gotoPrevPage(1, gTrue, gFalse);
- } else {
- viewer->core->scrollPageUp();
- }
- break;
- case 'v':
- viewer->core->goForward();
- break;
- case 'b':
- viewer->core->goBackward();
- break;
- case 'g':
- if (!viewer->app->getFullScreen()) {
- XmTextFieldSetSelection(
- viewer->pageNumText, 0,
- strlen(XmTextFieldGetString(viewer->pageNumText)),
- XtLastTimestampProcessed(viewer->display));
- XmProcessTraversal(viewer->pageNumText, XmTRAVERSE_CURRENT);
- }
- break;
- case 'h': // vi-style left
- if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
- viewer->core->scrollLeft();
- }
- break;
- case 'l': // vi-style right
- if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
- viewer->core->scrollRight();
- }
- break;
- case 'k': // vi-style up
- if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
- viewer->core->scrollUp();
- }
- break;
- case 'j': // vi-style down
- if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
- viewer->core->scrollDown();
- }
- break;
- case '0':
- if (!viewer->app->getFullScreen() &&
- viewer->core->getZoom() != defZoom) {
- XtVaSetValues(viewer->zoomMenu,
- XmNmenuHistory, viewer->getZoomMenuBtn(defZoom),
- NULL);
- viewer->displayPage(viewer->core->getPageNum(), defZoom,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- break;
- case '+':
- if (!viewer->app->getFullScreen() &&
- viewer->core->getZoom() >= minZoom &&
- viewer->core->getZoom() < maxZoom) {
- z = viewer->core->getZoom() + 1;
- XtVaSetValues(viewer->zoomMenu,
- XmNmenuHistory, viewer->getZoomMenuBtn(z),
- NULL);
- viewer->displayPage(viewer->core->getPageNum(), z,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- break;
- case '-':
- if (!viewer->app->getFullScreen() &&
- viewer->core->getZoom() > minZoom &&
- viewer->core->getZoom() <= maxZoom) {
- z = viewer->core->getZoom() - 1;
- XtVaSetValues(viewer->zoomMenu,
- XmNmenuHistory, viewer->getZoomMenuBtn(z),
- NULL);
- viewer->displayPage(viewer->core->getPageNum(), z,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- break;
- case 'z':
- if (!viewer->app->getFullScreen() &&
- viewer->core->getZoom() != zoomPage) {
- XtVaSetValues(viewer->zoomMenu,
- XmNmenuHistory, viewer->getZoomMenuBtn(zoomPage),
- NULL);
- viewer->displayPage(viewer->core->getPageNum(), zoomPage,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- break;
- case 'w':
- if (!viewer->app->getFullScreen() &&
- viewer->core->getZoom() != zoomWidth) {
- XtVaSetValues(viewer->zoomMenu,
- XmNmenuHistory, viewer->getZoomMenuBtn(zoomWidth),
- NULL);
- viewer->displayPage(viewer->core->getPageNum(), zoomWidth,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- break;
- case '\014': // ^L
- viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
- viewer->core->getRotate(), gFalse, gFalse);
- break;
- case '\027': // ^W
- viewer->app->close(viewer, gFalse);
- break;
- case '?':
- XtManageChild(viewer->aboutDialog);
- break;
- case 'Q':
- case 'q':
- viewer->app->quit();
- break;
- }
- }
-}
-
-void XPDFViewer::mouseCbk(void *data, XEvent *event) {
- XPDFViewer *viewer = (XPDFViewer *)data;
-
- if (event->type == ButtonPress && event->xbutton.button == 3) {
- XmMenuPosition(viewer->popupMenu, &event->xbutton);
- XtManageChild(viewer->popupMenu);
- }
-}
-
-//------------------------------------------------------------------------
-// GUI code: main window
-//------------------------------------------------------------------------
-
-void XPDFViewer::initWindow() {
- Widget btn, label, menuPane, lastBtn;
-#ifndef DISABLE_OUTLINE
- Widget clipWin;
-#endif
- Colormap colormap;
- XColor xcol;
- Arg args[20];
- int n;
- char *title;
- XmString s, s2, emptyString;
- char buf[16];
- int i;
-
- display = XtDisplay(app->getAppShell());
- screenNum = XScreenNumberOfScreen(XtScreen(app->getAppShell()));
-
- // private colormap
- if (app->getInstallCmap()) {
- XtVaGetValues(app->getAppShell(), XmNcolormap, &colormap, NULL);
- // ensure that BlackPixel and WhitePixel are reserved in the
- // new colormap
- xcol.red = xcol.green = xcol.blue = 0;
- XAllocColor(display, colormap, &xcol);
- xcol.red = xcol.green = xcol.blue = 65535;
- XAllocColor(display, colormap, &xcol);
- colormap = XCopyColormapAndFree(display, colormap);
- }
-
- // top-level window
- n = 0;
- title = app->getTitle() ? app->getTitle()->getCString()
- : (char *)xpdfAppName;
- XtSetArg(args[n], XmNtitle, title); ++n;
- XtSetArg(args[n], XmNiconName, title); ++n;
- XtSetArg(args[n], XmNminWidth, 100); ++n;
- XtSetArg(args[n], XmNminHeight, 100); ++n;
- XtSetArg(args[n], XmNbaseWidth, 0); ++n;
- XtSetArg(args[n], XmNbaseHeight, 0); ++n;
- XtSetArg(args[n], XmNdeleteResponse, XmDO_NOTHING); ++n;
- if (app->getFullScreen()) {
- XtSetArg(args[n], XmNmwmDecorations, 0); ++n;
- XtSetArg(args[n], XmNgeometry, "+0+0"); ++n;
- } else if (app->getGeometry()) {
- XtSetArg(args[n], XmNgeometry, app->getGeometry()->getCString()); ++n;
- }
- win = XtCreatePopupShell("win", topLevelShellWidgetClass,
- app->getAppShell(), args, n);
- if (app->getInstallCmap()) {
- XtVaSetValues(win, XmNcolormap, colormap, NULL);
- }
- XmAddWMProtocolCallback(win, XInternAtom(display, "WM_DELETE_WINDOW", False),
- &closeMsgCbk, this);
-
- // form
- n = 0;
- form = XmCreateForm(win, "form", args, n);
- XtManageChild(form);
-
- // toolbar
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- toolBar = XmCreateForm(form, "toolBar", args, n);
- XtManageChild(toolBar);
-
- // create an empty string -- this is used for buttons that will get
- // pixmaps later
- emptyString = XmStringCreateLocalized("");
-
- // page movement buttons
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- backBtn = XmCreatePushButton(toolBar, "back", args, n);
- XtManageChild(backBtn);
- XtAddCallback(backBtn, XmNactivateCallback,
- &backCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, backBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- prevTenPageBtn = XmCreatePushButton(toolBar, "prevTenPage", args, n);
- XtManageChild(prevTenPageBtn);
- XtAddCallback(prevTenPageBtn, XmNactivateCallback,
- &prevTenPageCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, prevTenPageBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- prevPageBtn = XmCreatePushButton(toolBar, "prevPage", args, n);
- XtManageChild(prevPageBtn);
- XtAddCallback(prevPageBtn, XmNactivateCallback,
- &prevPageCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, prevPageBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- nextPageBtn = XmCreatePushButton(toolBar, "nextPage", args, n);
- XtManageChild(nextPageBtn);
- XtAddCallback(nextPageBtn, XmNactivateCallback,
- &nextPageCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, nextPageBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- nextTenPageBtn = XmCreatePushButton(toolBar, "nextTenPage", args, n);
- XtManageChild(nextTenPageBtn);
- XtAddCallback(nextTenPageBtn, XmNactivateCallback,
- &nextTenPageCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, nextTenPageBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- forwardBtn = XmCreatePushButton(toolBar, "forward", args, n);
- XtManageChild(forwardBtn);
- XtAddCallback(forwardBtn, XmNactivateCallback,
- &forwardCbk, (XtPointer)this);
-
- // page number display
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, forwardBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- s = XmStringCreateLocalized("Page ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- label = XmCreateLabel(toolBar, "pageLabel", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, label); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 3); ++n;
- XtSetArg(args[n], XmNmarginHeight, 3); ++n;
- XtSetArg(args[n], XmNcolumns, 5); ++n;
- pageNumText = XmCreateTextField(toolBar, "pageNum", args, n);
- XtManageChild(pageNumText);
- XtAddCallback(pageNumText, XmNactivateCallback,
- &pageNumCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, pageNumText); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- s = XmStringCreateLocalized(" of 00000");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNalignment, XmALIGNMENT_BEGINNING); ++n;
- XtSetArg(args[n], XmNrecomputeSize, False); ++n;
- pageCountLabel = XmCreateLabel(toolBar, "pageCountLabel", args, n);
- XmStringFree(s);
- XtManageChild(pageCountLabel);
- s = XmStringCreateLocalized(" of 0");
- XtVaSetValues(pageCountLabel, XmNlabelString, s, NULL);
- XmStringFree(s);
-
- // zoom menu
- n = 0;
- menuPane = XmCreatePulldownMenu(toolBar, "zoomMenuPane", args, n);
- for (i = minZoom; i <= maxZoom; ++i) {
- n = 0;
- sprintf(buf, "%s%d", i > 0 ? "+" : "", i);
- s = XmStringCreateLocalized(buf);
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNuserData, (XtPointer)i); ++n;
- sprintf(buf, "zoom%s%d", i < 0 ? "M" : "", i < 0 ? -i : i);
- btn = XmCreatePushButton(menuPane, buf, args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &zoomMenuCbk, (XtPointer)this);
- zoomMenuBtns[i - minZoom] = btn;
- }
- n = 0;
- s = XmStringCreateLocalized("fit page");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNuserData, (XtPointer)zoomPage); ++n;
- btn = XmCreatePushButton(menuPane, "zoomPage", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &zoomMenuCbk, (XtPointer)this);
- zoomMenuBtns[maxZoom - minZoom + 1] = btn;
- n = 0;
- s = XmStringCreateLocalized("fit width");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNuserData, (XtPointer)zoomWidth); ++n;
- btn = XmCreatePushButton(menuPane, "zoomWidth", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &zoomMenuCbk, (XtPointer)this);
- zoomMenuBtns[maxZoom - minZoom + 2] = btn;
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, pageCountLabel); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 0); ++n;
- XtSetArg(args[n], XmNmarginHeight, 0); ++n;
- XtSetArg(args[n], XmNsubMenuId, menuPane); ++n;
- zoomMenu = XmCreateOptionMenu(toolBar, "zoomMenu", args, n);
- XtManageChild(zoomMenu);
-
- // find/print/about buttons
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, zoomMenu); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- findBtn = XmCreatePushButton(toolBar, "find", args, n);
- XtManageChild(findBtn);
- XtAddCallback(findBtn, XmNactivateCallback,
- &findCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, findBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- printBtn = XmCreatePushButton(toolBar, "print", args, n);
- XtManageChild(printBtn);
- XtAddCallback(printBtn, XmNactivateCallback,
- &printCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, printBtn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- XtSetArg(args[n], XmNlabelString, emptyString); ++n;
- aboutBtn = XmCreatePushButton(toolBar, "about", args, n);
- XtManageChild(aboutBtn);
- XtAddCallback(aboutBtn, XmNactivateCallback,
- &aboutCbk, (XtPointer)this);
- lastBtn = aboutBtn;
-
- // quit button
- n = 0;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNmarginWidth, 6); ++n;
- s = XmStringCreateLocalized("Quit");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- quitBtn = XmCreatePushButton(toolBar, "quit", args, n);
- XmStringFree(s);
- XtManageChild(quitBtn);
- XtAddCallback(quitBtn, XmNactivateCallback,
- &quitCbk, (XtPointer)this);
-
- // link label
- n = 0;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNleftWidget, lastBtn); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightWidget, btn); ++n;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- s = XmStringCreateLocalized("");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNrecomputeSize, True); ++n;
- XtSetArg(args[n], XmNalignment, XmALIGNMENT_BEGINNING); ++n;
- linkLabel = XmCreateLabel(toolBar, "linkLabel", args, n);
- XmStringFree(s);
- XtManageChild(linkLabel);
-
-#ifndef DISABLE_OUTLINE
- if (app->getFullScreen()) {
-#endif
-
- // core
- core = new XPDFCore(win, form, app->getPaperColor(),
- app->getFullScreen(), app->getReverseVideo(),
- app->getInstallCmap(), app->getRGBCubeSize());
- core->setUpdateCbk(&updateCbk, this);
- core->setActionCbk(&actionCbk, this);
- core->setKeyPressCbk(&keyPressCbk, this);
- core->setMouseCbk(&mouseCbk, this);
- core->setReqPasswordCbk(&reqPasswordCbk, this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNbottomWidget, toolBar); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetValues(core->getWidget(), args, n);
-
-#ifndef DISABLE_OUTLINE
- } else {
-
- // paned window
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNbottomWidget, toolBar); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- panedWin = XmCreatePanedWindow(form, "panedWin", args, n);
- XtManageChild(panedWin);
-
- // scrolled window for outline container
- n = 0;
- XtSetArg(args[n], XmNpositionIndex, 0); ++n;
- XtSetArg(args[n], XmNallowResize, True); ++n;
- XtSetArg(args[n], XmNpaneMinimum, 1); ++n;
- XtSetArg(args[n], XmNpaneMaximum, 10000); ++n;
- XtSetArg(args[n], XmNwidth, 1); ++n;
- XtSetArg(args[n], XmNscrollingPolicy, XmAUTOMATIC); ++n;
- outlineScroll = XmCreateScrolledWindow(panedWin, "outlineScroll", args, n);
- XtManageChild(outlineScroll);
- XtVaGetValues(outlineScroll, XmNclipWindow, &clipWin, NULL);
- XtVaSetValues(clipWin, XmNbackground, app->getPaperColor(), NULL);
-
- // outline tree
- n = 0;
- XtSetArg(args[n], XmNbackground, app->getPaperColor()); ++n;
- outlineTree = XPDFCreateTree(outlineScroll, "outlineTree", args, n);
- XtManageChild(outlineTree);
- XtAddCallback(outlineTree, XPDFNselectionCallback, &outlineSelectCbk,
- (XtPointer)this);
-
- // core
- core = new XPDFCore(win, panedWin, app->getPaperColor(),
- app->getFullScreen(), app->getReverseVideo(),
- app->getInstallCmap(), app->getRGBCubeSize());
- core->setUpdateCbk(&updateCbk, this);
- core->setActionCbk(&actionCbk, this);
- core->setKeyPressCbk(&keyPressCbk, this);
- core->setMouseCbk(&mouseCbk, this);
- core->setReqPasswordCbk(&reqPasswordCbk, this);
- n = 0;
- XtSetArg(args[n], XmNpositionIndex, 1); ++n;
- XtSetArg(args[n], XmNallowResize, True); ++n;
- XtSetArg(args[n], XmNpaneMinimum, 1); ++n;
- XtSetArg(args[n], XmNpaneMaximum, 10000); ++n;
- XtSetValues(core->getWidget(), args, n);
- }
-#endif
-
- // set the zoom menu to match the initial zoom setting
- XtVaSetValues(zoomMenu, XmNmenuHistory,
- getZoomMenuBtn(core->getZoom()), NULL);
-
- // set traversal order
- XtVaSetValues(core->getDrawAreaWidget(),
- XmNnavigationType, XmEXCLUSIVE_TAB_GROUP, NULL);
- XtVaSetValues(backBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(prevTenPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(prevPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(nextPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(nextTenPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(forwardBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(pageNumText, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(zoomMenu, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(findBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(printBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(aboutBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
- XtVaSetValues(quitBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
- NULL);
-
- // popup menu
- n = 0;
- XtSetArg(args[n], XmNmenuPost, "<Btn3Down>"); ++n;
- popupMenu = XmCreatePopupMenu(core->getDrawAreaWidget(), "popupMenu",
- args, n);
- n = 0;
- s = XmStringCreateLocalized("Open...");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- s2 = XmStringCreateLocalized("O");
- XtSetArg(args[n], XmNacceleratorText, s2); ++n;
- btn = XmCreatePushButton(popupMenu, "open", args, n);
- XmStringFree(s);
- XmStringFree(s2);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &openCbk, (XtPointer)this);
- n = 0;
- s = XmStringCreateLocalized("Open in new window...");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- btn = XmCreatePushButton(popupMenu, "openInNewWindow", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &openInNewWindowCbk, (XtPointer)this);
- n = 0;
- s = XmStringCreateLocalized("Reload");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- s2 = XmStringCreateLocalized("R");
- XtSetArg(args[n], XmNacceleratorText, s2); ++n;
- btn = XmCreatePushButton(popupMenu, "reload", args, n);
- XmStringFree(s);
- XmStringFree(s2);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &reloadCbk, (XtPointer)this);
- n = 0;
- s = XmStringCreateLocalized("Save as...");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- btn = XmCreatePushButton(popupMenu, "saveAs", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &saveAsCbk, (XtPointer)this);
- n = 0;
- btn = XmCreateSeparator(popupMenu, "sep1", args, n);
- XtManageChild(btn);
- n = 0;
- s = XmStringCreateLocalized("Rotate counterclockwise");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- btn = XmCreatePushButton(popupMenu, "rotateCCW", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &rotateCCWCbk, (XtPointer)this);
- n = 0;
- s = XmStringCreateLocalized("Rotate clockwise");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- btn = XmCreatePushButton(popupMenu, "rotateCW", args, n);
- XmStringFree(s);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &rotateCWCbk, (XtPointer)this);
- n = 0;
- btn = XmCreateSeparator(popupMenu, "sep2", args, n);
- XtManageChild(btn);
- n = 0;
- s = XmStringCreateLocalized("Close");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- s2 = XmStringCreateLocalized("Ctrl+W");
- XtSetArg(args[n], XmNacceleratorText, s2); ++n;
- btn = XmCreatePushButton(popupMenu, "close", args, n);
- XmStringFree(s);
- XmStringFree(s2);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &closeCbk, (XtPointer)this);
- n = 0;
- s = XmStringCreateLocalized("Quit");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- s2 = XmStringCreateLocalized("Q");
- XtSetArg(args[n], XmNacceleratorText, s2); ++n;
- btn = XmCreatePushButton(popupMenu, "quit", args, n);
- XmStringFree(s);
- XmStringFree(s2);
- XtManageChild(btn);
- XtAddCallback(btn, XmNactivateCallback,
- &quitCbk, (XtPointer)this);
-
- XmStringFree(emptyString);
-}
-
-void XPDFViewer::mapWindow() {
-#ifdef HAVE_X11_XPM_H
- Pixmap iconPixmap;
-#endif
- int depth;
- Pixel bg, arm;
-
- // show the window
- XtPopup(win, XtGrabNone);
- core->takeFocus();
-
- // create the icon
-#ifdef HAVE_X11_XPM_H
- if (XpmCreatePixmapFromData(display, XtWindow(win), xpdfIcon,
- &iconPixmap, NULL, NULL) == XpmSuccess) {
- XtVaSetValues(win, XmNiconPixmap, iconPixmap, NULL);
- }
-#endif
-
- // set button bitmaps (must be done after the window is mapped)
- XtVaGetValues(backBtn, XmNdepth, &depth,
- XmNbackground, &bg, XmNarmColor, &arm, NULL);
- XtVaSetValues(backBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)backArrow_bits,
- backArrow_width,
- backArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)backArrow_bits,
- backArrow_width,
- backArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)backArrowDis_bits,
- backArrowDis_width,
- backArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(prevTenPageBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblLeftArrow_bits,
- dblLeftArrow_width,
- dblLeftArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblLeftArrow_bits,
- dblLeftArrow_width,
- dblLeftArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblLeftArrowDis_bits,
- dblLeftArrowDis_width,
- dblLeftArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(prevPageBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)leftArrow_bits,
- leftArrow_width,
- leftArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)leftArrow_bits,
- leftArrow_width,
- leftArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)leftArrowDis_bits,
- leftArrowDis_width,
- leftArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(nextPageBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)rightArrow_bits,
- rightArrow_width,
- rightArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)rightArrow_bits,
- rightArrow_width,
- rightArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)rightArrowDis_bits,
- rightArrowDis_width,
- rightArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(nextTenPageBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblRightArrow_bits,
- dblRightArrow_width,
- dblRightArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblRightArrow_bits,
- dblRightArrow_width,
- dblRightArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)dblRightArrowDis_bits,
- dblRightArrowDis_width,
- dblRightArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(forwardBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)forwardArrow_bits,
- forwardArrow_width,
- forwardArrow_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)forwardArrow_bits,
- forwardArrow_width,
- forwardArrow_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)forwardArrowDis_bits,
- forwardArrowDis_width,
- forwardArrowDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(findBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)find_bits,
- find_width,
- find_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)find_bits,
- find_width,
- find_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)findDis_bits,
- findDis_width,
- findDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(printBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)print_bits,
- print_width,
- print_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)print_bits,
- print_width,
- print_height,
- BlackPixel(display, screenNum),
- arm, depth),
- XmNlabelInsensitivePixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)printDis_bits,
- printDis_width,
- printDis_height,
- BlackPixel(display, screenNum),
- bg, depth),
- NULL);
- XtVaSetValues(aboutBtn, XmNlabelType, XmPIXMAP,
- XmNlabelPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)about_bits,
- about_width,
- about_height,
- BlackPixel(display, screenNum),
- bg, depth),
- XmNarmPixmap,
- XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
- (char *)about_bits,
- about_width,
- about_height,
- BlackPixel(display, screenNum),
- arm, depth),
- NULL);
-}
-
-void XPDFViewer::closeWindow() {
- XtPopdown(win);
- XtDestroyWidget(win);
-}
-
-Widget XPDFViewer::getZoomMenuBtn(int z) {
- if (z >= minZoom && z <= maxZoom) {
- return zoomMenuBtns[z - minZoom];
- }
- if (z == zoomPage) {
- return zoomMenuBtns[maxZoom - minZoom + 1];
- }
- if (z == zoomWidth) {
- return zoomMenuBtns[maxZoom - minZoom + 2];
- }
- return zoomMenuBtns[0];
-}
-
-void XPDFViewer::prevPageCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->gotoPrevPage(1, gTrue, gFalse);
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::prevTenPageCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->gotoPrevPage(10, gTrue, gFalse);
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::nextPageCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->gotoNextPage(1, gTrue);
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::nextTenPageCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->gotoNextPage(10, gTrue);
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::backCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->goBackward();
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::forwardCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->goForward();
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::zoomMenuCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XtPointer userData;
-
- XtVaGetValues(widget, XmNuserData, &userData, NULL);
- if ((int)userData != viewer->core->getZoom()) {
- viewer->displayPage(viewer->core->getPageNum(), (int)userData,
- viewer->core->getRotate(), gTrue, gFalse);
- }
- viewer->core->takeFocus();
-}
-
-void XPDFViewer::findCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- if (!viewer->core->getDoc()) {
- return;
- }
- XtManageChild(viewer->findDialog);
-}
-
-void XPDFViewer::printCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- if (!viewer->core->getDoc()) {
- return;
- }
- XtManageChild(viewer->printDialog);
-}
-
-void XPDFViewer::aboutCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- XtManageChild(viewer->aboutDialog);
-}
-
-void XPDFViewer::quitCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->app->quit();
-}
-
-void XPDFViewer::openCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->mapOpenDialog(gFalse);
-}
-
-void XPDFViewer::openInNewWindowCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->mapOpenDialog(gTrue);
-}
-
-void XPDFViewer::reloadCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->reloadFile();
-}
-
-void XPDFViewer::saveAsCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- if (!viewer->core->getDoc()) {
- return;
- }
- viewer->mapSaveAsDialog();
-}
-
-void XPDFViewer::rotateCCWCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- int r;
-
- r = viewer->core->getRotate();
- r = (r == 0) ? 270 : r - 90;
- viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
- r, gTrue, gFalse);
-}
-
-void XPDFViewer::rotateCWCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- int r;
-
- r = viewer->core->getRotate();
- r = (r == 270) ? 0 : r + 90;
- viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
- r, gTrue, gFalse);
-}
-
-void XPDFViewer::closeCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->app->close(viewer, gFalse);
-}
-
-void XPDFViewer::closeMsgCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->app->close(viewer, gTrue);
-}
-
-void XPDFViewer::pageNumCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- char *s, *p;
- int pg;
- char buf[20];
-
- if (!viewer->core->getDoc()) {
- goto err;
- }
- s = XmTextFieldGetString(viewer->pageNumText);
- for (p = s; *p; ++p) {
- if (!isdigit(*p)) {
- goto err;
- }
- }
- pg = atoi(s);
- if (pg < 1 || pg > viewer->core->getDoc()->getNumPages()) {
- goto err;
- }
- viewer->displayPage(pg, viewer->core->getZoom(),
- viewer->core->getRotate(), gFalse, gTrue);
- viewer->core->takeFocus();
- return;
-
- err:
- XBell(viewer->display, 0);
- sprintf(buf, "%d", viewer->core->getPageNum());
- XmTextFieldSetString(viewer->pageNumText, buf);
-}
-
-void XPDFViewer::updateCbk(void *data, GString *fileName,
- int pageNum, int numPages, char *linkLabel) {
- XPDFViewer *viewer = (XPDFViewer *)data;
- GString *title;
- char buf[20];
- XmString s;
-
- if (fileName) {
- if (!(title = viewer->app->getTitle())) {
- title = (new GString(xpdfAppName))->append(": ")->append(fileName);
- }
- XtVaSetValues(viewer->win, XmNtitle, title->getCString(),
- XmNiconName, title->getCString(), NULL);
- if (!viewer->app->getTitle()) {
- delete title;
- }
-#ifndef DISABLE_OUTLINE
- if (!viewer->app->getFullScreen()) {
- viewer->setupOutline();
- }
-#endif
- viewer->setupPrintDialog();
- }
-
- if (pageNum >= 0) {
- s = XmStringCreateLocalized("");
- XtVaSetValues(viewer->linkLabel, XmNlabelString, s, NULL);
- XmStringFree(s);
- sprintf(buf, "%d", pageNum);
- XmTextFieldSetString(viewer->pageNumText, buf);
- XtVaSetValues(viewer->prevTenPageBtn, XmNsensitive,
- pageNum > 1, NULL);
- XtVaSetValues(viewer->prevPageBtn, XmNsensitive,
- pageNum > 1, NULL);
- XtVaSetValues(viewer->nextTenPageBtn, XmNsensitive,
- pageNum < viewer->core->getDoc()->getNumPages(), NULL);
- XtVaSetValues(viewer->nextPageBtn, XmNsensitive,
- pageNum < viewer->core->getDoc()->getNumPages(), NULL);
- XtVaSetValues(viewer->backBtn, XmNsensitive,
- viewer->core->canGoBack(), NULL);
- XtVaSetValues(viewer->forwardBtn, XmNsensitive,
- viewer->core->canGoForward(), NULL);
- }
-
- if (numPages >= 0) {
- sprintf(buf, " of %d", numPages);
- s = XmStringCreateLocalized(buf);
- XtVaSetValues(viewer->pageCountLabel, XmNlabelString, s, NULL);
- XmStringFree(s);
- }
-
- if (linkLabel) {
- s = XmStringCreateLocalized(linkLabel);
- XtVaSetValues(viewer->linkLabel, XmNlabelString, s, NULL);
- XmStringFree(s);
- }
-}
-
-
-//------------------------------------------------------------------------
-// GUI code: outline
-//------------------------------------------------------------------------
-
-#ifndef DISABLE_OUTLINE
-
-void XPDFViewer::setupOutline() {
- GList *items;
- UnicodeMap *uMap;
- GString *enc;
- int i;
-
- // unmanage and destroy the old labels
- if (outlineLabels) {
- XtUnmanageChildren(outlineLabels, outlineLabelsLength);
- for (i = 0; i < outlineLabelsLength; ++i) {
- XtDestroyWidget(outlineLabels[i]);
- }
- gfree(outlineLabels);
- outlineLabels = NULL;
- outlineLabelsLength = outlineLabelsSize = 0;
- }
-
- // create the new labels
- items = core->getDoc()->getOutline()->getItems();
- if (items && items->getLength() > 0) {
- enc = new GString("Latin1");
- uMap = globalParams->getUnicodeMap(enc);
- delete enc;
- setupOutlineItems(items, NULL, uMap);
- uMap->decRefCnt();
- }
-
- // manage the new labels
- XtManageChildren(outlineLabels, outlineLabelsLength);
-}
-
-void XPDFViewer::setupOutlineItems(GList *items, Widget parent,
- UnicodeMap *uMap) {
- OutlineItem *item;
- GList *kids;
- Widget label;
- Arg args[20];
- GString *title;
- char buf[8];
- XmString s;
- int i, j, n;
-
- for (i = 0; i < items->getLength(); ++i) {
- item = (OutlineItem *)items->get(i);
- title = new GString();
- for (j = 0; j < item->getTitleLength(); ++j) {
- n = uMap->mapUnicode(item->getTitle()[j], buf, sizeof(buf));
- title->append(buf, n);
- }
- n = 0;
- XtSetArg(args[n], XPDFNentryPosition, i); ++n;
- if (parent) {
- XtSetArg(args[n], XPDFNentryParent, parent); ++n;
- }
- XtSetArg(args[n], XPDFNentryExpanded, item->isOpen()); ++n;
- s = XmStringCreateLocalized(title->getCString());
- delete title;
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNuserData, item); ++n;
- XtSetArg(args[n], XmNmarginWidth, 0); ++n;
- XtSetArg(args[n], XmNmarginHeight, 2); ++n;
- XtSetArg(args[n], XmNshadowThickness, 0); ++n;
- XtSetArg(args[n], XmNforeground,
- app->getReverseVideo() ? WhitePixel(display, screenNum)
- : BlackPixel(display, screenNum)); ++n;
- XtSetArg(args[n], XmNbackground, app->getPaperColor()); ++n;
- label = XmCreateLabelGadget(outlineTree, "label", args, n);
- XmStringFree(s);
- if (outlineLabelsLength == outlineLabelsSize) {
- outlineLabelsSize += 64;
- outlineLabels = (Widget *)grealloc(outlineLabels,
- outlineLabelsSize * sizeof(Widget *));
- }
- outlineLabels[outlineLabelsLength++] = label;
- item->open();
- if ((kids = item->getKids())) {
- setupOutlineItems(kids, label, uMap);
- }
- }
-}
-
-void XPDFViewer::outlineSelectCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XPDFTreeSelectCallbackStruct *data =
- (XPDFTreeSelectCallbackStruct *)callData;
- OutlineItem *item;
-
- XtVaGetValues(data->selectedItem, XmNuserData, &item, NULL);
- if (item) {
- viewer->core->doAction(item->getAction());
- }
- viewer->core->takeFocus();
-}
-
-#endif // !DISABLE_OUTLINE
-
-//------------------------------------------------------------------------
-// GUI code: "about" dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initAboutDialog() {
- Widget scrolledWin, col, label, sep, closeBtn;
- Arg args[20];
- int n, i;
- XmString s;
- char buf[20];
-
- //----- dialog
- n = 0;
- s = XmStringCreateLocalized(xpdfAppName ": About");
- XtSetArg(args[n], XmNdialogTitle, s); ++n;
- XtSetArg(args[n], XmNwidth, 450); ++n;
- XtSetArg(args[n], XmNheight, 300); ++n;
- aboutDialog = XmCreateFormDialog(win, "aboutDialog", args, n);
- XmStringFree(s);
-
- //----- "close" button
- n = 0;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- closeBtn = XmCreatePushButton(aboutDialog, "Close", args, n);
- XtManageChild(closeBtn);
- n = 0;
- XtSetArg(args[n], XmNdefaultButton, closeBtn); ++n;
- XtSetArg(args[n], XmNcancelButton, closeBtn); ++n;
- XtSetValues(aboutDialog, args, n);
-
- //----- scrolled window and RowColumn
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNbottomWidget, closeBtn); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNscrollingPolicy, XmAUTOMATIC); ++n;
- scrolledWin = XmCreateScrolledWindow(aboutDialog, "scrolledWin", args, n);
- XtManageChild(scrolledWin);
- n = 0;
- XtSetArg(args[n], XmNorientation, XmVERTICAL); ++n;
- XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
- col = XmCreateRowColumn(scrolledWin, "col", args, n);
- XtManageChild(col);
-
- //----- fonts
- aboutBigFont = XmFontListAppendEntry(NULL,
- XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
- XLoadQueryFont(display,
- "-*-times-bold-i-normal--20-*-*-*-*-*-iso8859-1")));
- aboutVersionFont = XmFontListAppendEntry(NULL,
- XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
- XLoadQueryFont(display,
- "-*-times-medium-r-normal--16-*-*-*-*-*-iso8859-1")));
- aboutFixedFont = XmFontListAppendEntry(NULL,
- XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
- XLoadQueryFont(display,
- "-*-courier-medium-r-normal--12-*-*-*-*-*-iso8859-1")));
-
- //----- heading
- n = 0;
- s = XmStringCreateLocalized("Xpdf");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutBigFont); ++n;
- label = XmCreateLabel(col, "h0", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- s = XmStringCreateLocalized("Version " xpdfVersion);
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
- label = XmCreateLabel(col, "h1", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- s = XmStringCreateLocalized(xpdfCopyright);
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
- label = XmCreateLabel(col, "h2", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- s = XmStringCreateLocalized(" ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
- label = XmCreateLabel(col, "h3", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- sep = XmCreateSeparator(col, "sep", args, n);
- XtManageChild(sep);
- n = 0;
- s = XmStringCreateLocalized(" ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
- label = XmCreateLabel(col, "h4", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
-
- //----- text
- for (i = 0; aboutWinText[i]; ++i) {
- n = 0;
- s = XmStringCreateLocalized(aboutWinText[i]);
- XtSetArg(args[n], XmNlabelString, s); ++n;
- XtSetArg(args[n], XmNfontList, aboutFixedFont); ++n;
- sprintf(buf, "t%d", i);
- label = XmCreateLabel(col, buf, args, n);
- XtManageChild(label);
- XmStringFree(s);
- }
-}
-
-//------------------------------------------------------------------------
-// GUI code: "open" dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initOpenDialog() {
- Arg args[20];
- int n;
- XmString s1, s2, s3;
-
- n = 0;
- s1 = XmStringCreateLocalized("Open");
- XtSetArg(args[n], XmNokLabelString, s1); ++n;
- s2 = XmStringCreateLocalized("*.[Pp][Dd][Ff]");
- XtSetArg(args[n], XmNpattern, s2); ++n;
- s3 = XmStringCreateLocalized(xpdfAppName ": Open");
- XtSetArg(args[n], XmNdialogTitle, s3); ++n;
- XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
- XtSetArg(args[n], XmNautoUnmanage, True); ++n;
- openDialog = XmCreateFileSelectionDialog(win, "openDialog", args, n);
- XmStringFree(s1);
- XmStringFree(s2);
- XmStringFree(s3);
- XtUnmanageChild(XmFileSelectionBoxGetChild(openDialog,
- XmDIALOG_HELP_BUTTON));
- XtAddCallback(openDialog, XmNokCallback,
- &openOkCbk, (XtPointer)this);
-}
-
-void XPDFViewer::setOpenDialogDir(char *dir) {
- XmString s;
-
- s = XmStringCreateLocalized(dir);
- XtVaSetValues(openDialog, XmNdirectory, s, NULL);
- XmStringFree(s);
-}
-
-void XPDFViewer::mapOpenDialog(GBool openInNewWindowA) {
- openInNewWindow = openInNewWindowA;
- XmFileSelectionDoSearch(openDialog, NULL);
- XtManageChild(openDialog);
-}
-
-void XPDFViewer::openOkCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XmFileSelectionBoxCallbackStruct *data =
- (XmFileSelectionBoxCallbackStruct *)callData;
- char *fileName;
- XmStringContext context;
- XmStringCharSet charSet;
- XmStringDirection dir;
- Boolean sep;
- GString *fileNameStr;
-
- XmStringInitContext(&context, data->value);
- if (XmStringGetNextSegment(context, &fileName, &charSet, &dir, &sep)) {
- fileNameStr = new GString(fileName);
- if (viewer->openInNewWindow) {
- viewer->app->open(fileNameStr);
- } else {
- if (viewer->loadFile(fileNameStr)) {
- viewer->displayPage(1, viewer->core->getZoom(),
- viewer->core->getRotate(), gTrue, gTrue);
- }
- }
- delete fileNameStr;
- XtFree(charSet);
- XtFree(fileName);
- }
- XmStringFreeContext(context);
-}
-
-//------------------------------------------------------------------------
-// GUI code: "find" dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initFindDialog() {
- Widget row1, label, okBtn, closeBtn;
- Arg args[20];
- int n;
- XmString s;
-
- //----- dialog
- n = 0;
- s = XmStringCreateLocalized(xpdfAppName ": Find");
- XtSetArg(args[n], XmNdialogTitle, s); ++n;
- XtSetArg(args[n], XmNnavigationType, XmNONE); ++n;
- XtSetArg(args[n], XmNautoUnmanage, False); ++n;
- findDialog = XmCreateFormDialog(win, "findDialog", args, n);
- XmStringFree(s);
-
- //----- top row: search string entry
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNtopOffset, 4); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
- row1 = XmCreateRowColumn(findDialog, "row1", args, n);
- XtManageChild(row1);
- n = 0;
- s = XmStringCreateLocalized("Find text: ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- label = XmCreateLabel(row1, "label", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
- findText = XmCreateTextField(row1, "text", args, n);
- XtManageChild(findText);
-
- //----- "find" and "close" buttons
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, row1); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
- okBtn = XmCreatePushButton(findDialog, "Find", args, n);
- XtManageChild(okBtn);
- XtAddCallback(okBtn, XmNactivateCallback,
- &findFindCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, row1); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
- closeBtn = XmCreatePushButton(findDialog, "Close", args, n);
- XtManageChild(closeBtn);
- XtAddCallback(closeBtn, XmNactivateCallback,
- &findCloseCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
- XtSetArg(args[n], XmNcancelButton, closeBtn); ++n;
- XtSetArg(args[n], XmNinitialFocus, findText); ++n;
- XtSetValues(findDialog, args, n);
-}
-
-void XPDFViewer::findFindCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->core->find(XmTextFieldGetString(viewer->findText));
-}
-
-void XPDFViewer::findCloseCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- XtUnmanageChild(viewer->findDialog);
-}
-
-//------------------------------------------------------------------------
-// GUI code: "save as" dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initSaveAsDialog() {
- Arg args[20];
- int n;
- XmString s1, s2, s3;
-
- n = 0;
- s1 = XmStringCreateLocalized("Save");
- XtSetArg(args[n], XmNokLabelString, s1); ++n;
- s2 = XmStringCreateLocalized("*.[Pp][Dd][Ff]");
- XtSetArg(args[n], XmNpattern, s2); ++n;
- s3 = XmStringCreateLocalized(xpdfAppName ": Save as");
- XtSetArg(args[n], XmNdialogTitle, s3); ++n;
- XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
- XtSetArg(args[n], XmNautoUnmanage, True); ++n;
- saveAsDialog = XmCreateFileSelectionDialog(win, "saveAsDialog", args, n);
- XmStringFree(s1);
- XmStringFree(s2);
- XmStringFree(s3);
- XtUnmanageChild(XmFileSelectionBoxGetChild(saveAsDialog,
- XmDIALOG_HELP_BUTTON));
- XtAddCallback(saveAsDialog, XmNokCallback,
- &saveAsOkCbk, (XtPointer)this);
-}
-
-void XPDFViewer::setSaveAsDialogDir(char *dir) {
- XmString s;
-
- s = XmStringCreateLocalized(dir);
- XtVaSetValues(saveAsDialog, XmNdirectory, s, NULL);
- XmStringFree(s);
-}
-
-void XPDFViewer::mapSaveAsDialog() {
- XmFileSelectionDoSearch(saveAsDialog, NULL);
- XtManageChild(saveAsDialog);
-}
-
-void XPDFViewer::saveAsOkCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XmFileSelectionBoxCallbackStruct *data =
- (XmFileSelectionBoxCallbackStruct *)callData;
- char *fileName;
- GString *fileNameStr;
- XmStringContext context;
- XmStringCharSet charSet;
- XmStringDirection dir;
- Boolean sep;
-
- XmStringInitContext(&context, data->value);
- if (XmStringGetNextSegment(context, &fileName, &charSet, &dir, &sep)) {
- fileNameStr = new GString(fileName);
- viewer->core->getDoc()->saveAs(fileNameStr);
- delete fileNameStr;
- XtFree(charSet);
- XtFree(fileName);
- }
- XmStringFreeContext(context);
-}
-
-//------------------------------------------------------------------------
-// GUI code: "print" dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initPrintDialog() {
- Widget sep1, sep2, row, label1, label2, okBtn, cancelBtn;
- Arg args[20];
- int n;
- XmString s;
-
- //----- dialog
- n = 0;
- s = XmStringCreateLocalized(xpdfAppName ": Print");
- XtSetArg(args[n], XmNdialogTitle, s); ++n;
- XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
- printDialog = XmCreateFormDialog(win, "printDialog", args, n);
- XmStringFree(s);
-
- //----- "print with command"
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNtopOffset, 4); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNindicatorType, XmONE_OF_MANY); ++n;
- XtSetArg(args[n], XmNset, XmSET); ++n;
- s = XmStringCreateLocalized("Print with command:");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- printWithCmdBtn = XmCreateToggleButton(printDialog, "printWithCmd", args, n);
- XmStringFree(s);
- XtManageChild(printWithCmdBtn);
- XtAddCallback(printWithCmdBtn, XmNvalueChangedCallback,
- &printWithCmdBtnCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, printWithCmdBtn); ++n;
- XtSetArg(args[n], XmNtopOffset, 2); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 16); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNcolumns, 40); ++n;
- printCmdText = XmCreateTextField(printDialog, "printCmd", args, n);
- XtManageChild(printCmdText);
-
- //----- "print with command"
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, printCmdText); ++n;
- XtSetArg(args[n], XmNtopOffset, 4); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNindicatorType, XmONE_OF_MANY); ++n;
- XtSetArg(args[n], XmNset, XmUNSET); ++n;
- s = XmStringCreateLocalized("Print to file:");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- printToFileBtn = XmCreateToggleButton(printDialog, "printToFile", args, n);
- XmStringFree(s);
- XtManageChild(printToFileBtn);
- XtAddCallback(printToFileBtn, XmNvalueChangedCallback,
- &printToFileBtnCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, printToFileBtn); ++n;
- XtSetArg(args[n], XmNtopOffset, 2); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 16); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNcolumns, 40); ++n;
- XtSetArg(args[n], XmNsensitive, False); ++n;
- printFileText = XmCreateTextField(printDialog, "printFile", args, n);
- XtManageChild(printFileText);
-
- //----- separator
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, printFileText); ++n;
- XtSetArg(args[n], XmNtopOffset, 8); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 8); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 8); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- sep1 = XmCreateSeparator(printDialog, "sep1", args, n);
- XtManageChild(sep1);
-
- //----- page range
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, sep1); ++n;
- XtSetArg(args[n], XmNtopOffset, 8); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
- row = XmCreateRowColumn(printDialog, "row", args, n);
- XtManageChild(row);
- n = 0;
- s = XmStringCreateLocalized("Pages:");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- label1 = XmCreateLabel(row, "label1", args, n);
- XmStringFree(s);
- XtManageChild(label1);
- n = 0;
- XtSetArg(args[n], XmNcolumns, 5); ++n;
- printFirstPage = XmCreateTextField(row, "printFirstPage", args, n);
- XtManageChild(printFirstPage);
- n = 0;
- s = XmStringCreateLocalized("to");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- label2 = XmCreateLabel(row, "label2", args, n);
- XmStringFree(s);
- XtManageChild(label2);
- n = 0;
- XtSetArg(args[n], XmNcolumns, 5); ++n;
- printLastPage = XmCreateTextField(row, "printLastPage", args, n);
- XtManageChild(printLastPage);
-
- //----- separator
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, row); ++n;
- XtSetArg(args[n], XmNtopOffset, 8); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 8); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 8); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- sep2 = XmCreateSeparator(printDialog, "sep2", args, n);
- XtManageChild(sep2);
-
- //----- "print" and "cancel" buttons
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, sep2); ++n;
- XtSetArg(args[n], XmNtopOffset, 8); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- okBtn = XmCreatePushButton(printDialog, "Print", args, n);
- XtManageChild(okBtn);
- XtAddCallback(okBtn, XmNactivateCallback,
- &printPrintCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, sep2); ++n;
- XtSetArg(args[n], XmNtopOffset, 8); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- cancelBtn = XmCreatePushButton(printDialog, "Cancel", args, n);
- XtManageChild(cancelBtn);
- n = 0;
- XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
- XtSetArg(args[n], XmNcancelButton, cancelBtn); ++n;
- XtSetValues(printDialog, args, n);
-}
-
-void XPDFViewer::setupPrintDialog() {
- PDFDoc *doc;
- char buf[20];
- GString *pdfFileName, *psFileName;
- char *p;
-
- doc = core->getDoc();
-
- psFileName = globalParams->getPSFile();
- if (psFileName && psFileName->getChar(0) != '|') {
- XmTextFieldSetString(printFileText, psFileName->getCString());
- } else {
- pdfFileName = doc->getFileName();
- p = pdfFileName->getCString() + pdfFileName->getLength() - 4;
- if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
- psFileName = new GString(pdfFileName->getCString(),
- pdfFileName->getLength() - 4);
- } else {
- psFileName = pdfFileName->copy();
- }
- psFileName->append(".ps");
- XmTextFieldSetString(printFileText, psFileName->getCString());
- delete psFileName;
- }
-
- psFileName = globalParams->getPSFile();
- if (psFileName && psFileName->getChar(0) == '|') {
- XmTextFieldSetString(printCmdText,
- psFileName->getCString() + 1);
- }
-
- sprintf(buf, "%d", doc->getNumPages());
- XmTextFieldSetString(printFirstPage, "1");
- XmTextFieldSetString(printLastPage, buf);
-}
-
-void XPDFViewer::printWithCmdBtnCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XmToggleButtonCallbackStruct *data =
- (XmToggleButtonCallbackStruct *)callData;
-
- if (data->set != XmSET) {
- XmToggleButtonSetState(viewer->printWithCmdBtn, True, False);
- }
- XmToggleButtonSetState(viewer->printToFileBtn, False, False);
- XtVaSetValues(viewer->printCmdText, XmNsensitive, True, NULL);
- XtVaSetValues(viewer->printFileText, XmNsensitive, False, NULL);
-}
-
-void XPDFViewer::printToFileBtnCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XmToggleButtonCallbackStruct *data =
- (XmToggleButtonCallbackStruct *)callData;
-
- if (data->set != XmSET) {
- XmToggleButtonSetState(viewer->printToFileBtn, True, False);
- }
- XmToggleButtonSetState(viewer->printWithCmdBtn, False, False);
- XtVaSetValues(viewer->printFileText, XmNsensitive, True, NULL);
- XtVaSetValues(viewer->printCmdText, XmNsensitive, False, NULL);
-}
-
-void XPDFViewer::printPrintCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- unsigned char withCmd;
- GString *psFileName;
- int firstPage, lastPage;
- PDFDoc *doc;
- PSOutputDev *psOut;
-
- doc = viewer->core->getDoc();
- if (!doc->okToPrint()) {
- error(-1, "Printing this document is not allowed.");
- return;
- }
-
- viewer->core->setBusyCursor(gTrue);
-
- XtVaGetValues(viewer->printWithCmdBtn, XmNset, &withCmd, NULL);
- if (withCmd) {
- psFileName = new GString(XmTextFieldGetString(viewer->printCmdText));
- psFileName->insert(0, '|');
- } else {
- psFileName = new GString(XmTextFieldGetString(viewer->printFileText));
- }
-
- firstPage = atoi(XmTextFieldGetString(viewer->printFirstPage));
- lastPage = atoi(XmTextFieldGetString(viewer->printLastPage));
- if (firstPage < 1) {
- firstPage = 1;
- } else if (firstPage > doc->getNumPages()) {
- firstPage = doc->getNumPages();
- }
- if (lastPage < firstPage) {
- lastPage = firstPage;
- } else if (lastPage > doc->getNumPages()) {
- lastPage = doc->getNumPages();
- }
-
- psOut = new PSOutputDev(psFileName->getCString(), doc->getXRef(),
- doc->getCatalog(), firstPage, lastPage,
- psModePS);
- if (psOut->isOk()) {
- doc->displayPages(psOut, firstPage, lastPage, 72, 0, gFalse);
- }
- delete psOut;
- delete psFileName;
-
- viewer->core->setBusyCursor(gFalse);
-}
-
-//------------------------------------------------------------------------
-// GUI code: password dialog
-//------------------------------------------------------------------------
-
-void XPDFViewer::initPasswordDialog() {
- Widget row, label, okBtn, cancelBtn;
- Arg args[20];
- int n;
- XmString s;
-
- //----- dialog
- n = 0;
- s = XmStringCreateLocalized(xpdfAppName ": Password");
- XtSetArg(args[n], XmNdialogTitle, s); ++n;
- XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
- passwordDialog = XmCreateFormDialog(win, "passwordDialog", args, n);
- XmStringFree(s);
-
- //----- message
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNtopOffset, 4); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- s = XmStringCreateLocalized(" ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- passwordMsg = XmCreateLabel(passwordDialog, "msg", args, n);
- XmStringFree(s);
- XtManageChild(passwordMsg);
-
- //----- label and password entry
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, passwordMsg); ++n;
- XtSetArg(args[n], XmNtopOffset, 4); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
- XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
- row = XmCreateRowColumn(passwordDialog, "row", args, n);
- XtManageChild(row);
- n = 0;
- s = XmStringCreateLocalized("Password: ");
- XtSetArg(args[n], XmNlabelString, s); ++n;
- label = XmCreateLabel(row, "label", args, n);
- XmStringFree(s);
- XtManageChild(label);
- n = 0;
- XtSetArg(args[n], XmNcolumns, 16); ++n;
- passwordText = XmCreateTextField(row, "text", args, n);
- XtManageChild(passwordText);
- XtAddCallback(passwordText, XmNmodifyVerifyCallback,
- &passwordTextVerifyCbk, this);
-
- //----- "Ok" and "Cancel" buttons
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, row); ++n;
- XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNleftOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
- okBtn = XmCreatePushButton(passwordDialog, "Ok", args, n);
- XtManageChild(okBtn);
- XtAddCallback(okBtn, XmNactivateCallback,
- &passwordOkCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
- XtSetArg(args[n], XmNtopWidget, row); ++n;
- XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNrightOffset, 4); ++n;
- XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
- XtSetArg(args[n], XmNbottomOffset, 4); ++n;
- XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
- cancelBtn = XmCreatePushButton(passwordDialog, "Cancel", args, n);
- XtManageChild(cancelBtn);
- XtAddCallback(cancelBtn, XmNactivateCallback,
- &passwordCancelCbk, (XtPointer)this);
- n = 0;
- XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
- XtSetArg(args[n], XmNcancelButton, cancelBtn); ++n;
- XtSetArg(args[n], XmNinitialFocus, passwordText); ++n;
- XtSetValues(passwordDialog, args, n);
-}
-
-void XPDFViewer::passwordTextVerifyCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
- XmTextVerifyCallbackStruct *data =
- (XmTextVerifyCallbackStruct *)callData;
- int i, n;
-
- i = (int)data->startPos;
- n = (int)data->endPos - i;
- if (i > viewer->password->getLength()) {
- i = viewer->password->getLength();
- }
- if (i + n > viewer->password->getLength()) {
- n = viewer->password->getLength() - i;
- }
- viewer->password->del(i, n);
- viewer->password->insert(i, data->text->ptr, data->text->length);
-
- for (i = 0; i < data->text->length; ++i) {
- data->text->ptr[i] = '*';
- }
- data->doit = True;
-}
-
-void XPDFViewer::passwordOkCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->passwordDone = 1;
-}
-
-void XPDFViewer::passwordCancelCbk(Widget widget, XtPointer ptr,
- XtPointer callData) {
- XPDFViewer *viewer = (XPDFViewer *)ptr;
-
- viewer->passwordDone = -1;
-}
-
-void XPDFViewer::getPassword(GBool again) {
- XmString s;
- XEvent event;
-
- if (password) {
- delete password;
- }
- password = new GString();
-
- XmTextFieldSetString(passwordText, "");
- s = XmStringCreateLocalized(
- again ? (char *)"Incorrect password. Please try again."
- : (char *)"This document requires a password.");
- XtVaSetValues(passwordMsg, XmNlabelString, s, NULL);
- XmStringFree(s);
- XtManageChild(passwordDialog);
- passwordDone = 0;
- do {
- XtAppNextEvent(app->getAppContext(), &event);
- XtDispatchEvent(&event);
- } while (!passwordDone);
-
- if (passwordDone < 0) {
- delete password;
- password = NULL;
- }
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cpp b/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cpp
new file mode 100644
index 000000000..8327a7a22
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XPDFViewer.cpp
@@ -0,0 +1,2318 @@
+//========================================================================
+//
+// XPDFViewer.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <X11/cursorfont.h>
+#ifdef HAVE_X11_XPM_H
+#include <X11/xpm.h>
+#endif
+#include "gmem.h"
+#include "gfile.h"
+#include "GString.h"
+#include "GList.h"
+#include "Error.h"
+#include "GlobalParams.h"
+#include "PDFDoc.h"
+#include "ErrorCodes.h"
+#include "Outline.h"
+#include "UnicodeMap.h"
+#ifndef DISABLE_OUTLINE
+#define Object XtObject
+#include "XPDFTree.h"
+#undef Object
+#endif
+#include "XPDFApp.h"
+#include "XPDFViewer.h"
+#include "XPixmapOutputDev.h"
+#include "PSOutputDev.h"
+#include "config.h"
+
+// these macro defns conflict with xpdf's Object class
+#ifdef LESSTIF_VERSION
+#undef XtDisplay
+#undef XtScreen
+#undef XtWindow
+#undef XtParent
+#undef XtIsRealized
+#endif
+
+#if XmVERSION <= 1
+#define XmSET True
+#define XmUNSET False
+#endif
+
+//------------------------------------------------------------------------
+// GUI includes
+//------------------------------------------------------------------------
+
+#include "xpdfIcon.xpm"
+#include "leftArrow.xbm"
+#include "leftArrowDis.xbm"
+#include "dblLeftArrow.xbm"
+#include "dblLeftArrowDis.xbm"
+#include "rightArrow.xbm"
+#include "rightArrowDis.xbm"
+#include "dblRightArrow.xbm"
+#include "dblRightArrowDis.xbm"
+#include "backArrow.xbm"
+#include "backArrowDis.xbm"
+#include "forwardArrow.xbm"
+#include "forwardArrowDis.xbm"
+#include "find.xbm"
+#include "findDis.xbm"
+#include "print.xbm"
+#include "printDis.xbm"
+#include "about.xbm"
+#include "about-text.h"
+
+//------------------------------------------------------------------------
+
+XPDFViewer::XPDFViewer(XPDFApp *appA, GString *fileName,
+ int pageA, GString *destName,
+ GString *ownerPassword, GString *userPassword) {
+ LinkDest *dest;
+ int pg, z;
+ GString *dir;
+
+ app = appA;
+ win = NULL;
+ core = NULL;
+ password = NULL;
+ ok = gFalse;
+#ifndef DISABLE_OUTLINE
+ outlineLabels = NULL;
+ outlineLabelsLength = outlineLabelsSize = 0;
+#endif
+
+ // do Motif-specific initialization and create the window;
+ // this also creates the core object
+ initWindow();
+ initAboutDialog();
+ initOpenDialog();
+ initFindDialog();
+ initSaveAsDialog();
+ initPrintDialog();
+ initPasswordDialog();
+
+ dest = NULL; // make gcc happy
+ pg = pageA; // make gcc happy
+
+ if (fileName) {
+ if (loadFile(fileName, ownerPassword, userPassword)) {
+ getPageAndDest(pageA, destName, &pg, &dest);
+ if (pg > 0) {
+ core->resizeToPage(pg);
+ }
+ dir = makePathAbsolute(grabPath(fileName->getCString()));
+ setOpenDialogDir(dir->getCString());
+ setSaveAsDialogDir(dir->getCString());
+ delete dir;
+ } else {
+ return;
+ }
+ }
+
+ // map the window -- we do this after calling resizeToPage to avoid
+ // an annoying on-screen resize
+ mapWindow();
+
+ // display the first page
+ z = app->getFullScreen() ? zoomPage : core->getZoom();
+ if (dest) {
+ displayDest(dest, z, core->getRotate(), gTrue);
+ delete dest;
+ } else {
+ displayPage(pg, z, core->getRotate(), gTrue, gTrue);
+ }
+
+ ok = gTrue;
+}
+
+XPDFViewer::~XPDFViewer() {
+ delete core;
+ XmFontListFree(aboutBigFont);
+ XmFontListFree(aboutVersionFont);
+ XmFontListFree(aboutFixedFont);
+ closeWindow();
+#ifndef DISABLE_OUTLINE
+ if (outlineLabels) {
+ gfree(outlineLabels);
+ }
+#endif
+ if (password) {
+ delete password;
+ }
+}
+
+void XPDFViewer::open(GString *fileName, int pageA, GString *destName) {
+ LinkDest *dest;
+ int pg, z;
+
+ if (!core->getDoc() || fileName->cmp(core->getDoc()->getFileName())) {
+ if (!loadFile(fileName, NULL, NULL)) {
+ return;
+ }
+ }
+ getPageAndDest(pageA, destName, &pg, &dest);
+ z = app->getFullScreen() ? zoomPage : core->getZoom();
+ if (dest) {
+ displayDest(dest, z, core->getRotate(), gTrue);
+ delete dest;
+ } else {
+ displayPage(pg, z, core->getRotate(), gTrue, gTrue);
+ }
+}
+
+void XPDFViewer::clear() {
+ char *title;
+ XmString s;
+
+ core->clear();
+
+ // set up title, number-of-pages display
+ title = app->getTitle() ? app->getTitle()->getCString()
+ : (char *)xpdfAppName;
+ XtVaSetValues(win, XmNtitle, title, XmNiconName, title, NULL);
+ s = XmStringCreateLocalized("");
+ XtVaSetValues(pageNumText, XmNlabelString, s, NULL);
+ XmStringFree(s);
+ s = XmStringCreateLocalized(" of 0");
+ XtVaSetValues(pageCountLabel, XmNlabelString, s, NULL);
+ XmStringFree(s);
+
+ // disable buttons
+ XtVaSetValues(prevTenPageBtn, XmNsensitive, False, NULL);
+ XtVaSetValues(prevPageBtn, XmNsensitive, False, NULL);
+ XtVaSetValues(nextTenPageBtn, XmNsensitive, False, NULL);
+ XtVaSetValues(nextPageBtn, XmNsensitive, False, NULL);
+}
+
+//------------------------------------------------------------------------
+// load / display
+//------------------------------------------------------------------------
+
+GBool XPDFViewer::loadFile(GString *fileName, GString *ownerPassword,
+ GString *userPassword) {
+ return core->loadFile(fileName, ownerPassword, userPassword) == errNone;
+}
+
+void XPDFViewer::reloadFile() {
+ int pg;
+
+ if (!core->getDoc()) {
+ return;
+ }
+ pg = core->getPageNum();
+ loadFile(core->getDoc()->getFileName());
+ if (pg > core->getDoc()->getNumPages()) {
+ pg = core->getDoc()->getNumPages();
+ }
+ displayPage(pg, core->getZoom(), core->getRotate(), gFalse, gFalse);
+}
+
+void XPDFViewer::displayPage(int pageA, int zoomA, int rotateA,
+ GBool scrollToTop, GBool addToHist) {
+ core->displayPage(pageA, zoomA, rotateA, scrollToTop, addToHist);
+}
+
+void XPDFViewer::displayDest(LinkDest *dest, int zoomA, int rotateA,
+ GBool addToHist) {
+ core->displayDest(dest, zoomA, rotateA, addToHist);
+}
+
+void XPDFViewer::getPageAndDest(int pageA, GString *destName,
+ int *pageOut, LinkDest **destOut) {
+ Ref pageRef;
+
+ // find the page number for a named destination
+ *pageOut = pageA;
+ *destOut = NULL;
+ if (destName && (*destOut = core->getDoc()->findDest(destName))) {
+ if ((*destOut)->isPageRef()) {
+ pageRef = (*destOut)->getPageRef();
+ *pageOut = core->getDoc()->findPage(pageRef.num, pageRef.gen);
+ } else {
+ *pageOut = (*destOut)->getPageNum();
+ }
+ }
+
+ if (*pageOut <= 0) {
+ *pageOut = 1;
+ }
+ if (*pageOut > core->getDoc()->getNumPages()) {
+ *pageOut = core->getDoc()->getNumPages();
+ }
+}
+
+//------------------------------------------------------------------------
+// password dialog
+//------------------------------------------------------------------------
+
+GString *XPDFViewer::reqPasswordCbk(void *data, GBool again) {
+ XPDFViewer *viewer = (XPDFViewer *)data;
+
+ viewer->getPassword(again);
+ return viewer->password;
+}
+
+//------------------------------------------------------------------------
+// actions
+//------------------------------------------------------------------------
+
+void XPDFViewer::actionCbk(void *data, char *action) {
+ XPDFViewer *viewer = (XPDFViewer *)data;
+
+ if (!strcmp(action, "Quit")) {
+ viewer->app->quit();
+ }
+}
+
+//------------------------------------------------------------------------
+// keyboard/mouse input
+//------------------------------------------------------------------------
+
+void XPDFViewer::keyPressCbk(void *data, char *s, KeySym key,
+ Guint modifiers) {
+ XPDFViewer *viewer = (XPDFViewer *)data;
+ int z;
+
+ if (s[0]) {
+ switch (s[0]) {
+ case 'O':
+ case 'o':
+ viewer->mapOpenDialog(gFalse);
+ break;
+ case 'R':
+ case 'r':
+ viewer->reloadFile();
+ break;
+ case 'F':
+ case 'f':
+ case '\006': // ctrl-F
+ if (viewer->core->getDoc()) {
+ XtManageChild(viewer->findDialog);
+ }
+ break;
+ case '\007': // ctrl-G
+ if (viewer->core->getDoc()) {
+ XPDFViewer::findFindCbk(None, viewer, NULL);
+ }
+ break;
+ case '\020': // ctrl-P
+ if (viewer->core->getDoc()) {
+ XtManageChild(viewer->printDialog);
+ }
+ break;
+ case 'N':
+ case 'n':
+ viewer->core->gotoNextPage(1, !(modifiers & Mod5Mask));
+ break;
+ case 'P':
+ case 'p':
+ viewer->core->gotoPrevPage(1, !(modifiers & Mod5Mask), gFalse);
+ break;
+ case ' ':
+ if (viewer->app->getFullScreen()) {
+ viewer->core->gotoNextPage(1, gTrue);
+ } else {
+ viewer->core->scrollPageDown();
+ }
+ break;
+ case '\b': // bs
+ case '\177': // del
+ if (viewer->app->getFullScreen()) {
+ viewer->core->gotoPrevPage(1, gTrue, gFalse);
+ } else {
+ viewer->core->scrollPageUp();
+ }
+ break;
+ case 'v':
+ viewer->core->goForward();
+ break;
+ case 'b':
+ viewer->core->goBackward();
+ break;
+ case 'g':
+ if (!viewer->app->getFullScreen()) {
+ XmTextFieldSetSelection(
+ viewer->pageNumText, 0,
+ strlen(XmTextFieldGetString(viewer->pageNumText)),
+ XtLastTimestampProcessed(viewer->display));
+ XmProcessTraversal(viewer->pageNumText, XmTRAVERSE_CURRENT);
+ }
+ break;
+ case 'h': // vi-style left
+ if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
+ viewer->core->scrollLeft();
+ }
+ break;
+ case 'l': // vi-style right
+ if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
+ viewer->core->scrollRight();
+ }
+ break;
+ case 'k': // vi-style up
+ if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
+ viewer->core->scrollUp();
+ }
+ break;
+ case 'j': // vi-style down
+ if (!viewer->app->getFullScreen() && viewer->app->getViKeys()) {
+ viewer->core->scrollDown();
+ }
+ break;
+ case '0':
+ if (!viewer->app->getFullScreen() &&
+ viewer->core->getZoom() != defZoom) {
+ XtVaSetValues(viewer->zoomMenu,
+ XmNmenuHistory, viewer->getZoomMenuBtn(defZoom),
+ NULL);
+ viewer->displayPage(viewer->core->getPageNum(), defZoom,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ break;
+ case '+':
+ if (!viewer->app->getFullScreen() &&
+ viewer->core->getZoom() >= minZoom &&
+ viewer->core->getZoom() < maxZoom) {
+ z = viewer->core->getZoom() + 1;
+ XtVaSetValues(viewer->zoomMenu,
+ XmNmenuHistory, viewer->getZoomMenuBtn(z),
+ NULL);
+ viewer->displayPage(viewer->core->getPageNum(), z,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ break;
+ case '-':
+ if (!viewer->app->getFullScreen() &&
+ viewer->core->getZoom() > minZoom &&
+ viewer->core->getZoom() <= maxZoom) {
+ z = viewer->core->getZoom() - 1;
+ XtVaSetValues(viewer->zoomMenu,
+ XmNmenuHistory, viewer->getZoomMenuBtn(z),
+ NULL);
+ viewer->displayPage(viewer->core->getPageNum(), z,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ break;
+ case 'z':
+ if (!viewer->app->getFullScreen() &&
+ viewer->core->getZoom() != zoomPage) {
+ XtVaSetValues(viewer->zoomMenu,
+ XmNmenuHistory, viewer->getZoomMenuBtn(zoomPage),
+ NULL);
+ viewer->displayPage(viewer->core->getPageNum(), zoomPage,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ break;
+ case 'w':
+ if (!viewer->app->getFullScreen() &&
+ viewer->core->getZoom() != zoomWidth) {
+ XtVaSetValues(viewer->zoomMenu,
+ XmNmenuHistory, viewer->getZoomMenuBtn(zoomWidth),
+ NULL);
+ viewer->displayPage(viewer->core->getPageNum(), zoomWidth,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ break;
+ case '\014': // ^L
+ viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
+ viewer->core->getRotate(), gFalse, gFalse);
+ break;
+ case '\027': // ^W
+ viewer->app->close(viewer, gFalse);
+ break;
+ case '?':
+ XtManageChild(viewer->aboutDialog);
+ break;
+ case 'Q':
+ case 'q':
+ viewer->app->quit();
+ break;
+ }
+ }
+}
+
+void XPDFViewer::mouseCbk(void *data, XEvent *event) {
+ XPDFViewer *viewer = (XPDFViewer *)data;
+
+ if (event->type == ButtonPress && event->xbutton.button == 3) {
+ XmMenuPosition(viewer->popupMenu, &event->xbutton);
+ XtManageChild(viewer->popupMenu);
+ }
+}
+
+//------------------------------------------------------------------------
+// GUI code: main window
+//------------------------------------------------------------------------
+
+void XPDFViewer::initWindow() {
+ Widget btn, label, menuPane, lastBtn;
+#ifndef DISABLE_OUTLINE
+ Widget clipWin;
+#endif
+ Colormap colormap;
+ XColor xcol;
+ Arg args[20];
+ int n;
+ char *title;
+ XmString s, s2, emptyString;
+ char buf[16];
+ int i;
+
+ display = XtDisplay(app->getAppShell());
+ screenNum = XScreenNumberOfScreen(XtScreen(app->getAppShell()));
+
+ // private colormap
+ if (app->getInstallCmap()) {
+ XtVaGetValues(app->getAppShell(), XmNcolormap, &colormap, NULL);
+ // ensure that BlackPixel and WhitePixel are reserved in the
+ // new colormap
+ xcol.red = xcol.green = xcol.blue = 0;
+ XAllocColor(display, colormap, &xcol);
+ xcol.red = xcol.green = xcol.blue = 65535;
+ XAllocColor(display, colormap, &xcol);
+ colormap = XCopyColormapAndFree(display, colormap);
+ }
+
+ // top-level window
+ n = 0;
+ title = app->getTitle() ? app->getTitle()->getCString()
+ : (char *)xpdfAppName;
+ XtSetArg(args[n], XmNtitle, title); ++n;
+ XtSetArg(args[n], XmNiconName, title); ++n;
+ XtSetArg(args[n], XmNminWidth, 100); ++n;
+ XtSetArg(args[n], XmNminHeight, 100); ++n;
+ XtSetArg(args[n], XmNbaseWidth, 0); ++n;
+ XtSetArg(args[n], XmNbaseHeight, 0); ++n;
+ XtSetArg(args[n], XmNdeleteResponse, XmDO_NOTHING); ++n;
+ if (app->getFullScreen()) {
+ XtSetArg(args[n], XmNmwmDecorations, 0); ++n;
+ XtSetArg(args[n], XmNgeometry, "+0+0"); ++n;
+ } else if (app->getGeometry()) {
+ XtSetArg(args[n], XmNgeometry, app->getGeometry()->getCString()); ++n;
+ }
+ win = XtCreatePopupShell("win", topLevelShellWidgetClass,
+ app->getAppShell(), args, n);
+ if (app->getInstallCmap()) {
+ XtVaSetValues(win, XmNcolormap, colormap, NULL);
+ }
+ XmAddWMProtocolCallback(win, XInternAtom(display, "WM_DELETE_WINDOW", False),
+ &closeMsgCbk, this);
+
+ // form
+ n = 0;
+ form = XmCreateForm(win, "form", args, n);
+ XtManageChild(form);
+
+ // toolbar
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ toolBar = XmCreateForm(form, "toolBar", args, n);
+ XtManageChild(toolBar);
+
+ // create an empty string -- this is used for buttons that will get
+ // pixmaps later
+ emptyString = XmStringCreateLocalized("");
+
+ // page movement buttons
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ backBtn = XmCreatePushButton(toolBar, "back", args, n);
+ XtManageChild(backBtn);
+ XtAddCallback(backBtn, XmNactivateCallback,
+ &backCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, backBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ prevTenPageBtn = XmCreatePushButton(toolBar, "prevTenPage", args, n);
+ XtManageChild(prevTenPageBtn);
+ XtAddCallback(prevTenPageBtn, XmNactivateCallback,
+ &prevTenPageCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, prevTenPageBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ prevPageBtn = XmCreatePushButton(toolBar, "prevPage", args, n);
+ XtManageChild(prevPageBtn);
+ XtAddCallback(prevPageBtn, XmNactivateCallback,
+ &prevPageCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, prevPageBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ nextPageBtn = XmCreatePushButton(toolBar, "nextPage", args, n);
+ XtManageChild(nextPageBtn);
+ XtAddCallback(nextPageBtn, XmNactivateCallback,
+ &nextPageCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, nextPageBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ nextTenPageBtn = XmCreatePushButton(toolBar, "nextTenPage", args, n);
+ XtManageChild(nextTenPageBtn);
+ XtAddCallback(nextTenPageBtn, XmNactivateCallback,
+ &nextTenPageCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, nextTenPageBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ forwardBtn = XmCreatePushButton(toolBar, "forward", args, n);
+ XtManageChild(forwardBtn);
+ XtAddCallback(forwardBtn, XmNactivateCallback,
+ &forwardCbk, (XtPointer)this);
+
+ // page number display
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, forwardBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ s = XmStringCreateLocalized("Page ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ label = XmCreateLabel(toolBar, "pageLabel", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, label); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 3); ++n;
+ XtSetArg(args[n], XmNmarginHeight, 3); ++n;
+ XtSetArg(args[n], XmNcolumns, 5); ++n;
+ pageNumText = XmCreateTextField(toolBar, "pageNum", args, n);
+ XtManageChild(pageNumText);
+ XtAddCallback(pageNumText, XmNactivateCallback,
+ &pageNumCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, pageNumText); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ s = XmStringCreateLocalized(" of 00000");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNalignment, XmALIGNMENT_BEGINNING); ++n;
+ XtSetArg(args[n], XmNrecomputeSize, False); ++n;
+ pageCountLabel = XmCreateLabel(toolBar, "pageCountLabel", args, n);
+ XmStringFree(s);
+ XtManageChild(pageCountLabel);
+ s = XmStringCreateLocalized(" of 0");
+ XtVaSetValues(pageCountLabel, XmNlabelString, s, NULL);
+ XmStringFree(s);
+
+ // zoom menu
+ n = 0;
+ menuPane = XmCreatePulldownMenu(toolBar, "zoomMenuPane", args, n);
+ for (i = minZoom; i <= maxZoom; ++i) {
+ n = 0;
+ sprintf(buf, "%s%d", i > 0 ? "+" : "", i);
+ s = XmStringCreateLocalized(buf);
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNuserData, (XtPointer)i); ++n;
+ sprintf(buf, "zoom%s%d", i < 0 ? "M" : "", i < 0 ? -i : i);
+ btn = XmCreatePushButton(menuPane, buf, args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &zoomMenuCbk, (XtPointer)this);
+ zoomMenuBtns[i - minZoom] = btn;
+ }
+ n = 0;
+ s = XmStringCreateLocalized("fit page");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNuserData, (XtPointer)zoomPage); ++n;
+ btn = XmCreatePushButton(menuPane, "zoomPage", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &zoomMenuCbk, (XtPointer)this);
+ zoomMenuBtns[maxZoom - minZoom + 1] = btn;
+ n = 0;
+ s = XmStringCreateLocalized("fit width");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNuserData, (XtPointer)zoomWidth); ++n;
+ btn = XmCreatePushButton(menuPane, "zoomWidth", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &zoomMenuCbk, (XtPointer)this);
+ zoomMenuBtns[maxZoom - minZoom + 2] = btn;
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, pageCountLabel); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 0); ++n;
+ XtSetArg(args[n], XmNmarginHeight, 0); ++n;
+ XtSetArg(args[n], XmNsubMenuId, menuPane); ++n;
+ zoomMenu = XmCreateOptionMenu(toolBar, "zoomMenu", args, n);
+ XtManageChild(zoomMenu);
+
+ // find/print/about buttons
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, zoomMenu); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ findBtn = XmCreatePushButton(toolBar, "find", args, n);
+ XtManageChild(findBtn);
+ XtAddCallback(findBtn, XmNactivateCallback,
+ &findCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, findBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ printBtn = XmCreatePushButton(toolBar, "print", args, n);
+ XtManageChild(printBtn);
+ XtAddCallback(printBtn, XmNactivateCallback,
+ &printCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, printBtn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ XtSetArg(args[n], XmNlabelString, emptyString); ++n;
+ aboutBtn = XmCreatePushButton(toolBar, "about", args, n);
+ XtManageChild(aboutBtn);
+ XtAddCallback(aboutBtn, XmNactivateCallback,
+ &aboutCbk, (XtPointer)this);
+ lastBtn = aboutBtn;
+
+ // quit button
+ n = 0;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 6); ++n;
+ s = XmStringCreateLocalized("Quit");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ quitBtn = XmCreatePushButton(toolBar, "quit", args, n);
+ XmStringFree(s);
+ XtManageChild(quitBtn);
+ XtAddCallback(quitBtn, XmNactivateCallback,
+ &quitCbk, (XtPointer)this);
+
+ // link label
+ n = 0;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNleftWidget, lastBtn); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightWidget, btn); ++n;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ s = XmStringCreateLocalized("");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNrecomputeSize, True); ++n;
+ XtSetArg(args[n], XmNalignment, XmALIGNMENT_BEGINNING); ++n;
+ linkLabel = XmCreateLabel(toolBar, "linkLabel", args, n);
+ XmStringFree(s);
+ XtManageChild(linkLabel);
+
+#ifndef DISABLE_OUTLINE
+ if (app->getFullScreen()) {
+#endif
+
+ // core
+ core = new XPDFCore(win, form, app->getPaperColor(),
+ app->getFullScreen(), app->getReverseVideo(),
+ app->getInstallCmap(), app->getRGBCubeSize());
+ core->setUpdateCbk(&updateCbk, this);
+ core->setActionCbk(&actionCbk, this);
+ core->setKeyPressCbk(&keyPressCbk, this);
+ core->setMouseCbk(&mouseCbk, this);
+ core->setReqPasswordCbk(&reqPasswordCbk, this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNbottomWidget, toolBar); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetValues(core->getWidget(), args, n);
+
+#ifndef DISABLE_OUTLINE
+ } else {
+
+ // paned window
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNbottomWidget, toolBar); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ panedWin = XmCreatePanedWindow(form, "panedWin", args, n);
+ XtManageChild(panedWin);
+
+ // scrolled window for outline container
+ n = 0;
+ XtSetArg(args[n], XmNpositionIndex, 0); ++n;
+ XtSetArg(args[n], XmNallowResize, True); ++n;
+ XtSetArg(args[n], XmNpaneMinimum, 1); ++n;
+ XtSetArg(args[n], XmNpaneMaximum, 10000); ++n;
+ XtSetArg(args[n], XmNwidth, 1); ++n;
+ XtSetArg(args[n], XmNscrollingPolicy, XmAUTOMATIC); ++n;
+ outlineScroll = XmCreateScrolledWindow(panedWin, "outlineScroll", args, n);
+ XtManageChild(outlineScroll);
+ XtVaGetValues(outlineScroll, XmNclipWindow, &clipWin, NULL);
+ XtVaSetValues(clipWin, XmNbackground, app->getPaperColor(), NULL);
+
+ // outline tree
+ n = 0;
+ XtSetArg(args[n], XmNbackground, app->getPaperColor()); ++n;
+ outlineTree = XPDFCreateTree(outlineScroll, "outlineTree", args, n);
+ XtManageChild(outlineTree);
+ XtAddCallback(outlineTree, XPDFNselectionCallback, &outlineSelectCbk,
+ (XtPointer)this);
+
+ // core
+ core = new XPDFCore(win, panedWin, app->getPaperColor(),
+ app->getFullScreen(), app->getReverseVideo(),
+ app->getInstallCmap(), app->getRGBCubeSize());
+ core->setUpdateCbk(&updateCbk, this);
+ core->setActionCbk(&actionCbk, this);
+ core->setKeyPressCbk(&keyPressCbk, this);
+ core->setMouseCbk(&mouseCbk, this);
+ core->setReqPasswordCbk(&reqPasswordCbk, this);
+ n = 0;
+ XtSetArg(args[n], XmNpositionIndex, 1); ++n;
+ XtSetArg(args[n], XmNallowResize, True); ++n;
+ XtSetArg(args[n], XmNpaneMinimum, 1); ++n;
+ XtSetArg(args[n], XmNpaneMaximum, 10000); ++n;
+ XtSetValues(core->getWidget(), args, n);
+ }
+#endif
+
+ // set the zoom menu to match the initial zoom setting
+ XtVaSetValues(zoomMenu, XmNmenuHistory,
+ getZoomMenuBtn(core->getZoom()), NULL);
+
+ // set traversal order
+ XtVaSetValues(core->getDrawAreaWidget(),
+ XmNnavigationType, XmEXCLUSIVE_TAB_GROUP, NULL);
+ XtVaSetValues(backBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(prevTenPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(prevPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(nextPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(nextTenPageBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(forwardBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(pageNumText, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(zoomMenu, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(findBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(printBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(aboutBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+ XtVaSetValues(quitBtn, XmNnavigationType, XmEXCLUSIVE_TAB_GROUP,
+ NULL);
+
+ // popup menu
+ n = 0;
+ XtSetArg(args[n], XmNmenuPost, "<Btn3Down>"); ++n;
+ popupMenu = XmCreatePopupMenu(core->getDrawAreaWidget(), "popupMenu",
+ args, n);
+ n = 0;
+ s = XmStringCreateLocalized("Open...");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ s2 = XmStringCreateLocalized("O");
+ XtSetArg(args[n], XmNacceleratorText, s2); ++n;
+ btn = XmCreatePushButton(popupMenu, "open", args, n);
+ XmStringFree(s);
+ XmStringFree(s2);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &openCbk, (XtPointer)this);
+ n = 0;
+ s = XmStringCreateLocalized("Open in new window...");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ btn = XmCreatePushButton(popupMenu, "openInNewWindow", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &openInNewWindowCbk, (XtPointer)this);
+ n = 0;
+ s = XmStringCreateLocalized("Reload");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ s2 = XmStringCreateLocalized("R");
+ XtSetArg(args[n], XmNacceleratorText, s2); ++n;
+ btn = XmCreatePushButton(popupMenu, "reload", args, n);
+ XmStringFree(s);
+ XmStringFree(s2);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &reloadCbk, (XtPointer)this);
+ n = 0;
+ s = XmStringCreateLocalized("Save as...");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ btn = XmCreatePushButton(popupMenu, "saveAs", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &saveAsCbk, (XtPointer)this);
+ n = 0;
+ btn = XmCreateSeparator(popupMenu, "sep1", args, n);
+ XtManageChild(btn);
+ n = 0;
+ s = XmStringCreateLocalized("Rotate counterclockwise");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ btn = XmCreatePushButton(popupMenu, "rotateCCW", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &rotateCCWCbk, (XtPointer)this);
+ n = 0;
+ s = XmStringCreateLocalized("Rotate clockwise");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ btn = XmCreatePushButton(popupMenu, "rotateCW", args, n);
+ XmStringFree(s);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &rotateCWCbk, (XtPointer)this);
+ n = 0;
+ btn = XmCreateSeparator(popupMenu, "sep2", args, n);
+ XtManageChild(btn);
+ n = 0;
+ s = XmStringCreateLocalized("Close");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ s2 = XmStringCreateLocalized("Ctrl+W");
+ XtSetArg(args[n], XmNacceleratorText, s2); ++n;
+ btn = XmCreatePushButton(popupMenu, "close", args, n);
+ XmStringFree(s);
+ XmStringFree(s2);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &closeCbk, (XtPointer)this);
+ n = 0;
+ s = XmStringCreateLocalized("Quit");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ s2 = XmStringCreateLocalized("Q");
+ XtSetArg(args[n], XmNacceleratorText, s2); ++n;
+ btn = XmCreatePushButton(popupMenu, "quit", args, n);
+ XmStringFree(s);
+ XmStringFree(s2);
+ XtManageChild(btn);
+ XtAddCallback(btn, XmNactivateCallback,
+ &quitCbk, (XtPointer)this);
+
+ XmStringFree(emptyString);
+}
+
+void XPDFViewer::mapWindow() {
+#ifdef HAVE_X11_XPM_H
+ Pixmap iconPixmap;
+#endif
+ int depth;
+ Pixel bg, arm;
+
+ // show the window
+ XtPopup(win, XtGrabNone);
+ core->takeFocus();
+
+ // create the icon
+#ifdef HAVE_X11_XPM_H
+ if (XpmCreatePixmapFromData(display, XtWindow(win), xpdfIcon,
+ &iconPixmap, NULL, NULL) == XpmSuccess) {
+ XtVaSetValues(win, XmNiconPixmap, iconPixmap, NULL);
+ }
+#endif
+
+ // set button bitmaps (must be done after the window is mapped)
+ XtVaGetValues(backBtn, XmNdepth, &depth,
+ XmNbackground, &bg, XmNarmColor, &arm, NULL);
+ XtVaSetValues(backBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)backArrow_bits,
+ backArrow_width,
+ backArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)backArrow_bits,
+ backArrow_width,
+ backArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)backArrowDis_bits,
+ backArrowDis_width,
+ backArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(prevTenPageBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblLeftArrow_bits,
+ dblLeftArrow_width,
+ dblLeftArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblLeftArrow_bits,
+ dblLeftArrow_width,
+ dblLeftArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblLeftArrowDis_bits,
+ dblLeftArrowDis_width,
+ dblLeftArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(prevPageBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)leftArrow_bits,
+ leftArrow_width,
+ leftArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)leftArrow_bits,
+ leftArrow_width,
+ leftArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)leftArrowDis_bits,
+ leftArrowDis_width,
+ leftArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(nextPageBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)rightArrow_bits,
+ rightArrow_width,
+ rightArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)rightArrow_bits,
+ rightArrow_width,
+ rightArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)rightArrowDis_bits,
+ rightArrowDis_width,
+ rightArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(nextTenPageBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblRightArrow_bits,
+ dblRightArrow_width,
+ dblRightArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblRightArrow_bits,
+ dblRightArrow_width,
+ dblRightArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)dblRightArrowDis_bits,
+ dblRightArrowDis_width,
+ dblRightArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(forwardBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)forwardArrow_bits,
+ forwardArrow_width,
+ forwardArrow_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)forwardArrow_bits,
+ forwardArrow_width,
+ forwardArrow_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)forwardArrowDis_bits,
+ forwardArrowDis_width,
+ forwardArrowDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(findBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)find_bits,
+ find_width,
+ find_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)find_bits,
+ find_width,
+ find_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)findDis_bits,
+ findDis_width,
+ findDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(printBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)print_bits,
+ print_width,
+ print_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)print_bits,
+ print_width,
+ print_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ XmNlabelInsensitivePixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)printDis_bits,
+ printDis_width,
+ printDis_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ NULL);
+ XtVaSetValues(aboutBtn, XmNlabelType, XmPIXMAP,
+ XmNlabelPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)about_bits,
+ about_width,
+ about_height,
+ BlackPixel(display, screenNum),
+ bg, depth),
+ XmNarmPixmap,
+ XCreatePixmapFromBitmapData(display, XtWindow(toolBar),
+ (char *)about_bits,
+ about_width,
+ about_height,
+ BlackPixel(display, screenNum),
+ arm, depth),
+ NULL);
+}
+
+void XPDFViewer::closeWindow() {
+ XtPopdown(win);
+ XtDestroyWidget(win);
+}
+
+Widget XPDFViewer::getZoomMenuBtn(int z) {
+ if (z >= minZoom && z <= maxZoom) {
+ return zoomMenuBtns[z - minZoom];
+ }
+ if (z == zoomPage) {
+ return zoomMenuBtns[maxZoom - minZoom + 1];
+ }
+ if (z == zoomWidth) {
+ return zoomMenuBtns[maxZoom - minZoom + 2];
+ }
+ return zoomMenuBtns[0];
+}
+
+void XPDFViewer::prevPageCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->gotoPrevPage(1, gTrue, gFalse);
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::prevTenPageCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->gotoPrevPage(10, gTrue, gFalse);
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::nextPageCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->gotoNextPage(1, gTrue);
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::nextTenPageCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->gotoNextPage(10, gTrue);
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::backCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->goBackward();
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::forwardCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->goForward();
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::zoomMenuCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XtPointer userData;
+
+ XtVaGetValues(widget, XmNuserData, &userData, NULL);
+ if ((int)userData != viewer->core->getZoom()) {
+ viewer->displayPage(viewer->core->getPageNum(), (int)userData,
+ viewer->core->getRotate(), gTrue, gFalse);
+ }
+ viewer->core->takeFocus();
+}
+
+void XPDFViewer::findCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ if (!viewer->core->getDoc()) {
+ return;
+ }
+ XtManageChild(viewer->findDialog);
+}
+
+void XPDFViewer::printCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ if (!viewer->core->getDoc()) {
+ return;
+ }
+ XtManageChild(viewer->printDialog);
+}
+
+void XPDFViewer::aboutCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ XtManageChild(viewer->aboutDialog);
+}
+
+void XPDFViewer::quitCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->app->quit();
+}
+
+void XPDFViewer::openCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->mapOpenDialog(gFalse);
+}
+
+void XPDFViewer::openInNewWindowCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->mapOpenDialog(gTrue);
+}
+
+void XPDFViewer::reloadCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->reloadFile();
+}
+
+void XPDFViewer::saveAsCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ if (!viewer->core->getDoc()) {
+ return;
+ }
+ viewer->mapSaveAsDialog();
+}
+
+void XPDFViewer::rotateCCWCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ int r;
+
+ r = viewer->core->getRotate();
+ r = (r == 0) ? 270 : r - 90;
+ viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
+ r, gTrue, gFalse);
+}
+
+void XPDFViewer::rotateCWCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ int r;
+
+ r = viewer->core->getRotate();
+ r = (r == 270) ? 0 : r + 90;
+ viewer->displayPage(viewer->core->getPageNum(), viewer->core->getZoom(),
+ r, gTrue, gFalse);
+}
+
+void XPDFViewer::closeCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->app->close(viewer, gFalse);
+}
+
+void XPDFViewer::closeMsgCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->app->close(viewer, gTrue);
+}
+
+void XPDFViewer::pageNumCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ char *s, *p;
+ int pg;
+ char buf[20];
+
+ if (!viewer->core->getDoc()) {
+ goto err;
+ }
+ s = XmTextFieldGetString(viewer->pageNumText);
+ for (p = s; *p; ++p) {
+ if (!isdigit(*p)) {
+ goto err;
+ }
+ }
+ pg = atoi(s);
+ if (pg < 1 || pg > viewer->core->getDoc()->getNumPages()) {
+ goto err;
+ }
+ viewer->displayPage(pg, viewer->core->getZoom(),
+ viewer->core->getRotate(), gFalse, gTrue);
+ viewer->core->takeFocus();
+ return;
+
+ err:
+ XBell(viewer->display, 0);
+ sprintf(buf, "%d", viewer->core->getPageNum());
+ XmTextFieldSetString(viewer->pageNumText, buf);
+}
+
+void XPDFViewer::updateCbk(void *data, GString *fileName,
+ int pageNum, int numPages, char *linkLabel) {
+ XPDFViewer *viewer = (XPDFViewer *)data;
+ GString *title;
+ char buf[20];
+ XmString s;
+
+ if (fileName) {
+ if (!(title = viewer->app->getTitle())) {
+ title = (new GString(xpdfAppName))->append(": ")->append(fileName);
+ }
+ XtVaSetValues(viewer->win, XmNtitle, title->getCString(),
+ XmNiconName, title->getCString(), NULL);
+ if (!viewer->app->getTitle()) {
+ delete title;
+ }
+#ifndef DISABLE_OUTLINE
+ if (!viewer->app->getFullScreen()) {
+ viewer->setupOutline();
+ }
+#endif
+ viewer->setupPrintDialog();
+ }
+
+ if (pageNum >= 0) {
+ s = XmStringCreateLocalized("");
+ XtVaSetValues(viewer->linkLabel, XmNlabelString, s, NULL);
+ XmStringFree(s);
+ sprintf(buf, "%d", pageNum);
+ XmTextFieldSetString(viewer->pageNumText, buf);
+ XtVaSetValues(viewer->prevTenPageBtn, XmNsensitive,
+ pageNum > 1, NULL);
+ XtVaSetValues(viewer->prevPageBtn, XmNsensitive,
+ pageNum > 1, NULL);
+ XtVaSetValues(viewer->nextTenPageBtn, XmNsensitive,
+ pageNum < viewer->core->getDoc()->getNumPages(), NULL);
+ XtVaSetValues(viewer->nextPageBtn, XmNsensitive,
+ pageNum < viewer->core->getDoc()->getNumPages(), NULL);
+ XtVaSetValues(viewer->backBtn, XmNsensitive,
+ viewer->core->canGoBack(), NULL);
+ XtVaSetValues(viewer->forwardBtn, XmNsensitive,
+ viewer->core->canGoForward(), NULL);
+ }
+
+ if (numPages >= 0) {
+ sprintf(buf, " of %d", numPages);
+ s = XmStringCreateLocalized(buf);
+ XtVaSetValues(viewer->pageCountLabel, XmNlabelString, s, NULL);
+ XmStringFree(s);
+ }
+
+ if (linkLabel) {
+ s = XmStringCreateLocalized(linkLabel);
+ XtVaSetValues(viewer->linkLabel, XmNlabelString, s, NULL);
+ XmStringFree(s);
+ }
+}
+
+
+//------------------------------------------------------------------------
+// GUI code: outline
+//------------------------------------------------------------------------
+
+#ifndef DISABLE_OUTLINE
+
+void XPDFViewer::setupOutline() {
+ GList *items;
+ UnicodeMap *uMap;
+ GString *enc;
+ int i;
+
+ // unmanage and destroy the old labels
+ if (outlineLabels) {
+ XtUnmanageChildren(outlineLabels, outlineLabelsLength);
+ for (i = 0; i < outlineLabelsLength; ++i) {
+ XtDestroyWidget(outlineLabels[i]);
+ }
+ gfree(outlineLabels);
+ outlineLabels = NULL;
+ outlineLabelsLength = outlineLabelsSize = 0;
+ }
+
+ // create the new labels
+ items = core->getDoc()->getOutline()->getItems();
+ if (items && items->getLength() > 0) {
+ enc = new GString("Latin1");
+ uMap = globalParams->getUnicodeMap(enc);
+ delete enc;
+ setupOutlineItems(items, NULL, uMap);
+ uMap->decRefCnt();
+ }
+
+ // manage the new labels
+ XtManageChildren(outlineLabels, outlineLabelsLength);
+}
+
+void XPDFViewer::setupOutlineItems(GList *items, Widget parent,
+ UnicodeMap *uMap) {
+ OutlineItem *item;
+ GList *kids;
+ Widget label;
+ Arg args[20];
+ GString *title;
+ char buf[8];
+ XmString s;
+ int i, j, n;
+
+ for (i = 0; i < items->getLength(); ++i) {
+ item = (OutlineItem *)items->get(i);
+ title = new GString();
+ for (j = 0; j < item->getTitleLength(); ++j) {
+ n = uMap->mapUnicode(item->getTitle()[j], buf, sizeof(buf));
+ title->append(buf, n);
+ }
+ n = 0;
+ XtSetArg(args[n], XPDFNentryPosition, i); ++n;
+ if (parent) {
+ XtSetArg(args[n], XPDFNentryParent, parent); ++n;
+ }
+ XtSetArg(args[n], XPDFNentryExpanded, item->isOpen()); ++n;
+ s = XmStringCreateLocalized(title->getCString());
+ delete title;
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNuserData, item); ++n;
+ XtSetArg(args[n], XmNmarginWidth, 0); ++n;
+ XtSetArg(args[n], XmNmarginHeight, 2); ++n;
+ XtSetArg(args[n], XmNshadowThickness, 0); ++n;
+ XtSetArg(args[n], XmNforeground,
+ app->getReverseVideo() ? WhitePixel(display, screenNum)
+ : BlackPixel(display, screenNum)); ++n;
+ XtSetArg(args[n], XmNbackground, app->getPaperColor()); ++n;
+ label = XmCreateLabelGadget(outlineTree, "label", args, n);
+ XmStringFree(s);
+ if (outlineLabelsLength == outlineLabelsSize) {
+ outlineLabelsSize += 64;
+ outlineLabels = (Widget *)grealloc(outlineLabels,
+ outlineLabelsSize * sizeof(Widget *));
+ }
+ outlineLabels[outlineLabelsLength++] = label;
+ item->open();
+ if ((kids = item->getKids())) {
+ setupOutlineItems(kids, label, uMap);
+ }
+ }
+}
+
+void XPDFViewer::outlineSelectCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XPDFTreeSelectCallbackStruct *data =
+ (XPDFTreeSelectCallbackStruct *)callData;
+ OutlineItem *item;
+
+ XtVaGetValues(data->selectedItem, XmNuserData, &item, NULL);
+ if (item) {
+ viewer->core->doAction(item->getAction());
+ }
+ viewer->core->takeFocus();
+}
+
+#endif // !DISABLE_OUTLINE
+
+//------------------------------------------------------------------------
+// GUI code: "about" dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initAboutDialog() {
+ Widget scrolledWin, col, label, sep, closeBtn;
+ Arg args[20];
+ int n, i;
+ XmString s;
+ char buf[20];
+
+ //----- dialog
+ n = 0;
+ s = XmStringCreateLocalized(xpdfAppName ": About");
+ XtSetArg(args[n], XmNdialogTitle, s); ++n;
+ XtSetArg(args[n], XmNwidth, 450); ++n;
+ XtSetArg(args[n], XmNheight, 300); ++n;
+ aboutDialog = XmCreateFormDialog(win, "aboutDialog", args, n);
+ XmStringFree(s);
+
+ //----- "close" button
+ n = 0;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ closeBtn = XmCreatePushButton(aboutDialog, "Close", args, n);
+ XtManageChild(closeBtn);
+ n = 0;
+ XtSetArg(args[n], XmNdefaultButton, closeBtn); ++n;
+ XtSetArg(args[n], XmNcancelButton, closeBtn); ++n;
+ XtSetValues(aboutDialog, args, n);
+
+ //----- scrolled window and RowColumn
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNbottomWidget, closeBtn); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNscrollingPolicy, XmAUTOMATIC); ++n;
+ scrolledWin = XmCreateScrolledWindow(aboutDialog, "scrolledWin", args, n);
+ XtManageChild(scrolledWin);
+ n = 0;
+ XtSetArg(args[n], XmNorientation, XmVERTICAL); ++n;
+ XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
+ col = XmCreateRowColumn(scrolledWin, "col", args, n);
+ XtManageChild(col);
+
+ //----- fonts
+ aboutBigFont = XmFontListAppendEntry(NULL,
+ XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
+ XLoadQueryFont(display,
+ "-*-times-bold-i-normal--20-*-*-*-*-*-iso8859-1")));
+ aboutVersionFont = XmFontListAppendEntry(NULL,
+ XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
+ XLoadQueryFont(display,
+ "-*-times-medium-r-normal--16-*-*-*-*-*-iso8859-1")));
+ aboutFixedFont = XmFontListAppendEntry(NULL,
+ XmFontListEntryCreate(XmFONTLIST_DEFAULT_TAG, XmFONT_IS_FONT,
+ XLoadQueryFont(display,
+ "-*-courier-medium-r-normal--12-*-*-*-*-*-iso8859-1")));
+
+ //----- heading
+ n = 0;
+ s = XmStringCreateLocalized("Xpdf");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutBigFont); ++n;
+ label = XmCreateLabel(col, "h0", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ s = XmStringCreateLocalized("Version " xpdfVersion);
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
+ label = XmCreateLabel(col, "h1", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ s = XmStringCreateLocalized(xpdfCopyright);
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
+ label = XmCreateLabel(col, "h2", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ s = XmStringCreateLocalized(" ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
+ label = XmCreateLabel(col, "h3", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ sep = XmCreateSeparator(col, "sep", args, n);
+ XtManageChild(sep);
+ n = 0;
+ s = XmStringCreateLocalized(" ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutVersionFont); ++n;
+ label = XmCreateLabel(col, "h4", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+
+ //----- text
+ for (i = 0; aboutWinText[i]; ++i) {
+ n = 0;
+ s = XmStringCreateLocalized(aboutWinText[i]);
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ XtSetArg(args[n], XmNfontList, aboutFixedFont); ++n;
+ sprintf(buf, "t%d", i);
+ label = XmCreateLabel(col, buf, args, n);
+ XtManageChild(label);
+ XmStringFree(s);
+ }
+}
+
+//------------------------------------------------------------------------
+// GUI code: "open" dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initOpenDialog() {
+ Arg args[20];
+ int n;
+ XmString s1, s2, s3;
+
+ n = 0;
+ s1 = XmStringCreateLocalized("Open");
+ XtSetArg(args[n], XmNokLabelString, s1); ++n;
+ s2 = XmStringCreateLocalized("*.[Pp][Dd][Ff]");
+ XtSetArg(args[n], XmNpattern, s2); ++n;
+ s3 = XmStringCreateLocalized(xpdfAppName ": Open");
+ XtSetArg(args[n], XmNdialogTitle, s3); ++n;
+ XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
+ XtSetArg(args[n], XmNautoUnmanage, True); ++n;
+ openDialog = XmCreateFileSelectionDialog(win, "openDialog", args, n);
+ XmStringFree(s1);
+ XmStringFree(s2);
+ XmStringFree(s3);
+ XtUnmanageChild(XmFileSelectionBoxGetChild(openDialog,
+ XmDIALOG_HELP_BUTTON));
+ XtAddCallback(openDialog, XmNokCallback,
+ &openOkCbk, (XtPointer)this);
+}
+
+void XPDFViewer::setOpenDialogDir(char *dir) {
+ XmString s;
+
+ s = XmStringCreateLocalized(dir);
+ XtVaSetValues(openDialog, XmNdirectory, s, NULL);
+ XmStringFree(s);
+}
+
+void XPDFViewer::mapOpenDialog(GBool openInNewWindowA) {
+ openInNewWindow = openInNewWindowA;
+ XmFileSelectionDoSearch(openDialog, NULL);
+ XtManageChild(openDialog);
+}
+
+void XPDFViewer::openOkCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XmFileSelectionBoxCallbackStruct *data =
+ (XmFileSelectionBoxCallbackStruct *)callData;
+ char *fileName;
+ XmStringContext context;
+ XmStringCharSet charSet;
+ XmStringDirection dir;
+ Boolean sep;
+ GString *fileNameStr;
+
+ XmStringInitContext(&context, data->value);
+ if (XmStringGetNextSegment(context, &fileName, &charSet, &dir, &sep)) {
+ fileNameStr = new GString(fileName);
+ if (viewer->openInNewWindow) {
+ viewer->app->open(fileNameStr);
+ } else {
+ if (viewer->loadFile(fileNameStr)) {
+ viewer->displayPage(1, viewer->core->getZoom(),
+ viewer->core->getRotate(), gTrue, gTrue);
+ }
+ }
+ delete fileNameStr;
+ XtFree(charSet);
+ XtFree(fileName);
+ }
+ XmStringFreeContext(context);
+}
+
+//------------------------------------------------------------------------
+// GUI code: "find" dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initFindDialog() {
+ Widget row1, label, okBtn, closeBtn;
+ Arg args[20];
+ int n;
+ XmString s;
+
+ //----- dialog
+ n = 0;
+ s = XmStringCreateLocalized(xpdfAppName ": Find");
+ XtSetArg(args[n], XmNdialogTitle, s); ++n;
+ XtSetArg(args[n], XmNnavigationType, XmNONE); ++n;
+ XtSetArg(args[n], XmNautoUnmanage, False); ++n;
+ findDialog = XmCreateFormDialog(win, "findDialog", args, n);
+ XmStringFree(s);
+
+ //----- top row: search string entry
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNtopOffset, 4); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
+ row1 = XmCreateRowColumn(findDialog, "row1", args, n);
+ XtManageChild(row1);
+ n = 0;
+ s = XmStringCreateLocalized("Find text: ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ label = XmCreateLabel(row1, "label", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
+ findText = XmCreateTextField(row1, "text", args, n);
+ XtManageChild(findText);
+
+ //----- "find" and "close" buttons
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, row1); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
+ okBtn = XmCreatePushButton(findDialog, "Find", args, n);
+ XtManageChild(okBtn);
+ XtAddCallback(okBtn, XmNactivateCallback,
+ &findFindCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, row1); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
+ closeBtn = XmCreatePushButton(findDialog, "Close", args, n);
+ XtManageChild(closeBtn);
+ XtAddCallback(closeBtn, XmNactivateCallback,
+ &findCloseCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
+ XtSetArg(args[n], XmNcancelButton, closeBtn); ++n;
+ XtSetArg(args[n], XmNinitialFocus, findText); ++n;
+ XtSetValues(findDialog, args, n);
+}
+
+void XPDFViewer::findFindCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->core->find(XmTextFieldGetString(viewer->findText));
+}
+
+void XPDFViewer::findCloseCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ XtUnmanageChild(viewer->findDialog);
+}
+
+//------------------------------------------------------------------------
+// GUI code: "save as" dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initSaveAsDialog() {
+ Arg args[20];
+ int n;
+ XmString s1, s2, s3;
+
+ n = 0;
+ s1 = XmStringCreateLocalized("Save");
+ XtSetArg(args[n], XmNokLabelString, s1); ++n;
+ s2 = XmStringCreateLocalized("*.[Pp][Dd][Ff]");
+ XtSetArg(args[n], XmNpattern, s2); ++n;
+ s3 = XmStringCreateLocalized(xpdfAppName ": Save as");
+ XtSetArg(args[n], XmNdialogTitle, s3); ++n;
+ XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
+ XtSetArg(args[n], XmNautoUnmanage, True); ++n;
+ saveAsDialog = XmCreateFileSelectionDialog(win, "saveAsDialog", args, n);
+ XmStringFree(s1);
+ XmStringFree(s2);
+ XmStringFree(s3);
+ XtUnmanageChild(XmFileSelectionBoxGetChild(saveAsDialog,
+ XmDIALOG_HELP_BUTTON));
+ XtAddCallback(saveAsDialog, XmNokCallback,
+ &saveAsOkCbk, (XtPointer)this);
+}
+
+void XPDFViewer::setSaveAsDialogDir(char *dir) {
+ XmString s;
+
+ s = XmStringCreateLocalized(dir);
+ XtVaSetValues(saveAsDialog, XmNdirectory, s, NULL);
+ XmStringFree(s);
+}
+
+void XPDFViewer::mapSaveAsDialog() {
+ XmFileSelectionDoSearch(saveAsDialog, NULL);
+ XtManageChild(saveAsDialog);
+}
+
+void XPDFViewer::saveAsOkCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XmFileSelectionBoxCallbackStruct *data =
+ (XmFileSelectionBoxCallbackStruct *)callData;
+ char *fileName;
+ GString *fileNameStr;
+ XmStringContext context;
+ XmStringCharSet charSet;
+ XmStringDirection dir;
+ Boolean sep;
+
+ XmStringInitContext(&context, data->value);
+ if (XmStringGetNextSegment(context, &fileName, &charSet, &dir, &sep)) {
+ fileNameStr = new GString(fileName);
+ viewer->core->getDoc()->saveAs(fileNameStr);
+ delete fileNameStr;
+ XtFree(charSet);
+ XtFree(fileName);
+ }
+ XmStringFreeContext(context);
+}
+
+//------------------------------------------------------------------------
+// GUI code: "print" dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initPrintDialog() {
+ Widget sep1, sep2, row, label1, label2, okBtn, cancelBtn;
+ Arg args[20];
+ int n;
+ XmString s;
+
+ //----- dialog
+ n = 0;
+ s = XmStringCreateLocalized(xpdfAppName ": Print");
+ XtSetArg(args[n], XmNdialogTitle, s); ++n;
+ XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
+ printDialog = XmCreateFormDialog(win, "printDialog", args, n);
+ XmStringFree(s);
+
+ //----- "print with command"
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNtopOffset, 4); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNindicatorType, XmONE_OF_MANY); ++n;
+ XtSetArg(args[n], XmNset, XmSET); ++n;
+ s = XmStringCreateLocalized("Print with command:");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ printWithCmdBtn = XmCreateToggleButton(printDialog, "printWithCmd", args, n);
+ XmStringFree(s);
+ XtManageChild(printWithCmdBtn);
+ XtAddCallback(printWithCmdBtn, XmNvalueChangedCallback,
+ &printWithCmdBtnCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, printWithCmdBtn); ++n;
+ XtSetArg(args[n], XmNtopOffset, 2); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 16); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNcolumns, 40); ++n;
+ printCmdText = XmCreateTextField(printDialog, "printCmd", args, n);
+ XtManageChild(printCmdText);
+
+ //----- "print with command"
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, printCmdText); ++n;
+ XtSetArg(args[n], XmNtopOffset, 4); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNindicatorType, XmONE_OF_MANY); ++n;
+ XtSetArg(args[n], XmNset, XmUNSET); ++n;
+ s = XmStringCreateLocalized("Print to file:");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ printToFileBtn = XmCreateToggleButton(printDialog, "printToFile", args, n);
+ XmStringFree(s);
+ XtManageChild(printToFileBtn);
+ XtAddCallback(printToFileBtn, XmNvalueChangedCallback,
+ &printToFileBtnCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, printToFileBtn); ++n;
+ XtSetArg(args[n], XmNtopOffset, 2); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 16); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNcolumns, 40); ++n;
+ XtSetArg(args[n], XmNsensitive, False); ++n;
+ printFileText = XmCreateTextField(printDialog, "printFile", args, n);
+ XtManageChild(printFileText);
+
+ //----- separator
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, printFileText); ++n;
+ XtSetArg(args[n], XmNtopOffset, 8); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 8); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 8); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ sep1 = XmCreateSeparator(printDialog, "sep1", args, n);
+ XtManageChild(sep1);
+
+ //----- page range
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, sep1); ++n;
+ XtSetArg(args[n], XmNtopOffset, 8); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
+ row = XmCreateRowColumn(printDialog, "row", args, n);
+ XtManageChild(row);
+ n = 0;
+ s = XmStringCreateLocalized("Pages:");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ label1 = XmCreateLabel(row, "label1", args, n);
+ XmStringFree(s);
+ XtManageChild(label1);
+ n = 0;
+ XtSetArg(args[n], XmNcolumns, 5); ++n;
+ printFirstPage = XmCreateTextField(row, "printFirstPage", args, n);
+ XtManageChild(printFirstPage);
+ n = 0;
+ s = XmStringCreateLocalized("to");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ label2 = XmCreateLabel(row, "label2", args, n);
+ XmStringFree(s);
+ XtManageChild(label2);
+ n = 0;
+ XtSetArg(args[n], XmNcolumns, 5); ++n;
+ printLastPage = XmCreateTextField(row, "printLastPage", args, n);
+ XtManageChild(printLastPage);
+
+ //----- separator
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, row); ++n;
+ XtSetArg(args[n], XmNtopOffset, 8); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 8); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 8); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ sep2 = XmCreateSeparator(printDialog, "sep2", args, n);
+ XtManageChild(sep2);
+
+ //----- "print" and "cancel" buttons
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, sep2); ++n;
+ XtSetArg(args[n], XmNtopOffset, 8); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ okBtn = XmCreatePushButton(printDialog, "Print", args, n);
+ XtManageChild(okBtn);
+ XtAddCallback(okBtn, XmNactivateCallback,
+ &printPrintCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, sep2); ++n;
+ XtSetArg(args[n], XmNtopOffset, 8); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ cancelBtn = XmCreatePushButton(printDialog, "Cancel", args, n);
+ XtManageChild(cancelBtn);
+ n = 0;
+ XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
+ XtSetArg(args[n], XmNcancelButton, cancelBtn); ++n;
+ XtSetValues(printDialog, args, n);
+}
+
+void XPDFViewer::setupPrintDialog() {
+ PDFDoc *doc;
+ char buf[20];
+ GString *pdfFileName, *psFileName;
+ char *p;
+
+ doc = core->getDoc();
+
+ psFileName = globalParams->getPSFile();
+ if (psFileName && psFileName->getChar(0) != '|') {
+ XmTextFieldSetString(printFileText, psFileName->getCString());
+ } else {
+ pdfFileName = doc->getFileName();
+ p = pdfFileName->getCString() + pdfFileName->getLength() - 4;
+ if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
+ psFileName = new GString(pdfFileName->getCString(),
+ pdfFileName->getLength() - 4);
+ } else {
+ psFileName = pdfFileName->copy();
+ }
+ psFileName->append(".ps");
+ XmTextFieldSetString(printFileText, psFileName->getCString());
+ delete psFileName;
+ }
+
+ psFileName = globalParams->getPSFile();
+ if (psFileName && psFileName->getChar(0) == '|') {
+ XmTextFieldSetString(printCmdText,
+ psFileName->getCString() + 1);
+ }
+
+ sprintf(buf, "%d", doc->getNumPages());
+ XmTextFieldSetString(printFirstPage, "1");
+ XmTextFieldSetString(printLastPage, buf);
+}
+
+void XPDFViewer::printWithCmdBtnCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XmToggleButtonCallbackStruct *data =
+ (XmToggleButtonCallbackStruct *)callData;
+
+ if (data->set != XmSET) {
+ XmToggleButtonSetState(viewer->printWithCmdBtn, True, False);
+ }
+ XmToggleButtonSetState(viewer->printToFileBtn, False, False);
+ XtVaSetValues(viewer->printCmdText, XmNsensitive, True, NULL);
+ XtVaSetValues(viewer->printFileText, XmNsensitive, False, NULL);
+}
+
+void XPDFViewer::printToFileBtnCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XmToggleButtonCallbackStruct *data =
+ (XmToggleButtonCallbackStruct *)callData;
+
+ if (data->set != XmSET) {
+ XmToggleButtonSetState(viewer->printToFileBtn, True, False);
+ }
+ XmToggleButtonSetState(viewer->printWithCmdBtn, False, False);
+ XtVaSetValues(viewer->printFileText, XmNsensitive, True, NULL);
+ XtVaSetValues(viewer->printCmdText, XmNsensitive, False, NULL);
+}
+
+void XPDFViewer::printPrintCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ unsigned char withCmd;
+ GString *psFileName;
+ int firstPage, lastPage;
+ PDFDoc *doc;
+ PSOutputDev *psOut;
+
+ doc = viewer->core->getDoc();
+ if (!doc->okToPrint()) {
+ error(-1, "Printing this document is not allowed.");
+ return;
+ }
+
+ viewer->core->setBusyCursor(gTrue);
+
+ XtVaGetValues(viewer->printWithCmdBtn, XmNset, &withCmd, NULL);
+ if (withCmd) {
+ psFileName = new GString(XmTextFieldGetString(viewer->printCmdText));
+ psFileName->insert(0, '|');
+ } else {
+ psFileName = new GString(XmTextFieldGetString(viewer->printFileText));
+ }
+
+ firstPage = atoi(XmTextFieldGetString(viewer->printFirstPage));
+ lastPage = atoi(XmTextFieldGetString(viewer->printLastPage));
+ if (firstPage < 1) {
+ firstPage = 1;
+ } else if (firstPage > doc->getNumPages()) {
+ firstPage = doc->getNumPages();
+ }
+ if (lastPage < firstPage) {
+ lastPage = firstPage;
+ } else if (lastPage > doc->getNumPages()) {
+ lastPage = doc->getNumPages();
+ }
+
+ psOut = new PSOutputDev(psFileName->getCString(), doc->getXRef(),
+ doc->getCatalog(), firstPage, lastPage,
+ psModePS);
+ if (psOut->isOk()) {
+ doc->displayPages(psOut, firstPage, lastPage, 72, 0, gFalse);
+ }
+ delete psOut;
+ delete psFileName;
+
+ viewer->core->setBusyCursor(gFalse);
+}
+
+//------------------------------------------------------------------------
+// GUI code: password dialog
+//------------------------------------------------------------------------
+
+void XPDFViewer::initPasswordDialog() {
+ Widget row, label, okBtn, cancelBtn;
+ Arg args[20];
+ int n;
+ XmString s;
+
+ //----- dialog
+ n = 0;
+ s = XmStringCreateLocalized(xpdfAppName ": Password");
+ XtSetArg(args[n], XmNdialogTitle, s); ++n;
+ XtSetArg(args[n], XmNdialogStyle, XmDIALOG_PRIMARY_APPLICATION_MODAL); ++n;
+ passwordDialog = XmCreateFormDialog(win, "passwordDialog", args, n);
+ XmStringFree(s);
+
+ //----- message
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNtopOffset, 4); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ s = XmStringCreateLocalized(" ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ passwordMsg = XmCreateLabel(passwordDialog, "msg", args, n);
+ XmStringFree(s);
+ XtManageChild(passwordMsg);
+
+ //----- label and password entry
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, passwordMsg); ++n;
+ XtSetArg(args[n], XmNtopOffset, 4); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNorientation, XmHORIZONTAL); ++n;
+ XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); ++n;
+ row = XmCreateRowColumn(passwordDialog, "row", args, n);
+ XtManageChild(row);
+ n = 0;
+ s = XmStringCreateLocalized("Password: ");
+ XtSetArg(args[n], XmNlabelString, s); ++n;
+ label = XmCreateLabel(row, "label", args, n);
+ XmStringFree(s);
+ XtManageChild(label);
+ n = 0;
+ XtSetArg(args[n], XmNcolumns, 16); ++n;
+ passwordText = XmCreateTextField(row, "text", args, n);
+ XtManageChild(passwordText);
+ XtAddCallback(passwordText, XmNmodifyVerifyCallback,
+ &passwordTextVerifyCbk, this);
+
+ //----- "Ok" and "Cancel" buttons
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, row); ++n;
+ XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNleftOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
+ okBtn = XmCreatePushButton(passwordDialog, "Ok", args, n);
+ XtManageChild(okBtn);
+ XtAddCallback(okBtn, XmNactivateCallback,
+ &passwordOkCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); ++n;
+ XtSetArg(args[n], XmNtopWidget, row); ++n;
+ XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNrightOffset, 4); ++n;
+ XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); ++n;
+ XtSetArg(args[n], XmNbottomOffset, 4); ++n;
+ XtSetArg(args[n], XmNnavigationType, XmEXCLUSIVE_TAB_GROUP); ++n;
+ cancelBtn = XmCreatePushButton(passwordDialog, "Cancel", args, n);
+ XtManageChild(cancelBtn);
+ XtAddCallback(cancelBtn, XmNactivateCallback,
+ &passwordCancelCbk, (XtPointer)this);
+ n = 0;
+ XtSetArg(args[n], XmNdefaultButton, okBtn); ++n;
+ XtSetArg(args[n], XmNcancelButton, cancelBtn); ++n;
+ XtSetArg(args[n], XmNinitialFocus, passwordText); ++n;
+ XtSetValues(passwordDialog, args, n);
+}
+
+void XPDFViewer::passwordTextVerifyCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+ XmTextVerifyCallbackStruct *data =
+ (XmTextVerifyCallbackStruct *)callData;
+ int i, n;
+
+ i = (int)data->startPos;
+ n = (int)data->endPos - i;
+ if (i > viewer->password->getLength()) {
+ i = viewer->password->getLength();
+ }
+ if (i + n > viewer->password->getLength()) {
+ n = viewer->password->getLength() - i;
+ }
+ viewer->password->del(i, n);
+ viewer->password->insert(i, data->text->ptr, data->text->length);
+
+ for (i = 0; i < data->text->length; ++i) {
+ data->text->ptr[i] = '*';
+ }
+ data->doit = True;
+}
+
+void XPDFViewer::passwordOkCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->passwordDone = 1;
+}
+
+void XPDFViewer::passwordCancelCbk(Widget widget, XtPointer ptr,
+ XtPointer callData) {
+ XPDFViewer *viewer = (XPDFViewer *)ptr;
+
+ viewer->passwordDone = -1;
+}
+
+void XPDFViewer::getPassword(GBool again) {
+ XmString s;
+ XEvent event;
+
+ if (password) {
+ delete password;
+ }
+ password = new GString();
+
+ XmTextFieldSetString(passwordText, "");
+ s = XmStringCreateLocalized(
+ again ? (char *)"Incorrect password. Please try again."
+ : (char *)"This document requires a password.");
+ XtVaSetValues(passwordMsg, XmNlabelString, s, NULL);
+ XmStringFree(s);
+ XtManageChild(passwordDialog);
+ passwordDone = 0;
+ do {
+ XtAppNextEvent(app->getAppContext(), &event);
+ XtDispatchEvent(&event);
+ } while (!passwordDone);
+
+ if (passwordDone < 0) {
+ delete password;
+ password = NULL;
+ }
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cc b/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cc
deleted file mode 100644
index ecd149801..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cc
+++ /dev/null
@@ -1,84 +0,0 @@
-//========================================================================
-//
-// XPixmapOutputDev.cc
-//
-// Copyright 2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include "Object.h"
-#include "GfxState.h"
-#include "XPixmapOutputDev.h"
-
-//------------------------------------------------------------------------
-
-#define xoutRound(x) ((int)(x + 0.5))
-
-//------------------------------------------------------------------------
-
-XPixmapOutputDev::XPixmapOutputDev(Display *displayA, int screenNumA,
- Visual *visualA, Colormap colormapA,
- GBool reverseVideoA, Gulong paperColorA,
- GBool installCmapA, int rgbCubeSizeA,
- GBool incrementalUpdateA,
- void (*redrawCbkA)(void *data),
- void *redrawCbkDataA):
- XOutputDev(displayA, screenNumA, visualA, colormapA,
- reverseVideoA, paperColorA, installCmapA, rgbCubeSizeA)
-{
- incrementalUpdate = incrementalUpdateA;
- redrawCbk = redrawCbkA;
- redrawCbkData = redrawCbkDataA;
-}
-
-XPixmapOutputDev::~XPixmapOutputDev() {
- if (getPixmapWidth() > 0) {
- XFreePixmap(getDisplay(), getPixmap());
- }
-}
-
-void XPixmapOutputDev::clear() {
- startDoc(NULL);
- startPage(0, NULL);
-}
-
-void XPixmapOutputDev::startPage(int pageNum, GfxState *state) {
- int oldPixmapW, oldPixmapH, newPixmapW, newPixmapH;
-
- // resize the off-screen pixmap (if needed)
- oldPixmapW = getPixmapWidth();
- oldPixmapH = getPixmapHeight();
- newPixmapW = xoutRound(state ? state->getPageWidth() : 1);
- newPixmapH = xoutRound(state ? state->getPageHeight() : 1);
- if (oldPixmapW == 0 ||
- newPixmapW != oldPixmapW || newPixmapH != oldPixmapH) {
- if (oldPixmapW > 0) {
- XFreePixmap(getDisplay(), getPixmap());
- }
- setPixmap(XCreatePixmap(getDisplay(), win, newPixmapW, newPixmapH,
- getDepth()),
- newPixmapW, newPixmapH);
- }
-
- XOutputDev::startPage(pageNum, state);
-}
-
-void XPixmapOutputDev::endPage() {
- if (!incrementalUpdate) {
- (*redrawCbk)(redrawCbkData);
- }
- XOutputDev::endPage();
-}
-
-void XPixmapOutputDev::dump() {
- if (incrementalUpdate) {
- (*redrawCbk)(redrawCbkData);
- }
- XOutputDev::dump();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cpp b/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cpp
new file mode 100644
index 000000000..39fc474e2
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XPixmapOutputDev.cpp
@@ -0,0 +1,84 @@
+//========================================================================
+//
+// XPixmapOutputDev.cpp
+//
+// Copyright 2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include "Object.h"
+#include "GfxState.h"
+#include "XPixmapOutputDev.h"
+
+//------------------------------------------------------------------------
+
+#define xoutRound(x) ((int)(x + 0.5))
+
+//------------------------------------------------------------------------
+
+XPixmapOutputDev::XPixmapOutputDev(Display *displayA, int screenNumA,
+ Visual *visualA, Colormap colormapA,
+ GBool reverseVideoA, Gulong paperColorA,
+ GBool installCmapA, int rgbCubeSizeA,
+ GBool incrementalUpdateA,
+ void (*redrawCbkA)(void *data),
+ void *redrawCbkDataA):
+ XOutputDev(displayA, screenNumA, visualA, colormapA,
+ reverseVideoA, paperColorA, installCmapA, rgbCubeSizeA)
+{
+ incrementalUpdate = incrementalUpdateA;
+ redrawCbk = redrawCbkA;
+ redrawCbkData = redrawCbkDataA;
+}
+
+XPixmapOutputDev::~XPixmapOutputDev() {
+ if (getPixmapWidth() > 0) {
+ XFreePixmap(getDisplay(), getPixmap());
+ }
+}
+
+void XPixmapOutputDev::clear() {
+ startDoc(NULL);
+ startPage(0, NULL);
+}
+
+void XPixmapOutputDev::startPage(int pageNum, GfxState *state) {
+ int oldPixmapW, oldPixmapH, newPixmapW, newPixmapH;
+
+ // resize the off-screen pixmap (if needed)
+ oldPixmapW = getPixmapWidth();
+ oldPixmapH = getPixmapHeight();
+ newPixmapW = xoutRound(state ? state->getPageWidth() : 1);
+ newPixmapH = xoutRound(state ? state->getPageHeight() : 1);
+ if (oldPixmapW == 0 ||
+ newPixmapW != oldPixmapW || newPixmapH != oldPixmapH) {
+ if (oldPixmapW > 0) {
+ XFreePixmap(getDisplay(), getPixmap());
+ }
+ setPixmap(XCreatePixmap(getDisplay(), win, newPixmapW, newPixmapH,
+ getDepth()),
+ newPixmapW, newPixmapH);
+ }
+
+ XOutputDev::startPage(pageNum, state);
+}
+
+void XPixmapOutputDev::endPage() {
+ if (!incrementalUpdate) {
+ (*redrawCbk)(redrawCbkData);
+ }
+ XOutputDev::endPage();
+}
+
+void XPixmapOutputDev::dump() {
+ if (incrementalUpdate) {
+ (*redrawCbk)(redrawCbkData);
+ }
+ XOutputDev::dump();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/XRef.cc b/filters/kword/pdf/xpdf/xpdf/XRef.cc
deleted file mode 100644
index 0553b1595..000000000
--- a/filters/kword/pdf/xpdf/xpdf/XRef.cc
+++ /dev/null
@@ -1,693 +0,0 @@
-//========================================================================
-//
-// XRef.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-
-#ifdef USE_GCC_PRAGMAS
-#pragma implementation
-#endif
-
-#include <limits.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <ctype.h>
-#include "gmem.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Lexer.h"
-#include "Parser.h"
-#include "Dict.h"
-#ifndef NO_DECRYPTION
-#include "Decrypt.h"
-#endif
-#include "Error.h"
-#include "ErrorCodes.h"
-#include "XRef.h"
-
-//------------------------------------------------------------------------
-
-#define xrefSearchSize 1024 // read this many bytes at end of file
- // to look for 'startxref'
-
-#ifndef NO_DECRYPTION
-//------------------------------------------------------------------------
-// Permission bits
-//------------------------------------------------------------------------
-
-#define permPrint (1<<2)
-#define permChange (1<<3)
-#define permCopy (1<<4)
-#define permNotes (1<<5)
-#define defPermFlags 0xfffc
-#endif
-
-//------------------------------------------------------------------------
-// XRef
-//------------------------------------------------------------------------
-
-XRef::XRef(BaseStream *strA, GString *ownerPassword, GString *userPassword) {
- Guint pos;
- int i;
-
- ok = gTrue;
- errCode = errNone;
- size = 0;
- entries = NULL;
- streamEnds = NULL;
- streamEndsLen = 0;
-
- // read the trailer
- str = strA;
- start = str->getStart();
- pos = readTrailer();
-
- // if there was a problem with the trailer,
- // try to reconstruct the xref table
- if (pos == 0) {
- if (!(ok = constructXRef())) {
- errCode = errDamaged;
- return;
- }
-
- // trailer is ok - read the xref table
- } else {
- if ((unsigned) size >= INT_MAX / sizeof(XRefEntry)) {
- error(-1, "Invalid 'size' inside xref table.");
- ok = gFalse;
- errCode = errDamaged;
- return;
- }
- entries = (XRefEntry *)gmalloc(size * sizeof(XRefEntry));
- for (i = 0; i < size; ++i) {
- entries[i].offset = 0xffffffff;
- entries[i].used = gFalse;
- }
- while (readXRef(&pos)) ;
-
- // if there was a problem with the xref table,
- // try to reconstruct it
- if (!ok) {
- gfree(entries);
- size = 0;
- entries = NULL;
- if (!(ok = constructXRef())) {
- errCode = errDamaged;
- return;
- }
- }
- }
-
- // now set the trailer dictionary's xref pointer so we can fetch
- // indirect objects from it
- trailerDict.getDict()->setXRef(this);
-
- // check for encryption
-#ifndef NO_DECRYPTION
- encrypted = gFalse;
-#endif
- if (checkEncrypted(ownerPassword, userPassword)) {
- ok = gFalse;
- errCode = errEncrypted;
- return;
- }
-}
-
-XRef::~XRef() {
- gfree(entries);
- trailerDict.free();
- if (streamEnds) {
- gfree(streamEnds);
- }
-}
-
-// Read startxref position, xref table size, and root. Returns
-// first xref position.
-Guint XRef::readTrailer() {
- Parser *parser;
- Object obj;
- char buf[xrefSearchSize+1];
- int n;
- Guint pos, pos1;
- char *p;
- int c;
- int i;
-
- // read last xrefSearchSize bytes
- str->setPos(xrefSearchSize, -1);
- for (n = 0; n < xrefSearchSize; ++n) {
- if ((c = str->getChar()) == EOF)
- break;
- buf[n] = c;
- }
- buf[n] = '\0';
-
- // find startxref
- for (i = n - 9; i >= 0; --i) {
- if (!strncmp(&buf[i], "startxref", 9))
- break;
- }
- if (i < 0)
- return 0;
- for (p = &buf[i+9]; isspace(*p); ++p) ;
- pos = lastXRefPos = strToUnsigned(p);
-
- // find trailer dict by looking after first xref table
- // (NB: we can't just use the trailer dict at the end of the file --
- // this won't work for linearized files.)
- str->setPos(start + pos);
- for (i = 0; i < 4; ++i)
- buf[i] = str->getChar();
- if (strncmp(buf, "xref", 4))
- return 0;
- pos1 = pos + 4;
- while (1) {
- str->setPos(start + pos1);
- for (i = 0; i < 35; ++i) {
- if ((c = str->getChar()) == EOF)
- return 0;
- buf[i] = c;
- }
- if (!strncmp(buf, "trailer", 7))
- break;
- p = buf;
- while (isspace(*p)) ++p;
- while ('0' <= *p && *p <= '9') ++p;
- while (isspace(*p)) ++p;
- n = atoi(p);
- while ('0' <= *p && *p <= '9') ++p;
- while (isspace(*p)) ++p;
- if (p == buf)
- return 0;
- pos1 += (p - buf) + n * 20;
- }
- pos1 += 7;
-
- // read trailer dict
- obj.initNull();
- parser = new Parser(NULL,
- new Lexer(NULL,
- str->makeSubStream(start + pos1, gFalse, 0, &obj)));
- parser->getObj(&trailerDict);
- if (trailerDict.isDict()) {
- trailerDict.dictLookupNF("Size", &obj);
- if (obj.isInt())
- size = obj.getInt();
- else
- pos = 0;
- obj.free();
- trailerDict.dictLookupNF("Root", &obj);
- if (obj.isRef()) {
- rootNum = obj.getRefNum();
- rootGen = obj.getRefGen();
- } else {
- pos = 0;
- }
- obj.free();
- } else {
- pos = 0;
- }
- delete parser;
-
- // return first xref position
- return pos;
-}
-
-// Read an xref table and the prev pointer from the trailer.
-GBool XRef::readXRef(Guint *pos) {
- Parser *parser;
- Object obj, obj2;
- char s[20];
- GBool more;
- int first, newSize, n, i, j;
- int c;
-
- // seek to xref in stream
- str->setPos(start + *pos);
-
- // make sure it's an xref table
- while ((c = str->getChar()) != EOF && isspace(c)) ;
- s[0] = (char)c;
- s[1] = (char)str->getChar();
- s[2] = (char)str->getChar();
- s[3] = (char)str->getChar();
- if (!(s[0] == 'x' && s[1] == 'r' && s[2] == 'e' && s[3] == 'f')) {
- goto err2;
- }
-
- // read xref
- while (1) {
- while ((c = str->lookChar()) != EOF && isspace(c)) {
- str->getChar();
- }
- if (c == 't') {
- break;
- }
- for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i) {
- s[i] = (char)c;
- }
- if (i == 0) {
- goto err2;
- }
- s[i] = '\0';
- first = atoi(s);
- while ((c = str->lookChar()) != EOF && isspace(c)) {
- str->getChar();
- }
- for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i) {
- s[i] = (char)c;
- }
- if (i == 0) {
- goto err2;
- }
- s[i] = '\0';
- n = atoi(s);
- while ((c = str->lookChar()) != EOF && isspace(c)) {
- str->getChar();
- }
- // check for buggy PDF files with an incorrect (too small) xref
- // table size
- if (first + n > size) {
- newSize = size + 256;
- if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
- error(-1, "Invalid 'newSize'");
- goto err2;
- }
- entries = (XRefEntry *)grealloc(entries, newSize * sizeof(XRefEntry));
- for (i = size; i < newSize; ++i) {
- entries[i].offset = 0xffffffff;
- entries[i].used = gFalse;
- }
- size = newSize;
- }
- for (i = first; i < first + n; ++i) {
- for (j = 0; j < 20; ++j) {
- if ((c = str->getChar()) == EOF) {
- goto err2;
- }
- s[j] = (char)c;
- }
- if (entries[i].offset == 0xffffffff) {
- s[10] = '\0';
- entries[i].offset = strToUnsigned(s);
- s[16] = '\0';
- entries[i].gen = atoi(&s[11]);
- if (s[17] == 'n') {
- entries[i].used = gTrue;
- } else if (s[17] == 'f') {
- entries[i].used = gFalse;
- } else {
- goto err2;
- }
- // PDF files of patents from the IBM Intellectual Property
- // Network have a bug: the xref table claims to start at 1
- // instead of 0.
- if (i == 1 && first == 1 &&
- entries[1].offset == 0 && entries[1].gen == 65535 &&
- !entries[1].used) {
- i = first = 0;
- entries[0] = entries[1];
- entries[1].offset = 0xffffffff;
- }
- }
- }
- }
-
- // read prev pointer from trailer dictionary
- obj.initNull();
- parser = new Parser(NULL,
- new Lexer(NULL,
- str->makeSubStream(str->getPos(), gFalse, 0, &obj)));
- parser->getObj(&obj);
- if (!obj.isCmd("trailer")) {
- goto err1;
- }
- obj.free();
- parser->getObj(&obj);
- if (!obj.isDict()) {
- goto err1;
- }
- obj.getDict()->lookupNF("Prev", &obj2);
- if (obj2.isInt()) {
- *pos = (Guint)obj2.getInt();
- more = gTrue;
- } else {
- more = gFalse;
- }
- obj.free();
- obj2.free();
-
- delete parser;
- return more;
-
- err1:
- obj.free();
- err2:
- ok = gFalse;
- return gFalse;
-}
-
-// Attempt to construct an xref table for a damaged file.
-GBool XRef::constructXRef() {
- Parser *parser;
- Object obj;
- char buf[256];
- Guint pos;
- int num, gen;
- int newSize;
- int streamEndsSize;
- char *p;
- int i;
- GBool gotRoot;
-
- error(0, "PDF file is damaged - attempting to reconstruct xref table...");
- gotRoot = gFalse;
- streamEndsLen = streamEndsSize = 0;
-
- str->reset();
- while (1) {
- pos = str->getPos();
- if (!str->getLine(buf, 256)) {
- break;
- }
- p = buf;
-
- // got trailer dictionary
- if (!strncmp(p, "trailer", 7)) {
- obj.initNull();
- parser = new Parser(NULL,
- new Lexer(NULL,
- str->makeSubStream(start + pos + 7, gFalse, 0, &obj)));
- if (!trailerDict.isNone())
- trailerDict.free();
- parser->getObj(&trailerDict);
- if (trailerDict.isDict()) {
- trailerDict.dictLookupNF("Root", &obj);
- if (obj.isRef()) {
- rootNum = obj.getRefNum();
- rootGen = obj.getRefGen();
- gotRoot = gTrue;
- }
- obj.free();
- } else {
- pos = 0;
- }
- delete parser;
-
- // look for object
- } else if (isdigit(*p)) {
- num = atoi(p);
- do {
- ++p;
- } while (*p && isdigit(*p));
- if (isspace(*p)) {
- do {
- ++p;
- } while (*p && isspace(*p));
- if (isdigit(*p)) {
- gen = atoi(p);
- do {
- ++p;
- } while (*p && isdigit(*p));
- if (isspace(*p)) {
- do {
- ++p;
- } while (*p && isspace(*p));
- if (!strncmp(p, "obj", 3)) {
- if (num >= size) {
- newSize = (num + 1 + 255) & ~255;
- if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
- error(-1, "Invalid 'obj' parameters.");
- return gFalse;
- }
- entries = (XRefEntry *)
- grealloc(entries, newSize * sizeof(XRefEntry));
- for (i = size; i < newSize; ++i) {
- entries[i].offset = 0xffffffff;
- entries[i].used = gFalse;
- }
- size = newSize;
- }
- if (!entries[num].used || gen >= entries[num].gen) {
- entries[num].offset = pos - start;
- entries[num].gen = gen;
- entries[num].used = gTrue;
- }
- }
- }
- }
- }
-
- } else if (!strncmp(p, "endstream", 9)) {
- if (streamEndsLen == streamEndsSize) {
- streamEndsSize += 64;
- if ((unsigned) streamEndsSize >= INT_MAX / sizeof(int)) {
- error(-1, "Invalid 'endstream' parameter.");
- return gFalse;
- }
-
- streamEnds = (Guint *)grealloc(streamEnds,
- streamEndsSize * sizeof(int));
- }
- streamEnds[streamEndsLen++] = pos;
- }
- }
-
- if (gotRoot)
- return gTrue;
-
- error(-1, "Couldn't find trailer dictionary");
- return gFalse;
-}
-
-#ifndef NO_DECRYPTION
-GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
- Object encrypt, filterObj, versionObj, revisionObj, lengthObj;
- Object ownerKey, userKey, permissions, fileID, fileID1;
- GBool encrypted1;
- GBool ret;
-
- ret = gFalse;
-
- permFlags = defPermFlags;
- ownerPasswordOk = gFalse;
- trailerDict.dictLookup("Encrypt", &encrypt);
- if ((encrypted1 = encrypt.isDict())) {
- ret = gTrue;
- encrypt.dictLookup("Filter", &filterObj);
- if (filterObj.isName("Standard")) {
- encrypt.dictLookup("V", &versionObj);
- encrypt.dictLookup("R", &revisionObj);
- encrypt.dictLookup("Length", &lengthObj);
- encrypt.dictLookup("O", &ownerKey);
- encrypt.dictLookup("U", &userKey);
- encrypt.dictLookup("P", &permissions);
- trailerDict.dictLookup("ID", &fileID);
- if (versionObj.isInt() &&
- revisionObj.isInt() &&
- ownerKey.isString() && ownerKey.getString()->getLength() == 32 &&
- userKey.isString() && userKey.getString()->getLength() == 32 &&
- permissions.isInt() &&
- fileID.isArray()) {
- encVersion = versionObj.getInt();
- encRevision = revisionObj.getInt();
- if (lengthObj.isInt()) {
- keyLength = lengthObj.getInt() / 8;
- } else {
- keyLength = 5;
- }
- if (keyLength < 1) {
- keyLength = 1;
- }
- if (keyLength > 16) {
- keyLength = 16;
- }
- permFlags = permissions.getInt();
- if (encVersion >= 1 && encVersion <= 2 &&
- encRevision >= 2 && encRevision <= 3) {
- fileID.arrayGet(0, &fileID1);
- if (fileID1.isString()) {
- if (Decrypt::makeFileKey(encVersion, encRevision, keyLength,
- ownerKey.getString(), userKey.getString(),
- permFlags, fileID1.getString(),
- ownerPassword, userPassword, fileKey,
- &ownerPasswordOk)) {
- if (ownerPassword && !ownerPasswordOk) {
- error(-1, "Incorrect owner password");
- }
- ret = gFalse;
- } else {
- error(-1, "Incorrect password");
- }
- } else {
- error(-1, "Weird encryption info");
- }
- fileID1.free();
- } else {
- error(-1, "Unsupported version/revision (%d/%d) of Standard security handler",
- encVersion, encRevision);
- }
- } else {
- error(-1, "Weird encryption info");
- }
- fileID.free();
- permissions.free();
- userKey.free();
- ownerKey.free();
- lengthObj.free();
- revisionObj.free();
- versionObj.free();
- } else {
- error(-1, "Unknown security handler '%s'",
- filterObj.isName() ? filterObj.getName() : "???");
- }
- filterObj.free();
- }
- encrypt.free();
-
- // this flag has to be set *after* we read the O/U/P strings
- encrypted = encrypted1;
-
- return ret;
-}
-#else
-GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
- Object obj;
- GBool encrypted;
-
- trailerDict.dictLookup("Encrypt", &obj);
- if ((encrypted = !obj.isNull())) {
- error(-1, "PDF file is encrypted and this version of the Xpdf tools");
- error(-1, "was built without decryption support.");
- }
- obj.free();
- return encrypted;
-}
-#endif
-
-GBool XRef::okToPrint(GBool ignoreOwnerPW) {
-#ifndef NO_DECRYPTION
- if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permPrint)) {
- return gFalse;
- }
-#endif
- return gTrue;
-}
-
-GBool XRef::okToChange(GBool ignoreOwnerPW) {
-#ifndef NO_DECRYPTION
- if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permChange)) {
- return gFalse;
- }
-#endif
- return gTrue;
-}
-
-GBool XRef::okToCopy(GBool ignoreOwnerPW) {
-#ifndef NO_DECRYPTION
- if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permCopy)) {
- return gFalse;
- }
-#endif
- return gTrue;
-}
-
-GBool XRef::okToAddNotes(GBool ignoreOwnerPW) {
-#ifndef NO_DECRYPTION
- if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permNotes)) {
- return gFalse;
- }
-#endif
- return gTrue;
-}
-
-Object *XRef::fetch(int num, int gen, Object *obj) {
- XRefEntry *e;
- Parser *parser;
- Object obj1, obj2, obj3;
-
- // check for bogus ref - this can happen in corrupted PDF files
- if (num < 0 || num >= size) {
- obj->initNull();
- return obj;
- }
-
- e = &entries[num];
- if (e->gen == gen && e->offset != 0xffffffff) {
- obj1.initNull();
- parser = new Parser(this,
- new Lexer(this,
- str->makeSubStream(start + e->offset, gFalse, 0, &obj1)));
- parser->getObj(&obj1);
- parser->getObj(&obj2);
- parser->getObj(&obj3);
- if (obj1.isInt() && obj1.getInt() == num &&
- obj2.isInt() && obj2.getInt() == gen &&
- obj3.isCmd("obj")) {
-#ifndef NO_DECRYPTION
- parser->getObj(obj, encrypted ? fileKey : (Guchar *)NULL, keyLength,
- num, gen);
-#else
- parser->getObj(obj);
-#endif
- } else {
- obj->initNull();
- }
- obj1.free();
- obj2.free();
- obj3.free();
- delete parser;
- } else {
- obj->initNull();
- }
- return obj;
-}
-
-Object *XRef::getDocInfo(Object *obj) {
- return trailerDict.dictLookup("Info", obj);
-}
-
-// Added for the pdftex project.
-Object *XRef::getDocInfoNF(Object *obj) {
- return trailerDict.dictLookupNF("Info", obj);
-}
-
-GBool XRef::getStreamEnd(Guint streamStart, Guint *streamEnd) {
- int a, b, m;
-
- if (streamEndsLen == 0 ||
- streamStart > streamEnds[streamEndsLen - 1]) {
- return gFalse;
- }
-
- a = -1;
- b = streamEndsLen - 1;
- // invariant: streamEnds[a] < streamStart <= streamEnds[b]
- while (b - a > 1) {
- m = (a + b) / 2;
- if (streamStart <= streamEnds[m]) {
- b = m;
- } else {
- a = m;
- }
- }
- *streamEnd = streamEnds[b];
- return gTrue;
-}
-
-Guint XRef::strToUnsigned(char *s) {
- Guint x;
- char *p;
- int i;
-
- x = 0;
- for (p = s, i = 0; *p && isdigit(*p) && i < 10; ++p, ++i) {
- x = 10 * x + (*p - '0');
- }
- return x;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/XRef.cpp b/filters/kword/pdf/xpdf/xpdf/XRef.cpp
new file mode 100644
index 000000000..471d5c854
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/XRef.cpp
@@ -0,0 +1,693 @@
+//========================================================================
+//
+// XRef.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
+#pragma implementation
+#endif
+
+#include <limits.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <ctype.h>
+#include "gmem.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Lexer.h"
+#include "Parser.h"
+#include "Dict.h"
+#ifndef NO_DECRYPTION
+#include "Decrypt.h"
+#endif
+#include "Error.h"
+#include "ErrorCodes.h"
+#include "XRef.h"
+
+//------------------------------------------------------------------------
+
+#define xrefSearchSize 1024 // read this many bytes at end of file
+ // to look for 'startxref'
+
+#ifndef NO_DECRYPTION
+//------------------------------------------------------------------------
+// Permission bits
+//------------------------------------------------------------------------
+
+#define permPrint (1<<2)
+#define permChange (1<<3)
+#define permCopy (1<<4)
+#define permNotes (1<<5)
+#define defPermFlags 0xfffc
+#endif
+
+//------------------------------------------------------------------------
+// XRef
+//------------------------------------------------------------------------
+
+XRef::XRef(BaseStream *strA, GString *ownerPassword, GString *userPassword) {
+ Guint pos;
+ int i;
+
+ ok = gTrue;
+ errCode = errNone;
+ size = 0;
+ entries = NULL;
+ streamEnds = NULL;
+ streamEndsLen = 0;
+
+ // read the trailer
+ str = strA;
+ start = str->getStart();
+ pos = readTrailer();
+
+ // if there was a problem with the trailer,
+ // try to reconstruct the xref table
+ if (pos == 0) {
+ if (!(ok = constructXRef())) {
+ errCode = errDamaged;
+ return;
+ }
+
+ // trailer is ok - read the xref table
+ } else {
+ if ((unsigned) size >= INT_MAX / sizeof(XRefEntry)) {
+ error(-1, "Invalid 'size' inside xref table.");
+ ok = gFalse;
+ errCode = errDamaged;
+ return;
+ }
+ entries = (XRefEntry *)gmalloc(size * sizeof(XRefEntry));
+ for (i = 0; i < size; ++i) {
+ entries[i].offset = 0xffffffff;
+ entries[i].used = gFalse;
+ }
+ while (readXRef(&pos)) ;
+
+ // if there was a problem with the xref table,
+ // try to reconstruct it
+ if (!ok) {
+ gfree(entries);
+ size = 0;
+ entries = NULL;
+ if (!(ok = constructXRef())) {
+ errCode = errDamaged;
+ return;
+ }
+ }
+ }
+
+ // now set the trailer dictionary's xref pointer so we can fetch
+ // indirect objects from it
+ trailerDict.getDict()->setXRef(this);
+
+ // check for encryption
+#ifndef NO_DECRYPTION
+ encrypted = gFalse;
+#endif
+ if (checkEncrypted(ownerPassword, userPassword)) {
+ ok = gFalse;
+ errCode = errEncrypted;
+ return;
+ }
+}
+
+XRef::~XRef() {
+ gfree(entries);
+ trailerDict.free();
+ if (streamEnds) {
+ gfree(streamEnds);
+ }
+}
+
+// Read startxref position, xref table size, and root. Returns
+// first xref position.
+Guint XRef::readTrailer() {
+ Parser *parser;
+ Object obj;
+ char buf[xrefSearchSize+1];
+ int n;
+ Guint pos, pos1;
+ char *p;
+ int c;
+ int i;
+
+ // read last xrefSearchSize bytes
+ str->setPos(xrefSearchSize, -1);
+ for (n = 0; n < xrefSearchSize; ++n) {
+ if ((c = str->getChar()) == EOF)
+ break;
+ buf[n] = c;
+ }
+ buf[n] = '\0';
+
+ // find startxref
+ for (i = n - 9; i >= 0; --i) {
+ if (!strncmp(&buf[i], "startxref", 9))
+ break;
+ }
+ if (i < 0)
+ return 0;
+ for (p = &buf[i+9]; isspace(*p); ++p) ;
+ pos = lastXRefPos = strToUnsigned(p);
+
+ // find trailer dict by looking after first xref table
+ // (NB: we can't just use the trailer dict at the end of the file --
+ // this won't work for linearized files.)
+ str->setPos(start + pos);
+ for (i = 0; i < 4; ++i)
+ buf[i] = str->getChar();
+ if (strncmp(buf, "xref", 4))
+ return 0;
+ pos1 = pos + 4;
+ while (1) {
+ str->setPos(start + pos1);
+ for (i = 0; i < 35; ++i) {
+ if ((c = str->getChar()) == EOF)
+ return 0;
+ buf[i] = c;
+ }
+ if (!strncmp(buf, "trailer", 7))
+ break;
+ p = buf;
+ while (isspace(*p)) ++p;
+ while ('0' <= *p && *p <= '9') ++p;
+ while (isspace(*p)) ++p;
+ n = atoi(p);
+ while ('0' <= *p && *p <= '9') ++p;
+ while (isspace(*p)) ++p;
+ if (p == buf)
+ return 0;
+ pos1 += (p - buf) + n * 20;
+ }
+ pos1 += 7;
+
+ // read trailer dict
+ obj.initNull();
+ parser = new Parser(NULL,
+ new Lexer(NULL,
+ str->makeSubStream(start + pos1, gFalse, 0, &obj)));
+ parser->getObj(&trailerDict);
+ if (trailerDict.isDict()) {
+ trailerDict.dictLookupNF("Size", &obj);
+ if (obj.isInt())
+ size = obj.getInt();
+ else
+ pos = 0;
+ obj.free();
+ trailerDict.dictLookupNF("Root", &obj);
+ if (obj.isRef()) {
+ rootNum = obj.getRefNum();
+ rootGen = obj.getRefGen();
+ } else {
+ pos = 0;
+ }
+ obj.free();
+ } else {
+ pos = 0;
+ }
+ delete parser;
+
+ // return first xref position
+ return pos;
+}
+
+// Read an xref table and the prev pointer from the trailer.
+GBool XRef::readXRef(Guint *pos) {
+ Parser *parser;
+ Object obj, obj2;
+ char s[20];
+ GBool more;
+ int first, newSize, n, i, j;
+ int c;
+
+ // seek to xref in stream
+ str->setPos(start + *pos);
+
+ // make sure it's an xref table
+ while ((c = str->getChar()) != EOF && isspace(c)) ;
+ s[0] = (char)c;
+ s[1] = (char)str->getChar();
+ s[2] = (char)str->getChar();
+ s[3] = (char)str->getChar();
+ if (!(s[0] == 'x' && s[1] == 'r' && s[2] == 'e' && s[3] == 'f')) {
+ goto err2;
+ }
+
+ // read xref
+ while (1) {
+ while ((c = str->lookChar()) != EOF && isspace(c)) {
+ str->getChar();
+ }
+ if (c == 't') {
+ break;
+ }
+ for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i) {
+ s[i] = (char)c;
+ }
+ if (i == 0) {
+ goto err2;
+ }
+ s[i] = '\0';
+ first = atoi(s);
+ while ((c = str->lookChar()) != EOF && isspace(c)) {
+ str->getChar();
+ }
+ for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i) {
+ s[i] = (char)c;
+ }
+ if (i == 0) {
+ goto err2;
+ }
+ s[i] = '\0';
+ n = atoi(s);
+ while ((c = str->lookChar()) != EOF && isspace(c)) {
+ str->getChar();
+ }
+ // check for buggy PDF files with an incorrect (too small) xref
+ // table size
+ if (first + n > size) {
+ newSize = size + 256;
+ if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
+ error(-1, "Invalid 'newSize'");
+ goto err2;
+ }
+ entries = (XRefEntry *)grealloc(entries, newSize * sizeof(XRefEntry));
+ for (i = size; i < newSize; ++i) {
+ entries[i].offset = 0xffffffff;
+ entries[i].used = gFalse;
+ }
+ size = newSize;
+ }
+ for (i = first; i < first + n; ++i) {
+ for (j = 0; j < 20; ++j) {
+ if ((c = str->getChar()) == EOF) {
+ goto err2;
+ }
+ s[j] = (char)c;
+ }
+ if (entries[i].offset == 0xffffffff) {
+ s[10] = '\0';
+ entries[i].offset = strToUnsigned(s);
+ s[16] = '\0';
+ entries[i].gen = atoi(&s[11]);
+ if (s[17] == 'n') {
+ entries[i].used = gTrue;
+ } else if (s[17] == 'f') {
+ entries[i].used = gFalse;
+ } else {
+ goto err2;
+ }
+ // PDF files of patents from the IBM Intellectual Property
+ // Network have a bug: the xref table claims to start at 1
+ // instead of 0.
+ if (i == 1 && first == 1 &&
+ entries[1].offset == 0 && entries[1].gen == 65535 &&
+ !entries[1].used) {
+ i = first = 0;
+ entries[0] = entries[1];
+ entries[1].offset = 0xffffffff;
+ }
+ }
+ }
+ }
+
+ // read prev pointer from trailer dictionary
+ obj.initNull();
+ parser = new Parser(NULL,
+ new Lexer(NULL,
+ str->makeSubStream(str->getPos(), gFalse, 0, &obj)));
+ parser->getObj(&obj);
+ if (!obj.isCmd("trailer")) {
+ goto err1;
+ }
+ obj.free();
+ parser->getObj(&obj);
+ if (!obj.isDict()) {
+ goto err1;
+ }
+ obj.getDict()->lookupNF("Prev", &obj2);
+ if (obj2.isInt()) {
+ *pos = (Guint)obj2.getInt();
+ more = gTrue;
+ } else {
+ more = gFalse;
+ }
+ obj.free();
+ obj2.free();
+
+ delete parser;
+ return more;
+
+ err1:
+ obj.free();
+ err2:
+ ok = gFalse;
+ return gFalse;
+}
+
+// Attempt to construct an xref table for a damaged file.
+GBool XRef::constructXRef() {
+ Parser *parser;
+ Object obj;
+ char buf[256];
+ Guint pos;
+ int num, gen;
+ int newSize;
+ int streamEndsSize;
+ char *p;
+ int i;
+ GBool gotRoot;
+
+ error(0, "PDF file is damaged - attempting to reconstruct xref table...");
+ gotRoot = gFalse;
+ streamEndsLen = streamEndsSize = 0;
+
+ str->reset();
+ while (1) {
+ pos = str->getPos();
+ if (!str->getLine(buf, 256)) {
+ break;
+ }
+ p = buf;
+
+ // got trailer dictionary
+ if (!strncmp(p, "trailer", 7)) {
+ obj.initNull();
+ parser = new Parser(NULL,
+ new Lexer(NULL,
+ str->makeSubStream(start + pos + 7, gFalse, 0, &obj)));
+ if (!trailerDict.isNone())
+ trailerDict.free();
+ parser->getObj(&trailerDict);
+ if (trailerDict.isDict()) {
+ trailerDict.dictLookupNF("Root", &obj);
+ if (obj.isRef()) {
+ rootNum = obj.getRefNum();
+ rootGen = obj.getRefGen();
+ gotRoot = gTrue;
+ }
+ obj.free();
+ } else {
+ pos = 0;
+ }
+ delete parser;
+
+ // look for object
+ } else if (isdigit(*p)) {
+ num = atoi(p);
+ do {
+ ++p;
+ } while (*p && isdigit(*p));
+ if (isspace(*p)) {
+ do {
+ ++p;
+ } while (*p && isspace(*p));
+ if (isdigit(*p)) {
+ gen = atoi(p);
+ do {
+ ++p;
+ } while (*p && isdigit(*p));
+ if (isspace(*p)) {
+ do {
+ ++p;
+ } while (*p && isspace(*p));
+ if (!strncmp(p, "obj", 3)) {
+ if (num >= size) {
+ newSize = (num + 1 + 255) & ~255;
+ if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
+ error(-1, "Invalid 'obj' parameters.");
+ return gFalse;
+ }
+ entries = (XRefEntry *)
+ grealloc(entries, newSize * sizeof(XRefEntry));
+ for (i = size; i < newSize; ++i) {
+ entries[i].offset = 0xffffffff;
+ entries[i].used = gFalse;
+ }
+ size = newSize;
+ }
+ if (!entries[num].used || gen >= entries[num].gen) {
+ entries[num].offset = pos - start;
+ entries[num].gen = gen;
+ entries[num].used = gTrue;
+ }
+ }
+ }
+ }
+ }
+
+ } else if (!strncmp(p, "endstream", 9)) {
+ if (streamEndsLen == streamEndsSize) {
+ streamEndsSize += 64;
+ if ((unsigned) streamEndsSize >= INT_MAX / sizeof(int)) {
+ error(-1, "Invalid 'endstream' parameter.");
+ return gFalse;
+ }
+
+ streamEnds = (Guint *)grealloc(streamEnds,
+ streamEndsSize * sizeof(int));
+ }
+ streamEnds[streamEndsLen++] = pos;
+ }
+ }
+
+ if (gotRoot)
+ return gTrue;
+
+ error(-1, "Couldn't find trailer dictionary");
+ return gFalse;
+}
+
+#ifndef NO_DECRYPTION
+GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
+ Object encrypt, filterObj, versionObj, revisionObj, lengthObj;
+ Object ownerKey, userKey, permissions, fileID, fileID1;
+ GBool encrypted1;
+ GBool ret;
+
+ ret = gFalse;
+
+ permFlags = defPermFlags;
+ ownerPasswordOk = gFalse;
+ trailerDict.dictLookup("Encrypt", &encrypt);
+ if ((encrypted1 = encrypt.isDict())) {
+ ret = gTrue;
+ encrypt.dictLookup("Filter", &filterObj);
+ if (filterObj.isName("Standard")) {
+ encrypt.dictLookup("V", &versionObj);
+ encrypt.dictLookup("R", &revisionObj);
+ encrypt.dictLookup("Length", &lengthObj);
+ encrypt.dictLookup("O", &ownerKey);
+ encrypt.dictLookup("U", &userKey);
+ encrypt.dictLookup("P", &permissions);
+ trailerDict.dictLookup("ID", &fileID);
+ if (versionObj.isInt() &&
+ revisionObj.isInt() &&
+ ownerKey.isString() && ownerKey.getString()->getLength() == 32 &&
+ userKey.isString() && userKey.getString()->getLength() == 32 &&
+ permissions.isInt() &&
+ fileID.isArray()) {
+ encVersion = versionObj.getInt();
+ encRevision = revisionObj.getInt();
+ if (lengthObj.isInt()) {
+ keyLength = lengthObj.getInt() / 8;
+ } else {
+ keyLength = 5;
+ }
+ if (keyLength < 1) {
+ keyLength = 1;
+ }
+ if (keyLength > 16) {
+ keyLength = 16;
+ }
+ permFlags = permissions.getInt();
+ if (encVersion >= 1 && encVersion <= 2 &&
+ encRevision >= 2 && encRevision <= 3) {
+ fileID.arrayGet(0, &fileID1);
+ if (fileID1.isString()) {
+ if (Decrypt::makeFileKey(encVersion, encRevision, keyLength,
+ ownerKey.getString(), userKey.getString(),
+ permFlags, fileID1.getString(),
+ ownerPassword, userPassword, fileKey,
+ &ownerPasswordOk)) {
+ if (ownerPassword && !ownerPasswordOk) {
+ error(-1, "Incorrect owner password");
+ }
+ ret = gFalse;
+ } else {
+ error(-1, "Incorrect password");
+ }
+ } else {
+ error(-1, "Weird encryption info");
+ }
+ fileID1.free();
+ } else {
+ error(-1, "Unsupported version/revision (%d/%d) of Standard security handler",
+ encVersion, encRevision);
+ }
+ } else {
+ error(-1, "Weird encryption info");
+ }
+ fileID.free();
+ permissions.free();
+ userKey.free();
+ ownerKey.free();
+ lengthObj.free();
+ revisionObj.free();
+ versionObj.free();
+ } else {
+ error(-1, "Unknown security handler '%s'",
+ filterObj.isName() ? filterObj.getName() : "???");
+ }
+ filterObj.free();
+ }
+ encrypt.free();
+
+ // this flag has to be set *after* we read the O/U/P strings
+ encrypted = encrypted1;
+
+ return ret;
+}
+#else
+GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
+ Object obj;
+ GBool encrypted;
+
+ trailerDict.dictLookup("Encrypt", &obj);
+ if ((encrypted = !obj.isNull())) {
+ error(-1, "PDF file is encrypted and this version of the Xpdf tools");
+ error(-1, "was built without decryption support.");
+ }
+ obj.free();
+ return encrypted;
+}
+#endif
+
+GBool XRef::okToPrint(GBool ignoreOwnerPW) {
+#ifndef NO_DECRYPTION
+ if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permPrint)) {
+ return gFalse;
+ }
+#endif
+ return gTrue;
+}
+
+GBool XRef::okToChange(GBool ignoreOwnerPW) {
+#ifndef NO_DECRYPTION
+ if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permChange)) {
+ return gFalse;
+ }
+#endif
+ return gTrue;
+}
+
+GBool XRef::okToCopy(GBool ignoreOwnerPW) {
+#ifndef NO_DECRYPTION
+ if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permCopy)) {
+ return gFalse;
+ }
+#endif
+ return gTrue;
+}
+
+GBool XRef::okToAddNotes(GBool ignoreOwnerPW) {
+#ifndef NO_DECRYPTION
+ if ((ignoreOwnerPW || !ownerPasswordOk) && !(permFlags & permNotes)) {
+ return gFalse;
+ }
+#endif
+ return gTrue;
+}
+
+Object *XRef::fetch(int num, int gen, Object *obj) {
+ XRefEntry *e;
+ Parser *parser;
+ Object obj1, obj2, obj3;
+
+ // check for bogus ref - this can happen in corrupted PDF files
+ if (num < 0 || num >= size) {
+ obj->initNull();
+ return obj;
+ }
+
+ e = &entries[num];
+ if (e->gen == gen && e->offset != 0xffffffff) {
+ obj1.initNull();
+ parser = new Parser(this,
+ new Lexer(this,
+ str->makeSubStream(start + e->offset, gFalse, 0, &obj1)));
+ parser->getObj(&obj1);
+ parser->getObj(&obj2);
+ parser->getObj(&obj3);
+ if (obj1.isInt() && obj1.getInt() == num &&
+ obj2.isInt() && obj2.getInt() == gen &&
+ obj3.isCmd("obj")) {
+#ifndef NO_DECRYPTION
+ parser->getObj(obj, encrypted ? fileKey : (Guchar *)NULL, keyLength,
+ num, gen);
+#else
+ parser->getObj(obj);
+#endif
+ } else {
+ obj->initNull();
+ }
+ obj1.free();
+ obj2.free();
+ obj3.free();
+ delete parser;
+ } else {
+ obj->initNull();
+ }
+ return obj;
+}
+
+Object *XRef::getDocInfo(Object *obj) {
+ return trailerDict.dictLookup("Info", obj);
+}
+
+// Added for the pdftex project.
+Object *XRef::getDocInfoNF(Object *obj) {
+ return trailerDict.dictLookupNF("Info", obj);
+}
+
+GBool XRef::getStreamEnd(Guint streamStart, Guint *streamEnd) {
+ int a, b, m;
+
+ if (streamEndsLen == 0 ||
+ streamStart > streamEnds[streamEndsLen - 1]) {
+ return gFalse;
+ }
+
+ a = -1;
+ b = streamEndsLen - 1;
+ // invariant: streamEnds[a] < streamStart <= streamEnds[b]
+ while (b - a > 1) {
+ m = (a + b) / 2;
+ if (streamStart <= streamEnds[m]) {
+ b = m;
+ } else {
+ a = m;
+ }
+ }
+ *streamEnd = streamEnds[b];
+ return gTrue;
+}
+
+Guint XRef::strToUnsigned(char *s) {
+ Guint x;
+ char *p;
+ int i;
+
+ x = 0;
+ for (p = s, i = 0; *p && isdigit(*p) && i < 10; ++p, ++i) {
+ x = 10 * x + (*p - '0');
+ }
+ return x;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdffonts.cc b/filters/kword/pdf/xpdf/xpdf/pdffonts.cc
deleted file mode 100644
index fcb739a20..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdffonts.cc
+++ /dev/null
@@ -1,281 +0,0 @@
-//========================================================================
-//
-// pdffonts.cc
-//
-// Copyright 2001-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <math.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Error.h"
-#include "Object.h"
-#include "Dict.h"
-#include "GfxFont.h"
-#include "Annot.h"
-#include "PDFDoc.h"
-#include "config.h"
-
-static char *fontTypeNames[] = {
- "unknown",
- "Type 1",
- "Type 1C",
- "Type 3",
- "TrueType",
- "CID Type 0",
- "CID Type 0C",
- "CID TrueType"
-};
-
-static void scanFonts(Dict *resDict, PDFDoc *doc);
-static void scanFont(GfxFont *font, PDFDoc *doc);
-
-static int firstPage = 1;
-static int lastPage = 0;
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-f", argInt, &firstPage, 0,
- "first page to examine"},
- {"-l", argInt, &lastPage, 0,
- "last page to examine"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-static Ref *fonts;
-static int fontsLen;
-static int fontsSize;
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- GString *ownerPW, *userPW;
- GBool ok;
- Page *page;
- Dict *resDict;
- Annots *annots;
- Object obj1, obj2;
- int pg, i;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc != 2 || printVersion || printHelp) {
- fprintf(stderr, "pdfinfo version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdfinfo", "<PDF-file>", argDesc);
- }
- goto err0;
- }
- fileName = new GString(argv[1]);
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err1;
- }
-
- // get page range
- if (firstPage < 1) {
- firstPage = 1;
- }
- if (lastPage < 1 || lastPage > doc->getNumPages()) {
- lastPage = doc->getNumPages();
- }
-
- // scan the fonts
- printf("name type emb sub uni object ID\n");
- printf("------------------------------------ ------------ --- --- --- ---------\n");
- fonts = NULL;
- fontsLen = fontsSize = 0;
- for (pg = firstPage; pg <= lastPage; ++pg) {
- page = doc->getCatalog()->getPage(pg);
- if ((resDict = page->getResourceDict())) {
- scanFonts(resDict, doc);
- }
- annots = new Annots(doc->getXRef(), page->getAnnots(&obj1));
- obj1.free();
- for (i = 0; i < annots->getNumAnnots(); ++i) {
- if (annots->getAnnot(i)->getAppearance(&obj1)->isStream()) {
- obj1.streamGetDict()->lookup("Resources", &obj2);
- if (obj2.isDict()) {
- scanFonts(obj2.getDict(), doc);
- }
- obj2.free();
- }
- obj1.free();
- }
- delete annots;
- }
-
- exitCode = 0;
-
- // clean up
- gfree(fonts);
- err1:
- delete doc;
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
-
-static void scanFonts(Dict *resDict, PDFDoc *doc) {
- GfxFontDict *gfxFontDict;
- GfxFont *font;
- Object fontDict, xObjDict, xObj, resObj;
- int i;
-
- // scan the fonts in this resource dictionary
- resDict->lookup("Font", &fontDict);
- if (fontDict.isDict()) {
- gfxFontDict = new GfxFontDict(doc->getXRef(), fontDict.getDict());
- for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
- font = gfxFontDict->getFont(i);
- scanFont(font, doc);
- }
- delete gfxFontDict;
- }
- fontDict.free();
-
- // recursively scan any resource dictionaries in objects in this
- // resource dictionary
- resDict->lookup("XObject", &xObjDict);
- if (xObjDict.isDict()) {
- for (i = 0; i < xObjDict.dictGetLength(); ++i) {
- xObjDict.dictGetVal(i, &xObj);
- if (xObj.isStream()) {
- xObj.streamGetDict()->lookup("Resources", &resObj);
- if (resObj.isDict()) {
- scanFonts(resObj.getDict(), doc);
- }
- resObj.free();
- }
- xObj.free();
- }
- }
- xObjDict.free();
-}
-
-static void scanFont(GfxFont *font, PDFDoc *doc) {
- Ref fontRef, embRef;
- Object fontObj, nameObj, toUnicodeObj;
- GString *name;
- GBool subset, hasToUnicode;
- int i;
-
- fontRef = *font->getID();
-
- // check for an already-seen font
- for (i = 0; i < fontsLen; ++i) {
- if (fontRef.num == fonts[i].num && fontRef.gen == fonts[i].gen) {
- return;
- }
- }
-
- // get the original font name -- the GfxFont class munges substitute
- // Base-14 font names into proper form, so this code grabs the
- // original name from the font dictionary; also look for a ToUnicode
- // map
- name = NULL;
- hasToUnicode = gFalse;
- if (doc->getXRef()->fetch(fontRef.num, fontRef.gen, &fontObj)->isDict()) {
- if (fontObj.dictLookup("BaseFont", &nameObj)->isName()) {
- name = new GString(nameObj.getName());
- }
- nameObj.free();
- hasToUnicode = fontObj.dictLookup("ToUnicode", &toUnicodeObj)->isStream();
- toUnicodeObj.free();
- }
- fontObj.free();
-
- // check for a font subset name: capital letters followed by a '+'
- // sign
- subset = gFalse;
- if (name) {
- for (i = 0; i < name->getLength(); ++i) {
- if (name->getChar(i) < 'A' || name->getChar(i) > 'Z') {
- break;
- }
- }
- subset = i > 0 && i < name->getLength() && name->getChar(i) == '+';
- }
-
- // print the font info
- printf("%-36s %-12s %-3s %-3s %-3s",
- name ? name->getCString() : "[none]",
- fontTypeNames[font->getType()],
- font->getEmbeddedFontID(&embRef) ? "yes" : "no",
- subset ? "yes" : "no",
- hasToUnicode ? "yes" : "no");
- if (fontRef.gen == 999999) {
- printf(" [none]\n");
- } else {
- printf(" %6d %2d\n", fontRef.num, fontRef.gen);
- }
- if (name) {
- delete name;
- }
-
- // add this font to the list
- if (fontsLen == fontsSize) {
- fontsSize += 32;
- fonts = (Ref *)grealloc(fonts, fontsSize * sizeof(Ref));
- }
- fonts[fontsLen++] = *font->getID();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdffonts.cpp b/filters/kword/pdf/xpdf/xpdf/pdffonts.cpp
new file mode 100644
index 000000000..831e773ca
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdffonts.cpp
@@ -0,0 +1,281 @@
+//========================================================================
+//
+// pdffonts.cpp
+//
+// Copyright 2001-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <math.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Error.h"
+#include "Object.h"
+#include "Dict.h"
+#include "GfxFont.h"
+#include "Annot.h"
+#include "PDFDoc.h"
+#include "config.h"
+
+static char *fontTypeNames[] = {
+ "unknown",
+ "Type 1",
+ "Type 1C",
+ "Type 3",
+ "TrueType",
+ "CID Type 0",
+ "CID Type 0C",
+ "CID TrueType"
+};
+
+static void scanFonts(Dict *resDict, PDFDoc *doc);
+static void scanFont(GfxFont *font, PDFDoc *doc);
+
+static int firstPage = 1;
+static int lastPage = 0;
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-f", argInt, &firstPage, 0,
+ "first page to examine"},
+ {"-l", argInt, &lastPage, 0,
+ "last page to examine"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+static Ref *fonts;
+static int fontsLen;
+static int fontsSize;
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ GString *ownerPW, *userPW;
+ GBool ok;
+ Page *page;
+ Dict *resDict;
+ Annots *annots;
+ Object obj1, obj2;
+ int pg, i;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc != 2 || printVersion || printHelp) {
+ fprintf(stderr, "pdfinfo version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdfinfo", "<PDF-file>", argDesc);
+ }
+ goto err0;
+ }
+ fileName = new GString(argv[1]);
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err1;
+ }
+
+ // get page range
+ if (firstPage < 1) {
+ firstPage = 1;
+ }
+ if (lastPage < 1 || lastPage > doc->getNumPages()) {
+ lastPage = doc->getNumPages();
+ }
+
+ // scan the fonts
+ printf("name type emb sub uni object ID\n");
+ printf("------------------------------------ ------------ --- --- --- ---------\n");
+ fonts = NULL;
+ fontsLen = fontsSize = 0;
+ for (pg = firstPage; pg <= lastPage; ++pg) {
+ page = doc->getCatalog()->getPage(pg);
+ if ((resDict = page->getResourceDict())) {
+ scanFonts(resDict, doc);
+ }
+ annots = new Annots(doc->getXRef(), page->getAnnots(&obj1));
+ obj1.free();
+ for (i = 0; i < annots->getNumAnnots(); ++i) {
+ if (annots->getAnnot(i)->getAppearance(&obj1)->isStream()) {
+ obj1.streamGetDict()->lookup("Resources", &obj2);
+ if (obj2.isDict()) {
+ scanFonts(obj2.getDict(), doc);
+ }
+ obj2.free();
+ }
+ obj1.free();
+ }
+ delete annots;
+ }
+
+ exitCode = 0;
+
+ // clean up
+ gfree(fonts);
+ err1:
+ delete doc;
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
+
+static void scanFonts(Dict *resDict, PDFDoc *doc) {
+ GfxFontDict *gfxFontDict;
+ GfxFont *font;
+ Object fontDict, xObjDict, xObj, resObj;
+ int i;
+
+ // scan the fonts in this resource dictionary
+ resDict->lookup("Font", &fontDict);
+ if (fontDict.isDict()) {
+ gfxFontDict = new GfxFontDict(doc->getXRef(), fontDict.getDict());
+ for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
+ font = gfxFontDict->getFont(i);
+ scanFont(font, doc);
+ }
+ delete gfxFontDict;
+ }
+ fontDict.free();
+
+ // recursively scan any resource dictionaries in objects in this
+ // resource dictionary
+ resDict->lookup("XObject", &xObjDict);
+ if (xObjDict.isDict()) {
+ for (i = 0; i < xObjDict.dictGetLength(); ++i) {
+ xObjDict.dictGetVal(i, &xObj);
+ if (xObj.isStream()) {
+ xObj.streamGetDict()->lookup("Resources", &resObj);
+ if (resObj.isDict()) {
+ scanFonts(resObj.getDict(), doc);
+ }
+ resObj.free();
+ }
+ xObj.free();
+ }
+ }
+ xObjDict.free();
+}
+
+static void scanFont(GfxFont *font, PDFDoc *doc) {
+ Ref fontRef, embRef;
+ Object fontObj, nameObj, toUnicodeObj;
+ GString *name;
+ GBool subset, hasToUnicode;
+ int i;
+
+ fontRef = *font->getID();
+
+ // check for an already-seen font
+ for (i = 0; i < fontsLen; ++i) {
+ if (fontRef.num == fonts[i].num && fontRef.gen == fonts[i].gen) {
+ return;
+ }
+ }
+
+ // get the original font name -- the GfxFont class munges substitute
+ // Base-14 font names into proper form, so this code grabs the
+ // original name from the font dictionary; also look for a ToUnicode
+ // map
+ name = NULL;
+ hasToUnicode = gFalse;
+ if (doc->getXRef()->fetch(fontRef.num, fontRef.gen, &fontObj)->isDict()) {
+ if (fontObj.dictLookup("BaseFont", &nameObj)->isName()) {
+ name = new GString(nameObj.getName());
+ }
+ nameObj.free();
+ hasToUnicode = fontObj.dictLookup("ToUnicode", &toUnicodeObj)->isStream();
+ toUnicodeObj.free();
+ }
+ fontObj.free();
+
+ // check for a font subset name: capital letters followed by a '+'
+ // sign
+ subset = gFalse;
+ if (name) {
+ for (i = 0; i < name->getLength(); ++i) {
+ if (name->getChar(i) < 'A' || name->getChar(i) > 'Z') {
+ break;
+ }
+ }
+ subset = i > 0 && i < name->getLength() && name->getChar(i) == '+';
+ }
+
+ // print the font info
+ printf("%-36s %-12s %-3s %-3s %-3s",
+ name ? name->getCString() : "[none]",
+ fontTypeNames[font->getType()],
+ font->getEmbeddedFontID(&embRef) ? "yes" : "no",
+ subset ? "yes" : "no",
+ hasToUnicode ? "yes" : "no");
+ if (fontRef.gen == 999999) {
+ printf(" [none]\n");
+ } else {
+ printf(" %6d %2d\n", fontRef.num, fontRef.gen);
+ }
+ if (name) {
+ delete name;
+ }
+
+ // add this font to the list
+ if (fontsLen == fontsSize) {
+ fontsSize += 32;
+ fonts = (Ref *)grealloc(fonts, fontsSize * sizeof(Ref));
+ }
+ fonts[fontsLen++] = *font->getID();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdfimages.cc b/filters/kword/pdf/xpdf/xpdf/pdfimages.cc
deleted file mode 100644
index 5e35bfb48..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdfimages.cc
+++ /dev/null
@@ -1,154 +0,0 @@
-//========================================================================
-//
-// pdfimages.cc
-//
-// Copyright 1998-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "PDFDoc.h"
-#include "ImageOutputDev.h"
-#include "Error.h"
-#include "config.h"
-
-static int firstPage = 1;
-static int lastPage = 0;
-static GBool dumpJPEG = gFalse;
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static GBool quiet = gFalse;
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-f", argInt, &firstPage, 0,
- "first page to convert"},
- {"-l", argInt, &lastPage, 0,
- "last page to convert"},
- {"-j", argFlag, &dumpJPEG, 0,
- "write JPEG images as JPEG files"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-q", argFlag, &quiet, 0,
- "don't print any messages or errors"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- char *imgRoot;
- GString *ownerPW, *userPW;
- ImageOutputDev *imgOut;
- GBool ok;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc != 3 || printVersion || printHelp) {
- fprintf(stderr, "pdfimages version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdfimages", "<PDF-file> <image-root>", argDesc);
- }
- goto err0;
- }
- fileName = new GString(argv[1]);
- imgRoot = argv[2];
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (quiet) {
- globalParams->setErrQuiet(quiet);
- }
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err1;
- }
-
- // check for copy permission
- if (!doc->okToCopy()) {
- error(-1, "Copying of images from this document is not allowed.");
- exitCode = 3;
- goto err1;
- }
-
- // get page range
- if (firstPage < 1)
- firstPage = 1;
- if (lastPage < 1 || lastPage > doc->getNumPages())
- lastPage = doc->getNumPages();
-
- // write image files
- imgOut = new ImageOutputDev(imgRoot, dumpJPEG);
- if (imgOut->isOk()) {
- doc->displayPages(imgOut, firstPage, lastPage, 72, 0, gFalse);
- }
- delete imgOut;
-
- exitCode = 0;
-
- // clean up
- err1:
- delete doc;
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdfimages.cpp b/filters/kword/pdf/xpdf/xpdf/pdfimages.cpp
new file mode 100644
index 000000000..c2f4bf804
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdfimages.cpp
@@ -0,0 +1,154 @@
+//========================================================================
+//
+// pdfimages.cpp
+//
+// Copyright 1998-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "ImageOutputDev.h"
+#include "Error.h"
+#include "config.h"
+
+static int firstPage = 1;
+static int lastPage = 0;
+static GBool dumpJPEG = gFalse;
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool quiet = gFalse;
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-f", argInt, &firstPage, 0,
+ "first page to convert"},
+ {"-l", argInt, &lastPage, 0,
+ "last page to convert"},
+ {"-j", argFlag, &dumpJPEG, 0,
+ "write JPEG images as JPEG files"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-q", argFlag, &quiet, 0,
+ "don't print any messages or errors"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ char *imgRoot;
+ GString *ownerPW, *userPW;
+ ImageOutputDev *imgOut;
+ GBool ok;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc != 3 || printVersion || printHelp) {
+ fprintf(stderr, "pdfimages version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdfimages", "<PDF-file> <image-root>", argDesc);
+ }
+ goto err0;
+ }
+ fileName = new GString(argv[1]);
+ imgRoot = argv[2];
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (quiet) {
+ globalParams->setErrQuiet(quiet);
+ }
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err1;
+ }
+
+ // check for copy permission
+ if (!doc->okToCopy()) {
+ error(-1, "Copying of images from this document is not allowed.");
+ exitCode = 3;
+ goto err1;
+ }
+
+ // get page range
+ if (firstPage < 1)
+ firstPage = 1;
+ if (lastPage < 1 || lastPage > doc->getNumPages())
+ lastPage = doc->getNumPages();
+
+ // write image files
+ imgOut = new ImageOutputDev(imgRoot, dumpJPEG);
+ if (imgOut->isOk()) {
+ doc->displayPages(imgOut, firstPage, lastPage, 72, 0, gFalse);
+ }
+ delete imgOut;
+
+ exitCode = 0;
+
+ // clean up
+ err1:
+ delete doc;
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdfinfo.cc b/filters/kword/pdf/xpdf/xpdf/pdfinfo.cc
deleted file mode 100644
index 43bf38afb..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdfinfo.cc
+++ /dev/null
@@ -1,304 +0,0 @@
-//========================================================================
-//
-// pdfinfo.cc
-//
-// Copyright 1998-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include <time.h>
-#include <math.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "PDFDoc.h"
-#include "CharTypes.h"
-#include "UnicodeMap.h"
-#include "Error.h"
-#include "config.h"
-
-static void printInfoString(Dict *infoDict, char *key, char *text,
- UnicodeMap *uMap);
-static void printInfoDate(Dict *infoDict, char *key, char *text);
-
-static GBool printMetadata = gFalse;
-static char textEncName[128] = "";
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-meta", argFlag, &printMetadata, 0,
- "print the document metadata (XML)"},
- {"-enc", argString, textEncName, sizeof(textEncName),
- "output text encoding name"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- GString *ownerPW, *userPW;
- UnicodeMap *uMap;
- Object info;
- double w, h;
- FILE *f;
- GString *metadata;
- GBool ok;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc != 2 || printVersion || printHelp) {
- fprintf(stderr, "pdfinfo version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdfinfo", "<PDF-file>", argDesc);
- }
- goto err0;
- }
- fileName = new GString(argv[1]);
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (textEncName[0]) {
- globalParams->setTextEncoding(textEncName);
- }
-
- // get mapping to output encoding
- if (!(uMap = globalParams->getTextEncoding())) {
- error(-1, "Couldn't get text encoding");
- delete fileName;
- goto err1;
- }
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err2;
- }
-
- // print doc info
- doc->getDocInfo(&info);
- if (info.isDict()) {
- printInfoString(info.getDict(), "Title", "Title: ", uMap);
- printInfoString(info.getDict(), "Subject", "Subject: ", uMap);
- printInfoString(info.getDict(), "Keywords", "Keywords: ", uMap);
- printInfoString(info.getDict(), "Author", "Author: ", uMap);
- printInfoString(info.getDict(), "Creator", "Creator: ", uMap);
- printInfoString(info.getDict(), "Producer", "Producer: ", uMap);
- printInfoDate(info.getDict(), "CreationDate", "CreationDate: ");
- printInfoDate(info.getDict(), "ModDate", "ModDate: ");
- }
- info.free();
-
- // print tagging info
- printf("Tagged: %s\n",
- doc->getStructTreeRoot()->isDict() ? "yes" : "no");
-
- // print page count
- printf("Pages: %d\n", doc->getNumPages());
-
- // print encryption info
- printf("Encrypted: ");
- if (doc->isEncrypted()) {
- printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
- doc->okToPrint(gTrue) ? "yes" : "no",
- doc->okToCopy(gTrue) ? "yes" : "no",
- doc->okToChange(gTrue) ? "yes" : "no",
- doc->okToAddNotes(gTrue) ? "yes" : "no");
- } else {
- printf("no\n");
- }
-
- // print page size
- if (doc->getNumPages() >= 1) {
- w = doc->getPageWidth(1);
- h = doc->getPageHeight(1);
- printf("Page size: %g x %g pts", w, h);
- if ((fabs(w - 612) < 0.1 && fabs(h - 792) < 0.1) ||
- (fabs(w - 792) < 0.1 && fabs(h - 612) < 0.1)) {
- printf(" (letter)");
- } else if ((fabs(w - 595) < 0.1 && fabs(h - 842) < 0.1) ||
- (fabs(w - 842) < 0.1 && fabs(h - 595) < 0.1)) {
- printf(" (A4)");
- }
- printf("\n");
- }
-
- // print file size
-#ifdef VMS
- f = fopen(fileName->getCString(), "rb", "ctx=stm");
-#else
- f = fopen(fileName->getCString(), "rb");
-#endif
- if (f) {
-#ifdef HAVE_FSEEKO
- fseeko(f, 0, SEEK_END);
- printf("File size: %u bytes\n", (Guint)ftello(f));
-#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
- fseek64(f, 0, SEEK_END);
- printf("File size: %u bytes\n", (Guint)ftell64(f));
-#else
- fseek(f, 0, SEEK_END);
- printf("File size: %d bytes\n", (int)ftell(f));
-#endif
- fclose(f);
- }
-
- // print linearization info
- printf("Optimized: %s\n", doc->isLinearized() ? "yes" : "no");
-
- // print PDF version
- printf("PDF version: %.1f\n", doc->getPDFVersion());
-
- // print the metadata
- if (printMetadata && (metadata = doc->readMetadata())) {
- fputs("Metadata:\n", stdout);
- fputs(metadata->getCString(), stdout);
- fputc('\n', stdout);
- delete metadata;
- }
-
- exitCode = 0;
-
- // clean up
- err2:
- uMap->decRefCnt();
- delete doc;
- err1:
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
-
-static void printInfoString(Dict *infoDict, char *key, char *text,
- UnicodeMap *uMap) {
- Object obj;
- GString *s1;
- GBool isUnicode;
- Unicode u;
- char buf[8];
- int i, n;
-
- if (infoDict->lookup(key, &obj)->isString()) {
- fputs(text, stdout);
- s1 = obj.getString();
- if ((s1->getChar(0) & 0xff) == 0xfe &&
- (s1->getChar(1) & 0xff) == 0xff) {
- isUnicode = gTrue;
- i = 2;
- } else {
- isUnicode = gFalse;
- i = 0;
- }
- while (i < obj.getString()->getLength()) {
- if (isUnicode) {
- u = ((s1->getChar(i) & 0xff) << 8) |
- (s1->getChar(i+1) & 0xff);
- i += 2;
- } else {
- u = s1->getChar(i) & 0xff;
- ++i;
- }
- n = uMap->mapUnicode(u, buf, sizeof(buf));
- fwrite(buf, 1, n, stdout);
- }
- fputc('\n', stdout);
- }
- obj.free();
-}
-
-static void printInfoDate(Dict *infoDict, char *key, char *text) {
- Object obj;
- char *s;
- int year, mon, day, hour, min, sec;
- struct tm tmStruct;
- char buf[256];
-
- if (infoDict->lookup(key, &obj)->isString()) {
- fputs(text, stdout);
- s = obj.getString()->getCString();
- if (s[0] == 'D' && s[1] == ':') {
- s += 2;
- }
- if (sscanf(s, "%4d%2d%2d%2d%2d%2d",
- &year, &mon, &day, &hour, &min, &sec) == 6) {
- tmStruct.tm_year = year - 1900;
- tmStruct.tm_mon = mon - 1;
- tmStruct.tm_mday = day;
- tmStruct.tm_hour = hour;
- tmStruct.tm_min = min;
- tmStruct.tm_sec = sec;
- tmStruct.tm_wday = -1;
- tmStruct.tm_yday = -1;
- tmStruct.tm_isdst = -1;
- // compute the tm_wday and tm_yday fields
- if (mktime(&tmStruct) != (time_t)-1 &&
- strftime(buf, sizeof(buf), "%c", &tmStruct)) {
- fputs(buf, stdout);
- } else {
- fputs(s, stdout);
- }
- } else {
- fputs(s, stdout);
- }
- fputc('\n', stdout);
- }
- obj.free();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdfinfo.cpp b/filters/kword/pdf/xpdf/xpdf/pdfinfo.cpp
new file mode 100644
index 000000000..e21a299fd
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdfinfo.cpp
@@ -0,0 +1,304 @@
+//========================================================================
+//
+// pdfinfo.cpp
+//
+// Copyright 1998-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <time.h>
+#include <math.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "CharTypes.h"
+#include "UnicodeMap.h"
+#include "Error.h"
+#include "config.h"
+
+static void printInfoString(Dict *infoDict, char *key, char *text,
+ UnicodeMap *uMap);
+static void printInfoDate(Dict *infoDict, char *key, char *text);
+
+static GBool printMetadata = gFalse;
+static char textEncName[128] = "";
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-meta", argFlag, &printMetadata, 0,
+ "print the document metadata (XML)"},
+ {"-enc", argString, textEncName, sizeof(textEncName),
+ "output text encoding name"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ GString *ownerPW, *userPW;
+ UnicodeMap *uMap;
+ Object info;
+ double w, h;
+ FILE *f;
+ GString *metadata;
+ GBool ok;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc != 2 || printVersion || printHelp) {
+ fprintf(stderr, "pdfinfo version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdfinfo", "<PDF-file>", argDesc);
+ }
+ goto err0;
+ }
+ fileName = new GString(argv[1]);
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (textEncName[0]) {
+ globalParams->setTextEncoding(textEncName);
+ }
+
+ // get mapping to output encoding
+ if (!(uMap = globalParams->getTextEncoding())) {
+ error(-1, "Couldn't get text encoding");
+ delete fileName;
+ goto err1;
+ }
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err2;
+ }
+
+ // print doc info
+ doc->getDocInfo(&info);
+ if (info.isDict()) {
+ printInfoString(info.getDict(), "Title", "Title: ", uMap);
+ printInfoString(info.getDict(), "Subject", "Subject: ", uMap);
+ printInfoString(info.getDict(), "Keywords", "Keywords: ", uMap);
+ printInfoString(info.getDict(), "Author", "Author: ", uMap);
+ printInfoString(info.getDict(), "Creator", "Creator: ", uMap);
+ printInfoString(info.getDict(), "Producer", "Producer: ", uMap);
+ printInfoDate(info.getDict(), "CreationDate", "CreationDate: ");
+ printInfoDate(info.getDict(), "ModDate", "ModDate: ");
+ }
+ info.free();
+
+ // print tagging info
+ printf("Tagged: %s\n",
+ doc->getStructTreeRoot()->isDict() ? "yes" : "no");
+
+ // print page count
+ printf("Pages: %d\n", doc->getNumPages());
+
+ // print encryption info
+ printf("Encrypted: ");
+ if (doc->isEncrypted()) {
+ printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
+ doc->okToPrint(gTrue) ? "yes" : "no",
+ doc->okToCopy(gTrue) ? "yes" : "no",
+ doc->okToChange(gTrue) ? "yes" : "no",
+ doc->okToAddNotes(gTrue) ? "yes" : "no");
+ } else {
+ printf("no\n");
+ }
+
+ // print page size
+ if (doc->getNumPages() >= 1) {
+ w = doc->getPageWidth(1);
+ h = doc->getPageHeight(1);
+ printf("Page size: %g x %g pts", w, h);
+ if ((fabs(w - 612) < 0.1 && fabs(h - 792) < 0.1) ||
+ (fabs(w - 792) < 0.1 && fabs(h - 612) < 0.1)) {
+ printf(" (letter)");
+ } else if ((fabs(w - 595) < 0.1 && fabs(h - 842) < 0.1) ||
+ (fabs(w - 842) < 0.1 && fabs(h - 595) < 0.1)) {
+ printf(" (A4)");
+ }
+ printf("\n");
+ }
+
+ // print file size
+#ifdef VMS
+ f = fopen(fileName->getCString(), "rb", "ctx=stm");
+#else
+ f = fopen(fileName->getCString(), "rb");
+#endif
+ if (f) {
+#ifdef HAVE_FSEEKO
+ fseeko(f, 0, SEEK_END);
+ printf("File size: %u bytes\n", (Guint)ftello(f));
+#elif defined(HAVE_FSEEK64) && defined(HAVE_FTELL64)
+ fseek64(f, 0, SEEK_END);
+ printf("File size: %u bytes\n", (Guint)ftell64(f));
+#else
+ fseek(f, 0, SEEK_END);
+ printf("File size: %d bytes\n", (int)ftell(f));
+#endif
+ fclose(f);
+ }
+
+ // print linearization info
+ printf("Optimized: %s\n", doc->isLinearized() ? "yes" : "no");
+
+ // print PDF version
+ printf("PDF version: %.1f\n", doc->getPDFVersion());
+
+ // print the metadata
+ if (printMetadata && (metadata = doc->readMetadata())) {
+ fputs("Metadata:\n", stdout);
+ fputs(metadata->getCString(), stdout);
+ fputc('\n', stdout);
+ delete metadata;
+ }
+
+ exitCode = 0;
+
+ // clean up
+ err2:
+ uMap->decRefCnt();
+ delete doc;
+ err1:
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
+
+static void printInfoString(Dict *infoDict, char *key, char *text,
+ UnicodeMap *uMap) {
+ Object obj;
+ GString *s1;
+ GBool isUnicode;
+ Unicode u;
+ char buf[8];
+ int i, n;
+
+ if (infoDict->lookup(key, &obj)->isString()) {
+ fputs(text, stdout);
+ s1 = obj.getString();
+ if ((s1->getChar(0) & 0xff) == 0xfe &&
+ (s1->getChar(1) & 0xff) == 0xff) {
+ isUnicode = gTrue;
+ i = 2;
+ } else {
+ isUnicode = gFalse;
+ i = 0;
+ }
+ while (i < obj.getString()->getLength()) {
+ if (isUnicode) {
+ u = ((s1->getChar(i) & 0xff) << 8) |
+ (s1->getChar(i+1) & 0xff);
+ i += 2;
+ } else {
+ u = s1->getChar(i) & 0xff;
+ ++i;
+ }
+ n = uMap->mapUnicode(u, buf, sizeof(buf));
+ fwrite(buf, 1, n, stdout);
+ }
+ fputc('\n', stdout);
+ }
+ obj.free();
+}
+
+static void printInfoDate(Dict *infoDict, char *key, char *text) {
+ Object obj;
+ char *s;
+ int year, mon, day, hour, min, sec;
+ struct tm tmStruct;
+ char buf[256];
+
+ if (infoDict->lookup(key, &obj)->isString()) {
+ fputs(text, stdout);
+ s = obj.getString()->getCString();
+ if (s[0] == 'D' && s[1] == ':') {
+ s += 2;
+ }
+ if (sscanf(s, "%4d%2d%2d%2d%2d%2d",
+ &year, &mon, &day, &hour, &min, &sec) == 6) {
+ tmStruct.tm_year = year - 1900;
+ tmStruct.tm_mon = mon - 1;
+ tmStruct.tm_mday = day;
+ tmStruct.tm_hour = hour;
+ tmStruct.tm_min = min;
+ tmStruct.tm_sec = sec;
+ tmStruct.tm_wday = -1;
+ tmStruct.tm_yday = -1;
+ tmStruct.tm_isdst = -1;
+ // compute the tm_wday and tm_yday fields
+ if (mktime(&tmStruct) != (time_t)-1 &&
+ strftime(buf, sizeof(buf), "%c", &tmStruct)) {
+ fputs(buf, stdout);
+ } else {
+ fputs(s, stdout);
+ }
+ } else {
+ fputs(s, stdout);
+ }
+ fputc('\n', stdout);
+ }
+ obj.free();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftopbm.cc b/filters/kword/pdf/xpdf/xpdf/pdftopbm.cc
deleted file mode 100644
index 76f60a6af..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdftopbm.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-//========================================================================
-//
-// pdftopbm.cc
-//
-// Copyright 1998-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "PDFDoc.h"
-#include "PBMOutputDev.h"
-#include "Error.h"
-#include "config.h"
-
-static int firstPage = 1;
-static int lastPage = 0;
-static int resolution = 150;
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static GBool quiet = gFalse;
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-f", argInt, &firstPage, 0,
- "first page to print"},
- {"-l", argInt, &lastPage, 0,
- "last page to print"},
- {"-r", argInt, &resolution, 0,
- "resolution, in DPI (default is 150)"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-q", argFlag, &quiet, 0,
- "don't print any messages or errors"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- char *pbmRoot;
- GString *ownerPW, *userPW;
- PBMOutputDev *pbmOut;
- GBool ok;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc != 3 || printVersion || printHelp) {
- fprintf(stderr, "pdftopbm version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdftopbm", "<PDF-file> <PBM-root>", argDesc);
- }
- goto err0;
- }
- fileName = new GString(argv[1]);
- pbmRoot = argv[2];
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (quiet) {
- globalParams->setErrQuiet(quiet);
- }
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err1;
- }
-
- // get page range
- if (firstPage < 1)
- firstPage = 1;
- if (lastPage < 1 || lastPage > doc->getNumPages())
- lastPage = doc->getNumPages();
-
- // write PBM files
- pbmOut = PBMOutputDev::makePBMOutputDev(NULL, pbmRoot);
- pbmOut->startDoc(doc->getXRef());
- doc->displayPages(pbmOut, firstPage, lastPage, resolution, 0, gFalse);
- PBMOutputDev::killPBMOutputDev(pbmOut);
-
- exitCode = 0;
-
- // clean up
- err1:
- delete doc;
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftopbm.cpp b/filters/kword/pdf/xpdf/xpdf/pdftopbm.cpp
new file mode 100644
index 000000000..9a2002296
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdftopbm.cpp
@@ -0,0 +1,146 @@
+//========================================================================
+//
+// pdftopbm.cpp
+//
+// Copyright 1998-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "PBMOutputDev.h"
+#include "Error.h"
+#include "config.h"
+
+static int firstPage = 1;
+static int lastPage = 0;
+static int resolution = 150;
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool quiet = gFalse;
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-f", argInt, &firstPage, 0,
+ "first page to print"},
+ {"-l", argInt, &lastPage, 0,
+ "last page to print"},
+ {"-r", argInt, &resolution, 0,
+ "resolution, in DPI (default is 150)"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-q", argFlag, &quiet, 0,
+ "don't print any messages or errors"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ char *pbmRoot;
+ GString *ownerPW, *userPW;
+ PBMOutputDev *pbmOut;
+ GBool ok;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc != 3 || printVersion || printHelp) {
+ fprintf(stderr, "pdftopbm version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdftopbm", "<PDF-file> <PBM-root>", argDesc);
+ }
+ goto err0;
+ }
+ fileName = new GString(argv[1]);
+ pbmRoot = argv[2];
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (quiet) {
+ globalParams->setErrQuiet(quiet);
+ }
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err1;
+ }
+
+ // get page range
+ if (firstPage < 1)
+ firstPage = 1;
+ if (lastPage < 1 || lastPage > doc->getNumPages())
+ lastPage = doc->getNumPages();
+
+ // write PBM files
+ pbmOut = PBMOutputDev::makePBMOutputDev(NULL, pbmRoot);
+ pbmOut->startDoc(doc->getXRef());
+ doc->displayPages(pbmOut, firstPage, lastPage, resolution, 0, gFalse);
+ PBMOutputDev::killPBMOutputDev(pbmOut);
+
+ exitCode = 0;
+
+ // clean up
+ err1:
+ delete doc;
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftops.cc b/filters/kword/pdf/xpdf/xpdf/pdftops.cc
deleted file mode 100644
index d5d2de85d..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdftops.cc
+++ /dev/null
@@ -1,306 +0,0 @@
-//========================================================================
-//
-// pdftops.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "PDFDoc.h"
-#include "PSOutputDev.h"
-#include "Error.h"
-#include "config.h"
-
-static int firstPage = 1;
-static int lastPage = 0;
-static GBool level1 = gFalse;
-static GBool level1Sep = gFalse;
-static GBool level2 = gFalse;
-static GBool level2Sep = gFalse;
-static GBool level3 = gFalse;
-static GBool level3Sep = gFalse;
-static GBool doEPS = gFalse;
-static GBool doForm = gFalse;
-#if OPI_SUPPORT
-static GBool doOPI = gFalse;
-#endif
-static GBool noEmbedT1Fonts = gFalse;
-static GBool noEmbedTTFonts = gFalse;
-static GBool noEmbedCIDPSFonts = gFalse;
-static GBool noEmbedCIDTTFonts = gFalse;
-static char paperSize[15] = "";
-static int paperWidth = 0;
-static int paperHeight = 0;
-static GBool duplex = gFalse;
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static GBool quiet = gFalse;
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-f", argInt, &firstPage, 0,
- "first page to print"},
- {"-l", argInt, &lastPage, 0,
- "last page to print"},
- {"-level1", argFlag, &level1, 0,
- "generate Level 1 PostScript"},
- {"-level1sep", argFlag, &level1Sep, 0,
- "generate Level 1 separable PostScript"},
- {"-level2", argFlag, &level2, 0,
- "generate Level 2 PostScript"},
- {"-level2sep", argFlag, &level2Sep, 0,
- "generate Level 2 separable PostScript"},
- {"-level3", argFlag, &level3, 0,
- "generate Level 3 PostScript"},
- {"-level3sep", argFlag, &level3Sep, 0,
- "generate Level 3 separable PostScript"},
- {"-eps", argFlag, &doEPS, 0,
- "generate Encapsulated PostScript (EPS)"},
- {"-form", argFlag, &doForm, 0,
- "generate a PostScript form"},
-#if OPI_SUPPORT
- {"-opi", argFlag, &doOPI, 0,
- "generate OPI comments"},
-#endif
- {"-noembt1", argFlag, &noEmbedT1Fonts, 0,
- "don't embed Type 1 fonts"},
- {"-noembtt", argFlag, &noEmbedTTFonts, 0,
- "don't embed TrueType fonts"},
- {"-noembcidps", argFlag, &noEmbedCIDPSFonts, 0,
- "don't embed CID PostScript fonts"},
- {"-noembcidtt", argFlag, &noEmbedCIDTTFonts, 0,
- "don't embed CID TrueType fonts"},
- {"-paper", argString, paperSize, sizeof(paperSize),
- "paper size (letter, legal, A4, A3)"},
- {"-paperw", argInt, &paperWidth, 0,
- "paper width, in points"},
- {"-paperh", argInt, &paperHeight, 0,
- "paper height, in points"},
- {"-duplex", argFlag, &duplex, 0,
- "enable duplex printing"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-q", argFlag, &quiet, 0,
- "don't print any messages or errors"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- GString *psFileName;
- PSLevel level;
- PSOutMode mode;
- GString *ownerPW, *userPW;
- PSOutputDev *psOut;
- GBool ok;
- char *p;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc < 2 || argc > 3 || printVersion || printHelp) {
- fprintf(stderr, "pdftops version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdftops", "<PDF-file> [<PS-file>]", argDesc);
- }
- exit(1);
- }
- if ((level1 ? 1 : 0) +
- (level1Sep ? 1 : 0) +
- (level2 ? 1 : 0) +
- (level2Sep ? 1 : 0) +
- (level3 ? 1 : 0) +
- (level3Sep ? 1 : 0) > 1) {
- fprintf(stderr, "Error: use only one of the 'level' options.\n");
- exit(1);
- }
- if (doEPS && doForm) {
- fprintf(stderr, "Error: use only one of -eps and -form\n");
- exit(1);
- }
- if (level1) {
- level = psLevel1;
- } else if (level1Sep) {
- level = psLevel1Sep;
- } else if (level2Sep) {
- level = psLevel2Sep;
- } else if (level3) {
- level = psLevel3;
- } else if (level3Sep) {
- level = psLevel3Sep;
- } else {
- level = psLevel2;
- }
- if (doForm && level < psLevel2) {
- fprintf(stderr, "Error: forms are only available with Level 2 output.\n");
- exit(1);
- }
- mode = doEPS ? psModeEPS
- : doForm ? psModeForm
- : psModePS;
- fileName = new GString(argv[1]);
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (paperSize[0]) {
- if (!globalParams->setPSPaperSize(paperSize)) {
- fprintf(stderr, "Invalid paper size\n");
- goto err0;
- }
- } else {
- if (paperWidth) {
- globalParams->setPSPaperWidth(paperWidth);
- }
- if (paperHeight) {
- globalParams->setPSPaperHeight(paperHeight);
- }
- }
- if (duplex) {
- globalParams->setPSDuplex(duplex);
- }
- if (level1 || level1Sep || level2 || level2Sep || level3 || level3Sep) {
- globalParams->setPSLevel(level);
- }
- if (noEmbedT1Fonts) {
- globalParams->setPSEmbedType1(!noEmbedT1Fonts);
- }
- if (noEmbedTTFonts) {
- globalParams->setPSEmbedTrueType(!noEmbedTTFonts);
- }
- if (noEmbedCIDPSFonts) {
- globalParams->setPSEmbedCIDPostScript(!noEmbedCIDPSFonts);
- }
- if (noEmbedCIDTTFonts) {
- globalParams->setPSEmbedCIDTrueType(!noEmbedCIDTTFonts);
- }
-#if OPI_SUPPORT
- if (doOPI) {
- globalParams->setPSOPI(doOPI);
- }
-#endif
- if (quiet) {
- globalParams->setErrQuiet(quiet);
- }
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err1;
- }
-
- // check for print permission
- if (!doc->okToPrint()) {
- error(-1, "Printing this document is not allowed.");
- exitCode = 3;
- goto err1;
- }
-
- // construct PostScript file name
- if (argc == 3) {
- psFileName = new GString(argv[2]);
- } else {
- p = fileName->getCString() + fileName->getLength() - 4;
- if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
- psFileName = new GString(fileName->getCString(),
- fileName->getLength() - 4);
- } else {
- psFileName = fileName->copy();
- }
- psFileName->append(doEPS ? ".eps" : ".ps");
- }
-
- // get page range
- if (firstPage < 1) {
- firstPage = 1;
- }
- if (lastPage < 1 || lastPage > doc->getNumPages()) {
- lastPage = doc->getNumPages();
- }
-
- // check for multi-page EPS or form
- if ((doEPS || doForm) && firstPage != lastPage) {
- error(-1, "EPS and form files can only contain one page.");
- goto err2;
- }
-
- // write PostScript file
- psOut = new PSOutputDev(psFileName->getCString(), doc->getXRef(),
- doc->getCatalog(), firstPage, lastPage, mode);
- if (psOut->isOk()) {
- doc->displayPages(psOut, firstPage, lastPage, 72, 0, gFalse);
- } else {
- delete psOut;
- exitCode = 2;
- goto err2;
- }
- delete psOut;
-
- exitCode = 0;
-
- // clean up
- err2:
- delete psFileName;
- err1:
- delete doc;
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftops.cpp b/filters/kword/pdf/xpdf/xpdf/pdftops.cpp
new file mode 100644
index 000000000..91a324ac2
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdftops.cpp
@@ -0,0 +1,306 @@
+//========================================================================
+//
+// pdftops.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "PSOutputDev.h"
+#include "Error.h"
+#include "config.h"
+
+static int firstPage = 1;
+static int lastPage = 0;
+static GBool level1 = gFalse;
+static GBool level1Sep = gFalse;
+static GBool level2 = gFalse;
+static GBool level2Sep = gFalse;
+static GBool level3 = gFalse;
+static GBool level3Sep = gFalse;
+static GBool doEPS = gFalse;
+static GBool doForm = gFalse;
+#if OPI_SUPPORT
+static GBool doOPI = gFalse;
+#endif
+static GBool noEmbedT1Fonts = gFalse;
+static GBool noEmbedTTFonts = gFalse;
+static GBool noEmbedCIDPSFonts = gFalse;
+static GBool noEmbedCIDTTFonts = gFalse;
+static char paperSize[15] = "";
+static int paperWidth = 0;
+static int paperHeight = 0;
+static GBool duplex = gFalse;
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool quiet = gFalse;
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-f", argInt, &firstPage, 0,
+ "first page to print"},
+ {"-l", argInt, &lastPage, 0,
+ "last page to print"},
+ {"-level1", argFlag, &level1, 0,
+ "generate Level 1 PostScript"},
+ {"-level1sep", argFlag, &level1Sep, 0,
+ "generate Level 1 separable PostScript"},
+ {"-level2", argFlag, &level2, 0,
+ "generate Level 2 PostScript"},
+ {"-level2sep", argFlag, &level2Sep, 0,
+ "generate Level 2 separable PostScript"},
+ {"-level3", argFlag, &level3, 0,
+ "generate Level 3 PostScript"},
+ {"-level3sep", argFlag, &level3Sep, 0,
+ "generate Level 3 separable PostScript"},
+ {"-eps", argFlag, &doEPS, 0,
+ "generate Encapsulated PostScript (EPS)"},
+ {"-form", argFlag, &doForm, 0,
+ "generate a PostScript form"},
+#if OPI_SUPPORT
+ {"-opi", argFlag, &doOPI, 0,
+ "generate OPI comments"},
+#endif
+ {"-noembt1", argFlag, &noEmbedT1Fonts, 0,
+ "don't embed Type 1 fonts"},
+ {"-noembtt", argFlag, &noEmbedTTFonts, 0,
+ "don't embed TrueType fonts"},
+ {"-noembcidps", argFlag, &noEmbedCIDPSFonts, 0,
+ "don't embed CID PostScript fonts"},
+ {"-noembcidtt", argFlag, &noEmbedCIDTTFonts, 0,
+ "don't embed CID TrueType fonts"},
+ {"-paper", argString, paperSize, sizeof(paperSize),
+ "paper size (letter, legal, A4, A3)"},
+ {"-paperw", argInt, &paperWidth, 0,
+ "paper width, in points"},
+ {"-paperh", argInt, &paperHeight, 0,
+ "paper height, in points"},
+ {"-duplex", argFlag, &duplex, 0,
+ "enable duplex printing"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-q", argFlag, &quiet, 0,
+ "don't print any messages or errors"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ GString *psFileName;
+ PSLevel level;
+ PSOutMode mode;
+ GString *ownerPW, *userPW;
+ PSOutputDev *psOut;
+ GBool ok;
+ char *p;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc < 2 || argc > 3 || printVersion || printHelp) {
+ fprintf(stderr, "pdftops version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdftops", "<PDF-file> [<PS-file>]", argDesc);
+ }
+ exit(1);
+ }
+ if ((level1 ? 1 : 0) +
+ (level1Sep ? 1 : 0) +
+ (level2 ? 1 : 0) +
+ (level2Sep ? 1 : 0) +
+ (level3 ? 1 : 0) +
+ (level3Sep ? 1 : 0) > 1) {
+ fprintf(stderr, "Error: use only one of the 'level' options.\n");
+ exit(1);
+ }
+ if (doEPS && doForm) {
+ fprintf(stderr, "Error: use only one of -eps and -form\n");
+ exit(1);
+ }
+ if (level1) {
+ level = psLevel1;
+ } else if (level1Sep) {
+ level = psLevel1Sep;
+ } else if (level2Sep) {
+ level = psLevel2Sep;
+ } else if (level3) {
+ level = psLevel3;
+ } else if (level3Sep) {
+ level = psLevel3Sep;
+ } else {
+ level = psLevel2;
+ }
+ if (doForm && level < psLevel2) {
+ fprintf(stderr, "Error: forms are only available with Level 2 output.\n");
+ exit(1);
+ }
+ mode = doEPS ? psModeEPS
+ : doForm ? psModeForm
+ : psModePS;
+ fileName = new GString(argv[1]);
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (paperSize[0]) {
+ if (!globalParams->setPSPaperSize(paperSize)) {
+ fprintf(stderr, "Invalid paper size\n");
+ goto err0;
+ }
+ } else {
+ if (paperWidth) {
+ globalParams->setPSPaperWidth(paperWidth);
+ }
+ if (paperHeight) {
+ globalParams->setPSPaperHeight(paperHeight);
+ }
+ }
+ if (duplex) {
+ globalParams->setPSDuplex(duplex);
+ }
+ if (level1 || level1Sep || level2 || level2Sep || level3 || level3Sep) {
+ globalParams->setPSLevel(level);
+ }
+ if (noEmbedT1Fonts) {
+ globalParams->setPSEmbedType1(!noEmbedT1Fonts);
+ }
+ if (noEmbedTTFonts) {
+ globalParams->setPSEmbedTrueType(!noEmbedTTFonts);
+ }
+ if (noEmbedCIDPSFonts) {
+ globalParams->setPSEmbedCIDPostScript(!noEmbedCIDPSFonts);
+ }
+ if (noEmbedCIDTTFonts) {
+ globalParams->setPSEmbedCIDTrueType(!noEmbedCIDTTFonts);
+ }
+#if OPI_SUPPORT
+ if (doOPI) {
+ globalParams->setPSOPI(doOPI);
+ }
+#endif
+ if (quiet) {
+ globalParams->setErrQuiet(quiet);
+ }
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err1;
+ }
+
+ // check for print permission
+ if (!doc->okToPrint()) {
+ error(-1, "Printing this document is not allowed.");
+ exitCode = 3;
+ goto err1;
+ }
+
+ // construct PostScript file name
+ if (argc == 3) {
+ psFileName = new GString(argv[2]);
+ } else {
+ p = fileName->getCString() + fileName->getLength() - 4;
+ if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
+ psFileName = new GString(fileName->getCString(),
+ fileName->getLength() - 4);
+ } else {
+ psFileName = fileName->copy();
+ }
+ psFileName->append(doEPS ? ".eps" : ".ps");
+ }
+
+ // get page range
+ if (firstPage < 1) {
+ firstPage = 1;
+ }
+ if (lastPage < 1 || lastPage > doc->getNumPages()) {
+ lastPage = doc->getNumPages();
+ }
+
+ // check for multi-page EPS or form
+ if ((doEPS || doForm) && firstPage != lastPage) {
+ error(-1, "EPS and form files can only contain one page.");
+ goto err2;
+ }
+
+ // write PostScript file
+ psOut = new PSOutputDev(psFileName->getCString(), doc->getXRef(),
+ doc->getCatalog(), firstPage, lastPage, mode);
+ if (psOut->isOk()) {
+ doc->displayPages(psOut, firstPage, lastPage, 72, 0, gFalse);
+ } else {
+ delete psOut;
+ exitCode = 2;
+ goto err2;
+ }
+ delete psOut;
+
+ exitCode = 0;
+
+ // clean up
+ err2:
+ delete psFileName;
+ err1:
+ delete doc;
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftotext.cc b/filters/kword/pdf/xpdf/xpdf/pdftotext.cc
deleted file mode 100644
index 150954fc9..000000000
--- a/filters/kword/pdf/xpdf/xpdf/pdftotext.cc
+++ /dev/null
@@ -1,322 +0,0 @@
-//========================================================================
-//
-// pdftotext.cc
-//
-// Copyright 1997-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-#include <string.h>
-#include "parseargs.h"
-#include "GString.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "Stream.h"
-#include "Array.h"
-#include "Dict.h"
-#include "XRef.h"
-#include "Catalog.h"
-#include "Page.h"
-#include "PDFDoc.h"
-#include "TextOutputDev.h"
-#include "CharTypes.h"
-#include "UnicodeMap.h"
-#include "Error.h"
-#include "config.h"
-
-static void printInfoString(FILE *f, Dict *infoDict, char *key,
- char *text1, char *text2, UnicodeMap *uMap);
-static void printInfoDate(FILE *f, Dict *infoDict, char *key, char *fmt);
-
-static int firstPage = 1;
-static int lastPage = 0;
-static GBool rawOrder = gFalse;
-static GBool htmlMeta = gFalse;
-static char textEncName[128] = "";
-static char textEOL[16] = "";
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static GBool quiet = gFalse;
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-f", argInt, &firstPage, 0,
- "first page to convert"},
- {"-l", argInt, &lastPage, 0,
- "last page to convert"},
- {"-raw", argFlag, &rawOrder, 0,
- "keep strings in content stream order"},
- {"-htmlmeta", argFlag, &htmlMeta, 0,
- "generate a simple HTML file, including the meta information"},
- {"-enc", argString, textEncName, sizeof(textEncName),
- "output text encoding name"},
- {"-eol", argString, textEOL, sizeof(textEOL),
- "output end-of-line convention (unix, dos, or mac)"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-q", argFlag, &quiet, 0,
- "don't print any messages or errors"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-int main(int argc, char *argv[]) {
- PDFDoc *doc;
- GString *fileName;
- GString *textFileName;
- GString *ownerPW, *userPW;
- TextOutputDev *textOut;
- FILE *f;
- UnicodeMap *uMap;
- Object info;
- GBool ok;
- char *p;
- int exitCode;
-
- exitCode = 99;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
- if (!ok || argc < 2 || argc > 3 || printVersion || printHelp) {
- fprintf(stderr, "pdftotext version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("pdftotext", "<PDF-file> [<text-file>]", argDesc);
- }
- goto err0;
- }
- fileName = new GString(argv[1]);
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (textEncName[0]) {
- globalParams->setTextEncoding(textEncName);
- }
- if (textEOL[0]) {
- if (!globalParams->setTextEOL(textEOL)) {
- fprintf(stderr, "Bad '-eol' value on command line\n");
- }
- }
- if (quiet) {
- globalParams->setErrQuiet(quiet);
- }
-
- // get mapping to output encoding
- if (!(uMap = globalParams->getTextEncoding())) {
- error(-1, "Couldn't get text encoding");
- delete fileName;
- goto err1;
- }
-
- // open PDF file
- if (ownerPassword[0]) {
- ownerPW = new GString(ownerPassword);
- } else {
- ownerPW = NULL;
- }
- if (userPassword[0]) {
- userPW = new GString(userPassword);
- } else {
- userPW = NULL;
- }
- doc = new PDFDoc(fileName, ownerPW, userPW);
- if (userPW) {
- delete userPW;
- }
- if (ownerPW) {
- delete ownerPW;
- }
- if (!doc->isOk()) {
- exitCode = 1;
- goto err2;
- }
-
- // check for copy permission
- if (!doc->okToCopy()) {
- error(-1, "Copying of text from this document is not allowed.");
- exitCode = 3;
- goto err2;
- }
-
- // construct text file name
- if (argc == 3) {
- textFileName = new GString(argv[2]);
- } else {
- p = fileName->getCString() + fileName->getLength() - 4;
- if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
- textFileName = new GString(fileName->getCString(),
- fileName->getLength() - 4);
- } else {
- textFileName = fileName->copy();
- }
- textFileName->append(htmlMeta ? ".html" : ".txt");
- }
-
- // get page range
- if (firstPage < 1) {
- firstPage = 1;
- }
- if (lastPage < 1 || lastPage > doc->getNumPages()) {
- lastPage = doc->getNumPages();
- }
-
- // write HTML header
- if (htmlMeta) {
- if (!textFileName->cmp("-")) {
- f = stdout;
- } else {
- if (!(f = fopen(textFileName->getCString(), "wb"))) {
- error(-1, "Couldn't open text file '%s'", textFileName->getCString());
- exitCode = 2;
- goto err3;
- }
- }
- fputs("<html>\n", f);
- fputs("<head>\n", f);
- doc->getDocInfo(&info);
- if (info.isDict()) {
- printInfoString(f, info.getDict(), "Title", "<title>", "</title>\n",
- uMap);
- printInfoString(f, info.getDict(), "Subject",
- "<meta name=\"Subject\" content=\"", "\">\n", uMap);
- printInfoString(f, info.getDict(), "Keywords",
- "<meta name=\"Keywords\" content=\"", "\">\n", uMap);
- printInfoString(f, info.getDict(), "Author",
- "<meta name=\"Author\" content=\"", "\">\n", uMap);
- printInfoString(f, info.getDict(), "Creator",
- "<meta name=\"Creator\" content=\"", "\">\n", uMap);
- printInfoString(f, info.getDict(), "Producer",
- "<meta name=\"Producer\" content=\"", "\">\n", uMap);
- printInfoDate(f, info.getDict(), "CreationDate",
- "<meta name=\"CreationDate\" content=\"\">\n");
- printInfoDate(f, info.getDict(), "LastModifiedDate",
- "<meta name=\"ModDate\" content=\"\">\n");
- }
- info.free();
- fputs("</head>\n", f);
- fputs("<body>\n", f);
- fputs("<pre>\n", f);
- if (f != stdout) {
- fclose(f);
- }
- }
-
- // write text file
- textOut = new TextOutputDev(textFileName->getCString(), rawOrder, htmlMeta);
- if (textOut->isOk()) {
- doc->displayPages(textOut, firstPage, lastPage, 72, 0, gFalse);
- } else {
- delete textOut;
- exitCode = 2;
- goto err3;
- }
- delete textOut;
-
- // write end of HTML file
- if (htmlMeta) {
- if (!textFileName->cmp("-")) {
- f = stdout;
- } else {
- if (!(f = fopen(textFileName->getCString(), "ab"))) {
- error(-1, "Couldn't open text file '%s'", textFileName->getCString());
- exitCode = 2;
- goto err3;
- }
- }
- fputs("</pre>\n", f);
- fputs("</body>\n", f);
- fputs("</html>\n", f);
- if (f != stdout) {
- fclose(f);
- }
- }
-
- exitCode = 0;
-
- // clean up
- err3:
- delete textFileName;
- err2:
- delete doc;
- uMap->decRefCnt();
- err1:
- delete globalParams;
- err0:
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
-
-static void printInfoString(FILE *f, Dict *infoDict, char *key,
- char *text1, char *text2, UnicodeMap *uMap) {
- Object obj;
- GString *s1;
- GBool isUnicode;
- Unicode u;
- char buf[8];
- int i, n;
-
- if (infoDict->lookup(key, &obj)->isString()) {
- fputs(text1, f);
- s1 = obj.getString();
- if ((s1->getChar(0) & 0xff) == 0xfe &&
- (s1->getChar(1) & 0xff) == 0xff) {
- isUnicode = gTrue;
- i = 2;
- } else {
- isUnicode = gFalse;
- i = 0;
- }
- while (i < obj.getString()->getLength()) {
- if (isUnicode) {
- u = ((s1->getChar(i) & 0xff) << 8) |
- (s1->getChar(i+1) & 0xff);
- i += 2;
- } else {
- u = s1->getChar(i) & 0xff;
- ++i;
- }
- n = uMap->mapUnicode(u, buf, sizeof(buf));
- fwrite(buf, 1, n, f);
- }
- fputs(text2, f);
- }
- obj.free();
-}
-
-static void printInfoDate(FILE *f, Dict *infoDict, char *key, char *fmt) {
- Object obj;
- char *s;
-
- if (infoDict->lookup(key, &obj)->isString()) {
- s = obj.getString()->getCString();
- if (s[0] == 'D' && s[1] == ':') {
- s += 2;
- }
- fprintf(f, fmt, s);
- }
- obj.free();
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/pdftotext.cpp b/filters/kword/pdf/xpdf/xpdf/pdftotext.cpp
new file mode 100644
index 000000000..b2e68b422
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/pdftotext.cpp
@@ -0,0 +1,322 @@
+//========================================================================
+//
+// pdftotext.cpp
+//
+// Copyright 1997-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include "parseargs.h"
+#include "GString.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "Stream.h"
+#include "Array.h"
+#include "Dict.h"
+#include "XRef.h"
+#include "Catalog.h"
+#include "Page.h"
+#include "PDFDoc.h"
+#include "TextOutputDev.h"
+#include "CharTypes.h"
+#include "UnicodeMap.h"
+#include "Error.h"
+#include "config.h"
+
+static void printInfoString(FILE *f, Dict *infoDict, char *key,
+ char *text1, char *text2, UnicodeMap *uMap);
+static void printInfoDate(FILE *f, Dict *infoDict, char *key, char *fmt);
+
+static int firstPage = 1;
+static int lastPage = 0;
+static GBool rawOrder = gFalse;
+static GBool htmlMeta = gFalse;
+static char textEncName[128] = "";
+static char textEOL[16] = "";
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool quiet = gFalse;
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-f", argInt, &firstPage, 0,
+ "first page to convert"},
+ {"-l", argInt, &lastPage, 0,
+ "last page to convert"},
+ {"-raw", argFlag, &rawOrder, 0,
+ "keep strings in content stream order"},
+ {"-htmlmeta", argFlag, &htmlMeta, 0,
+ "generate a simple HTML file, including the meta information"},
+ {"-enc", argString, textEncName, sizeof(textEncName),
+ "output text encoding name"},
+ {"-eol", argString, textEOL, sizeof(textEOL),
+ "output end-of-line convention (unix, dos, or mac)"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-q", argFlag, &quiet, 0,
+ "don't print any messages or errors"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+int main(int argc, char *argv[]) {
+ PDFDoc *doc;
+ GString *fileName;
+ GString *textFileName;
+ GString *ownerPW, *userPW;
+ TextOutputDev *textOut;
+ FILE *f;
+ UnicodeMap *uMap;
+ Object info;
+ GBool ok;
+ char *p;
+ int exitCode;
+
+ exitCode = 99;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+ if (!ok || argc < 2 || argc > 3 || printVersion || printHelp) {
+ fprintf(stderr, "pdftotext version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("pdftotext", "<PDF-file> [<text-file>]", argDesc);
+ }
+ goto err0;
+ }
+ fileName = new GString(argv[1]);
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (textEncName[0]) {
+ globalParams->setTextEncoding(textEncName);
+ }
+ if (textEOL[0]) {
+ if (!globalParams->setTextEOL(textEOL)) {
+ fprintf(stderr, "Bad '-eol' value on command line\n");
+ }
+ }
+ if (quiet) {
+ globalParams->setErrQuiet(quiet);
+ }
+
+ // get mapping to output encoding
+ if (!(uMap = globalParams->getTextEncoding())) {
+ error(-1, "Couldn't get text encoding");
+ delete fileName;
+ goto err1;
+ }
+
+ // open PDF file
+ if (ownerPassword[0]) {
+ ownerPW = new GString(ownerPassword);
+ } else {
+ ownerPW = NULL;
+ }
+ if (userPassword[0]) {
+ userPW = new GString(userPassword);
+ } else {
+ userPW = NULL;
+ }
+ doc = new PDFDoc(fileName, ownerPW, userPW);
+ if (userPW) {
+ delete userPW;
+ }
+ if (ownerPW) {
+ delete ownerPW;
+ }
+ if (!doc->isOk()) {
+ exitCode = 1;
+ goto err2;
+ }
+
+ // check for copy permission
+ if (!doc->okToCopy()) {
+ error(-1, "Copying of text from this document is not allowed.");
+ exitCode = 3;
+ goto err2;
+ }
+
+ // construct text file name
+ if (argc == 3) {
+ textFileName = new GString(argv[2]);
+ } else {
+ p = fileName->getCString() + fileName->getLength() - 4;
+ if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
+ textFileName = new GString(fileName->getCString(),
+ fileName->getLength() - 4);
+ } else {
+ textFileName = fileName->copy();
+ }
+ textFileName->append(htmlMeta ? ".html" : ".txt");
+ }
+
+ // get page range
+ if (firstPage < 1) {
+ firstPage = 1;
+ }
+ if (lastPage < 1 || lastPage > doc->getNumPages()) {
+ lastPage = doc->getNumPages();
+ }
+
+ // write HTML header
+ if (htmlMeta) {
+ if (!textFileName->cmp("-")) {
+ f = stdout;
+ } else {
+ if (!(f = fopen(textFileName->getCString(), "wb"))) {
+ error(-1, "Couldn't open text file '%s'", textFileName->getCString());
+ exitCode = 2;
+ goto err3;
+ }
+ }
+ fputs("<html>\n", f);
+ fputs("<head>\n", f);
+ doc->getDocInfo(&info);
+ if (info.isDict()) {
+ printInfoString(f, info.getDict(), "Title", "<title>", "</title>\n",
+ uMap);
+ printInfoString(f, info.getDict(), "Subject",
+ "<meta name=\"Subject\" content=\"", "\">\n", uMap);
+ printInfoString(f, info.getDict(), "Keywords",
+ "<meta name=\"Keywords\" content=\"", "\">\n", uMap);
+ printInfoString(f, info.getDict(), "Author",
+ "<meta name=\"Author\" content=\"", "\">\n", uMap);
+ printInfoString(f, info.getDict(), "Creator",
+ "<meta name=\"Creator\" content=\"", "\">\n", uMap);
+ printInfoString(f, info.getDict(), "Producer",
+ "<meta name=\"Producer\" content=\"", "\">\n", uMap);
+ printInfoDate(f, info.getDict(), "CreationDate",
+ "<meta name=\"CreationDate\" content=\"\">\n");
+ printInfoDate(f, info.getDict(), "LastModifiedDate",
+ "<meta name=\"ModDate\" content=\"\">\n");
+ }
+ info.free();
+ fputs("</head>\n", f);
+ fputs("<body>\n", f);
+ fputs("<pre>\n", f);
+ if (f != stdout) {
+ fclose(f);
+ }
+ }
+
+ // write text file
+ textOut = new TextOutputDev(textFileName->getCString(), rawOrder, htmlMeta);
+ if (textOut->isOk()) {
+ doc->displayPages(textOut, firstPage, lastPage, 72, 0, gFalse);
+ } else {
+ delete textOut;
+ exitCode = 2;
+ goto err3;
+ }
+ delete textOut;
+
+ // write end of HTML file
+ if (htmlMeta) {
+ if (!textFileName->cmp("-")) {
+ f = stdout;
+ } else {
+ if (!(f = fopen(textFileName->getCString(), "ab"))) {
+ error(-1, "Couldn't open text file '%s'", textFileName->getCString());
+ exitCode = 2;
+ goto err3;
+ }
+ }
+ fputs("</pre>\n", f);
+ fputs("</body>\n", f);
+ fputs("</html>\n", f);
+ if (f != stdout) {
+ fclose(f);
+ }
+ }
+
+ exitCode = 0;
+
+ // clean up
+ err3:
+ delete textFileName;
+ err2:
+ delete doc;
+ uMap->decRefCnt();
+ err1:
+ delete globalParams;
+ err0:
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
+
+static void printInfoString(FILE *f, Dict *infoDict, char *key,
+ char *text1, char *text2, UnicodeMap *uMap) {
+ Object obj;
+ GString *s1;
+ GBool isUnicode;
+ Unicode u;
+ char buf[8];
+ int i, n;
+
+ if (infoDict->lookup(key, &obj)->isString()) {
+ fputs(text1, f);
+ s1 = obj.getString();
+ if ((s1->getChar(0) & 0xff) == 0xfe &&
+ (s1->getChar(1) & 0xff) == 0xff) {
+ isUnicode = gTrue;
+ i = 2;
+ } else {
+ isUnicode = gFalse;
+ i = 0;
+ }
+ while (i < obj.getString()->getLength()) {
+ if (isUnicode) {
+ u = ((s1->getChar(i) & 0xff) << 8) |
+ (s1->getChar(i+1) & 0xff);
+ i += 2;
+ } else {
+ u = s1->getChar(i) & 0xff;
+ ++i;
+ }
+ n = uMap->mapUnicode(u, buf, sizeof(buf));
+ fwrite(buf, 1, n, f);
+ }
+ fputs(text2, f);
+ }
+ obj.free();
+}
+
+static void printInfoDate(FILE *f, Dict *infoDict, char *key, char *fmt) {
+ Object obj;
+ char *s;
+
+ if (infoDict->lookup(key, &obj)->isString()) {
+ s = obj.getString()->getCString();
+ if (s[0] == 'D' && s[1] == ':') {
+ s += 2;
+ }
+ fprintf(f, fmt, s);
+ }
+ obj.free();
+}
diff --git a/filters/kword/pdf/xpdf/xpdf/xpdf.cc b/filters/kword/pdf/xpdf/xpdf/xpdf.cc
deleted file mode 100644
index ef47fb6e5..000000000
--- a/filters/kword/pdf/xpdf/xpdf/xpdf.cc
+++ /dev/null
@@ -1,289 +0,0 @@
-//========================================================================
-//
-// xpdf.cc
-//
-// Copyright 1996-2002 Glyph & Cog, LLC
-//
-//========================================================================
-
-#include <aconf.h>
-#include "gtypes.h"
-#include "GString.h"
-#include "parseargs.h"
-#include "gfile.h"
-#include "gmem.h"
-#include "GlobalParams.h"
-#include "Object.h"
-#include "XPDFApp.h"
-#include "config.h"
-
-//------------------------------------------------------------------------
-// command line options
-//------------------------------------------------------------------------
-
-static char t1libControlStr[16] = "";
-static char freetypeControlStr[16] = "";
-static char psFileArg[256];
-static char paperSize[15] = "";
-static int paperWidth = 0;
-static int paperHeight = 0;
-static GBool level1 = gFalse;
-static char textEncName[128] = "";
-static char textEOL[16] = "";
-static char ownerPassword[33] = "";
-static char userPassword[33] = "";
-static GBool fullScreen = gFalse;
-static char remoteName[100] = "xpdf_";
-static GBool doRemoteRaise = gFalse;
-static GBool doRemoteQuit = gFalse;
-static GBool printCommands = gFalse;
-static GBool quiet = gFalse;
-static char cfgFileName[256] = "";
-static GBool printVersion = gFalse;
-static GBool printHelp = gFalse;
-
-static ArgDesc argDesc[] = {
- {"-g", argStringDummy, NULL, 0,
- "initial window geometry"},
- {"-geometry", argStringDummy, NULL, 0,
- "initial window geometry"},
- {"-title", argStringDummy, NULL, 0,
- "window title"},
- {"-cmap", argFlagDummy, NULL, 0,
- "install a private colormap"},
- {"-rgb", argIntDummy, NULL, 0,
- "biggest RGB cube to allocate (default is 5)"},
- {"-rv", argFlagDummy, NULL, 0,
- "reverse video"},
- {"-papercolor", argStringDummy, NULL, 0,
- "color of paper background"},
- {"-z", argStringDummy, NULL, 0,
- "initial zoom level (-5..5, page, width)"},
-#if HAVE_T1LIB_H
- {"-t1lib", argString, t1libControlStr, sizeof(t1libControlStr),
- "t1lib font rasterizer control: none, plain, low, high"},
-#endif
-#if HAVE_FREETYPE_FREETYPE_H | HAVE_FREETYPE_H
- {"-freetype", argString, freetypeControlStr, sizeof(freetypeControlStr),
- "FreeType font rasterizer control: none, plain, low, high"},
-#endif
- {"-ps", argString, psFileArg, sizeof(psFileArg),
- "default PostScript file name or command"},
- {"-paper", argString, paperSize, sizeof(paperSize),
- "paper size (letter, legal, A4, A3)"},
- {"-paperw", argInt, &paperWidth, 0,
- "paper width, in points"},
- {"-paperh", argInt, &paperHeight, 0,
- "paper height, in points"},
- {"-level1", argFlag, &level1, 0,
- "generate Level 1 PostScript"},
- {"-enc", argString, textEncName, sizeof(textEncName),
- "output text encoding name"},
- {"-eol", argString, textEOL, sizeof(textEOL),
- "output end-of-line convention (unix, dos, or mac)"},
- {"-opw", argString, ownerPassword, sizeof(ownerPassword),
- "owner password (for encrypted files)"},
- {"-upw", argString, userPassword, sizeof(userPassword),
- "user password (for encrypted files)"},
- {"-fullscreen", argFlag, &fullScreen, 0,
- "run in full-screen (presentation) mode"},
- {"-remote", argString, remoteName + 5, sizeof(remoteName) - 5,
- "start/contact xpdf remote server with specified name"},
- {"-raise", argFlag, &doRemoteRaise, 0,
- "raise xpdf remote server window (with -remote only)"},
- {"-quit", argFlag, &doRemoteQuit, 0,
- "kill xpdf remote server (with -remote only)"},
- {"-cmd", argFlag, &printCommands, 0,
- "print commands as they're executed"},
- {"-q", argFlag, &quiet, 0,
- "don't print any messages or errors"},
- {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
- "configuration file to use in place of .xpdfrc"},
- {"-v", argFlag, &printVersion, 0,
- "print copyright and version info"},
- {"-h", argFlag, &printHelp, 0,
- "print usage information"},
- {"-help", argFlag, &printHelp, 0,
- "print usage information"},
- {"--help", argFlag, &printHelp, 0,
- "print usage information"},
- {"-?", argFlag, &printHelp, 0,
- "print usage information"},
- {NULL}
-};
-
-//------------------------------------------------------------------------
-
-int main(int argc, char *argv[]) {
- XPDFApp *app;
- GString *fileName;
- int pg;
- GString *destName;
- GString *userPasswordStr, *ownerPasswordStr;
- GBool ok;
- int exitCode;
-
- exitCode = 0;
- userPasswordStr = ownerPasswordStr = NULL;
-
- // parse args
- ok = parseArgs(argDesc, &argc, argv);
-
- // read config file
- globalParams = new GlobalParams(cfgFileName);
- if (psFileArg[0]) {
- globalParams->setPSFile(psFileArg);
- }
- if (paperSize[0]) {
- if (!globalParams->setPSPaperSize(paperSize)) {
- fprintf(stderr, "Invalid paper size\n");
- }
- } else {
- if (paperWidth) {
- globalParams->setPSPaperWidth(paperWidth);
- }
- if (paperHeight) {
- globalParams->setPSPaperHeight(paperHeight);
- }
- }
- if (level1) {
- globalParams->setPSLevel(psLevel1);
- }
- if (textEncName[0]) {
- globalParams->setTextEncoding(textEncName);
- }
- if (textEOL[0]) {
- if (!globalParams->setTextEOL(textEOL)) {
- fprintf(stderr, "Bad '-eol' value on command line\n");
- }
- }
- if (t1libControlStr[0]) {
- if (!globalParams->setT1libControl(t1libControlStr)) {
- fprintf(stderr, "Bad '-t1lib' value on command line\n");
- }
- }
- if (freetypeControlStr[0]) {
- if (!globalParams->setFreeTypeControl(freetypeControlStr)) {
- fprintf(stderr, "Bad '-freetype' value on command line\n");
- }
- }
- if (printCommands) {
- globalParams->setPrintCommands(printCommands);
- }
- if (quiet) {
- globalParams->setErrQuiet(quiet);
- }
-
- // create the XPDFApp object
- app = new XPDFApp(&argc, argv);
-
- // the initialZoom parameter can be set in either the config file or
- // as an X resource (or command line arg)
- if (app->getInitialZoom()) {
- globalParams->setInitialZoom(app->getInitialZoom()->getCString());
- }
-
- // check command line
- if (doRemoteRaise) {
- ok = ok && remoteName[5] && !doRemoteQuit && argc >= 1 && argc <= 3;
- } else if (doRemoteQuit) {
- ok = ok && remoteName[5] && argc == 1;
- } else {
- ok = ok && argc >= 1 && argc <= 3;
- }
- if (!ok || printVersion || printHelp) {
- fprintf(stderr, "xpdf version %s\n", xpdfVersion);
- fprintf(stderr, "%s\n", xpdfCopyright);
- if (!printVersion) {
- printUsage("xpdf", "[<PDF-file> [<page> | +<dest>]]", argDesc);
- }
- exitCode = 99;
- goto done1;
- }
- if (argc >= 2) {
- fileName = new GString(argv[1]);
- } else {
- fileName = NULL;
- }
- pg = 1;
- destName = NULL;
- if (argc == 3) {
- if (argv[2][0] == '+') {
- destName = new GString(&argv[2][1]);
- } else {
- pg = atoi(argv[2]);
- }
- }
-
- // handle remote server stuff
- if (remoteName[5]) {
- app->setRemoteName(remoteName);
- if (app->remoteServerRunning()) {
- if (fileName) {
- if (destName) {
- app->remoteOpenAtDest(fileName, destName, doRemoteRaise);
- } else {
- app->remoteOpen(fileName, pg, doRemoteRaise);
- }
- } else if (doRemoteRaise) {
- app->remoteRaise();
- } else if (doRemoteQuit) {
- app->remoteQuit();
- }
- goto done2;
- }
- if (doRemoteQuit) {
- goto done2;
- }
- }
-
- // set options
- app->setFullScreen(fullScreen);
-
- // check for password string(s)
- ownerPasswordStr = ownerPassword[0] ? new GString(ownerPassword)
- : (GString *)NULL;
- userPasswordStr = userPassword[0] ? new GString(userPassword)
- : (GString *)NULL;
-
- // open the file and run the main loop
- if (destName) {
- if (!app->openAtDest(fileName, destName,
- ownerPasswordStr, userPasswordStr)) {
- exitCode = 1;
- goto done2;
- }
- } else {
- if (!app->open(fileName, pg, ownerPasswordStr, userPasswordStr)) {
- exitCode = 1;
- goto done2;
- }
- }
- app->run();
-
- exitCode = 0;
-
- // clean up
- done2:
- if (userPasswordStr) {
- delete userPasswordStr;
- }
- if (ownerPasswordStr) {
- delete ownerPasswordStr;
- }
- if (destName) {
- delete destName;
- }
- if (fileName) {
- delete fileName;
- }
- done1:
- delete app;
- delete globalParams;
-
- // check for memory leaks
- Object::memCheck(stderr);
- gMemReport(stderr);
-
- return exitCode;
-}
diff --git a/filters/kword/pdf/xpdf/xpdf/xpdf.cpp b/filters/kword/pdf/xpdf/xpdf/xpdf.cpp
new file mode 100644
index 000000000..9cb3f82d7
--- /dev/null
+++ b/filters/kword/pdf/xpdf/xpdf/xpdf.cpp
@@ -0,0 +1,289 @@
+//========================================================================
+//
+// xpdf.cpp
+//
+// Copyright 1996-2002 Glyph & Cog, LLC
+//
+//========================================================================
+
+#include <aconf.h>
+#include "gtypes.h"
+#include "GString.h"
+#include "parseargs.h"
+#include "gfile.h"
+#include "gmem.h"
+#include "GlobalParams.h"
+#include "Object.h"
+#include "XPDFApp.h"
+#include "config.h"
+
+//------------------------------------------------------------------------
+// command line options
+//------------------------------------------------------------------------
+
+static char t1libControlStr[16] = "";
+static char freetypeControlStr[16] = "";
+static char psFileArg[256];
+static char paperSize[15] = "";
+static int paperWidth = 0;
+static int paperHeight = 0;
+static GBool level1 = gFalse;
+static char textEncName[128] = "";
+static char textEOL[16] = "";
+static char ownerPassword[33] = "";
+static char userPassword[33] = "";
+static GBool fullScreen = gFalse;
+static char remoteName[100] = "xpdf_";
+static GBool doRemoteRaise = gFalse;
+static GBool doRemoteQuit = gFalse;
+static GBool printCommands = gFalse;
+static GBool quiet = gFalse;
+static char cfgFileName[256] = "";
+static GBool printVersion = gFalse;
+static GBool printHelp = gFalse;
+
+static ArgDesc argDesc[] = {
+ {"-g", argStringDummy, NULL, 0,
+ "initial window geometry"},
+ {"-geometry", argStringDummy, NULL, 0,
+ "initial window geometry"},
+ {"-title", argStringDummy, NULL, 0,
+ "window title"},
+ {"-cmap", argFlagDummy, NULL, 0,
+ "install a private colormap"},
+ {"-rgb", argIntDummy, NULL, 0,
+ "biggest RGB cube to allocate (default is 5)"},
+ {"-rv", argFlagDummy, NULL, 0,
+ "reverse video"},
+ {"-papercolor", argStringDummy, NULL, 0,
+ "color of paper background"},
+ {"-z", argStringDummy, NULL, 0,
+ "initial zoom level (-5..5, page, width)"},
+#if HAVE_T1LIB_H
+ {"-t1lib", argString, t1libControlStr, sizeof(t1libControlStr),
+ "t1lib font rasterizer control: none, plain, low, high"},
+#endif
+#if HAVE_FREETYPE_FREETYPE_H | HAVE_FREETYPE_H
+ {"-freetype", argString, freetypeControlStr, sizeof(freetypeControlStr),
+ "FreeType font rasterizer control: none, plain, low, high"},
+#endif
+ {"-ps", argString, psFileArg, sizeof(psFileArg),
+ "default PostScript file name or command"},
+ {"-paper", argString, paperSize, sizeof(paperSize),
+ "paper size (letter, legal, A4, A3)"},
+ {"-paperw", argInt, &paperWidth, 0,
+ "paper width, in points"},
+ {"-paperh", argInt, &paperHeight, 0,
+ "paper height, in points"},
+ {"-level1", argFlag, &level1, 0,
+ "generate Level 1 PostScript"},
+ {"-enc", argString, textEncName, sizeof(textEncName),
+ "output text encoding name"},
+ {"-eol", argString, textEOL, sizeof(textEOL),
+ "output end-of-line convention (unix, dos, or mac)"},
+ {"-opw", argString, ownerPassword, sizeof(ownerPassword),
+ "owner password (for encrypted files)"},
+ {"-upw", argString, userPassword, sizeof(userPassword),
+ "user password (for encrypted files)"},
+ {"-fullscreen", argFlag, &fullScreen, 0,
+ "run in full-screen (presentation) mode"},
+ {"-remote", argString, remoteName + 5, sizeof(remoteName) - 5,
+ "start/contact xpdf remote server with specified name"},
+ {"-raise", argFlag, &doRemoteRaise, 0,
+ "raise xpdf remote server window (with -remote only)"},
+ {"-quit", argFlag, &doRemoteQuit, 0,
+ "kill xpdf remote server (with -remote only)"},
+ {"-cmd", argFlag, &printCommands, 0,
+ "print commands as they're executed"},
+ {"-q", argFlag, &quiet, 0,
+ "don't print any messages or errors"},
+ {"-cfg", argString, cfgFileName, sizeof(cfgFileName),
+ "configuration file to use in place of .xpdfrc"},
+ {"-v", argFlag, &printVersion, 0,
+ "print copyright and version info"},
+ {"-h", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"--help", argFlag, &printHelp, 0,
+ "print usage information"},
+ {"-?", argFlag, &printHelp, 0,
+ "print usage information"},
+ {NULL}
+};
+
+//------------------------------------------------------------------------
+
+int main(int argc, char *argv[]) {
+ XPDFApp *app;
+ GString *fileName;
+ int pg;
+ GString *destName;
+ GString *userPasswordStr, *ownerPasswordStr;
+ GBool ok;
+ int exitCode;
+
+ exitCode = 0;
+ userPasswordStr = ownerPasswordStr = NULL;
+
+ // parse args
+ ok = parseArgs(argDesc, &argc, argv);
+
+ // read config file
+ globalParams = new GlobalParams(cfgFileName);
+ if (psFileArg[0]) {
+ globalParams->setPSFile(psFileArg);
+ }
+ if (paperSize[0]) {
+ if (!globalParams->setPSPaperSize(paperSize)) {
+ fprintf(stderr, "Invalid paper size\n");
+ }
+ } else {
+ if (paperWidth) {
+ globalParams->setPSPaperWidth(paperWidth);
+ }
+ if (paperHeight) {
+ globalParams->setPSPaperHeight(paperHeight);
+ }
+ }
+ if (level1) {
+ globalParams->setPSLevel(psLevel1);
+ }
+ if (textEncName[0]) {
+ globalParams->setTextEncoding(textEncName);
+ }
+ if (textEOL[0]) {
+ if (!globalParams->setTextEOL(textEOL)) {
+ fprintf(stderr, "Bad '-eol' value on command line\n");
+ }
+ }
+ if (t1libControlStr[0]) {
+ if (!globalParams->setT1libControl(t1libControlStr)) {
+ fprintf(stderr, "Bad '-t1lib' value on command line\n");
+ }
+ }
+ if (freetypeControlStr[0]) {
+ if (!globalParams->setFreeTypeControl(freetypeControlStr)) {
+ fprintf(stderr, "Bad '-freetype' value on command line\n");
+ }
+ }
+ if (printCommands) {
+ globalParams->setPrintCommands(printCommands);
+ }
+ if (quiet) {
+ globalParams->setErrQuiet(quiet);
+ }
+
+ // create the XPDFApp object
+ app = new XPDFApp(&argc, argv);
+
+ // the initialZoom parameter can be set in either the config file or
+ // as an X resource (or command line arg)
+ if (app->getInitialZoom()) {
+ globalParams->setInitialZoom(app->getInitialZoom()->getCString());
+ }
+
+ // check command line
+ if (doRemoteRaise) {
+ ok = ok && remoteName[5] && !doRemoteQuit && argc >= 1 && argc <= 3;
+ } else if (doRemoteQuit) {
+ ok = ok && remoteName[5] && argc == 1;
+ } else {
+ ok = ok && argc >= 1 && argc <= 3;
+ }
+ if (!ok || printVersion || printHelp) {
+ fprintf(stderr, "xpdf version %s\n", xpdfVersion);
+ fprintf(stderr, "%s\n", xpdfCopyright);
+ if (!printVersion) {
+ printUsage("xpdf", "[<PDF-file> [<page> | +<dest>]]", argDesc);
+ }
+ exitCode = 99;
+ goto done1;
+ }
+ if (argc >= 2) {
+ fileName = new GString(argv[1]);
+ } else {
+ fileName = NULL;
+ }
+ pg = 1;
+ destName = NULL;
+ if (argc == 3) {
+ if (argv[2][0] == '+') {
+ destName = new GString(&argv[2][1]);
+ } else {
+ pg = atoi(argv[2]);
+ }
+ }
+
+ // handle remote server stuff
+ if (remoteName[5]) {
+ app->setRemoteName(remoteName);
+ if (app->remoteServerRunning()) {
+ if (fileName) {
+ if (destName) {
+ app->remoteOpenAtDest(fileName, destName, doRemoteRaise);
+ } else {
+ app->remoteOpen(fileName, pg, doRemoteRaise);
+ }
+ } else if (doRemoteRaise) {
+ app->remoteRaise();
+ } else if (doRemoteQuit) {
+ app->remoteQuit();
+ }
+ goto done2;
+ }
+ if (doRemoteQuit) {
+ goto done2;
+ }
+ }
+
+ // set options
+ app->setFullScreen(fullScreen);
+
+ // check for password string(s)
+ ownerPasswordStr = ownerPassword[0] ? new GString(ownerPassword)
+ : (GString *)NULL;
+ userPasswordStr = userPassword[0] ? new GString(userPassword)
+ : (GString *)NULL;
+
+ // open the file and run the main loop
+ if (destName) {
+ if (!app->openAtDest(fileName, destName,
+ ownerPasswordStr, userPasswordStr)) {
+ exitCode = 1;
+ goto done2;
+ }
+ } else {
+ if (!app->open(fileName, pg, ownerPasswordStr, userPasswordStr)) {
+ exitCode = 1;
+ goto done2;
+ }
+ }
+ app->run();
+
+ exitCode = 0;
+
+ // clean up
+ done2:
+ if (userPasswordStr) {
+ delete userPasswordStr;
+ }
+ if (ownerPasswordStr) {
+ delete ownerPasswordStr;
+ }
+ if (destName) {
+ delete destName;
+ }
+ if (fileName) {
+ delete fileName;
+ }
+ done1:
+ delete app;
+ delete globalParams;
+
+ // check for memory leaks
+ Object::memCheck(stderr);
+ gMemReport(stderr);
+
+ return exitCode;
+}
diff --git a/filters/kword/rtf/export/ExportFilter.cc b/filters/kword/rtf/export/ExportFilter.cpp
index eba2b645d..eba2b645d 100644
--- a/filters/kword/rtf/export/ExportFilter.cc
+++ b/filters/kword/rtf/export/ExportFilter.cpp
diff --git a/filters/kword/rtf/export/Makefile.am b/filters/kword/rtf/export/Makefile.am
index ba3d5c097..e6c49d00c 100644
--- a/filters/kword/rtf/export/Makefile.am
+++ b/filters/kword/rtf/export/Makefile.am
@@ -10,7 +10,7 @@ librtfexport_la_LIBADD = $(KOFFICE_LIBS) ../../libexport/libkwordexportfilters.l
kde_module_LTLIBRARIES = librtfexport.la
-librtfexport_la_SOURCES = rtfexport.cc ExportFilter.cc
+librtfexport_la_SOURCES = rtfexport.cpp ExportFilter.cpp
noinst_HEADERS = rtfexport.h ExportFilter.h
diff --git a/filters/kword/rtf/export/rtfexport.cc b/filters/kword/rtf/export/rtfexport.cc
deleted file mode 100644
index 6f23530b1..000000000
--- a/filters/kword/rtf/export/rtfexport.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// $Header$
-
-/*
- This file is part of the KDE project
- Copyright 2001, 2002 Nicolas GOUTTE <goutte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/*
- This file is based on the old file:
- /home/kde/koffice/filters/kword/ascii/asciiexport.cc
-
- The old file was copyrighted by
- Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
- Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
- Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
-
- The old file was licensed under the terms of the GNU Library General Public
- License version 2.
-*/
-
-#include <kdebug.h>
-#include <kgenericfactory.h>
-#include <kimageio.h>
-#include <KoFilterChain.h>
-
-#include <KWEFBaseWorker.h>
-#include <KWEFKWordLeader.h>
-
-#include "ExportFilter.h"
-
-#include <rtfexport.h>
-#include <rtfexport.moc>
-
-typedef KGenericFactory<RTFExport, KoFilter> RTFExportFactory;
-K_EXPORT_COMPONENT_FACTORY( librtfexport, RTFExportFactory( "kofficefilters" ) )
-
-//
-// RTFExport
-//
-
-RTFExport::RTFExport(KoFilter *, const char *, const TQStringList &) :
- KoFilter() {
-}
-
-KoFilter::ConversionStatus RTFExport::convert( const TQCString& from, const TQCString& to )
-{
- if ((from != "application/x-kword") || (to != "text/rtf" && to != "application/msword" ))
- {
- return KoFilter::NotImplemented;
- }
-
- KImageIO::registerFormats();
-
- RTFWorker* worker=new RTFWorker();
-
- KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
-
- if (!leader)
- {
- kdError(30515) << "Cannot create Worker! Aborting!" << endl;
- delete worker;
- return KoFilter::StupidError;
- }
-
- KoFilter::ConversionStatus result=leader->convert(m_chain, from,to );
-
- delete leader;
- delete worker;
-
- return result;
-}
-
diff --git a/filters/kword/rtf/export/rtfexport.cpp b/filters/kword/rtf/export/rtfexport.cpp
new file mode 100644
index 000000000..91f35523d
--- /dev/null
+++ b/filters/kword/rtf/export/rtfexport.cpp
@@ -0,0 +1,87 @@
+// $Header$
+
+/*
+ This file is part of the KDE project
+ Copyright 2001, 2002 Nicolas GOUTTE <goutte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This file is based on the old file:
+ /home/kde/koffice/filters/kword/ascii/asciiexport.cpp
+
+ The old file was copyrighted by
+ Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Copyright (c) 2000 ID-PRO Deutschland GmbH. All rights reserved.
+ Contact: Wolf-Michael Bolle <Bolle@ID-PRO.de>
+
+ The old file was licensed under the terms of the GNU Library General Public
+ License version 2.
+*/
+
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kimageio.h>
+#include <KoFilterChain.h>
+
+#include <KWEFBaseWorker.h>
+#include <KWEFKWordLeader.h>
+
+#include "ExportFilter.h"
+
+#include <rtfexport.h>
+#include <rtfexport.moc>
+
+typedef KGenericFactory<RTFExport, KoFilter> RTFExportFactory;
+K_EXPORT_COMPONENT_FACTORY( librtfexport, RTFExportFactory( "kofficefilters" ) )
+
+//
+// RTFExport
+//
+
+RTFExport::RTFExport(KoFilter *, const char *, const TQStringList &) :
+ KoFilter() {
+}
+
+KoFilter::ConversionStatus RTFExport::convert( const TQCString& from, const TQCString& to )
+{
+ if ((from != "application/x-kword") || (to != "text/rtf" && to != "application/msword" ))
+ {
+ return KoFilter::NotImplemented;
+ }
+
+ KImageIO::registerFormats();
+
+ RTFWorker* worker=new RTFWorker();
+
+ KWEFKWordLeader* leader=new KWEFKWordLeader(worker);
+
+ if (!leader)
+ {
+ kdError(30515) << "Cannot create Worker! Aborting!" << endl;
+ delete worker;
+ return KoFilter::StupidError;
+ }
+
+ KoFilter::ConversionStatus result=leader->convert(m_chain, from,to );
+
+ delete leader;
+ delete worker;
+
+ return result;
+}
+
diff --git a/filters/kword/starwriter/Makefile.am b/filters/kword/starwriter/Makefile.am
index 6ad15ba84..bba3714d3 100644
--- a/filters/kword/starwriter/Makefile.am
+++ b/filters/kword/starwriter/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libstarwriterimport.la
-libstarwriterimport_la_SOURCES = pole.cpp starwriterimport.cc
+libstarwriterimport_la_SOURCES = pole.cpp starwriterimport.cpp
libstarwriterimport_la_LDFLAGS = -module $(KDE_PLUGIN)
libstarwriterimport_la_LIBADD = $(KOFFICE_LIBS)
diff --git a/filters/kword/starwriter/starwriterimport.cc b/filters/kword/starwriter/starwriterimport.cpp
index 43dc1b623..43dc1b623 100644
--- a/filters/kword/starwriter/starwriterimport.cc
+++ b/filters/kword/starwriter/starwriterimport.cpp
diff --git a/filters/kword/wml/Makefile.am b/filters/kword/wml/Makefile.am
index d22ac2c59..892a57cbf 100644
--- a/filters/kword/wml/Makefile.am
+++ b/filters/kword/wml/Makefile.am
@@ -10,8 +10,8 @@ libwmlexport_la_LIBADD = $(KOFFICE_LIBS) ../libexport/libkwordexportfilters.la
kde_module_LTLIBRARIES = libwmlimport.la libwmlexport.la
-libwmlimport_la_SOURCES = wmlimport.cc wmlparser.cpp
-libwmlexport_la_SOURCES = wmlexport.cc
+libwmlimport_la_SOURCES = wmlimport.cpp wmlparser.cpp
+libwmlexport_la_SOURCES = wmlexport.cpp
noinst_HEADERS = wmlparser.h
diff --git a/filters/kword/wml/wmlexport.cc b/filters/kword/wml/wmlexport.cpp
index 978cb14d2..978cb14d2 100644
--- a/filters/kword/wml/wmlexport.cc
+++ b/filters/kword/wml/wmlexport.cpp
diff --git a/filters/kword/wml/wmlimport.cc b/filters/kword/wml/wmlimport.cpp
index 83e14d9f0..83e14d9f0 100644
--- a/filters/kword/wml/wmlimport.cc
+++ b/filters/kword/wml/wmlimport.cpp
diff --git a/filters/kword/wordperfect/export/Makefile.am b/filters/kword/wordperfect/export/Makefile.am
index a3ef671a3..bc23e5fd2 100644
--- a/filters/kword/wordperfect/export/Makefile.am
+++ b/filters/kword/wordperfect/export/Makefile.am
@@ -2,7 +2,7 @@
INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) -I$(srcdir)/../../libexport $(all_includes)
kde_module_LTLIBRARIES = libwpexport.la
-libwpexport_la_SOURCES = wpexport.cc wp5.cc wp6.cc
+libwpexport_la_SOURCES = wpexport.cpp wp5.cpp wp6.cpp
libwpexport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libwpexport_la_LIBADD = $(KOFFICE_LIBS) ../../libexport/libkwordexportfilters.la
diff --git a/filters/kword/wordperfect/export/wp5.cc b/filters/kword/wordperfect/export/wp5.cpp
index 965753537..965753537 100644
--- a/filters/kword/wordperfect/export/wp5.cc
+++ b/filters/kword/wordperfect/export/wp5.cpp
diff --git a/filters/kword/wordperfect/export/wp6.cc b/filters/kword/wordperfect/export/wp6.cpp
index 5d0079b44..5d0079b44 100644
--- a/filters/kword/wordperfect/export/wp6.cc
+++ b/filters/kword/wordperfect/export/wp6.cpp
diff --git a/filters/kword/wordperfect/export/wpexport.cc b/filters/kword/wordperfect/export/wpexport.cpp
index 619d5d476..619d5d476 100644
--- a/filters/kword/wordperfect/export/wpexport.cc
+++ b/filters/kword/wordperfect/export/wpexport.cpp
diff --git a/filters/kword/wordperfect/import/DocumentElement.cpp b/filters/kword/wordperfect/import/DocumentElement.cpp
new file mode 100644
index 000000000..f10e56969
--- /dev/null
+++ b/filters/kword/wordperfect/import/DocumentElement.cpp
@@ -0,0 +1,108 @@
+/* DocumentElement: The items we are collecting to be put into the Writer
+ * document: paragraph and spans of text, as well as section breaks.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#include "DocumentElement.h"
+#include "DocumentHandler.h"
+#include "FilterInternal.h"
+#include <string.h>
+
+#define ASCII_SPACE 0x0020
+
+void TagElement::print() const
+{
+ WRITER_DEBUG_MSG(("%s\n", msTagName.cstr()));
+}
+
+void TagOpenElement::write(DocumentHandler &xHandler) const
+{
+ xHandler.startElement(getTagName().cstr(), maAttrList);
+}
+
+void TagOpenElement::print() const
+{
+ TagElement::print();
+}
+
+void TagOpenElement::addAttribute(const char *szAttributeName, const _SH_String &sAttributeValue)
+{
+ maAttrList.insert(szAttributeName, sAttributeValue);
+}
+
+void TagCloseElement::write(DocumentHandler &xHandler) const
+{
+ WRITER_DEBUG_MSG(("TagCloseElement: write (%s)\n", getTagName().cstr()));
+
+ xHandler.endElement(getTagName().cstr());
+}
+
+void CharDataElement::write(DocumentHandler &xHandler) const
+{
+ WRITER_DEBUG_MSG(("TextElement: write\n"));
+ xHandler.characters(msData);
+}
+
+TextElement::TextElement(const _SH_String & sTextBuf) :
+#ifdef HAVE_LIBWPD_0100
+ msTextBuf(sTextBuf)
+#else
+ msTextBuf(sTextBuf, false)
+#endif
+{
+}
+
+// write: writes a text run, appropriately converting spaces to <text:s>
+// elements
+void TextElement::write(DocumentHandler &xHandler) const
+{
+ _SH_PropertyList xBlankAttrList;
+
+ _SH_String sTemp;
+
+ int iNumConsecutiveSpaces = 0;
+ _SH_String::Iter i(msTextBuf);
+ for (i.rewind(); i.next();)
+ {
+ if (*(i()) == ASCII_SPACE)
+ iNumConsecutiveSpaces++;
+ else
+ iNumConsecutiveSpaces = 0;
+
+ if (iNumConsecutiveSpaces > 1) {
+ if (sTemp.len() > 0) {
+ xHandler.characters(sTemp);
+ sTemp.clear();
+ }
+ xHandler.startElement("text:s", xBlankAttrList);
+ xHandler.endElement("text:s");
+ }
+ else {
+ sTemp.append(i());
+ }
+ }
+ xHandler.characters(sTemp);
+}
diff --git a/filters/kword/wordperfect/import/DocumentElement.cxx b/filters/kword/wordperfect/import/DocumentElement.cxx
deleted file mode 100644
index a1a928925..000000000
--- a/filters/kword/wordperfect/import/DocumentElement.cxx
+++ /dev/null
@@ -1,108 +0,0 @@
-/* DocumentElement: The items we are collecting to be put into the Writer
- * document: paragraph and spans of text, as well as section breaks.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#include "DocumentElement.hxx"
-#include "DocumentHandler.hxx"
-#include "FilterInternal.hxx"
-#include <string.h>
-
-#define ASCII_SPACE 0x0020
-
-void TagElement::print() const
-{
- WRITER_DEBUG_MSG(("%s\n", msTagName.cstr()));
-}
-
-void TagOpenElement::write(DocumentHandler &xHandler) const
-{
- xHandler.startElement(getTagName().cstr(), maAttrList);
-}
-
-void TagOpenElement::print() const
-{
- TagElement::print();
-}
-
-void TagOpenElement::addAttribute(const char *szAttributeName, const _SH_String &sAttributeValue)
-{
- maAttrList.insert(szAttributeName, sAttributeValue);
-}
-
-void TagCloseElement::write(DocumentHandler &xHandler) const
-{
- WRITER_DEBUG_MSG(("TagCloseElement: write (%s)\n", getTagName().cstr()));
-
- xHandler.endElement(getTagName().cstr());
-}
-
-void CharDataElement::write(DocumentHandler &xHandler) const
-{
- WRITER_DEBUG_MSG(("TextElement: write\n"));
- xHandler.characters(msData);
-}
-
-TextElement::TextElement(const _SH_String & sTextBuf) :
-#ifdef HAVE_LIBWPD_0100
- msTextBuf(sTextBuf)
-#else
- msTextBuf(sTextBuf, false)
-#endif
-{
-}
-
-// write: writes a text run, appropriately converting spaces to <text:s>
-// elements
-void TextElement::write(DocumentHandler &xHandler) const
-{
- _SH_PropertyList xBlankAttrList;
-
- _SH_String sTemp;
-
- int iNumConsecutiveSpaces = 0;
- _SH_String::Iter i(msTextBuf);
- for (i.rewind(); i.next();)
- {
- if (*(i()) == ASCII_SPACE)
- iNumConsecutiveSpaces++;
- else
- iNumConsecutiveSpaces = 0;
-
- if (iNumConsecutiveSpaces > 1) {
- if (sTemp.len() > 0) {
- xHandler.characters(sTemp);
- sTemp.clear();
- }
- xHandler.startElement("text:s", xBlankAttrList);
- xHandler.endElement("text:s");
- }
- else {
- sTemp.append(i());
- }
- }
- xHandler.characters(sTemp);
-}
diff --git a/filters/kword/wordperfect/import/DocumentElement.h b/filters/kword/wordperfect/import/DocumentElement.h
new file mode 100644
index 000000000..3fc2cf532
--- /dev/null
+++ b/filters/kword/wordperfect/import/DocumentElement.h
@@ -0,0 +1,97 @@
+/* DocumentElement: The items we are collecting to be put into the Writer
+ * document: paragraph and spans of text, as well as section breaks.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#ifndef _DOCUMENTELEMENT_H
+#define _DOCUMENTELEMENT_H
+
+#include <libwpd/libwpd.h>
+#include <vector>
+#include "shared_headers.h"
+#include "DocumentHandler.h"
+
+const float fDefaultSideMargin = 1.0f; // inches
+const float fDefaultPageWidth = 8.5f; // inches (OOo required default: we will handle this later)
+const float fDefaultPageHeight = 11.0f; // inches
+
+class DocumentElement
+{
+public:
+ virtual ~DocumentElement() {}
+ virtual void write(DocumentHandler &xHandler) const = 0;
+ virtual void print() const {}
+};
+
+class TagElement : public DocumentElement
+{
+public:
+ TagElement(const char *szTagName) : msTagName(szTagName) {}
+ const _SH_String & getTagName() const { return msTagName; }
+ virtual void print() const;
+private:
+ _SH_String msTagName;
+};
+
+class TagOpenElement : public TagElement
+{
+public:
+ TagOpenElement(const char *szTagName) : TagElement(szTagName) {}
+ ~TagOpenElement() {}
+ void addAttribute(const char *szAttributeName, const _SH_String &sAttributeValue);
+ virtual void write(DocumentHandler &xHandler) const;
+ virtual void print () const;
+private:
+ _SH_PropertyList maAttrList;
+};
+
+class TagCloseElement : public TagElement
+{
+public:
+ TagCloseElement(const char *szTagName) : TagElement(szTagName) {}
+ virtual void write(DocumentHandler &xHandler) const;
+};
+
+class CharDataElement : public DocumentElement
+{
+public:
+ CharDataElement(const char *sData) : DocumentElement(), msData(sData) {}
+ virtual void write(DocumentHandler &xHandler) const;
+private:
+ _SH_String msData;
+};
+
+class TextElement : public DocumentElement
+{
+public:
+ TextElement(const _SH_String & sTextBuf);
+ virtual void write(DocumentHandler &xHandler) const;
+
+private:
+ _SH_String msTextBuf;
+};
+
+#endif
diff --git a/filters/kword/wordperfect/import/DocumentElement.hxx b/filters/kword/wordperfect/import/DocumentElement.hxx
deleted file mode 100644
index 764758e83..000000000
--- a/filters/kword/wordperfect/import/DocumentElement.hxx
+++ /dev/null
@@ -1,97 +0,0 @@
-/* DocumentElement: The items we are collecting to be put into the Writer
- * document: paragraph and spans of text, as well as section breaks.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#ifndef _DOCUMENTELEMENT_H
-#define _DOCUMENTELEMENT_H
-
-#include <libwpd/libwpd.h>
-#include <vector>
-#include "shared_headers.h"
-#include "DocumentHandler.hxx"
-
-const float fDefaultSideMargin = 1.0f; // inches
-const float fDefaultPageWidth = 8.5f; // inches (OOo required default: we will handle this later)
-const float fDefaultPageHeight = 11.0f; // inches
-
-class DocumentElement
-{
-public:
- virtual ~DocumentElement() {}
- virtual void write(DocumentHandler &xHandler) const = 0;
- virtual void print() const {}
-};
-
-class TagElement : public DocumentElement
-{
-public:
- TagElement(const char *szTagName) : msTagName(szTagName) {}
- const _SH_String & getTagName() const { return msTagName; }
- virtual void print() const;
-private:
- _SH_String msTagName;
-};
-
-class TagOpenElement : public TagElement
-{
-public:
- TagOpenElement(const char *szTagName) : TagElement(szTagName) {}
- ~TagOpenElement() {}
- void addAttribute(const char *szAttributeName, const _SH_String &sAttributeValue);
- virtual void write(DocumentHandler &xHandler) const;
- virtual void print () const;
-private:
- _SH_PropertyList maAttrList;
-};
-
-class TagCloseElement : public TagElement
-{
-public:
- TagCloseElement(const char *szTagName) : TagElement(szTagName) {}
- virtual void write(DocumentHandler &xHandler) const;
-};
-
-class CharDataElement : public DocumentElement
-{
-public:
- CharDataElement(const char *sData) : DocumentElement(), msData(sData) {}
- virtual void write(DocumentHandler &xHandler) const;
-private:
- _SH_String msData;
-};
-
-class TextElement : public DocumentElement
-{
-public:
- TextElement(const _SH_String & sTextBuf);
- virtual void write(DocumentHandler &xHandler) const;
-
-private:
- _SH_String msTextBuf;
-};
-
-#endif
diff --git a/filters/kword/wordperfect/import/DocumentHandler.hxx b/filters/kword/wordperfect/import/DocumentHandler.h
index ff8e39f03..ff8e39f03 100644
--- a/filters/kword/wordperfect/import/DocumentHandler.hxx
+++ b/filters/kword/wordperfect/import/DocumentHandler.h
diff --git a/filters/kword/wordperfect/import/FilterInternal.h b/filters/kword/wordperfect/import/FilterInternal.h
new file mode 100644
index 000000000..0a20f7c60
--- /dev/null
+++ b/filters/kword/wordperfect/import/FilterInternal.h
@@ -0,0 +1,36 @@
+/* FilterInternal: Debugging information
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+#include <stdio.h>
+#ifdef DEBUG
+#define WRITER_DEBUG_MSG(M) printf M
+#else
+#define WRITER_DEBUG_MSG(M)
+#endif
+
+#if 0
+#include <rtl/string.h>
+inline rtl::OString utf8_itoa(int i)
+{
+ return rtl::OString::valueOf( (sal_Int32) i );
+}
+#endif
diff --git a/filters/kword/wordperfect/import/FilterInternal.hxx b/filters/kword/wordperfect/import/FilterInternal.hxx
deleted file mode 100644
index 51615951e..000000000
--- a/filters/kword/wordperfect/import/FilterInternal.hxx
+++ /dev/null
@@ -1,36 +0,0 @@
-/* FilterInternal: Debugging information
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-#include <stdio.h>
-#ifdef DEBUG
-#define WRITER_DEBUG_MSG(M) printf M
-#else
-#define WRITER_DEBUG_MSG(M)
-#endif
-
-#if 0
-#include <rtl/string.hxx>
-inline rtl::OString utf8_itoa(int i)
-{
- return rtl::OString::valueOf( (sal_Int32) i );
-}
-#endif
diff --git a/filters/kword/wordperfect/import/FontStyle.cpp b/filters/kword/wordperfect/import/FontStyle.cpp
new file mode 100644
index 000000000..6099e7e39
--- /dev/null
+++ b/filters/kword/wordperfect/import/FontStyle.cpp
@@ -0,0 +1,51 @@
+/* FontStyle: Stores (and writes) font-based information that is needed at
+ * the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include "FontStyle.h"
+#include "WriterProperties.h"
+#include "DocumentElement.h"
+
+FontStyle::FontStyle(const char *psName, const char *psFontFamily) : Style(psName),
+ msFontFamily(psFontFamily),
+ msFontPitch(IMP_DEFAULT_FONT_PITCH)
+{
+}
+
+FontStyle::~FontStyle()
+{
+}
+
+void FontStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement styleOpen("style:font-decl");
+ styleOpen.addAttribute("style:name", getName());
+ styleOpen.addAttribute("fo:font-family", msFontFamily);
+ styleOpen.addAttribute("style:font-pitch", msFontPitch);
+ styleOpen.write(xHandler);
+ TagCloseElement styleClose("style:font-decl");
+ styleClose.write(xHandler);
+}
diff --git a/filters/kword/wordperfect/import/FontStyle.cxx b/filters/kword/wordperfect/import/FontStyle.cxx
deleted file mode 100644
index b926ccddc..000000000
--- a/filters/kword/wordperfect/import/FontStyle.cxx
+++ /dev/null
@@ -1,51 +0,0 @@
-/* FontStyle: Stores (and writes) font-based information that is needed at
- * the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include "FontStyle.hxx"
-#include "WriterProperties.hxx"
-#include "DocumentElement.hxx"
-
-FontStyle::FontStyle(const char *psName, const char *psFontFamily) : Style(psName),
- msFontFamily(psFontFamily),
- msFontPitch(IMP_DEFAULT_FONT_PITCH)
-{
-}
-
-FontStyle::~FontStyle()
-{
-}
-
-void FontStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement styleOpen("style:font-decl");
- styleOpen.addAttribute("style:name", getName());
- styleOpen.addAttribute("fo:font-family", msFontFamily);
- styleOpen.addAttribute("style:font-pitch", msFontPitch);
- styleOpen.write(xHandler);
- TagCloseElement styleClose("style:font-decl");
- styleClose.write(xHandler);
-}
diff --git a/filters/kword/wordperfect/import/FontStyle.h b/filters/kword/wordperfect/import/FontStyle.h
new file mode 100644
index 000000000..994184950
--- /dev/null
+++ b/filters/kword/wordperfect/import/FontStyle.h
@@ -0,0 +1,48 @@
+/* FontStyle: Stores (and writes) font-based information that is needed at
+ * the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#ifndef _FONTSTYLE_H
+#define _FONTSTYLE_H
+
+#include <libwpd/libwpd.h>
+#include "Style.h"
+#include "WriterProperties.h"
+#include "shared_headers.h"
+
+class FontStyle : public Style
+{
+public:
+ FontStyle(const char *psName, const char *psFontFamily);
+ ~FontStyle();
+ virtual void write(DocumentHandler &xHandler) const;
+ const _SH_String &getFontFamily() const { return msFontFamily; }
+
+private:
+ _SH_String msFontFamily;
+ _SH_String msFontPitch;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/FontStyle.hxx b/filters/kword/wordperfect/import/FontStyle.hxx
deleted file mode 100644
index 6d09de5c8..000000000
--- a/filters/kword/wordperfect/import/FontStyle.hxx
+++ /dev/null
@@ -1,48 +0,0 @@
-/* FontStyle: Stores (and writes) font-based information that is needed at
- * the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#ifndef _FONTSTYLE_H
-#define _FONTSTYLE_H
-
-#include <libwpd/libwpd.h>
-#include "Style.hxx"
-#include "WriterProperties.hxx"
-#include "shared_headers.h"
-
-class FontStyle : public Style
-{
-public:
- FontStyle(const char *psName, const char *psFontFamily);
- ~FontStyle();
- virtual void write(DocumentHandler &xHandler) const;
- const _SH_String &getFontFamily() const { return msFontFamily; }
-
-private:
- _SH_String msFontFamily;
- _SH_String msFontPitch;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/ListStyle.cpp b/filters/kword/wordperfect/import/ListStyle.cpp
new file mode 100644
index 000000000..baba4b679
--- /dev/null
+++ b/filters/kword/wordperfect/import/ListStyle.cpp
@@ -0,0 +1,162 @@
+/* ListStyle: Stores (and writes) list-based information that is
+ * needed at the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include "FilterInternal.h"
+#include "ListStyle.h"
+#include "DocumentElement.h"
+
+OrderedListLevelStyle::OrderedListLevelStyle(const _SH_PropertyList &xPropList) :
+ mPropList(xPropList)
+{
+}
+
+void OrderedListStyle::updateListLevel(const int iLevel, const _SH_PropertyList &xPropList)
+{
+ if (iLevel < 0)
+ return;
+ if (!isListLevelDefined(iLevel))
+ setListLevel(iLevel, new OrderedListLevelStyle(xPropList));
+}
+
+void OrderedListLevelStyle::write(DocumentHandler &xHandler, int iLevel) const
+{
+ _SH_String sLevel;
+ sLevel.sprintf("%i", (iLevel+1));
+
+ TagOpenElement listLevelStyleOpen("text:list-level-style-number");
+ listLevelStyleOpen.addAttribute("text:level", sLevel);
+ listLevelStyleOpen.addAttribute("text:style-name", "Numbering Symbols");
+ if (mPropList["style:num-prefix"])
+ listLevelStyleOpen.addAttribute("style:num-prefix", mPropList["style:num-prefix"]->getStr());
+ if (mPropList["style:num-suffix"])
+ listLevelStyleOpen.addAttribute("style:num-suffix", mPropList["style:num-suffix"]->getStr());
+ if (mPropList["style:num-format"])
+ listLevelStyleOpen.addAttribute("style:num-format", mPropList["style:num-format"]->getStr());
+ if (mPropList["text:start-value"])
+ listLevelStyleOpen.addAttribute("text:start-value", mPropList["text:start-value"]->getStr());
+ listLevelStyleOpen.write(xHandler);
+
+ TagOpenElement stylePropertiesOpen("style:properties");
+ if (mPropList["text:space-before"])
+ stylePropertiesOpen.addAttribute("text:space-before", mPropList["text:space-before"]->getStr());
+ if (mPropList["text:min-label-width"])
+ stylePropertiesOpen.addAttribute("text:min-label-width", mPropList["text:min-label-width"]->getStr());
+ if (mPropList["text:min-label-distance"])
+ stylePropertiesOpen.addAttribute("text:min-label-distance", mPropList["text:min-label-distance"]->getStr());
+ stylePropertiesOpen.write(xHandler);
+
+ xHandler.endElement("style:properties");
+ xHandler.endElement("text:list-level-style-number");
+}
+
+UnorderedListLevelStyle::UnorderedListLevelStyle(const _SH_PropertyList &xPropList)
+ : mPropList(xPropList)
+{
+}
+
+void UnorderedListStyle::updateListLevel(const int iLevel, const _SH_PropertyList &xPropList)
+{
+ if (iLevel < 0)
+ return;
+ if (!isListLevelDefined(iLevel))
+ setListLevel(iLevel, new UnorderedListLevelStyle(xPropList));
+}
+
+void UnorderedListLevelStyle::write(DocumentHandler &xHandler, int iLevel) const
+{
+ _SH_String sLevel;
+ sLevel.sprintf("%i", (iLevel+1));
+ TagOpenElement listLevelStyleOpen("text:list-level-style-bullet");
+ listLevelStyleOpen.addAttribute("text:level", sLevel);
+ listLevelStyleOpen.addAttribute("text:style-name", "Bullet Symbols");
+ listLevelStyleOpen.addAttribute("style:num-suffice", ".");
+ if (mPropList["text:bullet-char"])
+ listLevelStyleOpen.addAttribute("text:bullet-char", mPropList["text:bullet-char"]->getStr());
+ listLevelStyleOpen.write(xHandler);
+
+ TagOpenElement stylePropertiesOpen("style:properties");
+ if (mPropList["text:space-before"])
+ stylePropertiesOpen.addAttribute("text:space-before", mPropList["text:space-before"]->getStr());
+ if (mPropList["text:min-label-width"])
+ stylePropertiesOpen.addAttribute("text:min-label-width", mPropList["text:min-label-width"]->getStr());
+ if (mPropList["text:min-label-distance"])
+ stylePropertiesOpen.addAttribute("text:min-label-distance", mPropList["text:min-label-distance"]->getStr());
+ stylePropertiesOpen.addAttribute("style:font-name", "OpenSymbol");
+ stylePropertiesOpen.write(xHandler);
+
+ xHandler.endElement("style:properties");
+ xHandler.endElement("text:list-level-style-bullet");
+}
+
+ListStyle::ListStyle(const char *psName, const int iListID) :
+ Style(psName),
+ miListID(iListID)
+{
+ for (int i=0; i<WP6_NUM_LIST_LEVELS; i++)
+ mppListLevels[i] = NULL;
+
+}
+
+ListStyle::~ListStyle()
+{
+ for (int i=0; i<WP6_NUM_LIST_LEVELS; i++) {
+ if (mppListLevels[i])
+ delete(mppListLevels[i]);
+ }
+
+}
+
+const bool ListStyle::isListLevelDefined(int iLevel) const
+{
+ if (mppListLevels[iLevel] == NULL)
+ return false;
+
+ return true;
+}
+
+void ListStyle::setListLevel(int iLevel, ListLevelStyle *iListLevelStyle)
+{
+ // can't uncomment this next line without adding some extra logic.
+ // figure out which is best: use the initial message, or constantly
+ // update?
+ if (mppListLevels[iLevel] == NULL)
+ mppListLevels[iLevel] = iListLevelStyle;
+}
+
+void ListStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement listStyleOpenElement("text:list-style");
+ listStyleOpenElement.addAttribute("style:name", getName());
+ listStyleOpenElement.write(xHandler);
+
+ for (int i=0; i<WP6_NUM_LIST_LEVELS; i++) {
+ if (mppListLevels[i] != NULL)
+ mppListLevels[i]->write(xHandler, i);
+ }
+
+ xHandler.endElement("text:list-style");
+}
diff --git a/filters/kword/wordperfect/import/ListStyle.cxx b/filters/kword/wordperfect/import/ListStyle.cxx
deleted file mode 100644
index 66373a109..000000000
--- a/filters/kword/wordperfect/import/ListStyle.cxx
+++ /dev/null
@@ -1,162 +0,0 @@
-/* ListStyle: Stores (and writes) list-based information that is
- * needed at the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include "FilterInternal.hxx"
-#include "ListStyle.hxx"
-#include "DocumentElement.hxx"
-
-OrderedListLevelStyle::OrderedListLevelStyle(const _SH_PropertyList &xPropList) :
- mPropList(xPropList)
-{
-}
-
-void OrderedListStyle::updateListLevel(const int iLevel, const _SH_PropertyList &xPropList)
-{
- if (iLevel < 0)
- return;
- if (!isListLevelDefined(iLevel))
- setListLevel(iLevel, new OrderedListLevelStyle(xPropList));
-}
-
-void OrderedListLevelStyle::write(DocumentHandler &xHandler, int iLevel) const
-{
- _SH_String sLevel;
- sLevel.sprintf("%i", (iLevel+1));
-
- TagOpenElement listLevelStyleOpen("text:list-level-style-number");
- listLevelStyleOpen.addAttribute("text:level", sLevel);
- listLevelStyleOpen.addAttribute("text:style-name", "Numbering Symbols");
- if (mPropList["style:num-prefix"])
- listLevelStyleOpen.addAttribute("style:num-prefix", mPropList["style:num-prefix"]->getStr());
- if (mPropList["style:num-suffix"])
- listLevelStyleOpen.addAttribute("style:num-suffix", mPropList["style:num-suffix"]->getStr());
- if (mPropList["style:num-format"])
- listLevelStyleOpen.addAttribute("style:num-format", mPropList["style:num-format"]->getStr());
- if (mPropList["text:start-value"])
- listLevelStyleOpen.addAttribute("text:start-value", mPropList["text:start-value"]->getStr());
- listLevelStyleOpen.write(xHandler);
-
- TagOpenElement stylePropertiesOpen("style:properties");
- if (mPropList["text:space-before"])
- stylePropertiesOpen.addAttribute("text:space-before", mPropList["text:space-before"]->getStr());
- if (mPropList["text:min-label-width"])
- stylePropertiesOpen.addAttribute("text:min-label-width", mPropList["text:min-label-width"]->getStr());
- if (mPropList["text:min-label-distance"])
- stylePropertiesOpen.addAttribute("text:min-label-distance", mPropList["text:min-label-distance"]->getStr());
- stylePropertiesOpen.write(xHandler);
-
- xHandler.endElement("style:properties");
- xHandler.endElement("text:list-level-style-number");
-}
-
-UnorderedListLevelStyle::UnorderedListLevelStyle(const _SH_PropertyList &xPropList)
- : mPropList(xPropList)
-{
-}
-
-void UnorderedListStyle::updateListLevel(const int iLevel, const _SH_PropertyList &xPropList)
-{
- if (iLevel < 0)
- return;
- if (!isListLevelDefined(iLevel))
- setListLevel(iLevel, new UnorderedListLevelStyle(xPropList));
-}
-
-void UnorderedListLevelStyle::write(DocumentHandler &xHandler, int iLevel) const
-{
- _SH_String sLevel;
- sLevel.sprintf("%i", (iLevel+1));
- TagOpenElement listLevelStyleOpen("text:list-level-style-bullet");
- listLevelStyleOpen.addAttribute("text:level", sLevel);
- listLevelStyleOpen.addAttribute("text:style-name", "Bullet Symbols");
- listLevelStyleOpen.addAttribute("style:num-suffice", ".");
- if (mPropList["text:bullet-char"])
- listLevelStyleOpen.addAttribute("text:bullet-char", mPropList["text:bullet-char"]->getStr());
- listLevelStyleOpen.write(xHandler);
-
- TagOpenElement stylePropertiesOpen("style:properties");
- if (mPropList["text:space-before"])
- stylePropertiesOpen.addAttribute("text:space-before", mPropList["text:space-before"]->getStr());
- if (mPropList["text:min-label-width"])
- stylePropertiesOpen.addAttribute("text:min-label-width", mPropList["text:min-label-width"]->getStr());
- if (mPropList["text:min-label-distance"])
- stylePropertiesOpen.addAttribute("text:min-label-distance", mPropList["text:min-label-distance"]->getStr());
- stylePropertiesOpen.addAttribute("style:font-name", "OpenSymbol");
- stylePropertiesOpen.write(xHandler);
-
- xHandler.endElement("style:properties");
- xHandler.endElement("text:list-level-style-bullet");
-}
-
-ListStyle::ListStyle(const char *psName, const int iListID) :
- Style(psName),
- miListID(iListID)
-{
- for (int i=0; i<WP6_NUM_LIST_LEVELS; i++)
- mppListLevels[i] = NULL;
-
-}
-
-ListStyle::~ListStyle()
-{
- for (int i=0; i<WP6_NUM_LIST_LEVELS; i++) {
- if (mppListLevels[i])
- delete(mppListLevels[i]);
- }
-
-}
-
-const bool ListStyle::isListLevelDefined(int iLevel) const
-{
- if (mppListLevels[iLevel] == NULL)
- return false;
-
- return true;
-}
-
-void ListStyle::setListLevel(int iLevel, ListLevelStyle *iListLevelStyle)
-{
- // can't uncomment this next line without adding some extra logic.
- // figure out which is best: use the initial message, or constantly
- // update?
- if (mppListLevels[iLevel] == NULL)
- mppListLevels[iLevel] = iListLevelStyle;
-}
-
-void ListStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement listStyleOpenElement("text:list-style");
- listStyleOpenElement.addAttribute("style:name", getName());
- listStyleOpenElement.write(xHandler);
-
- for (int i=0; i<WP6_NUM_LIST_LEVELS; i++) {
- if (mppListLevels[i] != NULL)
- mppListLevels[i]->write(xHandler, i);
- }
-
- xHandler.endElement("text:list-style");
-}
diff --git a/filters/kword/wordperfect/import/ListStyle.h b/filters/kword/wordperfect/import/ListStyle.h
new file mode 100644
index 000000000..11bda504d
--- /dev/null
+++ b/filters/kword/wordperfect/import/ListStyle.h
@@ -0,0 +1,97 @@
+/* ListStyle: Stores (and writes) list-based information that is
+ * needed at the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#ifndef _LISTSTYLE_H
+#define _LISTSTYLE_H
+#include <libwpd/libwpd.h>
+#include "shared_headers.h"
+
+#define WP6_NUM_LIST_LEVELS 8 // see WP6FileStructure.h (we shouldn't need to reference this)
+
+#include "Style.h"
+#include "WriterProperties.h"
+
+class DocumentElement;
+
+class ListLevelStyle
+{
+public:
+ virtual void write(DocumentHandler &xHandler, int iLevel) const = 0;
+ virtual ~ListLevelStyle() {}
+};
+
+class OrderedListLevelStyle : public ListLevelStyle
+{
+public:
+ OrderedListLevelStyle(const _SH_PropertyList &xPropList);
+ virtual void write(DocumentHandler &xHandler, int iLevel) const;
+private:
+ _SH_PropertyList mPropList;
+};
+
+class UnorderedListLevelStyle : public ListLevelStyle
+{
+public:
+ UnorderedListLevelStyle(const _SH_PropertyList &xPropList);
+ virtual void write(DocumentHandler &xHandler, int iLevel) const;
+private:
+ _SH_PropertyList mPropList;
+};
+
+class ListStyle : public Style
+{
+public:
+ ListStyle(const char *psName, const int iListID);
+ virtual ~ListStyle();
+ virtual void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList) = 0;
+ virtual void write(DocumentHandler &xHandler) const;
+ const int getListID() { return miListID; }
+ const bool isListLevelDefined(int iLevel) const;
+
+protected:
+ void setListLevel(int iLevel, ListLevelStyle *iListLevelStyle);
+
+private:
+ ListLevelStyle *mppListLevels[WP6_NUM_LIST_LEVELS];
+ int miNumListLevels;
+ const int miListID;
+};
+
+class OrderedListStyle : public ListStyle
+{
+public:
+ OrderedListStyle(const char *psName, const int iListID) : ListStyle(psName, iListID) {}
+ void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList);
+};
+
+class UnorderedListStyle : public ListStyle
+{
+public:
+ UnorderedListStyle(const char *psName, const int iListID) : ListStyle(psName, iListID) {}
+ void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList);
+};
+#endif
diff --git a/filters/kword/wordperfect/import/ListStyle.hxx b/filters/kword/wordperfect/import/ListStyle.hxx
deleted file mode 100644
index d8e6a25f2..000000000
--- a/filters/kword/wordperfect/import/ListStyle.hxx
+++ /dev/null
@@ -1,97 +0,0 @@
-/* ListStyle: Stores (and writes) list-based information that is
- * needed at the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#ifndef _LISTSTYLE_H
-#define _LISTSTYLE_H
-#include <libwpd/libwpd.h>
-#include "shared_headers.h"
-
-#define WP6_NUM_LIST_LEVELS 8 // see WP6FileStructure.h (we shouldn't need to reference this)
-
-#include "Style.hxx"
-#include "WriterProperties.hxx"
-
-class DocumentElement;
-
-class ListLevelStyle
-{
-public:
- virtual void write(DocumentHandler &xHandler, int iLevel) const = 0;
- virtual ~ListLevelStyle() {}
-};
-
-class OrderedListLevelStyle : public ListLevelStyle
-{
-public:
- OrderedListLevelStyle(const _SH_PropertyList &xPropList);
- virtual void write(DocumentHandler &xHandler, int iLevel) const;
-private:
- _SH_PropertyList mPropList;
-};
-
-class UnorderedListLevelStyle : public ListLevelStyle
-{
-public:
- UnorderedListLevelStyle(const _SH_PropertyList &xPropList);
- virtual void write(DocumentHandler &xHandler, int iLevel) const;
-private:
- _SH_PropertyList mPropList;
-};
-
-class ListStyle : public Style
-{
-public:
- ListStyle(const char *psName, const int iListID);
- virtual ~ListStyle();
- virtual void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList) = 0;
- virtual void write(DocumentHandler &xHandler) const;
- const int getListID() { return miListID; }
- const bool isListLevelDefined(int iLevel) const;
-
-protected:
- void setListLevel(int iLevel, ListLevelStyle *iListLevelStyle);
-
-private:
- ListLevelStyle *mppListLevels[WP6_NUM_LIST_LEVELS];
- int miNumListLevels;
- const int miListID;
-};
-
-class OrderedListStyle : public ListStyle
-{
-public:
- OrderedListStyle(const char *psName, const int iListID) : ListStyle(psName, iListID) {}
- void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList);
-};
-
-class UnorderedListStyle : public ListStyle
-{
-public:
- UnorderedListStyle(const char *psName, const int iListID) : ListStyle(psName, iListID) {}
- void updateListLevel(const int iLevel, const _SH_PropertyList &xPropList);
-};
-#endif
diff --git a/filters/kword/wordperfect/import/Makefile.am b/filters/kword/wordperfect/import/Makefile.am
index 92494e0ea..f5380749a 100644
--- a/filters/kword/wordperfect/import/Makefile.am
+++ b/filters/kword/wordperfect/import/Makefile.am
@@ -2,11 +2,11 @@ INCLUDES= -I$(srcdir) $(KOFFICE_INCLUDES) $(LIBWPD_CFLAGS) $(all_includes)
kde_module_LTLIBRARIES = libwpimport.la
-libwpimport_la_SOURCES = wpimport.cc DocumentElement.cxx FontStyle.cxx ListStyle.cxx PageSpan.cxx SectionStyle.cxx TableStyle.cxx TextRunStyle.cxx WordPerfectCollector.cxx
+libwpimport_la_SOURCES = wpimport.cpp DocumentElement.cpp FontStyle.cpp ListStyle.cpp PageSpan.cpp SectionStyle.cpp TableStyle.cpp TextRunStyle.cpp WordPerfectCollector.cpp
libwpimport_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined
libwpimport_la_LIBADD = $(KOFFICE_LIBS) $(LIBWPD_LIBS)
-noinst_HEADERS = wpimport.h FilterInternal.hxx Style.hxx WriterProperties.hxx DocumentElement.hxx DocumentHandler.hxx FontStyle.hxx ListStyle.hxx PageSpan.hxx SectionStyle.hxx TableStyle.hxx TextRunStyle.hxx WordPerfectCollector.hxx
+noinst_HEADERS = wpimport.h FilterInternal.h Style.h WriterProperties.h DocumentElement.h DocumentHandler.h FontStyle.h ListStyle.h PageSpan.h SectionStyle.h TableStyle.h TextRunStyle.h WordPerfectCollector.h
METASOURCES = AUTO
diff --git a/filters/kword/wordperfect/import/PageSpan.cpp b/filters/kword/wordperfect/import/PageSpan.cpp
new file mode 100644
index 000000000..0127d0804
--- /dev/null
+++ b/filters/kword/wordperfect/import/PageSpan.cpp
@@ -0,0 +1,180 @@
+/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
+ * break needs a new section) that is needed at the head of an OO document and
+ * is referenced throughout the entire document
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include <config.h>
+
+#include "FilterInternal.h"
+#include "PageSpan.h"
+#include "DocumentElement.h"
+
+
+PageSpan::PageSpan(const _SH_PropertyList &xPropList) :
+#if 0
+const int iSpan, const float fFormLength, const float fFormWidth, const WPXFormQt::Orientation fFormQt::Orientation,
+ const float fLeftMargin, const float fRightMargin, const float fTopMargin, const float fBottomMargin):
+ miSpan(iSpan),
+ mfFormLength(fFormLength),
+ mfFormWidth(fFormWidth),
+ mfFormQt::Orientation(fFormQt::Orientation),
+ mfMarginLeft(fLeftMargin),
+ mfMarginRight(fRightMargin),
+ mfMarginTop(fTopMargin),
+ mfMarginBottom(fBottomMargin),
+#endif
+ mxPropList(xPropList),
+ mpHeaderContent(NULL),
+ mpFooterContent(NULL),
+ mpHeaderLeftContent(NULL),
+ mpFooterLeftContent(NULL)
+{
+}
+
+PageSpan::~PageSpan()
+{
+ delete mpHeaderContent;
+ delete mpHeaderLeftContent;
+ delete mpFooterContent;
+ delete mpFooterLeftContent;
+}
+
+int PageSpan::getSpan() const
+{
+ if (mxPropList["libwpd:num-pages"])
+ return mxPropList["libwpd:num-pages"]->getInt();
+
+ return 0; // should never happen
+}
+
+float PageSpan::getMarginLeft() const
+{
+ if (mxPropList["fo:margin-left"])
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+ return mxPropList["fo:margin-left"]->getDouble();
+#else
+ return mxPropList["fo:margin-left"]->getFloat();
+#endif
+
+ return 0.0f;
+}
+
+float PageSpan::getMarginRight() const
+{
+ if (mxPropList["fo:margin-right"])
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+ return mxPropList["fo:margin-right"]->getDouble();
+#else
+ return mxPropList["fo:margin-right"]->getFloat();
+#endif
+
+ return 0.0f;
+}
+
+void PageSpan::writePageMaster(const int iNum, DocumentHandler &xHandler) const
+{
+ _SH_PropertyList propList;
+
+ _SH_String sPageMasterName;
+ sPageMasterName.sprintf("PM%i", iNum+2);
+ propList.insert("style:name", sPageMasterName);
+ xHandler.startElement("style:page-master", propList);
+
+ _SH_PropertyList tempPropList = mxPropList;
+ if (!tempPropList["style:writing-mode"])
+ tempPropList.insert("style:writing-mode", _SH_String("lr-tb"));
+ if (!tempPropList["style:footnote-max-height"])
+ tempPropList.insert("style:footnote-max-height", _SH_String("0inch"));
+ xHandler.startElement("style:properties", tempPropList);
+
+ _SH_PropertyList footnoteSepPropList;
+ footnoteSepPropList.insert("style:width", _SH_String("0.0071inch"));
+ footnoteSepPropList.insert("style:distance-before-sep", _SH_String("0.0398inch"));
+ footnoteSepPropList.insert("style:distance-after-sep", _SH_String("0.0398inch"));
+ footnoteSepPropList.insert("style:adjustment", _SH_String("left"));
+ footnoteSepPropList.insert("style:rel-width", _SH_String("25\%"));
+ footnoteSepPropList.insert("style:color", _SH_String("#000000"));
+ xHandler.startElement("style:footnote-sep", footnoteSepPropList);
+
+ xHandler.endElement("style:footnote-sep");
+ xHandler.endElement("style:properties");
+ xHandler.endElement("style:page-master");
+}
+
+void PageSpan::writeMasterPages(const int iStartingNum, const int iPageMasterNum, const bool bLastPageSpan,
+ DocumentHandler &xHandler) const
+{
+ _SH_PropertyList propList; // scratch space
+
+ int iSpan = 0;
+ (bLastPageSpan) ? iSpan = 1 : iSpan = getSpan();
+
+ for (int i=iStartingNum; i<(iStartingNum+iSpan); i++)
+ {
+ TagOpenElement masterPageOpen("style:master-page");
+ _SH_String sMasterPageName;
+ sMasterPageName.sprintf("Page Style %i", i);
+ _SH_String sPageMasterName;
+ sPageMasterName.sprintf("PM%i", iPageMasterNum+2);
+ propList.insert("style:name", sMasterPageName);
+ propList.insert("style:page-master-name", sPageMasterName);
+ if (!bLastPageSpan)
+ {
+ _SH_String sNextMasterPageName;
+ sNextMasterPageName.sprintf("Page Style %i", (i+1));
+ propList.insert("style:next-style-name", sNextMasterPageName);
+ }
+ xHandler.startElement("style:master-page", propList);
+
+ if (mpHeaderContent)
+ _writeHeaderFooter("style:header", *mpHeaderContent, xHandler);
+ if (mpHeaderLeftContent)
+ _writeHeaderFooter("style:header-left", *mpHeaderLeftContent, xHandler);
+ if (mpFooterContent)
+ _writeHeaderFooter("style:footer", *mpFooterContent, xHandler);
+ if (mpFooterLeftContent)
+ _writeHeaderFooter("style:footer-left", *mpFooterLeftContent, xHandler);
+
+ xHandler.endElement("style:master-page");
+ }
+
+}
+
+void PageSpan::_writeHeaderFooter(const char *headerFooterTagName,
+ const std::vector<DocumentElement *> & headerFooterContent,
+ DocumentHandler &xHandler) const
+{
+ TagOpenElement headerFooterOpen(headerFooterTagName);
+ headerFooterOpen.write(xHandler);
+ for (std::vector<DocumentElement *>::const_iterator iter = headerFooterContent.begin();
+ iter != headerFooterContent.end();
+ iter++) {
+ (*iter)->write(xHandler);
+ }
+ TagCloseElement headerFooterClose(headerFooterTagName);
+ headerFooterClose.write(xHandler);
+}
+
diff --git a/filters/kword/wordperfect/import/PageSpan.cxx b/filters/kword/wordperfect/import/PageSpan.cxx
deleted file mode 100644
index 1113004d7..000000000
--- a/filters/kword/wordperfect/import/PageSpan.cxx
+++ /dev/null
@@ -1,180 +0,0 @@
-/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
- * break needs a new section) that is needed at the head of an OO document and
- * is referenced throughout the entire document
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include <config.h>
-
-#include "FilterInternal.hxx"
-#include "PageSpan.hxx"
-#include "DocumentElement.hxx"
-
-
-PageSpan::PageSpan(const _SH_PropertyList &xPropList) :
-#if 0
-const int iSpan, const float fFormLength, const float fFormWidth, const WPXFormQt::Orientation fFormQt::Orientation,
- const float fLeftMargin, const float fRightMargin, const float fTopMargin, const float fBottomMargin):
- miSpan(iSpan),
- mfFormLength(fFormLength),
- mfFormWidth(fFormWidth),
- mfFormQt::Orientation(fFormQt::Orientation),
- mfMarginLeft(fLeftMargin),
- mfMarginRight(fRightMargin),
- mfMarginTop(fTopMargin),
- mfMarginBottom(fBottomMargin),
-#endif
- mxPropList(xPropList),
- mpHeaderContent(NULL),
- mpFooterContent(NULL),
- mpHeaderLeftContent(NULL),
- mpFooterLeftContent(NULL)
-{
-}
-
-PageSpan::~PageSpan()
-{
- delete mpHeaderContent;
- delete mpHeaderLeftContent;
- delete mpFooterContent;
- delete mpFooterLeftContent;
-}
-
-int PageSpan::getSpan() const
-{
- if (mxPropList["libwpd:num-pages"])
- return mxPropList["libwpd:num-pages"]->getInt();
-
- return 0; // should never happen
-}
-
-float PageSpan::getMarginLeft() const
-{
- if (mxPropList["fo:margin-left"])
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
- return mxPropList["fo:margin-left"]->getDouble();
-#else
- return mxPropList["fo:margin-left"]->getFloat();
-#endif
-
- return 0.0f;
-}
-
-float PageSpan::getMarginRight() const
-{
- if (mxPropList["fo:margin-right"])
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
- return mxPropList["fo:margin-right"]->getDouble();
-#else
- return mxPropList["fo:margin-right"]->getFloat();
-#endif
-
- return 0.0f;
-}
-
-void PageSpan::writePageMaster(const int iNum, DocumentHandler &xHandler) const
-{
- _SH_PropertyList propList;
-
- _SH_String sPageMasterName;
- sPageMasterName.sprintf("PM%i", iNum+2);
- propList.insert("style:name", sPageMasterName);
- xHandler.startElement("style:page-master", propList);
-
- _SH_PropertyList tempPropList = mxPropList;
- if (!tempPropList["style:writing-mode"])
- tempPropList.insert("style:writing-mode", _SH_String("lr-tb"));
- if (!tempPropList["style:footnote-max-height"])
- tempPropList.insert("style:footnote-max-height", _SH_String("0inch"));
- xHandler.startElement("style:properties", tempPropList);
-
- _SH_PropertyList footnoteSepPropList;
- footnoteSepPropList.insert("style:width", _SH_String("0.0071inch"));
- footnoteSepPropList.insert("style:distance-before-sep", _SH_String("0.0398inch"));
- footnoteSepPropList.insert("style:distance-after-sep", _SH_String("0.0398inch"));
- footnoteSepPropList.insert("style:adjustment", _SH_String("left"));
- footnoteSepPropList.insert("style:rel-width", _SH_String("25\%"));
- footnoteSepPropList.insert("style:color", _SH_String("#000000"));
- xHandler.startElement("style:footnote-sep", footnoteSepPropList);
-
- xHandler.endElement("style:footnote-sep");
- xHandler.endElement("style:properties");
- xHandler.endElement("style:page-master");
-}
-
-void PageSpan::writeMasterPages(const int iStartingNum, const int iPageMasterNum, const bool bLastPageSpan,
- DocumentHandler &xHandler) const
-{
- _SH_PropertyList propList; // scratch space
-
- int iSpan = 0;
- (bLastPageSpan) ? iSpan = 1 : iSpan = getSpan();
-
- for (int i=iStartingNum; i<(iStartingNum+iSpan); i++)
- {
- TagOpenElement masterPageOpen("style:master-page");
- _SH_String sMasterPageName;
- sMasterPageName.sprintf("Page Style %i", i);
- _SH_String sPageMasterName;
- sPageMasterName.sprintf("PM%i", iPageMasterNum+2);
- propList.insert("style:name", sMasterPageName);
- propList.insert("style:page-master-name", sPageMasterName);
- if (!bLastPageSpan)
- {
- _SH_String sNextMasterPageName;
- sNextMasterPageName.sprintf("Page Style %i", (i+1));
- propList.insert("style:next-style-name", sNextMasterPageName);
- }
- xHandler.startElement("style:master-page", propList);
-
- if (mpHeaderContent)
- _writeHeaderFooter("style:header", *mpHeaderContent, xHandler);
- if (mpHeaderLeftContent)
- _writeHeaderFooter("style:header-left", *mpHeaderLeftContent, xHandler);
- if (mpFooterContent)
- _writeHeaderFooter("style:footer", *mpFooterContent, xHandler);
- if (mpFooterLeftContent)
- _writeHeaderFooter("style:footer-left", *mpFooterLeftContent, xHandler);
-
- xHandler.endElement("style:master-page");
- }
-
-}
-
-void PageSpan::_writeHeaderFooter(const char *headerFooterTagName,
- const std::vector<DocumentElement *> & headerFooterContent,
- DocumentHandler &xHandler) const
-{
- TagOpenElement headerFooterOpen(headerFooterTagName);
- headerFooterOpen.write(xHandler);
- for (std::vector<DocumentElement *>::const_iterator iter = headerFooterContent.begin();
- iter != headerFooterContent.end();
- iter++) {
- (*iter)->write(xHandler);
- }
- TagCloseElement headerFooterClose(headerFooterTagName);
- headerFooterClose.write(xHandler);
-}
-
diff --git a/filters/kword/wordperfect/import/PageSpan.hxx b/filters/kword/wordperfect/import/PageSpan.h
index 58c5ad811..58c5ad811 100644
--- a/filters/kword/wordperfect/import/PageSpan.hxx
+++ b/filters/kword/wordperfect/import/PageSpan.h
diff --git a/filters/kword/wordperfect/import/SectionStyle.cpp b/filters/kword/wordperfect/import/SectionStyle.cpp
new file mode 100644
index 000000000..9a8b6790f
--- /dev/null
+++ b/filters/kword/wordperfect/import/SectionStyle.cpp
@@ -0,0 +1,79 @@
+/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
+ * break needs a new section) that is needed at the head of an OO document and
+ * is referenced throughout the entire document
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (c) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include "FilterInternal.h"
+#include "SectionStyle.h"
+#include "DocumentElement.h"
+#include <math.h>
+
+#ifdef _MSC_VER
+double rint(double x);
+#endif /* _WIN32 */
+
+
+SectionStyle::SectionStyle(const _SH_PropertyList &xPropList,
+ const _SH_PropertyListVector &xColumns,
+ const char *psName) :
+ Style(psName),
+ mPropList(xPropList),
+ mColumns(xColumns)
+{
+}
+
+void SectionStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement styleOpen("style:style");
+ styleOpen.addAttribute("style:name", getName());
+ styleOpen.addAttribute("style:family", "section");
+ styleOpen.write(xHandler);
+
+ // if the number of columns is <= 1, we will never come here. This is only an additional check
+ if (mColumns.count() > 1)
+ {
+ // style properties
+ xHandler.startElement("style:properties", mPropList);
+
+ // column properties
+ _SH_PropertyList columnProps;
+ columnProps.insert("fo:column-count", (int)mColumns.count());
+ xHandler.startElement("style:columns", columnProps);
+
+ _SH_PropertyListVector::Iter i(mColumns);
+ for (i.rewind(); i.next();)
+ {
+ xHandler.startElement("style:column", i());
+ xHandler.endElement("style:column");
+ }
+
+ xHandler.endElement("style:columns");
+ xHandler.endElement("style:properties");
+ }
+
+ xHandler.endElement("style:style");
+}
diff --git a/filters/kword/wordperfect/import/SectionStyle.cxx b/filters/kword/wordperfect/import/SectionStyle.cxx
deleted file mode 100644
index 153ee45d7..000000000
--- a/filters/kword/wordperfect/import/SectionStyle.cxx
+++ /dev/null
@@ -1,79 +0,0 @@
-/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
- * break needs a new section) that is needed at the head of an OO document and
- * is referenced throughout the entire document
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- * Copyright (c) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include "FilterInternal.hxx"
-#include "SectionStyle.hxx"
-#include "DocumentElement.hxx"
-#include <math.h>
-
-#ifdef _MSC_VER
-double rint(double x);
-#endif /* _WIN32 */
-
-
-SectionStyle::SectionStyle(const _SH_PropertyList &xPropList,
- const _SH_PropertyListVector &xColumns,
- const char *psName) :
- Style(psName),
- mPropList(xPropList),
- mColumns(xColumns)
-{
-}
-
-void SectionStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement styleOpen("style:style");
- styleOpen.addAttribute("style:name", getName());
- styleOpen.addAttribute("style:family", "section");
- styleOpen.write(xHandler);
-
- // if the number of columns is <= 1, we will never come here. This is only an additional check
- if (mColumns.count() > 1)
- {
- // style properties
- xHandler.startElement("style:properties", mPropList);
-
- // column properties
- _SH_PropertyList columnProps;
- columnProps.insert("fo:column-count", (int)mColumns.count());
- xHandler.startElement("style:columns", columnProps);
-
- _SH_PropertyListVector::Iter i(mColumns);
- for (i.rewind(); i.next();)
- {
- xHandler.startElement("style:column", i());
- xHandler.endElement("style:column");
- }
-
- xHandler.endElement("style:columns");
- xHandler.endElement("style:properties");
- }
-
- xHandler.endElement("style:style");
-}
diff --git a/filters/kword/wordperfect/import/SectionStyle.h b/filters/kword/wordperfect/import/SectionStyle.h
new file mode 100644
index 000000000..5614f1182
--- /dev/null
+++ b/filters/kword/wordperfect/import/SectionStyle.h
@@ -0,0 +1,47 @@
+/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
+ * change needs a new section) that is needed at the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#ifndef _SECTIONSTYLE_H
+#define _SECTIONSTYLE_H
+#include <libwpd/libwpd.h>
+#include "shared_headers.h"
+
+#include "Style.h"
+#include "WriterProperties.h"
+
+
+class SectionStyle : public Style
+{
+public:
+ SectionStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &xColumns, const char *psName);
+ virtual void write(DocumentHandler &xHandler) const;
+
+private:
+ _SH_PropertyList mPropList;
+ _SH_PropertyListVector mColumns;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/SectionStyle.hxx b/filters/kword/wordperfect/import/SectionStyle.hxx
deleted file mode 100644
index 2f01d7520..000000000
--- a/filters/kword/wordperfect/import/SectionStyle.hxx
+++ /dev/null
@@ -1,47 +0,0 @@
-/* SectionStyle: Stores (and writes) section-based information (e.g.: a column
- * change needs a new section) that is needed at the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#ifndef _SECTIONSTYLE_H
-#define _SECTIONSTYLE_H
-#include <libwpd/libwpd.h>
-#include "shared_headers.h"
-
-#include "Style.hxx"
-#include "WriterProperties.hxx"
-
-
-class SectionStyle : public Style
-{
-public:
- SectionStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &xColumns, const char *psName);
- virtual void write(DocumentHandler &xHandler) const;
-
-private:
- _SH_PropertyList mPropList;
- _SH_PropertyListVector mColumns;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/Style.h b/filters/kword/wordperfect/import/Style.h
new file mode 100644
index 000000000..08e53eff4
--- /dev/null
+++ b/filters/kword/wordperfect/import/Style.h
@@ -0,0 +1,60 @@
+/* Style: A base class from which all other styles are inherited, includes
+ * a name.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#ifndef _STYLE_H
+#define _STYLE_H
+#include <libwpd/libwpd.h>
+#include "DocumentElement.h"
+
+#include <cstddef>
+
+class TopLevelElementStyle
+{
+public:
+ TopLevelElementStyle() : mpsMasterPageName(NULL) { }
+ virtual ~TopLevelElementStyle() { if (mpsMasterPageName) delete mpsMasterPageName; }
+ void setMasterPageName(_SH_String &sMasterPageName) { mpsMasterPageName = new _SH_String(sMasterPageName); }
+ const _SH_String * getMasterPageName() const { return mpsMasterPageName; }
+
+private:
+ _SH_String *mpsMasterPageName;
+};
+
+class Style
+{
+ public:
+ Style(const _SH_String &psName) : msName(psName) {}
+ virtual ~Style() {}
+
+ virtual void write(DocumentHandler &xHandler) const {};
+ const _SH_String &getName() const { return msName; }
+
+ private:
+ _SH_String msName;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/Style.hxx b/filters/kword/wordperfect/import/Style.hxx
deleted file mode 100644
index 49f5e28e4..000000000
--- a/filters/kword/wordperfect/import/Style.hxx
+++ /dev/null
@@ -1,60 +0,0 @@
-/* Style: A base class from which all other styles are inherited, includes
- * a name.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#ifndef _STYLE_H
-#define _STYLE_H
-#include <libwpd/libwpd.h>
-#include "DocumentElement.hxx"
-
-#include <cstddef>
-
-class TopLevelElementStyle
-{
-public:
- TopLevelElementStyle() : mpsMasterPageName(NULL) { }
- virtual ~TopLevelElementStyle() { if (mpsMasterPageName) delete mpsMasterPageName; }
- void setMasterPageName(_SH_String &sMasterPageName) { mpsMasterPageName = new _SH_String(sMasterPageName); }
- const _SH_String * getMasterPageName() const { return mpsMasterPageName; }
-
-private:
- _SH_String *mpsMasterPageName;
-};
-
-class Style
-{
- public:
- Style(const _SH_String &psName) : msName(psName) {}
- virtual ~Style() {}
-
- virtual void write(DocumentHandler &xHandler) const {};
- const _SH_String &getName() const { return msName; }
-
- private:
- _SH_String msName;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/TableStyle.cpp b/filters/kword/wordperfect/import/TableStyle.cpp
new file mode 100644
index 000000000..e35d7acb8
--- /dev/null
+++ b/filters/kword/wordperfect/import/TableStyle.cpp
@@ -0,0 +1,161 @@
+/* TableStyle: Stores (and writes) table-based information that is
+ * needed at the head of an OO document.
+ *
+ * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2004 Net Integration Technologies, Inc. (http://www.net-itech.com)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include <cstring>
+#include <math.h>
+#include "FilterInternal.h"
+#include "TableStyle.h"
+#include "DocumentElement.h"
+
+#ifdef _MSC_VER
+#include <minmax.h>
+#endif
+
+TableCellStyle::TableCellStyle(const _SH_PropertyList &xPropList, const char *psName) :
+ Style(psName),
+ mPropList(xPropList)
+{
+}
+
+void TableCellStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement styleOpen("style:style");
+ styleOpen.addAttribute("style:name", getName());
+ styleOpen.addAttribute("style:family", "table-cell");
+ styleOpen.write(xHandler);
+
+ // WLACH_REFACTORING: Only temporary.. a much better solution is to
+ // generalize this sort of thing into the "Style" superclass
+ _SH_PropertyList stylePropList;
+ _SH_PropertyList::Iter i(mPropList);
+ for (i.rewind(); i.next();)
+ {
+ if (strlen(i.key()) > 2 && strncmp(i.key(), "fo", 2) == 0)
+ stylePropList.insert(i.key(), i()->clone());
+ }
+ stylePropList.insert("fo:padding", "0.0382inch");
+ xHandler.startElement("style:properties", stylePropList);
+ xHandler.endElement("style:properties");
+
+ xHandler.endElement("style:style");
+}
+
+TableRowStyle::TableRowStyle(const _SH_PropertyList &propList, const char *psName) :
+ Style(psName),
+ mPropList(propList)
+{
+}
+
+void TableRowStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement styleOpen("style:style");
+ styleOpen.addAttribute("style:name", getName());
+ styleOpen.addAttribute("style:family", "table-row");
+ styleOpen.write(xHandler);
+
+ TagOpenElement stylePropertiesOpen("style:properties");
+ if (mPropList["style:min-row-height"])
+ stylePropertiesOpen.addAttribute("style:min-row-height", mPropList["style:min-row-height"]->getStr());
+ else if (mPropList["style:row-height"])
+ stylePropertiesOpen.addAttribute("style:row-height", mPropList["style:row-height"]->getStr());
+ stylePropertiesOpen.write(xHandler);
+ xHandler.endElement("style:properties");
+
+ xHandler.endElement("style:style");
+}
+
+
+TableStyle::TableStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &columns, const char *psName) :
+ Style(psName),
+ mPropList(xPropList),
+ mColumns(columns)
+{
+}
+
+TableStyle::~TableStyle()
+{
+ typedef std::vector<TableCellStyle *>::iterator TCSVIter;
+ for (TCSVIter iterTableCellStyles = mTableCellStyles.begin() ; iterTableCellStyles != mTableCellStyles.end(); iterTableCellStyles++)
+ delete(*iterTableCellStyles);
+
+}
+
+void TableStyle::write(DocumentHandler &xHandler) const
+{
+ TagOpenElement styleOpen("style:style");
+ styleOpen.addAttribute("style:name", getName());
+ styleOpen.addAttribute("style:family", "table");
+ if (getMasterPageName())
+ styleOpen.addAttribute("style:master-page-name", getMasterPageName()->cstr());
+ styleOpen.write(xHandler);
+
+ TagOpenElement stylePropertiesOpen("style:properties");
+ if (mPropList["table:align"])
+ stylePropertiesOpen.addAttribute("table:align", mPropList["table:align"]->getStr());
+ if (mPropList["fo:margin-left"])
+ stylePropertiesOpen.addAttribute("fo:margin-left", mPropList["fo:margin-left"]->getStr());
+ if (mPropList["fo:margin-right"])
+ stylePropertiesOpen.addAttribute("fo:margin-right", mPropList["fo:margin-right"]->getStr());
+ if (mPropList["style:width"])
+ stylePropertiesOpen.addAttribute("style:width", mPropList["style:width"]->getStr());
+ if (mPropList["fo:break-before"])
+ stylePropertiesOpen.addAttribute("fo:break-before", mPropList["fo:break-before"]->getStr());
+ stylePropertiesOpen.write(xHandler);
+
+ xHandler.endElement("style:properties");
+
+ xHandler.endElement("style:style");
+
+ int i=1;
+ _SH_PropertyListVector::Iter j(mColumns);
+ for (j.rewind(); j.next();)
+ {
+ TagOpenElement styleOpen("style:style");
+ _SH_String sColumnName;
+ sColumnName.sprintf("%s.Column%i", getName().cstr(), i);
+ styleOpen.addAttribute("style:name", sColumnName);
+ styleOpen.addAttribute("style:family", "table-column");
+ styleOpen.write(xHandler);
+
+ xHandler.startElement("style:properties", j());
+ xHandler.endElement("style:properties");
+
+ xHandler.endElement("style:style");
+
+ i++;
+ }
+
+ typedef std::vector<TableRowStyle *>::const_iterator TRSVIter;
+ for (TRSVIter iterTableRow = mTableRowStyles.begin() ; iterTableRow != mTableRowStyles.end(); iterTableRow++)
+ (*iterTableRow)->write(xHandler);
+
+ typedef std::vector<TableCellStyle *>::const_iterator TCSVIter;
+ for (TCSVIter iterTableCell = mTableCellStyles.begin() ; iterTableCell != mTableCellStyles.end(); iterTableCell++)
+ (*iterTableCell)->write(xHandler);
+}
diff --git a/filters/kword/wordperfect/import/TableStyle.cxx b/filters/kword/wordperfect/import/TableStyle.cxx
deleted file mode 100644
index 2913fea1f..000000000
--- a/filters/kword/wordperfect/import/TableStyle.cxx
+++ /dev/null
@@ -1,161 +0,0 @@
-/* TableStyle: Stores (and writes) table-based information that is
- * needed at the head of an OO document.
- *
- * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2004 Net Integration Technologies, Inc. (http://www.net-itech.com)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include <cstring>
-#include <math.h>
-#include "FilterInternal.hxx"
-#include "TableStyle.hxx"
-#include "DocumentElement.hxx"
-
-#ifdef _MSC_VER
-#include <minmax.h>
-#endif
-
-TableCellStyle::TableCellStyle(const _SH_PropertyList &xPropList, const char *psName) :
- Style(psName),
- mPropList(xPropList)
-{
-}
-
-void TableCellStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement styleOpen("style:style");
- styleOpen.addAttribute("style:name", getName());
- styleOpen.addAttribute("style:family", "table-cell");
- styleOpen.write(xHandler);
-
- // WLACH_REFACTORING: Only temporary.. a much better solution is to
- // generalize this sort of thing into the "Style" superclass
- _SH_PropertyList stylePropList;
- _SH_PropertyList::Iter i(mPropList);
- for (i.rewind(); i.next();)
- {
- if (strlen(i.key()) > 2 && strncmp(i.key(), "fo", 2) == 0)
- stylePropList.insert(i.key(), i()->clone());
- }
- stylePropList.insert("fo:padding", "0.0382inch");
- xHandler.startElement("style:properties", stylePropList);
- xHandler.endElement("style:properties");
-
- xHandler.endElement("style:style");
-}
-
-TableRowStyle::TableRowStyle(const _SH_PropertyList &propList, const char *psName) :
- Style(psName),
- mPropList(propList)
-{
-}
-
-void TableRowStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement styleOpen("style:style");
- styleOpen.addAttribute("style:name", getName());
- styleOpen.addAttribute("style:family", "table-row");
- styleOpen.write(xHandler);
-
- TagOpenElement stylePropertiesOpen("style:properties");
- if (mPropList["style:min-row-height"])
- stylePropertiesOpen.addAttribute("style:min-row-height", mPropList["style:min-row-height"]->getStr());
- else if (mPropList["style:row-height"])
- stylePropertiesOpen.addAttribute("style:row-height", mPropList["style:row-height"]->getStr());
- stylePropertiesOpen.write(xHandler);
- xHandler.endElement("style:properties");
-
- xHandler.endElement("style:style");
-}
-
-
-TableStyle::TableStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &columns, const char *psName) :
- Style(psName),
- mPropList(xPropList),
- mColumns(columns)
-{
-}
-
-TableStyle::~TableStyle()
-{
- typedef std::vector<TableCellStyle *>::iterator TCSVIter;
- for (TCSVIter iterTableCellStyles = mTableCellStyles.begin() ; iterTableCellStyles != mTableCellStyles.end(); iterTableCellStyles++)
- delete(*iterTableCellStyles);
-
-}
-
-void TableStyle::write(DocumentHandler &xHandler) const
-{
- TagOpenElement styleOpen("style:style");
- styleOpen.addAttribute("style:name", getName());
- styleOpen.addAttribute("style:family", "table");
- if (getMasterPageName())
- styleOpen.addAttribute("style:master-page-name", getMasterPageName()->cstr());
- styleOpen.write(xHandler);
-
- TagOpenElement stylePropertiesOpen("style:properties");
- if (mPropList["table:align"])
- stylePropertiesOpen.addAttribute("table:align", mPropList["table:align"]->getStr());
- if (mPropList["fo:margin-left"])
- stylePropertiesOpen.addAttribute("fo:margin-left", mPropList["fo:margin-left"]->getStr());
- if (mPropList["fo:margin-right"])
- stylePropertiesOpen.addAttribute("fo:margin-right", mPropList["fo:margin-right"]->getStr());
- if (mPropList["style:width"])
- stylePropertiesOpen.addAttribute("style:width", mPropList["style:width"]->getStr());
- if (mPropList["fo:break-before"])
- stylePropertiesOpen.addAttribute("fo:break-before", mPropList["fo:break-before"]->getStr());
- stylePropertiesOpen.write(xHandler);
-
- xHandler.endElement("style:properties");
-
- xHandler.endElement("style:style");
-
- int i=1;
- _SH_PropertyListVector::Iter j(mColumns);
- for (j.rewind(); j.next();)
- {
- TagOpenElement styleOpen("style:style");
- _SH_String sColumnName;
- sColumnName.sprintf("%s.Column%i", getName().cstr(), i);
- styleOpen.addAttribute("style:name", sColumnName);
- styleOpen.addAttribute("style:family", "table-column");
- styleOpen.write(xHandler);
-
- xHandler.startElement("style:properties", j());
- xHandler.endElement("style:properties");
-
- xHandler.endElement("style:style");
-
- i++;
- }
-
- typedef std::vector<TableRowStyle *>::const_iterator TRSVIter;
- for (TRSVIter iterTableRow = mTableRowStyles.begin() ; iterTableRow != mTableRowStyles.end(); iterTableRow++)
- (*iterTableRow)->write(xHandler);
-
- typedef std::vector<TableCellStyle *>::const_iterator TCSVIter;
- for (TCSVIter iterTableCell = mTableCellStyles.begin() ; iterTableCell != mTableCellStyles.end(); iterTableCell++)
- (*iterTableCell)->write(xHandler);
-}
diff --git a/filters/kword/wordperfect/import/TableStyle.h b/filters/kword/wordperfect/import/TableStyle.h
new file mode 100644
index 000000000..c15f4d81f
--- /dev/null
+++ b/filters/kword/wordperfect/import/TableStyle.h
@@ -0,0 +1,75 @@
+/* TableStyle: Stores (and writes) table-based information that is
+ * needed at the head of an OO document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#ifndef _TABLESTYLE_H
+#define _TABLESTYLE_H
+#include <libwpd/libwpd.h>
+#include <vector>
+#include "shared_headers.h"
+#include "Style.h"
+#include "WriterProperties.h"
+
+class DocumentElement;
+class DocumentHandler;
+
+class TableCellStyle : public Style
+{
+public:
+ TableCellStyle(const _SH_PropertyList &xPropList, const char *psName);
+ virtual void write(DocumentHandler &xHandler) const;
+private:
+ _SH_PropertyList mPropList;
+};
+
+class TableRowStyle : public Style
+{
+public:
+ TableRowStyle(const _SH_PropertyList &propList, const char *psName);
+ virtual void write(DocumentHandler &xHandler) const;
+private:
+ _SH_PropertyList mPropList;
+};
+
+class TableStyle : public Style, public TopLevelElementStyle
+{
+public:
+ TableStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &columns, const char *psName);
+ ~TableStyle();
+ virtual void write(DocumentHandler &xHandler) const;
+ const int getNumColumns() const { return mColumns.count(); }
+ void addTableCellStyle(TableCellStyle *pTableCellStyle) { mTableCellStyles.push_back(pTableCellStyle); }
+ int getNumTableCellStyles() { return mTableCellStyles.size(); }
+ void addTableRowStyle(TableRowStyle *pTableRowStyle) { mTableRowStyles.push_back(pTableRowStyle); }
+ int getNumTableRowStyles() { return mTableRowStyles.size(); }
+private:
+ _SH_PropertyList mPropList;
+ _SH_PropertyListVector mColumns;
+ std::vector<TableCellStyle *> mTableCellStyles;
+ std::vector<TableRowStyle *> mTableRowStyles;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/TableStyle.hxx b/filters/kword/wordperfect/import/TableStyle.hxx
deleted file mode 100644
index 3730da4b2..000000000
--- a/filters/kword/wordperfect/import/TableStyle.hxx
+++ /dev/null
@@ -1,75 +0,0 @@
-/* TableStyle: Stores (and writes) table-based information that is
- * needed at the head of an OO document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#ifndef _TABLESTYLE_H
-#define _TABLESTYLE_H
-#include <libwpd/libwpd.h>
-#include <vector>
-#include "shared_headers.h"
-#include "Style.hxx"
-#include "WriterProperties.hxx"
-
-class DocumentElement;
-class DocumentHandler;
-
-class TableCellStyle : public Style
-{
-public:
- TableCellStyle(const _SH_PropertyList &xPropList, const char *psName);
- virtual void write(DocumentHandler &xHandler) const;
-private:
- _SH_PropertyList mPropList;
-};
-
-class TableRowStyle : public Style
-{
-public:
- TableRowStyle(const _SH_PropertyList &propList, const char *psName);
- virtual void write(DocumentHandler &xHandler) const;
-private:
- _SH_PropertyList mPropList;
-};
-
-class TableStyle : public Style, public TopLevelElementStyle
-{
-public:
- TableStyle(const _SH_PropertyList &xPropList, const _SH_PropertyListVector &columns, const char *psName);
- ~TableStyle();
- virtual void write(DocumentHandler &xHandler) const;
- const int getNumColumns() const { return mColumns.count(); }
- void addTableCellStyle(TableCellStyle *pTableCellStyle) { mTableCellStyles.push_back(pTableCellStyle); }
- int getNumTableCellStyles() { return mTableCellStyles.size(); }
- void addTableRowStyle(TableRowStyle *pTableRowStyle) { mTableRowStyles.push_back(pTableRowStyle); }
- int getNumTableRowStyles() { return mTableRowStyles.size(); }
-private:
- _SH_PropertyList mPropList;
- _SH_PropertyListVector mColumns;
- std::vector<TableCellStyle *> mTableCellStyles;
- std::vector<TableRowStyle *> mTableRowStyles;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/TextRunStyle.cpp b/filters/kword/wordperfect/import/TextRunStyle.cpp
new file mode 100644
index 000000000..06cbc4c6c
--- /dev/null
+++ b/filters/kword/wordperfect/import/TextRunStyle.cpp
@@ -0,0 +1,163 @@
+/* TextRunStyle: Stores (and writes) paragraph/span-style-based information
+ * (e.g.: a paragraph might be bold) that is needed at the head of an OO
+ * document.
+ *
+ * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2004 Net Integration Technologies, Inc. (http://www.net-itech.com)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+#include "FilterInternal.h"
+#include "TextRunStyle.h"
+#include "WriterProperties.h"
+#include "DocumentElement.h"
+
+#include <cstring>
+
+#ifdef _MSC_VER
+#include <minmax.h>
+#endif
+
+ParagraphStyle::ParagraphStyle(_SH_PropertyList *pPropList, const _SH_PropertyListVector &xTabStops, const _SH_String &sName) :
+ mpPropList(pPropList),
+ mxTabStops(xTabStops),
+ msName(sName)
+{
+}
+
+ParagraphStyle::~ParagraphStyle()
+{
+ delete mpPropList;
+}
+
+void ParagraphStyle::write(DocumentHandler &xHandler) const
+{
+ WRITER_DEBUG_MSG(("Writing a paragraph style..\n"));
+
+ _SH_PropertyList propList;
+ propList.insert("style:name", msName.cstr());
+ propList.insert("style:family", "paragraph");
+ propList.insert("style:parent-style-name", (*mpPropList)["style:parent-style-name"]->getStr());
+ if ((*mpPropList)["style:master-page-name"])
+ propList.insert("style:master-page-name", (*mpPropList)["style:master-page-name"]->getStr());
+ xHandler.startElement("style:style", propList);
+
+ propList.clear();
+ _SH_PropertyList::Iter i((*mpPropList));
+ for (i.rewind(); i.next(); )
+ {
+ if (strcmp(i.key(), "style:list-style-name") == 0)
+ propList.insert("style:list-style-name", i()->getStr());
+ if (strcmp(i.key(), "fo:margin-left") == 0)
+ propList.insert("fo:margin-left", i()->getStr());
+ if (strcmp(i.key(), "fo:margin-right") == 0)
+ propList.insert("fo:margin-right", i()->getStr());
+ if (strcmp(i.key(), "fo:text-indent") == 0)
+ propList.insert("fo:text-indent", i()->getStr());
+ if (strcmp(i.key(), "fo:margin-top") == 0)
+ propList.insert("fo:margin-top", i()->getStr());
+ if (strcmp(i.key(), "fo:margin-bottom") == 0)
+ propList.insert("fo:margin-bottom", i()->getStr());
+ if (strcmp(i.key(), "fo:line-height") == 0)
+ propList.insert("fo:line-height", i()->getStr());
+ if (strcmp(i.key(), "fo:break-before") == 0)
+ propList.insert("fo:break-before", i()->getStr());
+ if (strcmp(i.key(), "fo:text-align") == 0)
+ propList.insert("fo:text-align", i()->getStr());
+ if (strcmp(i.key(), "fo:text-align-last") == 0)
+ propList.insert("fo:text-align-last", i()->getStr());
+ }
+
+ propList.insert("style:justify-single-word", "false");
+ xHandler.startElement("style:properties", propList);
+
+ if (mxTabStops.count() > 0)
+ {
+ TagOpenElement tabListOpen("style:tab-stops");
+ tabListOpen.write(xHandler);
+ _SH_PropertyListVector::Iter i(mxTabStops);
+ for (i.rewind(); i.next();)
+ {
+ TagOpenElement tabStopOpen("style:tab-stop");
+
+ _SH_PropertyList::Iter j(i());
+ for (j.rewind(); j.next(); )
+ {
+ tabStopOpen.addAttribute(j.key(), j()->getStr().cstr());
+ }
+ tabStopOpen.write(xHandler);
+ xHandler.endElement("style:tab-stop");
+ }
+ xHandler.endElement("style:tab-stops");
+ }
+
+ xHandler.endElement("style:properties");
+ xHandler.endElement("style:style");
+}
+
+SpanStyle::SpanStyle(const char *psName, const _SH_PropertyList &xPropList) :
+ Style(psName),
+ mPropList(xPropList)
+{
+}
+
+void SpanStyle::write(DocumentHandler &xHandler) const
+{
+ WRITER_DEBUG_MSG(("Writing a span style..\n"));
+ _SH_PropertyList styleOpenList;
+ styleOpenList.insert("style:name", getName());
+ styleOpenList.insert("style:family", "text");
+ xHandler.startElement("style:style", styleOpenList);
+
+ _SH_PropertyList propList(mPropList);
+
+ if (mPropList["style:font-name"])
+ {
+ propList.insert("style:font-name-asian", mPropList["style:font-name"]->getStr());
+ propList.insert("style:font-name-complex", mPropList["style:font-name"]->getStr());
+ }
+
+ if (mPropList["fo:font-size"])
+ {
+ propList.insert("style:font-size-asian", mPropList["fo:font-size"]->getStr());
+ propList.insert("style:font-size-complex", mPropList["fo:font-size"]->getStr());
+ }
+
+ if (mPropList["fo:font-weight"])
+ {
+ propList.insert("style:font-weight-asian", mPropList["fo:font-weight"]->getStr());
+ propList.insert("style:font-weight-complex", mPropList["fo:font-weight"]->getStr());
+ }
+
+ if (mPropList["fo:font-style"])
+ {
+ propList.insert("style:font-style-asian", mPropList["fo:font-style"]->getStr());
+ propList.insert("style:font-style-complex", mPropList["fo:font-style"]->getStr());
+ }
+
+ xHandler.startElement("style:properties", propList);
+
+ xHandler.endElement("style:properties");
+ xHandler.endElement("style:style");
+}
diff --git a/filters/kword/wordperfect/import/TextRunStyle.cxx b/filters/kword/wordperfect/import/TextRunStyle.cxx
deleted file mode 100644
index b188632c5..000000000
--- a/filters/kword/wordperfect/import/TextRunStyle.cxx
+++ /dev/null
@@ -1,163 +0,0 @@
-/* TextRunStyle: Stores (and writes) paragraph/span-style-based information
- * (e.g.: a paragraph might be bold) that is needed at the head of an OO
- * document.
- *
- * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2004 Net Integration Technologies, Inc. (http://www.net-itech.com)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-#include "FilterInternal.hxx"
-#include "TextRunStyle.hxx"
-#include "WriterProperties.hxx"
-#include "DocumentElement.hxx"
-
-#include <cstring>
-
-#ifdef _MSC_VER
-#include <minmax.h>
-#endif
-
-ParagraphStyle::ParagraphStyle(_SH_PropertyList *pPropList, const _SH_PropertyListVector &xTabStops, const _SH_String &sName) :
- mpPropList(pPropList),
- mxTabStops(xTabStops),
- msName(sName)
-{
-}
-
-ParagraphStyle::~ParagraphStyle()
-{
- delete mpPropList;
-}
-
-void ParagraphStyle::write(DocumentHandler &xHandler) const
-{
- WRITER_DEBUG_MSG(("Writing a paragraph style..\n"));
-
- _SH_PropertyList propList;
- propList.insert("style:name", msName.cstr());
- propList.insert("style:family", "paragraph");
- propList.insert("style:parent-style-name", (*mpPropList)["style:parent-style-name"]->getStr());
- if ((*mpPropList)["style:master-page-name"])
- propList.insert("style:master-page-name", (*mpPropList)["style:master-page-name"]->getStr());
- xHandler.startElement("style:style", propList);
-
- propList.clear();
- _SH_PropertyList::Iter i((*mpPropList));
- for (i.rewind(); i.next(); )
- {
- if (strcmp(i.key(), "style:list-style-name") == 0)
- propList.insert("style:list-style-name", i()->getStr());
- if (strcmp(i.key(), "fo:margin-left") == 0)
- propList.insert("fo:margin-left", i()->getStr());
- if (strcmp(i.key(), "fo:margin-right") == 0)
- propList.insert("fo:margin-right", i()->getStr());
- if (strcmp(i.key(), "fo:text-indent") == 0)
- propList.insert("fo:text-indent", i()->getStr());
- if (strcmp(i.key(), "fo:margin-top") == 0)
- propList.insert("fo:margin-top", i()->getStr());
- if (strcmp(i.key(), "fo:margin-bottom") == 0)
- propList.insert("fo:margin-bottom", i()->getStr());
- if (strcmp(i.key(), "fo:line-height") == 0)
- propList.insert("fo:line-height", i()->getStr());
- if (strcmp(i.key(), "fo:break-before") == 0)
- propList.insert("fo:break-before", i()->getStr());
- if (strcmp(i.key(), "fo:text-align") == 0)
- propList.insert("fo:text-align", i()->getStr());
- if (strcmp(i.key(), "fo:text-align-last") == 0)
- propList.insert("fo:text-align-last", i()->getStr());
- }
-
- propList.insert("style:justify-single-word", "false");
- xHandler.startElement("style:properties", propList);
-
- if (mxTabStops.count() > 0)
- {
- TagOpenElement tabListOpen("style:tab-stops");
- tabListOpen.write(xHandler);
- _SH_PropertyListVector::Iter i(mxTabStops);
- for (i.rewind(); i.next();)
- {
- TagOpenElement tabStopOpen("style:tab-stop");
-
- _SH_PropertyList::Iter j(i());
- for (j.rewind(); j.next(); )
- {
- tabStopOpen.addAttribute(j.key(), j()->getStr().cstr());
- }
- tabStopOpen.write(xHandler);
- xHandler.endElement("style:tab-stop");
- }
- xHandler.endElement("style:tab-stops");
- }
-
- xHandler.endElement("style:properties");
- xHandler.endElement("style:style");
-}
-
-SpanStyle::SpanStyle(const char *psName, const _SH_PropertyList &xPropList) :
- Style(psName),
- mPropList(xPropList)
-{
-}
-
-void SpanStyle::write(DocumentHandler &xHandler) const
-{
- WRITER_DEBUG_MSG(("Writing a span style..\n"));
- _SH_PropertyList styleOpenList;
- styleOpenList.insert("style:name", getName());
- styleOpenList.insert("style:family", "text");
- xHandler.startElement("style:style", styleOpenList);
-
- _SH_PropertyList propList(mPropList);
-
- if (mPropList["style:font-name"])
- {
- propList.insert("style:font-name-asian", mPropList["style:font-name"]->getStr());
- propList.insert("style:font-name-complex", mPropList["style:font-name"]->getStr());
- }
-
- if (mPropList["fo:font-size"])
- {
- propList.insert("style:font-size-asian", mPropList["fo:font-size"]->getStr());
- propList.insert("style:font-size-complex", mPropList["fo:font-size"]->getStr());
- }
-
- if (mPropList["fo:font-weight"])
- {
- propList.insert("style:font-weight-asian", mPropList["fo:font-weight"]->getStr());
- propList.insert("style:font-weight-complex", mPropList["fo:font-weight"]->getStr());
- }
-
- if (mPropList["fo:font-style"])
- {
- propList.insert("style:font-style-asian", mPropList["fo:font-style"]->getStr());
- propList.insert("style:font-style-complex", mPropList["fo:font-style"]->getStr());
- }
-
- xHandler.startElement("style:properties", propList);
-
- xHandler.endElement("style:properties");
- xHandler.endElement("style:style");
-}
diff --git a/filters/kword/wordperfect/import/TextRunStyle.h b/filters/kword/wordperfect/import/TextRunStyle.h
new file mode 100644
index 000000000..139b32bec
--- /dev/null
+++ b/filters/kword/wordperfect/import/TextRunStyle.h
@@ -0,0 +1,65 @@
+/* TextRunStyle: Stores (and writes) paragraph/span-style-based information
+ * (e.g.: a paragraph might be bold) that is needed at the head of an OO
+ * document.
+ *
+ * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#ifndef _TEXTRUNSTYLE_H
+#define _TEXTRUNSTYLE_H
+
+#include <libwpd/libwpd.h>
+#include "Style.h"
+#include "shared_headers.h"
+
+class TagOpenElement;
+class DocumentElement;
+class DocumentHandler;
+
+class ParagraphStyle
+{
+public:
+ ParagraphStyle(_SH_PropertyList *propList, const _SH_PropertyListVector &tabStops, const _SH_String &sName);
+ virtual ~ParagraphStyle();
+ virtual void write(DocumentHandler &xHandler) const;
+ _SH_String getName() const { return msName; }
+private:
+ _SH_PropertyList *mpPropList;
+ _SH_PropertyListVector mxTabStops;
+ _SH_String msName;
+};
+
+
+class SpanStyle : public Style
+{
+public:
+ SpanStyle(const char *psName, const _SH_PropertyList &xPropList);
+ virtual void write(DocumentHandler &xHandler) const;
+
+private:
+ _SH_PropertyList mPropList;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/TextRunStyle.hxx b/filters/kword/wordperfect/import/TextRunStyle.hxx
deleted file mode 100644
index e0847e2fa..000000000
--- a/filters/kword/wordperfect/import/TextRunStyle.hxx
+++ /dev/null
@@ -1,65 +0,0 @@
-/* TextRunStyle: Stores (and writes) paragraph/span-style-based information
- * (e.g.: a paragraph might be bold) that is needed at the head of an OO
- * document.
- *
- * Copyright (C) 2002-2003 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#ifndef _TEXTRUNSTYLE_H
-#define _TEXTRUNSTYLE_H
-
-#include <libwpd/libwpd.h>
-#include "Style.hxx"
-#include "shared_headers.h"
-
-class TagOpenElement;
-class DocumentElement;
-class DocumentHandler;
-
-class ParagraphStyle
-{
-public:
- ParagraphStyle(_SH_PropertyList *propList, const _SH_PropertyListVector &tabStops, const _SH_String &sName);
- virtual ~ParagraphStyle();
- virtual void write(DocumentHandler &xHandler) const;
- _SH_String getName() const { return msName; }
-private:
- _SH_PropertyList *mpPropList;
- _SH_PropertyListVector mxTabStops;
- _SH_String msName;
-};
-
-
-class SpanStyle : public Style
-{
-public:
- SpanStyle(const char *psName, const _SH_PropertyList &xPropList);
- virtual void write(DocumentHandler &xHandler) const;
-
-private:
- _SH_PropertyList mPropList;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/WordPerfectCollector.cpp b/filters/kword/wordperfect/import/WordPerfectCollector.cpp
new file mode 100644
index 000000000..76fe6fc65
--- /dev/null
+++ b/filters/kword/wordperfect/import/WordPerfectCollector.cpp
@@ -0,0 +1,973 @@
+/* WordPerfectCollector: Collects sections and runs of text from a
+ * wordperfect file (and styles to go along with them) and writes them
+ * to a Writer target document
+ *
+ * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#include <config.h>
+
+#include <libwpd/libwpd.h>
+#include <string.h> // for strcmp
+
+#include "WordPerfectCollector.h"
+#include "DocumentElement.h"
+#include "TextRunStyle.h"
+#include "FontStyle.h"
+#include "ListStyle.h"
+#include "PageSpan.h"
+#include "SectionStyle.h"
+#include "TableStyle.h"
+#include "FilterInternal.h"
+#include "WriterProperties.h"
+
+_WriterDocumentState::_WriterDocumentState() :
+ mbFirstElement(true),
+ mbInFakeSection(false),
+ mbListElementOpenedAtCurrentLevel(false),
+ mbTableCellOpened(false),
+ mbHeaderRow(false),
+ mbInNote(false)
+{
+}
+
+WordPerfectCollector::WordPerfectCollector(_SH_InputStream *pInput, DocumentHandler *pHandler) :
+ mpInput(pInput),
+ mpHandler(pHandler),
+ mbUsed(false),
+ mfSectionSpaceAfter(0.0f),
+ miNumListStyles(0),
+ mpCurrentContentElements(&mBodyElements),
+ mpCurrentPageSpan(NULL),
+ miNumPageStyles(0),
+ mpCurrentListStyle(NULL),
+ miCurrentListLevel(0),
+ miLastListLevel(0),
+ miLastListNumber(0),
+ mbListContinueNumbering(false),
+ mbListElementOpened(false),
+ mbListElementParagraphOpened(false)
+{
+}
+
+WordPerfectCollector::~WordPerfectCollector()
+{
+}
+
+bool WordPerfectCollector::filter()
+{
+ // The contract for WordPerfectCollector is that it will only be used once after it is
+ // instantiated
+ if (mbUsed)
+ return false;
+
+ mbUsed = true;
+
+ // parse & write
+ // WLACH_REFACTORING: Remove these args..
+ if (!_parseSourceDocument(*mpInput))
+ return false;
+ if (!_writeTargetDocument(*mpHandler))
+ return false;
+
+ // clean up the mess we made
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Cleaning up our mess..\n"));
+
+ WRITER_DEBUG_MSG(("Destroying the body elements\n"));
+ for (std::vector<DocumentElement *>::iterator iterBody = mBodyElements.begin(); iterBody != mBodyElements.end(); iterBody++) {
+ delete((*iterBody));
+ (*iterBody) = NULL;
+ }
+
+ WRITER_DEBUG_MSG(("Destroying the styles elements\n"));
+ for (std::vector<DocumentElement *>::iterator iterStyles = mStylesElements.begin(); iterStyles != mStylesElements.end(); iterStyles++) {
+ delete (*iterStyles);
+ (*iterStyles) = NULL; // we may pass over the same element again (in the case of headers/footers spanning multiple pages)
+ // so make sure we don't do a double del
+ }
+
+ WRITER_DEBUG_MSG(("Destroying the rest of the styles elements\n"));
+ for (std::map<_SH_String, ParagraphStyle *, ltstr>::iterator iterTextStyle = mTextStyleHash.begin(); iterTextStyle != mTextStyleHash.end(); iterTextStyle++) {
+ delete(iterTextStyle->second);
+ }
+ for (std::map<_SH_String, FontStyle *, ltstr>::iterator iterFont = mFontHash.begin(); iterFont != mFontHash.end(); iterFont++) {
+ delete(iterFont->second);
+ }
+
+ for (std::vector<ListStyle *>::iterator iterListStyles = mListStyles.begin(); iterListStyles != mListStyles.end(); iterListStyles++) {
+ delete((*iterListStyles));
+ }
+ for (std::vector<SectionStyle *>::iterator iterSectionStyles = mSectionStyles.begin(); iterSectionStyles != mSectionStyles.end(); iterSectionStyles++) {
+ delete((*iterSectionStyles));
+ }
+ for (std::vector<TableStyle *>::iterator iterTableStyles = mTableStyles.begin(); iterTableStyles != mTableStyles.end(); iterTableStyles++) {
+ delete((*iterTableStyles));
+ }
+
+ for (std::vector<PageSpan *>::iterator iterPageSpans = mPageSpans.begin(); iterPageSpans != mPageSpans.end(); iterPageSpans++) {
+ delete((*iterPageSpans));
+ }
+
+ return true;
+}
+
+bool WordPerfectCollector::_parseSourceDocument(_SH_InputStream &input)
+{
+#if defined(HAVE_LIBWPD_0100)
+ libwpd::WPDResult result = libwpd::WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this), NULL);
+#elif defined(HAVE_LIBWPD_090)
+ WPDResult result = WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this), NULL);
+#else
+ WPDResult result = WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this));
+#endif
+#if defined(HAVE_LIBWPD_0100)
+ if (result != libwpd::WPD_OK)
+#else
+ if (result != WPD_OK)
+#endif
+ return false;
+
+ return true;
+}
+
+void WordPerfectCollector::_writeDefaultStyles(DocumentHandler &xHandler)
+{
+ TagOpenElement stylesOpenElement("office:styles");
+ stylesOpenElement.write(xHandler);
+
+ TagOpenElement defaultParagraphStyleOpenElement("style:default-style");
+ defaultParagraphStyleOpenElement.addAttribute("style:family", "paragraph");
+ defaultParagraphStyleOpenElement.write(xHandler);
+
+ TagOpenElement defaultParagraphStylePropertiesOpenElement("style:properties");
+ defaultParagraphStylePropertiesOpenElement.addAttribute("style:family", "paragraph");
+ defaultParagraphStylePropertiesOpenElement.addAttribute("style:tab-stop-distance", "0.5inch");
+ defaultParagraphStylePropertiesOpenElement.write(xHandler);
+ TagCloseElement defaultParagraphStylePropertiesCloseElement("style:properties");
+ defaultParagraphStylePropertiesCloseElement.write(xHandler);
+
+ TagCloseElement defaultParagraphStyleCloseElement("style:default-style");
+ defaultParagraphStyleCloseElement.write(xHandler);
+
+ TagOpenElement standardStyleOpenElement("style:style");
+ standardStyleOpenElement.addAttribute("style:name", "Standard");
+ standardStyleOpenElement.addAttribute("style:family", "paragraph");
+ standardStyleOpenElement.addAttribute("style:class", "text");
+ standardStyleOpenElement.write(xHandler);
+ TagCloseElement standardStyleCloseElement("style:style");
+ standardStyleCloseElement.write(xHandler);
+
+ TagOpenElement textBodyStyleOpenElement("style:style");
+ textBodyStyleOpenElement.addAttribute("style:name", "Text Body");
+ textBodyStyleOpenElement.addAttribute("style:family", "paragraph");
+ textBodyStyleOpenElement.addAttribute("style:parent-style-name", "Standard");
+ textBodyStyleOpenElement.addAttribute("style:class", "text");
+ textBodyStyleOpenElement.write(xHandler);
+ TagCloseElement textBodyStyleCloseElement("style:style");
+ textBodyStyleCloseElement.write(xHandler);
+
+ TagOpenElement tableContentsStyleOpenElement("style:style");
+ tableContentsStyleOpenElement.addAttribute("style:name", "Table Contents");
+ tableContentsStyleOpenElement.addAttribute("style:family", "paragraph");
+ tableContentsStyleOpenElement.addAttribute("style:parent-style-name", "Text Body");
+ tableContentsStyleOpenElement.addAttribute("style:class", "extra");
+ tableContentsStyleOpenElement.write(xHandler);
+ TagCloseElement tableContentsStyleCloseElement("style:style");
+ tableContentsStyleCloseElement.write(xHandler);
+
+ TagOpenElement tableHeadingStyleOpenElement("style:style");
+ tableHeadingStyleOpenElement.addAttribute("style:name", "Table Heading");
+ tableHeadingStyleOpenElement.addAttribute("style:family", "paragraph");
+ tableHeadingStyleOpenElement.addAttribute("style:parent-style-name", "Table Contents");
+ tableHeadingStyleOpenElement.addAttribute("style:class", "extra");
+ tableHeadingStyleOpenElement.write(xHandler);
+ TagCloseElement tableHeadingStyleCloseElement("style:style");
+ tableHeadingStyleCloseElement.write(xHandler);
+
+ TagCloseElement stylesCloseElement("office:styles");
+ stylesCloseElement.write(xHandler);
+
+}
+
+// writes everything up to the automatic styles declarations..
+void WordPerfectCollector::_writeBegin()
+{
+}
+
+void WordPerfectCollector::_writeMasterPages(DocumentHandler &xHandler)
+{
+ _SH_PropertyList xBlankAttrList;
+
+ xHandler.startElement("office:master-styles", xBlankAttrList);
+ int pageNumber = 1;
+ for (int i=0; i<mPageSpans.size(); i++)
+ {
+ bool bLastPage;
+ (i == (mPageSpans.size() - 1)) ? bLastPage = true : bLastPage = false;
+ mPageSpans[i]->writeMasterPages(pageNumber, i, bLastPage, xHandler);
+ pageNumber += mPageSpans[i]->getSpan();
+ }
+ xHandler.endElement("office:master-styles");
+}
+
+void WordPerfectCollector::_writePageMasters(DocumentHandler &xHandler)
+{
+ int pageNumber = 1;
+ for (int i=0; i<mPageSpans.size(); i++)
+ {
+ mPageSpans[i]->writePageMaster(i, xHandler);
+ }
+}
+
+bool WordPerfectCollector::_writeTargetDocument(DocumentHandler &xHandler)
+{
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Printing out the header stuff..\n"));
+ _SH_PropertyList xBlankAttrList;
+
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Start Document\n"));
+ mpHandler->startDocument();
+
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: preamble\n"));
+ _SH_PropertyList docContentPropList;
+ docContentPropList.insert("xmlns:office", "http://openoffice.org/2000/office");
+ docContentPropList.insert("xmlns:style", "http://openoffice.org/2000/style");
+ docContentPropList.insert("xmlns:text", "http://openoffice.org/2000/text");
+ docContentPropList.insert("xmlns:table", "http://openoffice.org/2000/table");
+ docContentPropList.insert("xmlns:draw", "http://openoffice.org/2000/draw");
+ docContentPropList.insert("xmlns:fo", "http://www.w3.org/1999/XSL/Format");
+ docContentPropList.insert("xmlns:xlink", "http://www.w3.org/1999/xlink");
+ docContentPropList.insert("xmlns:number", "http://openoffice.org/2000/datastyle");
+ docContentPropList.insert("xmlns:svg", "http://www.w3.org/2000/svg");
+ docContentPropList.insert("xmlns:chart", "http://openoffice.org/2000/chart");
+ docContentPropList.insert("xmlns:dr3d", "http://openoffice.org/2000/dr3d");
+ docContentPropList.insert("xmlns:math", "http://www.w3.org/1998/Math/MathML");
+ docContentPropList.insert("xmlns:form", "http://openoffice.org/2000/form");
+ docContentPropList.insert("xmlns:script", "http://openoffice.org/2000/script");
+ docContentPropList.insert("office:class", "text");
+ docContentPropList.insert("office:version", "1.0");
+ mpHandler->startElement("office:document-content", docContentPropList);
+
+ // write out the font styles
+ mpHandler->startElement("office:font-decls", xBlankAttrList);
+ for (std::map<_SH_String, FontStyle *, ltstr>::iterator iterFont = mFontHash.begin(); iterFont != mFontHash.end(); iterFont++) {
+ iterFont->second->write(*mpHandler);
+ }
+ TagOpenElement symbolFontOpen("style:font-decl");
+ symbolFontOpen.addAttribute("style:name", "StarSymbol");
+ symbolFontOpen.addAttribute("fo:font-family", "StarSymbol");
+ symbolFontOpen.addAttribute("style:font-charset", "x-symbol");
+ symbolFontOpen.write(*mpHandler);
+ mpHandler->endElement("style:font-decl");
+
+ mpHandler->endElement("office:font-decls");
+
+
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Writing out the styles..\n"));
+
+ // write default styles
+ _writeDefaultStyles(*mpHandler);
+
+ mpHandler->startElement("office:automatic-styles", xBlankAttrList);
+
+ for (std::map<_SH_String, ParagraphStyle *, ltstr>::iterator iterTextStyle = mTextStyleHash.begin();
+ iterTextStyle != mTextStyleHash.end(); iterTextStyle++)
+ {
+ // writing out the paragraph styles
+ if (strcmp((iterTextStyle->second)->getName().cstr(), "Standard"))
+ {
+ // don't write standard paragraph "no styles" style
+ (iterTextStyle->second)->write(xHandler);
+ }
+ }
+
+ // span styles..
+ for (std::map<_SH_String, SpanStyle *, ltstr>::iterator iterSpanStyle = mSpanStyleHash.begin();
+ iterSpanStyle != mSpanStyleHash.end(); iterSpanStyle++)
+ {
+ (iterSpanStyle->second)->write(xHandler);
+ }
+
+ // writing out the sections styles
+ for (std::vector<SectionStyle *>::iterator iterSectionStyles = mSectionStyles.begin(); iterSectionStyles != mSectionStyles.end(); iterSectionStyles++) {
+ (*iterSectionStyles)->write(xHandler);
+ }
+
+ // writing out the lists styles
+ for (std::vector<ListStyle *>::iterator iterListStyles = mListStyles.begin(); iterListStyles != mListStyles.end(); iterListStyles++) {
+ (*iterListStyles)->write(xHandler);
+ }
+
+ // writing out the table styles
+ for (std::vector<TableStyle *>::iterator iterTableStyles = mTableStyles.begin(); iterTableStyles != mTableStyles.end(); iterTableStyles++) {
+ (*iterTableStyles)->write(xHandler);
+ }
+
+ // writing out the page masters
+ _writePageMasters(xHandler);
+
+
+ xHandler.endElement("office:automatic-styles");
+
+ _writeMasterPages(xHandler);
+
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Writing out the document..\n"));
+ // writing out the document
+ xHandler.startElement("office:body", xBlankAttrList);
+
+ for (std::vector<DocumentElement *>::iterator iterBodyElements = mBodyElements.begin(); iterBodyElements != mBodyElements.end(); iterBodyElements++) {
+ (*iterBodyElements)->write(xHandler);
+ }
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Finished writing all doc els..\n"));
+
+ xHandler.endElement("office:body");
+ xHandler.endElement("office:document-content");
+
+ xHandler.endDocument();
+
+ return true;
+}
+
+
+_SH_String propListToStyleKey(const _SH_PropertyList & xPropList)
+{
+ _SH_String sKey;
+ _SH_PropertyList::Iter i(xPropList);
+ for (i.rewind(); i.next(); )
+ {
+ _SH_String sProp;
+ sProp.sprintf("[%s:%s]", i.key(), i()->getStr().cstr());
+ sKey.append(sProp);
+ }
+
+ return sKey;
+}
+
+_SH_String getParagraphStyleKey(const _SH_PropertyList & xPropList, const _SH_PropertyListVector & xTabStops)
+{
+ _SH_String sKey = propListToStyleKey(xPropList);
+
+ _SH_String sTabStops;
+ sTabStops.sprintf("[num-tab-stops:%i]", xTabStops.count());
+ _SH_PropertyListVector::Iter i(xTabStops);
+ for (i.rewind(); i.next();)
+ {
+ sTabStops.append(propListToStyleKey(i()));
+ }
+ sKey.append(sTabStops);
+
+ return sKey;
+}
+
+// _allocateFontName: add a (potentially mapped) font style to the hash if it's not already there, do nothing otherwise
+void WordPerfectCollector::_allocateFontName(const _SH_String & sFontName)
+{
+ if (mFontHash.find(sFontName) == mFontHash.end())
+ {
+ FontStyle *pFontStyle = new FontStyle(sFontName.cstr(), sFontName.cstr());
+ mFontHash[sFontName] = pFontStyle;
+ }
+}
+
+void WordPerfectCollector::openPageSpan(const _SH_PropertyList &propList)
+{
+ PageSpan *pPageSpan = new PageSpan(propList);
+ mPageSpans.push_back(pPageSpan);
+ mpCurrentPageSpan = pPageSpan;
+}
+
+void WordPerfectCollector::openHeader(const _SH_PropertyList &propList)
+{
+ std::vector<DocumentElement *> * pHeaderFooterContentElements = new std::vector<DocumentElement *>;
+
+ if (propList["libwpd:occurence"]->getStr() == "even")
+ mpCurrentPageSpan->setHeaderLeftContent(pHeaderFooterContentElements);
+ else
+ mpCurrentPageSpan->setHeaderContent(pHeaderFooterContentElements);
+
+ mpCurrentContentElements = pHeaderFooterContentElements;
+}
+
+void WordPerfectCollector::closeHeader()
+{
+ mpCurrentContentElements = &mBodyElements;
+}
+
+void WordPerfectCollector::openFooter(const _SH_PropertyList &propList)
+{
+ std::vector<DocumentElement *> * pHeaderFooterContentElements = new std::vector<DocumentElement *>;
+
+ if (propList["libwpd:occurence"]->getStr() == "even")
+ mpCurrentPageSpan->setFooterLeftContent(pHeaderFooterContentElements);
+ else
+ mpCurrentPageSpan->setFooterContent(pHeaderFooterContentElements);
+
+ mpCurrentContentElements = pHeaderFooterContentElements;
+}
+
+void WordPerfectCollector::closeFooter()
+{
+ mpCurrentContentElements = &mBodyElements;
+}
+
+void WordPerfectCollector::openSection(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns)
+{
+ int iNumColumns = columns.count();
+
+ if (iNumColumns > 1)
+ {
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+ mfSectionSpaceAfter = propList["fo:margin-bottom"]->getDouble();
+#else
+ mfSectionSpaceAfter = propList["fo:margin-bottom"]->getFloat();
+#endif
+ _SH_String sSectionName;
+ sSectionName.sprintf("Section%i", mSectionStyles.size());
+
+ SectionStyle *pSectionStyle = new SectionStyle(propList, columns, sSectionName.cstr());
+ mSectionStyles.push_back(pSectionStyle);
+
+ TagOpenElement *pSectionOpenElement = new TagOpenElement("text:section");
+ pSectionOpenElement->addAttribute("text:style-name", pSectionStyle->getName());
+ pSectionOpenElement->addAttribute("text:name", pSectionStyle->getName());
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pSectionOpenElement));
+ }
+ else
+ mWriterDocumentState.mbInFakeSection = true;
+}
+
+void WordPerfectCollector::closeSection()
+{
+ if (!mWriterDocumentState.mbInFakeSection)
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:section")));
+ else
+ mWriterDocumentState.mbInFakeSection = false;
+
+ // open as many paragraphs as needed to simulate section space after
+ // WLACH_REFACTORING: disable this for now..
+ #if 0
+ for (float f=0.0f; f<mfSectionSpaceAfter; f+=1.0f) {
+ vector<WPXTabStop> dummyTabStops;
+ openParagraph(WPX_PARAGRAPH_JUSTIFICATION_LEFT, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, dummyTabStops, false, false);
+ closeParagraph();
+ }
+ #endif
+ mfSectionSpaceAfter = 0.0f;
+}
+
+void WordPerfectCollector::openParagraph(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops)
+{
+ // FIXMENOW: What happens if we open a footnote inside a table? do we then inherit the footnote's style
+ // from "Table Contents"
+
+ _SH_PropertyList *pPersistPropList = new _SH_PropertyList(propList);
+ ParagraphStyle *pStyle = NULL;
+
+ if (mWriterDocumentState.mbFirstElement && mpCurrentContentElements == &mBodyElements)
+ {
+ // we don't have to go through the fuss of determining if the paragraph style is
+ // unique in this case, because if we are the first document element, then we
+ // are singular. Neither do we have to determine what our parent style is-- we can't
+ // be inside a table in this case (the table would be the first document element
+ //in that case)
+ pPersistPropList->insert("style:parent-style-name", "Standard");
+ _SH_String sName;
+ sName.sprintf("FS");
+
+ _SH_String sParagraphHashKey("P|FS");
+ pPersistPropList->insert("style:master-page-name", "Page Style 1");
+ pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
+ mTextStyleHash[sParagraphHashKey] = pStyle;
+ mWriterDocumentState.mbFirstElement = false;
+ }
+ else
+ {
+ if (mWriterDocumentState.mbTableCellOpened)
+ {
+ if (mWriterDocumentState.mbHeaderRow)
+ pPersistPropList->insert("style:parent-style-name", "Table Heading");
+ else
+ pPersistPropList->insert("style:parent-style-name", "Table Contents");
+ }
+ else
+ pPersistPropList->insert("style:parent-style-name", "Standard");
+
+ _SH_String sKey = getParagraphStyleKey(*pPersistPropList, tabStops);
+
+ if (mTextStyleHash.find(sKey) == mTextStyleHash.end()) {
+ _SH_String sName;
+ sName.sprintf("S%i", mTextStyleHash.size());
+
+ pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
+
+ mTextStyleHash[sKey] = pStyle;
+ }
+ else
+ {
+ pStyle = mTextStyleHash[sKey];
+ delete pPersistPropList;
+ }
+ }
+ // create a document element corresponding to the paragraph, and append it to our list of document elements
+ TagOpenElement *pParagraphOpenElement = new TagOpenElement("text:p");
+ pParagraphOpenElement->addAttribute("text:style-name", pStyle->getName());
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pParagraphOpenElement));
+}
+
+void WordPerfectCollector::closeParagraph()
+{
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
+}
+
+void WordPerfectCollector::openSpan(const _SH_PropertyList &propList)
+{
+ if (propList["style:font-name"])
+ _allocateFontName(propList["style:font-name"]->getStr());
+ _SH_String sSpanHashKey = propListToStyleKey(propList);
+ WRITER_DEBUG_MSG(("WriterWordPerfect: Span Hash Key: %s\n", sSpanHashKey.cstr()));
+
+ // Get the style
+ _SH_String sName;
+ if (mSpanStyleHash.find(sSpanHashKey) == mSpanStyleHash.end())
+ {
+ // allocate a new paragraph style
+ sName.sprintf("Span%i", mSpanStyleHash.size());
+ SpanStyle *pStyle = new SpanStyle(sName.cstr(), propList);
+
+ mSpanStyleHash[sSpanHashKey] = pStyle;
+ }
+ else
+ {
+ sName.sprintf("%s", mSpanStyleHash.find(sSpanHashKey)->second->getName().cstr());
+ }
+
+ // create a document element corresponding to the paragraph, and append it to our list of document elements
+ TagOpenElement *pSpanOpenElement = new TagOpenElement("text:span");
+ pSpanOpenElement->addAttribute("text:style-name", sName.cstr());
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pSpanOpenElement));
+}
+
+void WordPerfectCollector::closeSpan()
+{
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:span")));
+}
+
+void WordPerfectCollector::defineOrderedListLevel(const _SH_PropertyList &propList)
+{
+ int id = 0;
+ if (propList["libwpd:id"])
+ id = propList["libwpd:id"]->getInt();
+
+ OrderedListStyle *pOrderedListStyle = NULL;
+ if (mpCurrentListStyle && mpCurrentListStyle->getListID() == id)
+ pOrderedListStyle = static_cast<OrderedListStyle *>(mpCurrentListStyle); // FIXME: using a dynamic cast here causes oo to crash?!
+
+ // this rather appalling conditional makes sure we only start a new list (rather than continue an old
+ // one) if: (1) we have no prior list OR (2) the prior list is actually definitively different
+ // from the list that is just being defined (listIDs differ) OR (3) we can tell that the user actually
+ // is starting a new list at level 1 (and only level 1)
+ if (pOrderedListStyle == NULL || pOrderedListStyle->getListID() != id ||
+ (propList["libwpd:level"] && propList["libwpd:level"]->getInt()==1 &&
+ (propList["text:start-value"] && propList["text:start-value"]->getInt() != (miLastListNumber+1))))
+ {
+ WRITER_DEBUG_MSG(("Attempting to create a new ordered list style (listid: %i)\n", id));
+ _SH_String sName;
+ sName.sprintf("OL%i", miNumListStyles);
+ miNumListStyles++;
+ pOrderedListStyle = new OrderedListStyle(sName.cstr(), propList["libwpd:id"]->getInt());
+ mListStyles.push_back(static_cast<ListStyle *>(pOrderedListStyle));
+ mpCurrentListStyle = static_cast<ListStyle *>(pOrderedListStyle);
+ mbListContinueNumbering = false;
+ miLastListNumber = 0;
+ }
+ else
+ mbListContinueNumbering = true;
+
+ // Iterate through ALL list styles with the same WordPerfect list id and define a level if it is not already defined
+ // This solves certain problems with lists that start and finish without reaching certain levels and then begin again
+ // and reach those levels. See gradguide0405_PC.wpd in the regression suite
+ for (std::vector<ListStyle *>::iterator iterOrderedListStyles = mListStyles.begin(); iterOrderedListStyles != mListStyles.end(); iterOrderedListStyles++)
+ {
+ if ((* iterOrderedListStyles)->getListID() == propList["libwpd:id"]->getInt())
+ (* iterOrderedListStyles)->updateListLevel((propList["libwpd:level"]->getInt() - 1), propList);
+ }
+}
+
+void WordPerfectCollector::defineUnorderedListLevel(const _SH_PropertyList &propList)
+{
+ int id = 0;
+ if (propList["libwpd:id"])
+ id = propList["libwpd:id"]->getInt();
+
+ UnorderedListStyle *pUnorderedListStyle = NULL;
+ if (mpCurrentListStyle && mpCurrentListStyle->getListID() == id)
+ pUnorderedListStyle = static_cast<UnorderedListStyle *>(mpCurrentListStyle); // FIXME: using a dynamic cast here causes oo to crash?!
+
+ if (pUnorderedListStyle == NULL) {
+ WRITER_DEBUG_MSG(("Attempting to create a new unordered list style (listid: %i)\n", id));
+ _SH_String sName;
+ sName.sprintf("UL%i", miNumListStyles);
+ pUnorderedListStyle = new UnorderedListStyle(sName.cstr(), id);
+ mListStyles.push_back(static_cast<ListStyle *>(pUnorderedListStyle));
+ mpCurrentListStyle = static_cast<ListStyle *>(pUnorderedListStyle);
+ }
+
+ // See comment in WordPerfectCollector::defineOrderedListLevel
+ for (std::vector<ListStyle *>::iterator iterUnorderedListStyles = mListStyles.begin(); iterUnorderedListStyles != mListStyles.end(); iterUnorderedListStyles++)
+ {
+ if ((* iterUnorderedListStyles)->getListID() == propList["libwpd:id"]->getInt())
+ (* iterUnorderedListStyles)->updateListLevel((propList["libwpd:level"]->getInt() - 1), propList);
+ }
+}
+
+void WordPerfectCollector::openOrderedListLevel(const _SH_PropertyList &propList)
+{
+ miCurrentListLevel++;
+ TagOpenElement *pListLevelOpenElement = new TagOpenElement("text:ordered-list");
+ _openListLevel(pListLevelOpenElement);
+
+ if (mbListContinueNumbering) {
+ pListLevelOpenElement->addAttribute("text:continue-numbering", "true");
+ }
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pListLevelOpenElement));
+}
+
+void WordPerfectCollector::openUnorderedListLevel(const _SH_PropertyList &propList)
+{
+ miCurrentListLevel++;
+ TagOpenElement *pListLevelOpenElement = new TagOpenElement("text:unordered-list");
+ _openListLevel(pListLevelOpenElement);
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pListLevelOpenElement));
+}
+
+void WordPerfectCollector::_openListLevel(TagOpenElement *pListLevelOpenElement)
+{
+ if (!mbListElementOpened && miCurrentListLevel > 1)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:list-item")));
+ }
+ else if (mbListElementParagraphOpened)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
+ mbListElementParagraphOpened = false;
+ }
+
+ if (miCurrentListLevel==1) {
+ pListLevelOpenElement->addAttribute("text:style-name", mpCurrentListStyle->getName());
+ }
+
+ mbListElementOpened = false;
+}
+
+void WordPerfectCollector::closeOrderedListLevel()
+{
+ _closeListLevel("ordered-list");
+}
+
+void WordPerfectCollector::closeUnorderedListLevel()
+{
+ _closeListLevel("unordered-list");
+}
+
+void WordPerfectCollector::_closeListLevel(const char *szListType)
+{
+ if (mbListElementOpened)
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
+
+ miCurrentListLevel--;
+
+ _SH_String sCloseElement;
+ sCloseElement.sprintf("text:%s", szListType);
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement(sCloseElement.cstr())));
+
+ if (miCurrentListLevel > 0)
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
+ mbListElementOpened = false;
+}
+
+void WordPerfectCollector::openListElement(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops)
+{
+ miLastListLevel = miCurrentListLevel;
+ if (miCurrentListLevel == 1)
+ miLastListNumber++;
+
+ if (mbListElementOpened)
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
+
+ ParagraphStyle *pStyle = NULL;
+
+ _SH_PropertyList *pPersistPropList = new _SH_PropertyList(propList);
+ pPersistPropList->insert("style:list-style-name", mpCurrentListStyle->getName());
+ pPersistPropList->insert("style:parent-style-name", "Standard");
+
+ _SH_String sKey = getParagraphStyleKey(*pPersistPropList, tabStops);
+
+ if (mTextStyleHash.find(sKey) == mTextStyleHash.end())
+ {
+ _SH_String sName;
+ sName.sprintf("S%i", mTextStyleHash.size());
+
+ pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
+
+ mTextStyleHash[sKey] = pStyle;
+ }
+ else
+ {
+ pStyle = mTextStyleHash[sKey];
+ delete pPersistPropList;
+ }
+
+ TagOpenElement *pOpenListElement = new TagOpenElement("text:list-item");
+ TagOpenElement *pOpenListElementParagraph = new TagOpenElement("text:p");
+
+ pOpenListElementParagraph->addAttribute("text:style-name", pStyle->getName());
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenListElement));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenListElementParagraph));
+
+ mbListElementOpened = true;
+ mbListElementParagraphOpened = true;
+ mbListContinueNumbering = false;
+}
+
+void WordPerfectCollector::closeListElement()
+{
+ // this code is kind of tricky, because we don't actually close the list element (because this list element
+ // could contain another list level in OOo's implementation of lists). that is done in the closeListLevel
+ // code (or when we open another list element)
+
+ if (mbListElementParagraphOpened)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
+ mbListElementParagraphOpened = false;
+ }
+}
+
+void WordPerfectCollector::openFootnote(const _SH_PropertyList &propList)
+{
+ TagOpenElement *pOpenFootNote = new TagOpenElement("text:footnote");
+ if (propList["libwpd:number"])
+ {
+ _SH_String tmpString("ftn");
+ tmpString.append(propList["libwpd:number"]->getStr());
+ pOpenFootNote->addAttribute("text:id", tmpString);
+ }
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenFootNote));
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:footnote-citation")));
+ if (propList["libwpd:number"])
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new CharDataElement(propList["libwpd:number"]->getStr().cstr())));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote-citation")));
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:footnote-body")));
+
+ mWriterDocumentState.mbInNote = true;
+}
+
+void WordPerfectCollector::closeFootnote()
+{
+ mWriterDocumentState.mbInNote = false;
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote-body")));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote")));
+}
+
+void WordPerfectCollector::openEndnote(const _SH_PropertyList &propList)
+{
+ TagOpenElement *pOpenEndNote = new TagOpenElement("text:endnote");
+ if (propList["libwpd:number"])
+ {
+ _SH_String tmpString("edn");
+ tmpString.append(propList["libwpd:number"]->getStr());
+ pOpenEndNote->addAttribute("text:id", tmpString);
+ }
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenEndNote));
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:endnote-citation")));
+ if (propList["libwpd:number"])
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new CharDataElement(propList["libwpd:number"]->getStr().cstr())));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote-citation")));
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:endnote-body")));
+
+ mWriterDocumentState.mbInNote = true;
+}
+
+void WordPerfectCollector::closeEndnote()
+{
+ mWriterDocumentState.mbInNote = false;
+
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote-body")));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote")));
+}
+
+void WordPerfectCollector::openTable(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns)
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ _SH_String sTableName;
+ sTableName.sprintf("Table%i", mTableStyles.size());
+
+ // FIXME: we base the table style off of the page's margin left, ignoring (potential) wordperfect margin
+ // state which is transmitted inside the page. could this lead to unacceptable behaviour?
+ // WLACH_REFACTORING: characterize this behaviour, probably should nip it at the bud within libwpd
+ TableStyle *pTableStyle = new TableStyle(propList, columns, sTableName.cstr());
+
+ if (mWriterDocumentState.mbFirstElement && mpCurrentContentElements == &mBodyElements)
+ {
+ _SH_String sMasterPageName("Page Style 1");
+ pTableStyle->setMasterPageName(sMasterPageName);
+ mWriterDocumentState.mbFirstElement = false;
+ }
+
+ mTableStyles.push_back(pTableStyle);
+
+ mpCurrentTableStyle = pTableStyle;
+
+ TagOpenElement *pTableOpenElement = new TagOpenElement("table:table");
+
+ pTableOpenElement->addAttribute("table:name", sTableName.cstr());
+ pTableOpenElement->addAttribute("table:style-name", sTableName.cstr());
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableOpenElement));
+
+ for (int i=0; i<pTableStyle->getNumColumns(); i++)
+ {
+ TagOpenElement *pTableColumnOpenElement = new TagOpenElement("table:table-column");
+ _SH_String sColumnStyleName;
+ sColumnStyleName.sprintf("%s.Column%i", sTableName.cstr(), (i+1));
+ pTableColumnOpenElement->addAttribute("table:style-name", sColumnStyleName.cstr());
+ mpCurrentContentElements->push_back(pTableColumnOpenElement);
+
+ TagCloseElement *pTableColumnCloseElement = new TagCloseElement("table:table-column");
+ mpCurrentContentElements->push_back(pTableColumnCloseElement);
+ }
+ }
+}
+
+void WordPerfectCollector::openTableRow(const _SH_PropertyList &propList)
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ if (propList["libwpd:is-header-row"] && (propList["libwpd:is-header-row"]->getInt()))
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("table:table-header-rows")));
+ mWriterDocumentState.mbHeaderRow = true;
+ }
+
+ _SH_String sTableRowStyleName;
+ sTableRowStyleName.sprintf("%s.Row%i", mpCurrentTableStyle->getName().cstr(), mpCurrentTableStyle->getNumTableRowStyles());
+ TableRowStyle *pTableRowStyle = new TableRowStyle(propList, sTableRowStyleName.cstr());
+ mpCurrentTableStyle->addTableRowStyle(pTableRowStyle);
+
+ TagOpenElement *pTableRowOpenElement = new TagOpenElement("table:table-row");
+ pTableRowOpenElement->addAttribute("table:style-name", sTableRowStyleName);
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableRowOpenElement));
+ }
+}
+
+void WordPerfectCollector::closeTableRow()
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-row")));
+ if (mWriterDocumentState.mbHeaderRow)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-header-rows")));
+ mWriterDocumentState.mbHeaderRow = false;
+ }
+ }
+}
+
+void WordPerfectCollector::openTableCell(const _SH_PropertyList &propList)
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ _SH_String sTableCellStyleName;
+ sTableCellStyleName.sprintf( "%s.Cell%i", mpCurrentTableStyle->getName().cstr(), mpCurrentTableStyle->getNumTableCellStyles());
+ TableCellStyle *pTableCellStyle = new TableCellStyle(propList, sTableCellStyleName.cstr());
+ mpCurrentTableStyle->addTableCellStyle(pTableCellStyle);
+
+ TagOpenElement *pTableCellOpenElement = new TagOpenElement("table:table-cell");
+ pTableCellOpenElement->addAttribute("table:style-name", sTableCellStyleName);
+ if (propList["table:number-columns-spanned"])
+ pTableCellOpenElement->addAttribute("table:number-columns-spanned",
+ propList["table:number-columns-spanned"]->getStr().cstr());
+ if (propList["table:number-rows-spanned"])
+ pTableCellOpenElement->addAttribute("table:number-rows-spanned",
+ propList["table:number-rows-spanned"]->getStr().cstr());
+ pTableCellOpenElement->addAttribute("table:value-type", "string");
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableCellOpenElement));
+
+ mWriterDocumentState.mbTableCellOpened = true;
+ }
+}
+
+void WordPerfectCollector::closeTableCell()
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-cell")));
+ mWriterDocumentState.mbTableCellOpened = false;
+ }
+}
+
+void WordPerfectCollector::insertCoveredTableCell(const _SH_PropertyList &propList)
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("table:covered-table-cell")));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:covered-table-cell")));
+ }
+}
+
+void WordPerfectCollector::closeTable()
+{
+ if (!mWriterDocumentState.mbInNote)
+ {
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table")));
+ }
+}
+
+
+void WordPerfectCollector::insertTab()
+{
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:tab-stop")));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:tab-stop")));
+}
+
+void WordPerfectCollector::insertLineBreak()
+{
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:line-break")));
+ mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:line-break")));
+}
+
+void WordPerfectCollector::insertText(const _SH_String &text)
+{
+ DocumentElement *pText = new TextElement(text);
+ mpCurrentContentElements->push_back(pText);
+}
diff --git a/filters/kword/wordperfect/import/WordPerfectCollector.cxx b/filters/kword/wordperfect/import/WordPerfectCollector.cxx
deleted file mode 100644
index eb59a70f0..000000000
--- a/filters/kword/wordperfect/import/WordPerfectCollector.cxx
+++ /dev/null
@@ -1,973 +0,0 @@
-/* WordPerfectCollector: Collects sections and runs of text from a
- * wordperfect file (and styles to go along with them) and writes them
- * to a Writer target document
- *
- * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#include <config.h>
-
-#include <libwpd/libwpd.h>
-#include <string.h> // for strcmp
-
-#include "WordPerfectCollector.hxx"
-#include "DocumentElement.hxx"
-#include "TextRunStyle.hxx"
-#include "FontStyle.hxx"
-#include "ListStyle.hxx"
-#include "PageSpan.hxx"
-#include "SectionStyle.hxx"
-#include "TableStyle.hxx"
-#include "FilterInternal.hxx"
-#include "WriterProperties.hxx"
-
-_WriterDocumentState::_WriterDocumentState() :
- mbFirstElement(true),
- mbInFakeSection(false),
- mbListElementOpenedAtCurrentLevel(false),
- mbTableCellOpened(false),
- mbHeaderRow(false),
- mbInNote(false)
-{
-}
-
-WordPerfectCollector::WordPerfectCollector(_SH_InputStream *pInput, DocumentHandler *pHandler) :
- mpInput(pInput),
- mpHandler(pHandler),
- mbUsed(false),
- mfSectionSpaceAfter(0.0f),
- miNumListStyles(0),
- mpCurrentContentElements(&mBodyElements),
- mpCurrentPageSpan(NULL),
- miNumPageStyles(0),
- mpCurrentListStyle(NULL),
- miCurrentListLevel(0),
- miLastListLevel(0),
- miLastListNumber(0),
- mbListContinueNumbering(false),
- mbListElementOpened(false),
- mbListElementParagraphOpened(false)
-{
-}
-
-WordPerfectCollector::~WordPerfectCollector()
-{
-}
-
-bool WordPerfectCollector::filter()
-{
- // The contract for WordPerfectCollector is that it will only be used once after it is
- // instantiated
- if (mbUsed)
- return false;
-
- mbUsed = true;
-
- // parse & write
- // WLACH_REFACTORING: Remove these args..
- if (!_parseSourceDocument(*mpInput))
- return false;
- if (!_writeTargetDocument(*mpHandler))
- return false;
-
- // clean up the mess we made
- WRITER_DEBUG_MSG(("WriterWordPerfect: Cleaning up our mess..\n"));
-
- WRITER_DEBUG_MSG(("Destroying the body elements\n"));
- for (std::vector<DocumentElement *>::iterator iterBody = mBodyElements.begin(); iterBody != mBodyElements.end(); iterBody++) {
- delete((*iterBody));
- (*iterBody) = NULL;
- }
-
- WRITER_DEBUG_MSG(("Destroying the styles elements\n"));
- for (std::vector<DocumentElement *>::iterator iterStyles = mStylesElements.begin(); iterStyles != mStylesElements.end(); iterStyles++) {
- delete (*iterStyles);
- (*iterStyles) = NULL; // we may pass over the same element again (in the case of headers/footers spanning multiple pages)
- // so make sure we don't do a double del
- }
-
- WRITER_DEBUG_MSG(("Destroying the rest of the styles elements\n"));
- for (std::map<_SH_String, ParagraphStyle *, ltstr>::iterator iterTextStyle = mTextStyleHash.begin(); iterTextStyle != mTextStyleHash.end(); iterTextStyle++) {
- delete(iterTextStyle->second);
- }
- for (std::map<_SH_String, FontStyle *, ltstr>::iterator iterFont = mFontHash.begin(); iterFont != mFontHash.end(); iterFont++) {
- delete(iterFont->second);
- }
-
- for (std::vector<ListStyle *>::iterator iterListStyles = mListStyles.begin(); iterListStyles != mListStyles.end(); iterListStyles++) {
- delete((*iterListStyles));
- }
- for (std::vector<SectionStyle *>::iterator iterSectionStyles = mSectionStyles.begin(); iterSectionStyles != mSectionStyles.end(); iterSectionStyles++) {
- delete((*iterSectionStyles));
- }
- for (std::vector<TableStyle *>::iterator iterTableStyles = mTableStyles.begin(); iterTableStyles != mTableStyles.end(); iterTableStyles++) {
- delete((*iterTableStyles));
- }
-
- for (std::vector<PageSpan *>::iterator iterPageSpans = mPageSpans.begin(); iterPageSpans != mPageSpans.end(); iterPageSpans++) {
- delete((*iterPageSpans));
- }
-
- return true;
-}
-
-bool WordPerfectCollector::_parseSourceDocument(_SH_InputStream &input)
-{
-#if defined(HAVE_LIBWPD_0100)
- libwpd::WPDResult result = libwpd::WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this), NULL);
-#elif defined(HAVE_LIBWPD_090)
- WPDResult result = WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this), NULL);
-#else
- WPDResult result = WPDocument::parse(&input, static_cast<_SH_DocumentInterface*>(this));
-#endif
-#if defined(HAVE_LIBWPD_0100)
- if (result != libwpd::WPD_OK)
-#else
- if (result != WPD_OK)
-#endif
- return false;
-
- return true;
-}
-
-void WordPerfectCollector::_writeDefaultStyles(DocumentHandler &xHandler)
-{
- TagOpenElement stylesOpenElement("office:styles");
- stylesOpenElement.write(xHandler);
-
- TagOpenElement defaultParagraphStyleOpenElement("style:default-style");
- defaultParagraphStyleOpenElement.addAttribute("style:family", "paragraph");
- defaultParagraphStyleOpenElement.write(xHandler);
-
- TagOpenElement defaultParagraphStylePropertiesOpenElement("style:properties");
- defaultParagraphStylePropertiesOpenElement.addAttribute("style:family", "paragraph");
- defaultParagraphStylePropertiesOpenElement.addAttribute("style:tab-stop-distance", "0.5inch");
- defaultParagraphStylePropertiesOpenElement.write(xHandler);
- TagCloseElement defaultParagraphStylePropertiesCloseElement("style:properties");
- defaultParagraphStylePropertiesCloseElement.write(xHandler);
-
- TagCloseElement defaultParagraphStyleCloseElement("style:default-style");
- defaultParagraphStyleCloseElement.write(xHandler);
-
- TagOpenElement standardStyleOpenElement("style:style");
- standardStyleOpenElement.addAttribute("style:name", "Standard");
- standardStyleOpenElement.addAttribute("style:family", "paragraph");
- standardStyleOpenElement.addAttribute("style:class", "text");
- standardStyleOpenElement.write(xHandler);
- TagCloseElement standardStyleCloseElement("style:style");
- standardStyleCloseElement.write(xHandler);
-
- TagOpenElement textBodyStyleOpenElement("style:style");
- textBodyStyleOpenElement.addAttribute("style:name", "Text Body");
- textBodyStyleOpenElement.addAttribute("style:family", "paragraph");
- textBodyStyleOpenElement.addAttribute("style:parent-style-name", "Standard");
- textBodyStyleOpenElement.addAttribute("style:class", "text");
- textBodyStyleOpenElement.write(xHandler);
- TagCloseElement textBodyStyleCloseElement("style:style");
- textBodyStyleCloseElement.write(xHandler);
-
- TagOpenElement tableContentsStyleOpenElement("style:style");
- tableContentsStyleOpenElement.addAttribute("style:name", "Table Contents");
- tableContentsStyleOpenElement.addAttribute("style:family", "paragraph");
- tableContentsStyleOpenElement.addAttribute("style:parent-style-name", "Text Body");
- tableContentsStyleOpenElement.addAttribute("style:class", "extra");
- tableContentsStyleOpenElement.write(xHandler);
- TagCloseElement tableContentsStyleCloseElement("style:style");
- tableContentsStyleCloseElement.write(xHandler);
-
- TagOpenElement tableHeadingStyleOpenElement("style:style");
- tableHeadingStyleOpenElement.addAttribute("style:name", "Table Heading");
- tableHeadingStyleOpenElement.addAttribute("style:family", "paragraph");
- tableHeadingStyleOpenElement.addAttribute("style:parent-style-name", "Table Contents");
- tableHeadingStyleOpenElement.addAttribute("style:class", "extra");
- tableHeadingStyleOpenElement.write(xHandler);
- TagCloseElement tableHeadingStyleCloseElement("style:style");
- tableHeadingStyleCloseElement.write(xHandler);
-
- TagCloseElement stylesCloseElement("office:styles");
- stylesCloseElement.write(xHandler);
-
-}
-
-// writes everything up to the automatic styles declarations..
-void WordPerfectCollector::_writeBegin()
-{
-}
-
-void WordPerfectCollector::_writeMasterPages(DocumentHandler &xHandler)
-{
- _SH_PropertyList xBlankAttrList;
-
- xHandler.startElement("office:master-styles", xBlankAttrList);
- int pageNumber = 1;
- for (int i=0; i<mPageSpans.size(); i++)
- {
- bool bLastPage;
- (i == (mPageSpans.size() - 1)) ? bLastPage = true : bLastPage = false;
- mPageSpans[i]->writeMasterPages(pageNumber, i, bLastPage, xHandler);
- pageNumber += mPageSpans[i]->getSpan();
- }
- xHandler.endElement("office:master-styles");
-}
-
-void WordPerfectCollector::_writePageMasters(DocumentHandler &xHandler)
-{
- int pageNumber = 1;
- for (int i=0; i<mPageSpans.size(); i++)
- {
- mPageSpans[i]->writePageMaster(i, xHandler);
- }
-}
-
-bool WordPerfectCollector::_writeTargetDocument(DocumentHandler &xHandler)
-{
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Printing out the header stuff..\n"));
- _SH_PropertyList xBlankAttrList;
-
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Start Document\n"));
- mpHandler->startDocument();
-
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: preamble\n"));
- _SH_PropertyList docContentPropList;
- docContentPropList.insert("xmlns:office", "http://openoffice.org/2000/office");
- docContentPropList.insert("xmlns:style", "http://openoffice.org/2000/style");
- docContentPropList.insert("xmlns:text", "http://openoffice.org/2000/text");
- docContentPropList.insert("xmlns:table", "http://openoffice.org/2000/table");
- docContentPropList.insert("xmlns:draw", "http://openoffice.org/2000/draw");
- docContentPropList.insert("xmlns:fo", "http://www.w3.org/1999/XSL/Format");
- docContentPropList.insert("xmlns:xlink", "http://www.w3.org/1999/xlink");
- docContentPropList.insert("xmlns:number", "http://openoffice.org/2000/datastyle");
- docContentPropList.insert("xmlns:svg", "http://www.w3.org/2000/svg");
- docContentPropList.insert("xmlns:chart", "http://openoffice.org/2000/chart");
- docContentPropList.insert("xmlns:dr3d", "http://openoffice.org/2000/dr3d");
- docContentPropList.insert("xmlns:math", "http://www.w3.org/1998/Math/MathML");
- docContentPropList.insert("xmlns:form", "http://openoffice.org/2000/form");
- docContentPropList.insert("xmlns:script", "http://openoffice.org/2000/script");
- docContentPropList.insert("office:class", "text");
- docContentPropList.insert("office:version", "1.0");
- mpHandler->startElement("office:document-content", docContentPropList);
-
- // write out the font styles
- mpHandler->startElement("office:font-decls", xBlankAttrList);
- for (std::map<_SH_String, FontStyle *, ltstr>::iterator iterFont = mFontHash.begin(); iterFont != mFontHash.end(); iterFont++) {
- iterFont->second->write(*mpHandler);
- }
- TagOpenElement symbolFontOpen("style:font-decl");
- symbolFontOpen.addAttribute("style:name", "StarSymbol");
- symbolFontOpen.addAttribute("fo:font-family", "StarSymbol");
- symbolFontOpen.addAttribute("style:font-charset", "x-symbol");
- symbolFontOpen.write(*mpHandler);
- mpHandler->endElement("style:font-decl");
-
- mpHandler->endElement("office:font-decls");
-
-
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Writing out the styles..\n"));
-
- // write default styles
- _writeDefaultStyles(*mpHandler);
-
- mpHandler->startElement("office:automatic-styles", xBlankAttrList);
-
- for (std::map<_SH_String, ParagraphStyle *, ltstr>::iterator iterTextStyle = mTextStyleHash.begin();
- iterTextStyle != mTextStyleHash.end(); iterTextStyle++)
- {
- // writing out the paragraph styles
- if (strcmp((iterTextStyle->second)->getName().cstr(), "Standard"))
- {
- // don't write standard paragraph "no styles" style
- (iterTextStyle->second)->write(xHandler);
- }
- }
-
- // span styles..
- for (std::map<_SH_String, SpanStyle *, ltstr>::iterator iterSpanStyle = mSpanStyleHash.begin();
- iterSpanStyle != mSpanStyleHash.end(); iterSpanStyle++)
- {
- (iterSpanStyle->second)->write(xHandler);
- }
-
- // writing out the sections styles
- for (std::vector<SectionStyle *>::iterator iterSectionStyles = mSectionStyles.begin(); iterSectionStyles != mSectionStyles.end(); iterSectionStyles++) {
- (*iterSectionStyles)->write(xHandler);
- }
-
- // writing out the lists styles
- for (std::vector<ListStyle *>::iterator iterListStyles = mListStyles.begin(); iterListStyles != mListStyles.end(); iterListStyles++) {
- (*iterListStyles)->write(xHandler);
- }
-
- // writing out the table styles
- for (std::vector<TableStyle *>::iterator iterTableStyles = mTableStyles.begin(); iterTableStyles != mTableStyles.end(); iterTableStyles++) {
- (*iterTableStyles)->write(xHandler);
- }
-
- // writing out the page masters
- _writePageMasters(xHandler);
-
-
- xHandler.endElement("office:automatic-styles");
-
- _writeMasterPages(xHandler);
-
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Writing out the document..\n"));
- // writing out the document
- xHandler.startElement("office:body", xBlankAttrList);
-
- for (std::vector<DocumentElement *>::iterator iterBodyElements = mBodyElements.begin(); iterBodyElements != mBodyElements.end(); iterBodyElements++) {
- (*iterBodyElements)->write(xHandler);
- }
- WRITER_DEBUG_MSG(("WriterWordPerfect: Document Body: Finished writing all doc els..\n"));
-
- xHandler.endElement("office:body");
- xHandler.endElement("office:document-content");
-
- xHandler.endDocument();
-
- return true;
-}
-
-
-_SH_String propListToStyleKey(const _SH_PropertyList & xPropList)
-{
- _SH_String sKey;
- _SH_PropertyList::Iter i(xPropList);
- for (i.rewind(); i.next(); )
- {
- _SH_String sProp;
- sProp.sprintf("[%s:%s]", i.key(), i()->getStr().cstr());
- sKey.append(sProp);
- }
-
- return sKey;
-}
-
-_SH_String getParagraphStyleKey(const _SH_PropertyList & xPropList, const _SH_PropertyListVector & xTabStops)
-{
- _SH_String sKey = propListToStyleKey(xPropList);
-
- _SH_String sTabStops;
- sTabStops.sprintf("[num-tab-stops:%i]", xTabStops.count());
- _SH_PropertyListVector::Iter i(xTabStops);
- for (i.rewind(); i.next();)
- {
- sTabStops.append(propListToStyleKey(i()));
- }
- sKey.append(sTabStops);
-
- return sKey;
-}
-
-// _allocateFontName: add a (potentially mapped) font style to the hash if it's not already there, do nothing otherwise
-void WordPerfectCollector::_allocateFontName(const _SH_String & sFontName)
-{
- if (mFontHash.find(sFontName) == mFontHash.end())
- {
- FontStyle *pFontStyle = new FontStyle(sFontName.cstr(), sFontName.cstr());
- mFontHash[sFontName] = pFontStyle;
- }
-}
-
-void WordPerfectCollector::openPageSpan(const _SH_PropertyList &propList)
-{
- PageSpan *pPageSpan = new PageSpan(propList);
- mPageSpans.push_back(pPageSpan);
- mpCurrentPageSpan = pPageSpan;
-}
-
-void WordPerfectCollector::openHeader(const _SH_PropertyList &propList)
-{
- std::vector<DocumentElement *> * pHeaderFooterContentElements = new std::vector<DocumentElement *>;
-
- if (propList["libwpd:occurence"]->getStr() == "even")
- mpCurrentPageSpan->setHeaderLeftContent(pHeaderFooterContentElements);
- else
- mpCurrentPageSpan->setHeaderContent(pHeaderFooterContentElements);
-
- mpCurrentContentElements = pHeaderFooterContentElements;
-}
-
-void WordPerfectCollector::closeHeader()
-{
- mpCurrentContentElements = &mBodyElements;
-}
-
-void WordPerfectCollector::openFooter(const _SH_PropertyList &propList)
-{
- std::vector<DocumentElement *> * pHeaderFooterContentElements = new std::vector<DocumentElement *>;
-
- if (propList["libwpd:occurence"]->getStr() == "even")
- mpCurrentPageSpan->setFooterLeftContent(pHeaderFooterContentElements);
- else
- mpCurrentPageSpan->setFooterContent(pHeaderFooterContentElements);
-
- mpCurrentContentElements = pHeaderFooterContentElements;
-}
-
-void WordPerfectCollector::closeFooter()
-{
- mpCurrentContentElements = &mBodyElements;
-}
-
-void WordPerfectCollector::openSection(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns)
-{
- int iNumColumns = columns.count();
-
- if (iNumColumns > 1)
- {
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
- mfSectionSpaceAfter = propList["fo:margin-bottom"]->getDouble();
-#else
- mfSectionSpaceAfter = propList["fo:margin-bottom"]->getFloat();
-#endif
- _SH_String sSectionName;
- sSectionName.sprintf("Section%i", mSectionStyles.size());
-
- SectionStyle *pSectionStyle = new SectionStyle(propList, columns, sSectionName.cstr());
- mSectionStyles.push_back(pSectionStyle);
-
- TagOpenElement *pSectionOpenElement = new TagOpenElement("text:section");
- pSectionOpenElement->addAttribute("text:style-name", pSectionStyle->getName());
- pSectionOpenElement->addAttribute("text:name", pSectionStyle->getName());
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pSectionOpenElement));
- }
- else
- mWriterDocumentState.mbInFakeSection = true;
-}
-
-void WordPerfectCollector::closeSection()
-{
- if (!mWriterDocumentState.mbInFakeSection)
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:section")));
- else
- mWriterDocumentState.mbInFakeSection = false;
-
- // open as many paragraphs as needed to simulate section space after
- // WLACH_REFACTORING: disable this for now..
- #if 0
- for (float f=0.0f; f<mfSectionSpaceAfter; f+=1.0f) {
- vector<WPXTabStop> dummyTabStops;
- openParagraph(WPX_PARAGRAPH_JUSTIFICATION_LEFT, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, dummyTabStops, false, false);
- closeParagraph();
- }
- #endif
- mfSectionSpaceAfter = 0.0f;
-}
-
-void WordPerfectCollector::openParagraph(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops)
-{
- // FIXMENOW: What happens if we open a footnote inside a table? do we then inherit the footnote's style
- // from "Table Contents"
-
- _SH_PropertyList *pPersistPropList = new _SH_PropertyList(propList);
- ParagraphStyle *pStyle = NULL;
-
- if (mWriterDocumentState.mbFirstElement && mpCurrentContentElements == &mBodyElements)
- {
- // we don't have to go through the fuss of determining if the paragraph style is
- // unique in this case, because if we are the first document element, then we
- // are singular. Neither do we have to determine what our parent style is-- we can't
- // be inside a table in this case (the table would be the first document element
- //in that case)
- pPersistPropList->insert("style:parent-style-name", "Standard");
- _SH_String sName;
- sName.sprintf("FS");
-
- _SH_String sParagraphHashKey("P|FS");
- pPersistPropList->insert("style:master-page-name", "Page Style 1");
- pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
- mTextStyleHash[sParagraphHashKey] = pStyle;
- mWriterDocumentState.mbFirstElement = false;
- }
- else
- {
- if (mWriterDocumentState.mbTableCellOpened)
- {
- if (mWriterDocumentState.mbHeaderRow)
- pPersistPropList->insert("style:parent-style-name", "Table Heading");
- else
- pPersistPropList->insert("style:parent-style-name", "Table Contents");
- }
- else
- pPersistPropList->insert("style:parent-style-name", "Standard");
-
- _SH_String sKey = getParagraphStyleKey(*pPersistPropList, tabStops);
-
- if (mTextStyleHash.find(sKey) == mTextStyleHash.end()) {
- _SH_String sName;
- sName.sprintf("S%i", mTextStyleHash.size());
-
- pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
-
- mTextStyleHash[sKey] = pStyle;
- }
- else
- {
- pStyle = mTextStyleHash[sKey];
- delete pPersistPropList;
- }
- }
- // create a document element corresponding to the paragraph, and append it to our list of document elements
- TagOpenElement *pParagraphOpenElement = new TagOpenElement("text:p");
- pParagraphOpenElement->addAttribute("text:style-name", pStyle->getName());
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pParagraphOpenElement));
-}
-
-void WordPerfectCollector::closeParagraph()
-{
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
-}
-
-void WordPerfectCollector::openSpan(const _SH_PropertyList &propList)
-{
- if (propList["style:font-name"])
- _allocateFontName(propList["style:font-name"]->getStr());
- _SH_String sSpanHashKey = propListToStyleKey(propList);
- WRITER_DEBUG_MSG(("WriterWordPerfect: Span Hash Key: %s\n", sSpanHashKey.cstr()));
-
- // Get the style
- _SH_String sName;
- if (mSpanStyleHash.find(sSpanHashKey) == mSpanStyleHash.end())
- {
- // allocate a new paragraph style
- sName.sprintf("Span%i", mSpanStyleHash.size());
- SpanStyle *pStyle = new SpanStyle(sName.cstr(), propList);
-
- mSpanStyleHash[sSpanHashKey] = pStyle;
- }
- else
- {
- sName.sprintf("%s", mSpanStyleHash.find(sSpanHashKey)->second->getName().cstr());
- }
-
- // create a document element corresponding to the paragraph, and append it to our list of document elements
- TagOpenElement *pSpanOpenElement = new TagOpenElement("text:span");
- pSpanOpenElement->addAttribute("text:style-name", sName.cstr());
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pSpanOpenElement));
-}
-
-void WordPerfectCollector::closeSpan()
-{
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:span")));
-}
-
-void WordPerfectCollector::defineOrderedListLevel(const _SH_PropertyList &propList)
-{
- int id = 0;
- if (propList["libwpd:id"])
- id = propList["libwpd:id"]->getInt();
-
- OrderedListStyle *pOrderedListStyle = NULL;
- if (mpCurrentListStyle && mpCurrentListStyle->getListID() == id)
- pOrderedListStyle = static_cast<OrderedListStyle *>(mpCurrentListStyle); // FIXME: using a dynamic cast here causes oo to crash?!
-
- // this rather appalling conditional makes sure we only start a new list (rather than continue an old
- // one) if: (1) we have no prior list OR (2) the prior list is actually definitively different
- // from the list that is just being defined (listIDs differ) OR (3) we can tell that the user actually
- // is starting a new list at level 1 (and only level 1)
- if (pOrderedListStyle == NULL || pOrderedListStyle->getListID() != id ||
- (propList["libwpd:level"] && propList["libwpd:level"]->getInt()==1 &&
- (propList["text:start-value"] && propList["text:start-value"]->getInt() != (miLastListNumber+1))))
- {
- WRITER_DEBUG_MSG(("Attempting to create a new ordered list style (listid: %i)\n", id));
- _SH_String sName;
- sName.sprintf("OL%i", miNumListStyles);
- miNumListStyles++;
- pOrderedListStyle = new OrderedListStyle(sName.cstr(), propList["libwpd:id"]->getInt());
- mListStyles.push_back(static_cast<ListStyle *>(pOrderedListStyle));
- mpCurrentListStyle = static_cast<ListStyle *>(pOrderedListStyle);
- mbListContinueNumbering = false;
- miLastListNumber = 0;
- }
- else
- mbListContinueNumbering = true;
-
- // Iterate through ALL list styles with the same WordPerfect list id and define a level if it is not already defined
- // This solves certain problems with lists that start and finish without reaching certain levels and then begin again
- // and reach those levels. See gradguide0405_PC.wpd in the regression suite
- for (std::vector<ListStyle *>::iterator iterOrderedListStyles = mListStyles.begin(); iterOrderedListStyles != mListStyles.end(); iterOrderedListStyles++)
- {
- if ((* iterOrderedListStyles)->getListID() == propList["libwpd:id"]->getInt())
- (* iterOrderedListStyles)->updateListLevel((propList["libwpd:level"]->getInt() - 1), propList);
- }
-}
-
-void WordPerfectCollector::defineUnorderedListLevel(const _SH_PropertyList &propList)
-{
- int id = 0;
- if (propList["libwpd:id"])
- id = propList["libwpd:id"]->getInt();
-
- UnorderedListStyle *pUnorderedListStyle = NULL;
- if (mpCurrentListStyle && mpCurrentListStyle->getListID() == id)
- pUnorderedListStyle = static_cast<UnorderedListStyle *>(mpCurrentListStyle); // FIXME: using a dynamic cast here causes oo to crash?!
-
- if (pUnorderedListStyle == NULL) {
- WRITER_DEBUG_MSG(("Attempting to create a new unordered list style (listid: %i)\n", id));
- _SH_String sName;
- sName.sprintf("UL%i", miNumListStyles);
- pUnorderedListStyle = new UnorderedListStyle(sName.cstr(), id);
- mListStyles.push_back(static_cast<ListStyle *>(pUnorderedListStyle));
- mpCurrentListStyle = static_cast<ListStyle *>(pUnorderedListStyle);
- }
-
- // See comment in WordPerfectCollector::defineOrderedListLevel
- for (std::vector<ListStyle *>::iterator iterUnorderedListStyles = mListStyles.begin(); iterUnorderedListStyles != mListStyles.end(); iterUnorderedListStyles++)
- {
- if ((* iterUnorderedListStyles)->getListID() == propList["libwpd:id"]->getInt())
- (* iterUnorderedListStyles)->updateListLevel((propList["libwpd:level"]->getInt() - 1), propList);
- }
-}
-
-void WordPerfectCollector::openOrderedListLevel(const _SH_PropertyList &propList)
-{
- miCurrentListLevel++;
- TagOpenElement *pListLevelOpenElement = new TagOpenElement("text:ordered-list");
- _openListLevel(pListLevelOpenElement);
-
- if (mbListContinueNumbering) {
- pListLevelOpenElement->addAttribute("text:continue-numbering", "true");
- }
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pListLevelOpenElement));
-}
-
-void WordPerfectCollector::openUnorderedListLevel(const _SH_PropertyList &propList)
-{
- miCurrentListLevel++;
- TagOpenElement *pListLevelOpenElement = new TagOpenElement("text:unordered-list");
- _openListLevel(pListLevelOpenElement);
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pListLevelOpenElement));
-}
-
-void WordPerfectCollector::_openListLevel(TagOpenElement *pListLevelOpenElement)
-{
- if (!mbListElementOpened && miCurrentListLevel > 1)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:list-item")));
- }
- else if (mbListElementParagraphOpened)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
- mbListElementParagraphOpened = false;
- }
-
- if (miCurrentListLevel==1) {
- pListLevelOpenElement->addAttribute("text:style-name", mpCurrentListStyle->getName());
- }
-
- mbListElementOpened = false;
-}
-
-void WordPerfectCollector::closeOrderedListLevel()
-{
- _closeListLevel("ordered-list");
-}
-
-void WordPerfectCollector::closeUnorderedListLevel()
-{
- _closeListLevel("unordered-list");
-}
-
-void WordPerfectCollector::_closeListLevel(const char *szListType)
-{
- if (mbListElementOpened)
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
-
- miCurrentListLevel--;
-
- _SH_String sCloseElement;
- sCloseElement.sprintf("text:%s", szListType);
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement(sCloseElement.cstr())));
-
- if (miCurrentListLevel > 0)
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
- mbListElementOpened = false;
-}
-
-void WordPerfectCollector::openListElement(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops)
-{
- miLastListLevel = miCurrentListLevel;
- if (miCurrentListLevel == 1)
- miLastListNumber++;
-
- if (mbListElementOpened)
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:list-item")));
-
- ParagraphStyle *pStyle = NULL;
-
- _SH_PropertyList *pPersistPropList = new _SH_PropertyList(propList);
- pPersistPropList->insert("style:list-style-name", mpCurrentListStyle->getName());
- pPersistPropList->insert("style:parent-style-name", "Standard");
-
- _SH_String sKey = getParagraphStyleKey(*pPersistPropList, tabStops);
-
- if (mTextStyleHash.find(sKey) == mTextStyleHash.end())
- {
- _SH_String sName;
- sName.sprintf("S%i", mTextStyleHash.size());
-
- pStyle = new ParagraphStyle(pPersistPropList, tabStops, sName);
-
- mTextStyleHash[sKey] = pStyle;
- }
- else
- {
- pStyle = mTextStyleHash[sKey];
- delete pPersistPropList;
- }
-
- TagOpenElement *pOpenListElement = new TagOpenElement("text:list-item");
- TagOpenElement *pOpenListElementParagraph = new TagOpenElement("text:p");
-
- pOpenListElementParagraph->addAttribute("text:style-name", pStyle->getName());
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenListElement));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenListElementParagraph));
-
- mbListElementOpened = true;
- mbListElementParagraphOpened = true;
- mbListContinueNumbering = false;
-}
-
-void WordPerfectCollector::closeListElement()
-{
- // this code is kind of tricky, because we don't actually close the list element (because this list element
- // could contain another list level in OOo's implementation of lists). that is done in the closeListLevel
- // code (or when we open another list element)
-
- if (mbListElementParagraphOpened)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:p")));
- mbListElementParagraphOpened = false;
- }
-}
-
-void WordPerfectCollector::openFootnote(const _SH_PropertyList &propList)
-{
- TagOpenElement *pOpenFootNote = new TagOpenElement("text:footnote");
- if (propList["libwpd:number"])
- {
- _SH_String tmpString("ftn");
- tmpString.append(propList["libwpd:number"]->getStr());
- pOpenFootNote->addAttribute("text:id", tmpString);
- }
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenFootNote));
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:footnote-citation")));
- if (propList["libwpd:number"])
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new CharDataElement(propList["libwpd:number"]->getStr().cstr())));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote-citation")));
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:footnote-body")));
-
- mWriterDocumentState.mbInNote = true;
-}
-
-void WordPerfectCollector::closeFootnote()
-{
- mWriterDocumentState.mbInNote = false;
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote-body")));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:footnote")));
-}
-
-void WordPerfectCollector::openEndnote(const _SH_PropertyList &propList)
-{
- TagOpenElement *pOpenEndNote = new TagOpenElement("text:endnote");
- if (propList["libwpd:number"])
- {
- _SH_String tmpString("edn");
- tmpString.append(propList["libwpd:number"]->getStr());
- pOpenEndNote->addAttribute("text:id", tmpString);
- }
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pOpenEndNote));
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:endnote-citation")));
- if (propList["libwpd:number"])
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new CharDataElement(propList["libwpd:number"]->getStr().cstr())));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote-citation")));
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:endnote-body")));
-
- mWriterDocumentState.mbInNote = true;
-}
-
-void WordPerfectCollector::closeEndnote()
-{
- mWriterDocumentState.mbInNote = false;
-
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote-body")));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:endnote")));
-}
-
-void WordPerfectCollector::openTable(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns)
-{
- if (!mWriterDocumentState.mbInNote)
- {
- _SH_String sTableName;
- sTableName.sprintf("Table%i", mTableStyles.size());
-
- // FIXME: we base the table style off of the page's margin left, ignoring (potential) wordperfect margin
- // state which is transmitted inside the page. could this lead to unacceptable behaviour?
- // WLACH_REFACTORING: characterize this behaviour, probably should nip it at the bud within libwpd
- TableStyle *pTableStyle = new TableStyle(propList, columns, sTableName.cstr());
-
- if (mWriterDocumentState.mbFirstElement && mpCurrentContentElements == &mBodyElements)
- {
- _SH_String sMasterPageName("Page Style 1");
- pTableStyle->setMasterPageName(sMasterPageName);
- mWriterDocumentState.mbFirstElement = false;
- }
-
- mTableStyles.push_back(pTableStyle);
-
- mpCurrentTableStyle = pTableStyle;
-
- TagOpenElement *pTableOpenElement = new TagOpenElement("table:table");
-
- pTableOpenElement->addAttribute("table:name", sTableName.cstr());
- pTableOpenElement->addAttribute("table:style-name", sTableName.cstr());
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableOpenElement));
-
- for (int i=0; i<pTableStyle->getNumColumns(); i++)
- {
- TagOpenElement *pTableColumnOpenElement = new TagOpenElement("table:table-column");
- _SH_String sColumnStyleName;
- sColumnStyleName.sprintf("%s.Column%i", sTableName.cstr(), (i+1));
- pTableColumnOpenElement->addAttribute("table:style-name", sColumnStyleName.cstr());
- mpCurrentContentElements->push_back(pTableColumnOpenElement);
-
- TagCloseElement *pTableColumnCloseElement = new TagCloseElement("table:table-column");
- mpCurrentContentElements->push_back(pTableColumnCloseElement);
- }
- }
-}
-
-void WordPerfectCollector::openTableRow(const _SH_PropertyList &propList)
-{
- if (!mWriterDocumentState.mbInNote)
- {
- if (propList["libwpd:is-header-row"] && (propList["libwpd:is-header-row"]->getInt()))
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("table:table-header-rows")));
- mWriterDocumentState.mbHeaderRow = true;
- }
-
- _SH_String sTableRowStyleName;
- sTableRowStyleName.sprintf("%s.Row%i", mpCurrentTableStyle->getName().cstr(), mpCurrentTableStyle->getNumTableRowStyles());
- TableRowStyle *pTableRowStyle = new TableRowStyle(propList, sTableRowStyleName.cstr());
- mpCurrentTableStyle->addTableRowStyle(pTableRowStyle);
-
- TagOpenElement *pTableRowOpenElement = new TagOpenElement("table:table-row");
- pTableRowOpenElement->addAttribute("table:style-name", sTableRowStyleName);
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableRowOpenElement));
- }
-}
-
-void WordPerfectCollector::closeTableRow()
-{
- if (!mWriterDocumentState.mbInNote)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-row")));
- if (mWriterDocumentState.mbHeaderRow)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-header-rows")));
- mWriterDocumentState.mbHeaderRow = false;
- }
- }
-}
-
-void WordPerfectCollector::openTableCell(const _SH_PropertyList &propList)
-{
- if (!mWriterDocumentState.mbInNote)
- {
- _SH_String sTableCellStyleName;
- sTableCellStyleName.sprintf( "%s.Cell%i", mpCurrentTableStyle->getName().cstr(), mpCurrentTableStyle->getNumTableCellStyles());
- TableCellStyle *pTableCellStyle = new TableCellStyle(propList, sTableCellStyleName.cstr());
- mpCurrentTableStyle->addTableCellStyle(pTableCellStyle);
-
- TagOpenElement *pTableCellOpenElement = new TagOpenElement("table:table-cell");
- pTableCellOpenElement->addAttribute("table:style-name", sTableCellStyleName);
- if (propList["table:number-columns-spanned"])
- pTableCellOpenElement->addAttribute("table:number-columns-spanned",
- propList["table:number-columns-spanned"]->getStr().cstr());
- if (propList["table:number-rows-spanned"])
- pTableCellOpenElement->addAttribute("table:number-rows-spanned",
- propList["table:number-rows-spanned"]->getStr().cstr());
- pTableCellOpenElement->addAttribute("table:value-type", "string");
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(pTableCellOpenElement));
-
- mWriterDocumentState.mbTableCellOpened = true;
- }
-}
-
-void WordPerfectCollector::closeTableCell()
-{
- if (!mWriterDocumentState.mbInNote)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table-cell")));
- mWriterDocumentState.mbTableCellOpened = false;
- }
-}
-
-void WordPerfectCollector::insertCoveredTableCell(const _SH_PropertyList &propList)
-{
- if (!mWriterDocumentState.mbInNote)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("table:covered-table-cell")));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:covered-table-cell")));
- }
-}
-
-void WordPerfectCollector::closeTable()
-{
- if (!mWriterDocumentState.mbInNote)
- {
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("table:table")));
- }
-}
-
-
-void WordPerfectCollector::insertTab()
-{
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:tab-stop")));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:tab-stop")));
-}
-
-void WordPerfectCollector::insertLineBreak()
-{
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagOpenElement("text:line-break")));
- mpCurrentContentElements->push_back(static_cast<DocumentElement *>(new TagCloseElement("text:line-break")));
-}
-
-void WordPerfectCollector::insertText(const _SH_String &text)
-{
- DocumentElement *pText = new TextElement(text);
- mpCurrentContentElements->push_back(pText);
-}
diff --git a/filters/kword/wordperfect/import/WordPerfectCollector.h b/filters/kword/wordperfect/import/WordPerfectCollector.h
new file mode 100644
index 000000000..2f0af74a3
--- /dev/null
+++ b/filters/kword/wordperfect/import/WordPerfectCollector.h
@@ -0,0 +1,231 @@
+/* WordPerfectCollector: Collects sections and runs of text from a
+ * wordperfect file (and styles to go along with them) and writes them
+ * to a target file
+ *
+ * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
+ * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com)
+ * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * For further information visit http://libwpd.sourceforge.net
+ *
+ */
+
+/* "This product is not manufactured, approved, or supported by
+ * Corel Corporation or Corel Corporation Limited."
+ */
+
+#ifndef _WORDPERFECTCOLLECTOR_H
+#define _WORDPERFECTCOLLECTOR_H
+
+#include "SectionStyle.h"
+
+#include <config.h>
+#include <libwpd/libwpd.h>
+#include "shared_headers.h"
+#include <vector>
+#include <map>
+#include <stack>
+
+class DocumentElement;
+class DocumentHandler;
+class TagOpenElement;
+class FontStyle;
+class ListStyle;
+
+class ParagraphStyle;
+class SpanStyle;
+class TableStyle;
+class PageSpan;
+
+// the state we use for writing the final document
+typedef struct _WriterDocumentState WriterDocumentState;
+struct _WriterDocumentState
+{
+ _WriterDocumentState();
+
+ bool mbFirstElement;
+ bool mbInFakeSection;
+ bool mbListElementOpenedAtCurrentLevel;
+ bool mbTableCellOpened;
+ bool mbHeaderRow;
+ bool mbInNote;
+};
+
+enum WriterListType { unordered, ordered };
+
+struct ltstr
+{
+ bool operator()(const _SH_String & s1, const _SH_String & s2) const
+ {
+ return strcmp(s1.cstr(), s2.cstr()) < 0;
+ }
+};
+
+class WordPerfectCollector : public _SH_DocumentInterface
+{
+public:
+ WordPerfectCollector(_SH_InputStream *pInput, DocumentHandler *pHandler);
+ virtual ~WordPerfectCollector();
+ bool filter();
+
+ virtual void setDocumentMetaData(const _SH_PropertyList &propList) {};
+ virtual void startDocument();
+ virtual void endDocument();
+
+ virtual void openPageSpan(const _SH_PropertyList &propList);
+ virtual void closePageSpan();
+ virtual void openHeader(const _SH_PropertyList &propList);
+ virtual void closeHeader();
+ virtual void openFooter(const _SH_PropertyList &propList);
+ virtual void closeFooter();
+ virtual void openParagraph(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops);
+ virtual void closeParagraph();
+ virtual void openSpan(const _SH_PropertyList &propList);
+ virtual void closeSpan();
+ virtual void openSection(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns);
+ virtual void closeSection();
+ virtual void insertTab();
+ virtual void insertText(const _SH_String &text);
+ virtual void insertLineBreak();
+ virtual void defineOrderedListLevel(const _SH_PropertyList &propList);
+ virtual void defineUnorderedListLevel(const _SH_PropertyList &propList);
+ virtual void openOrderedListLevel(const _SH_PropertyList &propList);
+ virtual void openUnorderedListLevel(const _SH_PropertyList &propList);
+ virtual void closeOrderedListLevel();
+ virtual void closeUnorderedListLevel();
+ virtual void openListElement(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops);
+ virtual void closeListElement();
+ virtual void openFootnote(const _SH_PropertyList &propList);
+ virtual void closeFootnote();
+ virtual void openEndnote(const _SH_PropertyList &propList);
+ virtual void closeEndnote();
+ virtual void openTable(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns);
+ virtual void openTableRow(const _SH_PropertyList &propList);
+ virtual void closeTableRow();
+ virtual void openTableCell(const _SH_PropertyList &propList);
+ virtual void closeTableCell();
+ virtual void insertCoveredTableCell(const _SH_PropertyList &propList);
+ virtual void closeTable();
+
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+ virtual void definePageStyle(const _SH_PropertyList &propList) {}
+ virtual void defineParagraphStyle(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops) {}
+ virtual void defineCharacterStyle(const _SH_PropertyList &propList) {}
+ virtual void defineSectionStyle(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns) {}
+ virtual void insertSpace() {}
+ virtual void insertField(const _SH_String &type, const _SH_PropertyList &propList) {}
+ virtual void openComment(const _SH_PropertyList &propList) {}
+ virtual void closeComment() {}
+ virtual void openTextBox(const _SH_PropertyList &propList) {}
+ virtual void closeTextBox() {}
+ virtual void openFrame(const _SH_PropertyList &propList) {}
+ virtual void closeFrame() {}
+ virtual void insertBinaryObject(const _SH_PropertyList &propList, const _SH_BinaryData &data) {}
+ virtual void insertEquation(const _SH_PropertyList &propList, const _SH_String &data) {}
+#endif
+
+#if defined(HAVE_LIBWPD_0100)
+ virtual void startDocument(const _SH_PropertyList &propList) {}
+ virtual void defineEmbeddedFont(const _SH_PropertyList &propList) {}
+ virtual void defineParagraphStyle(const _SH_PropertyList &propList) {}
+ virtual void openParagraph(const _SH_PropertyList &propList) {}
+ virtual void openLink(const _SH_PropertyList &propList) {}
+ virtual void closeLink() {}
+ virtual void defineSectionStyle(const _SH_PropertyList &propList) {}
+ virtual void openSection(const _SH_PropertyList &propList) {}
+ virtual void insertField(const _SH_PropertyList &propList) {}
+ virtual void openListElement(const _SH_PropertyList &propList) {}
+ virtual void openTable(const _SH_PropertyList &propList) {}
+ virtual void insertBinaryObject(const _SH_PropertyList &propList) {}
+ virtual void insertEquation(const _SH_PropertyList &propList) {}
+ virtual void openGroup(const _SH_PropertyList &propList) {}
+ virtual void closeGroup() {}
+ virtual void defineGraphicStyle(const _SH_PropertyList &propList) {}
+ virtual void drawRectangle(const _SH_PropertyList &propList) {}
+ virtual void drawEllipse(const _SH_PropertyList &propList) {}
+ virtual void drawPolygon(const _SH_PropertyList &propList) {}
+ virtual void drawPolyline(const _SH_PropertyList &propList) {}
+ virtual void drawPath(const _SH_PropertyList &propList) {}
+ virtual void drawConnector(const _SH_PropertyList &propList) {}
+#endif
+
+protected:
+ void _resetDocumentState();
+ bool _parseSourceDocument(_SH_InputStream &input);
+ bool _writeTargetDocument(DocumentHandler &xHandler);
+ void _writeBegin();
+ void _writeDefaultStyles(DocumentHandler &xHandler);
+ void _writeMasterPages(DocumentHandler &xHandler);
+ void _writePageMasters(DocumentHandler &xHandler);
+ void _allocateFontName(const _SH_String &);
+
+private:
+ void _openListLevel(TagOpenElement *pListLevelOpenElement);
+ void _closeListLevel(const char *szListType);
+
+ _SH_InputStream *mpInput;
+ DocumentHandler *mpHandler;
+ bool mbUsed; // whether or not it has been before (you can only use me once!)
+
+ WriterDocumentState mWriterDocumentState;
+
+ // paragraph styles
+ std::map<_SH_String, ParagraphStyle *, ltstr> mTextStyleHash;
+
+ // span styles
+ std::map<_SH_String, SpanStyle *, ltstr> mSpanStyleHash;
+
+ // font styles
+ std::map<_SH_String, FontStyle *, ltstr> mFontHash;
+
+ // section styles
+ std::vector<SectionStyle *> mSectionStyles;
+ float mfSectionSpaceAfter;
+
+ // table styles
+ std::vector<TableStyle *> mTableStyles;
+
+ // list styles
+ unsigned int miNumListStyles;
+
+ // style elements
+ std::vector<DocumentElement *> mStylesElements;
+ // content elements
+ std::vector<DocumentElement *> mBodyElements;
+ // the current set of elements that we're writing to
+ std::vector<DocumentElement *> * mpCurrentContentElements;
+
+ // page state
+ std::vector<PageSpan *> mPageSpans;
+ PageSpan *mpCurrentPageSpan;
+ int miNumPageStyles;
+
+ // list styles / state
+ ListStyle *mpCurrentListStyle;
+ unsigned int miCurrentListLevel;
+ unsigned int miLastListLevel;
+ unsigned int miLastListNumber;
+ std::vector<ListStyle *> mListStyles;
+ bool mbListContinueNumbering;
+ bool mbListElementOpened;
+ bool mbListElementParagraphOpened;
+
+ // table state
+ TableStyle *mpCurrentTableStyle;
+};
+#endif
diff --git a/filters/kword/wordperfect/import/WordPerfectCollector.hxx b/filters/kword/wordperfect/import/WordPerfectCollector.hxx
deleted file mode 100644
index 7c5e8286b..000000000
--- a/filters/kword/wordperfect/import/WordPerfectCollector.hxx
+++ /dev/null
@@ -1,231 +0,0 @@
-/* WordPerfectCollector: Collects sections and runs of text from a
- * wordperfect file (and styles to go along with them) and writes them
- * to a target file
- *
- * Copyright (C) 2002-2004 William Lachance (william.lachance@sympatico.ca)
- * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com)
- * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * For further information visit http://libwpd.sourceforge.net
- *
- */
-
-/* "This product is not manufactured, approved, or supported by
- * Corel Corporation or Corel Corporation Limited."
- */
-
-#ifndef _WORDPERFECTCOLLECTOR_H
-#define _WORDPERFECTCOLLECTOR_H
-
-#include "SectionStyle.hxx"
-
-#include <config.h>
-#include <libwpd/libwpd.h>
-#include "shared_headers.h"
-#include <vector>
-#include <map>
-#include <stack>
-
-class DocumentElement;
-class DocumentHandler;
-class TagOpenElement;
-class FontStyle;
-class ListStyle;
-
-class ParagraphStyle;
-class SpanStyle;
-class TableStyle;
-class PageSpan;
-
-// the state we use for writing the final document
-typedef struct _WriterDocumentState WriterDocumentState;
-struct _WriterDocumentState
-{
- _WriterDocumentState();
-
- bool mbFirstElement;
- bool mbInFakeSection;
- bool mbListElementOpenedAtCurrentLevel;
- bool mbTableCellOpened;
- bool mbHeaderRow;
- bool mbInNote;
-};
-
-enum WriterListType { unordered, ordered };
-
-struct ltstr
-{
- bool operator()(const _SH_String & s1, const _SH_String & s2) const
- {
- return strcmp(s1.cstr(), s2.cstr()) < 0;
- }
-};
-
-class WordPerfectCollector : public _SH_DocumentInterface
-{
-public:
- WordPerfectCollector(_SH_InputStream *pInput, DocumentHandler *pHandler);
- virtual ~WordPerfectCollector();
- bool filter();
-
- virtual void setDocumentMetaData(const _SH_PropertyList &propList) {};
- virtual void startDocument();
- virtual void endDocument();
-
- virtual void openPageSpan(const _SH_PropertyList &propList);
- virtual void closePageSpan();
- virtual void openHeader(const _SH_PropertyList &propList);
- virtual void closeHeader();
- virtual void openFooter(const _SH_PropertyList &propList);
- virtual void closeFooter();
- virtual void openParagraph(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops);
- virtual void closeParagraph();
- virtual void openSpan(const _SH_PropertyList &propList);
- virtual void closeSpan();
- virtual void openSection(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns);
- virtual void closeSection();
- virtual void insertTab();
- virtual void insertText(const _SH_String &text);
- virtual void insertLineBreak();
- virtual void defineOrderedListLevel(const _SH_PropertyList &propList);
- virtual void defineUnorderedListLevel(const _SH_PropertyList &propList);
- virtual void openOrderedListLevel(const _SH_PropertyList &propList);
- virtual void openUnorderedListLevel(const _SH_PropertyList &propList);
- virtual void closeOrderedListLevel();
- virtual void closeUnorderedListLevel();
- virtual void openListElement(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops);
- virtual void closeListElement();
- virtual void openFootnote(const _SH_PropertyList &propList);
- virtual void closeFootnote();
- virtual void openEndnote(const _SH_PropertyList &propList);
- virtual void closeEndnote();
- virtual void openTable(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns);
- virtual void openTableRow(const _SH_PropertyList &propList);
- virtual void closeTableRow();
- virtual void openTableCell(const _SH_PropertyList &propList);
- virtual void closeTableCell();
- virtual void insertCoveredTableCell(const _SH_PropertyList &propList);
- virtual void closeTable();
-
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
- virtual void definePageStyle(const _SH_PropertyList &propList) {}
- virtual void defineParagraphStyle(const _SH_PropertyList &propList, const _SH_PropertyListVector &tabStops) {}
- virtual void defineCharacterStyle(const _SH_PropertyList &propList) {}
- virtual void defineSectionStyle(const _SH_PropertyList &propList, const _SH_PropertyListVector &columns) {}
- virtual void insertSpace() {}
- virtual void insertField(const _SH_String &type, const _SH_PropertyList &propList) {}
- virtual void openComment(const _SH_PropertyList &propList) {}
- virtual void closeComment() {}
- virtual void openTextBox(const _SH_PropertyList &propList) {}
- virtual void closeTextBox() {}
- virtual void openFrame(const _SH_PropertyList &propList) {}
- virtual void closeFrame() {}
- virtual void insertBinaryObject(const _SH_PropertyList &propList, const _SH_BinaryData &data) {}
- virtual void insertEquation(const _SH_PropertyList &propList, const _SH_String &data) {}
-#endif
-
-#if defined(HAVE_LIBWPD_0100)
- virtual void startDocument(const _SH_PropertyList &propList) {}
- virtual void defineEmbeddedFont(const _SH_PropertyList &propList) {}
- virtual void defineParagraphStyle(const _SH_PropertyList &propList) {}
- virtual void openParagraph(const _SH_PropertyList &propList) {}
- virtual void openLink(const _SH_PropertyList &propList) {}
- virtual void closeLink() {}
- virtual void defineSectionStyle(const _SH_PropertyList &propList) {}
- virtual void openSection(const _SH_PropertyList &propList) {}
- virtual void insertField(const _SH_PropertyList &propList) {}
- virtual void openListElement(const _SH_PropertyList &propList) {}
- virtual void openTable(const _SH_PropertyList &propList) {}
- virtual void insertBinaryObject(const _SH_PropertyList &propList) {}
- virtual void insertEquation(const _SH_PropertyList &propList) {}
- virtual void openGroup(const _SH_PropertyList &propList) {}
- virtual void closeGroup() {}
- virtual void defineGraphicStyle(const _SH_PropertyList &propList) {}
- virtual void drawRectangle(const _SH_PropertyList &propList) {}
- virtual void drawEllipse(const _SH_PropertyList &propList) {}
- virtual void drawPolygon(const _SH_PropertyList &propList) {}
- virtual void drawPolyline(const _SH_PropertyList &propList) {}
- virtual void drawPath(const _SH_PropertyList &propList) {}
- virtual void drawConnector(const _SH_PropertyList &propList) {}
-#endif
-
-protected:
- void _resetDocumentState();
- bool _parseSourceDocument(_SH_InputStream &input);
- bool _writeTargetDocument(DocumentHandler &xHandler);
- void _writeBegin();
- void _writeDefaultStyles(DocumentHandler &xHandler);
- void _writeMasterPages(DocumentHandler &xHandler);
- void _writePageMasters(DocumentHandler &xHandler);
- void _allocateFontName(const _SH_String &);
-
-private:
- void _openListLevel(TagOpenElement *pListLevelOpenElement);
- void _closeListLevel(const char *szListType);
-
- _SH_InputStream *mpInput;
- DocumentHandler *mpHandler;
- bool mbUsed; // whether or not it has been before (you can only use me once!)
-
- WriterDocumentState mWriterDocumentState;
-
- // paragraph styles
- std::map<_SH_String, ParagraphStyle *, ltstr> mTextStyleHash;
-
- // span styles
- std::map<_SH_String, SpanStyle *, ltstr> mSpanStyleHash;
-
- // font styles
- std::map<_SH_String, FontStyle *, ltstr> mFontHash;
-
- // section styles
- std::vector<SectionStyle *> mSectionStyles;
- float mfSectionSpaceAfter;
-
- // table styles
- std::vector<TableStyle *> mTableStyles;
-
- // list styles
- unsigned int miNumListStyles;
-
- // style elements
- std::vector<DocumentElement *> mStylesElements;
- // content elements
- std::vector<DocumentElement *> mBodyElements;
- // the current set of elements that we're writing to
- std::vector<DocumentElement *> * mpCurrentContentElements;
-
- // page state
- std::vector<PageSpan *> mPageSpans;
- PageSpan *mpCurrentPageSpan;
- int miNumPageStyles;
-
- // list styles / state
- ListStyle *mpCurrentListStyle;
- unsigned int miCurrentListLevel;
- unsigned int miLastListLevel;
- unsigned int miLastListNumber;
- std::vector<ListStyle *> mListStyles;
- bool mbListContinueNumbering;
- bool mbListElementOpened;
- bool mbListElementParagraphOpened;
-
- // table state
- TableStyle *mpCurrentTableStyle;
-};
-#endif
diff --git a/filters/kword/wordperfect/import/WriterProperties.hxx b/filters/kword/wordperfect/import/WriterProperties.h
index a3c643301..a3c643301 100644
--- a/filters/kword/wordperfect/import/WriterProperties.hxx
+++ b/filters/kword/wordperfect/import/WriterProperties.h
diff --git a/filters/kword/wordperfect/import/wpimport.cc b/filters/kword/wordperfect/import/wpimport.cc
deleted file mode 100644
index e8537b76c..000000000
--- a/filters/kword/wordperfect/import/wpimport.cc
+++ /dev/null
@@ -1,391 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001-2005 Ariya Hidayat <ariya@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#include <kdebug.h>
-#include <KoFilterChain.h>
-#include <kgenericfactory.h>
-
-#include <wpimport.h>
-
-#include <stdio.h> // debug
-
-typedef KGenericFactory<WPImport, KoFilter> WPImportFactory;
-K_EXPORT_COMPONENT_FACTORY( libwpimport, WPImportFactory( "kofficefilters" ) )
-
-#include <libwpd/libwpd.h>
-#include "DocumentHandler.hxx"
-#include "WordPerfectCollector.hxx"
-
-class _SH_MemoryInputStream : public _SH_InputStream
-{
-public:
- _SH_MemoryInputStream(unsigned char *data, unsigned long size);
- virtual ~_SH_MemoryInputStream();
-
- virtual bool isOLEStream() { return false; }
-#if defined(HAVE_LIBWPD_0100) || defined(HAVE_LIBWPD_090)
- virtual _SH_InputStream * getDocumentOLEStream(const char *name = NULL) { return NULL; }
- const virtual unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead);
-#else
- virtual _SH_InputStream * getDocumentOLEStream() { return NULL; }
- const virtual uint8_t *read(size_t numBytes, size_t &numBytesRead);
-#endif
-
- virtual int seek(long offset, _SH_SEEK_TYPE seekType);
- virtual long tell();
- virtual bool atEOS();
-
-#ifdef HAVE_LIBWPD_0100
- virtual bool isStructured() { return false; }
- virtual unsigned subStreamCount() { return 0U; }
- virtual const char *subStreamName(unsigned id) { return NULL; }
- virtual bool existsSubStream(const char *name) { return false; }
- virtual RVNGInputStream *getSubStreamByName(const char *name) { return NULL; }
- virtual RVNGInputStream *getSubStreamById(unsigned id) { return NULL; }
- virtual bool isEnd() { return false; }
-#endif
-
-private:
- long m_offset;
- size_t m_size;
- unsigned char *m_data;
-};
-
-_SH_MemoryInputStream::_SH_MemoryInputStream(unsigned char *data, unsigned long size) :
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
- _SH_InputStream(),
-#else
- _SH_InputStream(false),
-#endif
- m_offset(0),
- m_size(size),
- m_data(data)
-{
-}
-
-_SH_MemoryInputStream::~_SH_MemoryInputStream()
-{
- if (m_data)
- delete [] m_data;
-}
-
-#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
-const unsigned char * _SH_MemoryInputStream::read(unsigned long numBytes, unsigned long &numBytesRead)
-#else
-const uint8_t * _SH_MemoryInputStream::read(size_t numBytes, size_t &numBytesRead)
-#endif
-{
- numBytesRead = 0;
-
- if (numBytes == 0)
- return 0;
-
- int numBytesToRead;
-
- if ((m_offset+numBytes) < m_size)
- numBytesToRead = numBytes;
- else
- numBytesToRead = m_size - m_offset;
-
- numBytesRead = numBytesToRead; // about as paranoid as we can be..
-
- if (numBytesToRead == 0)
- return 0;
-
- long oldOffset = m_offset;
- m_offset += numBytesToRead;
-
- return &m_data[oldOffset];
-}
-
-int _SH_MemoryInputStream::seek(long offset, _SH_SEEK_TYPE seekType)
-{
- if (seekType == _SH_SEEK_CUR)
- m_offset += offset;
- else if (seekType == _SH_SEEK_SET)
- m_offset = offset;
-
- if (m_offset < 0)
- {
- m_offset = 0;
- return 1;
- }
- if ((long)m_offset > (long)m_size)
- {
- m_offset = m_size;
- return 1;
- }
-
- return 0;
-}
-
-long _SH_MemoryInputStream::tell()
-{
- return m_offset;
-}
-
-bool _SH_MemoryInputStream::atEOS()
-{
- if ((long)m_offset == (long)m_size)
- return true;
-
- return false;
-}
-
-class KWordHandler : public DocumentHandler
-{
-public:
- KWordHandler();
- virtual ~KWordHandler() {};
- void startDocument();
- void endDocument();
- void startElement(const char *psName, const _SH_PropertyList &xPropList);
- void endElement(const char *psName);
- void characters(const _SH_String &sCharacters);
- _SH_String documentstring;
-private:
- bool isTagOpened;
- _SH_String openedTagName;
-};
-
-KWordHandler::KWordHandler() :
- isTagOpened(false)
-{
-}
-
-void KWordHandler::startDocument()
-{
- documentstring.clear();
-}
-
-void KWordHandler::startElement(const char *psName, const _SH_PropertyList &xPropList)
-{
- if (isTagOpened)
- {
- documentstring.append( ">" );
- isTagOpened = false;
- }
- _SH_String tempString;
- tempString.sprintf("<%s", psName);
- documentstring.append( tempString );
- _SH_PropertyList::Iter i(xPropList);
- for (i.rewind(); i.next(); )
- {
- // filter out libwpd elements
- if (strlen(i.key()) > 6 && strncmp(i.key(), "libwpd", 6) != 0)
- {
- tempString.sprintf(" %s=\"%s\"", i.key(), i()->getStr().cstr());
- documentstring.append( tempString );
- }
- }
- isTagOpened = true;
- openedTagName.sprintf("%s", psName);
-}
-
-void KWordHandler::endElement(const char *psName)
-{
- if ((isTagOpened) && (openedTagName == psName))
- documentstring.append( " />" );
- else
- {
- _SH_String tempString;
- tempString.sprintf("</%s>", psName);
- documentstring.append( tempString );
- }
- isTagOpened = false;
-}
-
-void KWordHandler::characters(const _SH_String &sCharacters)
-{
- if (isTagOpened)
- {
- documentstring.append( ">" );
- isTagOpened = false;
- }
-#ifdef HAVE_LIBWPD_0100
- documentstring.append( _SH_String::escapeXML(sCharacters) );
-#else
- documentstring.append( _SH_String(sCharacters, true) );
-#endif
-}
-
-
-void KWordHandler::endDocument()
-{
- if (isTagOpened)
- {
- documentstring.append( ">" );
- isTagOpened = false;
- }
-}
-
-
-
-WPImport::WPImport( KoFilter *, const char *, const TQStringList& ): KoFilter()
-{
-}
-
-KoFilter::ConversionStatus WPImport::convert( const TQCString& from, const TQCString& to )
-{
- // check for proper conversion
- if(to!= "application/vnd.sun.xml.writer" || from != "application/wordperfect" )
- return KoFilter::NotImplemented;
-
- // open input file
- const char* infile = m_chain->inputFile().latin1();
- FILE *f = fopen( infile, "rb" );
- if( !f )
- return KoFilter::StupidError;
-
- fseek( f, 0, SEEK_END );
- long fsize = ftell( f );
- fseek( f, 0, SEEK_SET );
-
- unsigned char* buf = new unsigned char[fsize];
- fread( buf, 1, fsize, f );
- fclose( f );
-
- // instream now owns buf, no need to delete buf later
- _SH_MemoryInputStream instream = _SH_MemoryInputStream( buf, fsize );
-
-#if defined(HAVE_LIBWPD_0100)
- libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&instream);
-#elif defined(HAVE_LIBWPD_090)
- WPDConfidence confidence = WPDocument::isFileFormatSupported(&instream);
-#else
- WPDConfidence confidence = WPDocument::isFileFormatSupported(&instream, false);
-#endif
-#if defined(HAVE_LIBWPD_0100)
- if( confidence == libwpd::WPD_CONFIDENCE_NONE )
-#else
- if( confidence == WPD_CONFIDENCE_NONE )
-#endif
- {
- fprintf(stderr, "ERROR: We have no confidence that you are giving us a valid WordPerfect document.\n");
- return KoFilter::StupidError;
- }
- instream.seek(0, _SH_SEEK_SET);
-
- // open and parse the file
- KWordHandler handler;
-
- WordPerfectCollector collector(&instream, &handler);
-
- if ( !collector.filter() ) return KoFilter::StupidError;
-
- // prepare storage
- KoStoreDevice* manifest = m_chain->storageFile( "META-INF/manifest.xml", KoStore::Write );
- if ( manifest )
- {
- TQCString manifeststring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
-<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n\
-<manifest:manifest xmlns:manifest=\"http://openoffice.org/2001/manifest\">\n\
-<manifest:file-entry manifest:media-type=\"application/vnd.sun.xml.writer\" manifest:full-path=\"/\"/>\n\
-<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n\
-<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>\n\
-</manifest:manifest>\n";
- manifest->writeBlock( (const char*) manifeststring, manifeststring.length() );
- }
-
- KoStoreDevice* styles = m_chain->storageFile( "styles.xml", KoStore::Write );
- if ( styles )
- {
- TQCString stylesstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
-<!DOCTYPE office:document-styles PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\" \"office.dtd\">\
-<office:document-styles xmlns:office=\"http://openoffice.org/2000/office\" xmlns:style=\"http://openoffice.org/2000/style\"\
- xmlns:text=\"http://openoffice.org/2000/text\" xmlns:table=\"http://openoffice.org/2000/table\"\
- xmlns:draw=\"http://openoffice.org/2000/drawing\" xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"\
- xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:number=\"http://openoffice.org/2000/datastyle\"\
- xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:chart=\"http://openoffice.org/2000/chart\" xmlns:dr3d=\"http://openoffice.org/2000/dr3d\"\
- xmlns:math=\"http://www.w3.org/1998/Math/MathML\" xmlns:form=\"http://openoffice.org/2000/form\"\
- xmlns:script=\"http://openoffice.org/2000/script\" office:version=\"1.0\">\
-<office:styles>\
-<style:default-style style:family=\"paragraph\">\
-<style:properties style:use-window-font-color=\"true\" style:text-autospace=\"ideograph-alpha\"\
- style:punctuation-wrap=\"hanging\" style:line-break=\"strict\" style:writing-mode=\"page\"/>\
-</style:default-style>\
-<style:default-style style:family=\"table\"/>\
-<style:default-style style:family=\"table-row\"/>\
-<style:default-style style:family=\"table-column\"/>\
-<style:style style:name=\"Standard\" style:family=\"paragraph\" style:class=\"text\"/>\
-<style:style style:name=\"Text body\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"text\"/>\
-<style:style style:name=\"List\" style:family=\"paragraph\" style:parent-style-name=\"Text body\" style:class=\"list\"/>\
-<style:style style:name=\"Header\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
-<style:style style:name=\"Footer\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
-<style:style style:name=\"Caption\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
-<style:style style:name=\"Footnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
-<style:style style:name=\"Endnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
-<style:style style:name=\"Index\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"index\"/>\
-<style:style style:name=\"Footnote Symbol\" style:family=\"text\">\
-<style:properties style:text-position=\"super 58%\"/>\
-</style:style>\
-<style:style style:name=\"Endnote Symbol\" style:family=\"text\">\
-<style:properties style:text-position=\"super 58%\"/>\
-</style:style>\
-<style:style style:name=\"Footnote anchor\" style:family=\"text\">\
-<style:properties style:text-position=\"super 58%\"/>\
-</style:style>\
-<style:style style:name=\"Endnote anchor\" style:family=\"text\">\
-<style:properties style:text-position=\"super 58%\"/>\
-</style:style>\
-<text:footnotes-configuration text:citation-style-name=\"Footnote Symbol\" text:citation-body-style-name=\"Footnote anchor\"\
- style:num-format=\"1\" text:start-value=\"0\" text:footnotes-position=\"page\" text:start-numbering-at=\"document\"/>\
-<text:endnotes-configuration text:citation-style-name=\"Endnote Symbol\" text:citation-body-style-name=\"Endnote anchor\"\
- text:master-page-name=\"Endnote\" style:num-format=\"i\" text:start-value=\"0\"/>\
-<text:linenumbering-configuration text:number-lines=\"false\" text:offset=\"0.1965inch\" style:num-format=\"1\"\
- text:number-position=\"left\" text:increment=\"5\"/>\
-</office:styles>\
-<office:automatic-styles>\
-<style:page-master style:name=\"PM0\">\
-<style:properties fo:margin-bottom=\"1.0000inch\" fo:margin-left=\"1.0000inch\" fo:margin-right=\"1.0000inch\" fo:margin-top=\"1.0000inch\"\
- fo:page-height=\"11.0000inch\" fo:page-width=\"8.5000inch\" style:print-orientation=\"portrait\">\
-<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:distance-after-sep=\"0.0398inch\"\
- style:distance-before-sep=\"0.0398inch\" style:rel-width=\"25%\" style:width=\"0.0071inch\"/>\
-</style:properties>\
-</style:page-master>\
-<style:page-master style:name=\"PM1\">\
-<style:properties fo:margin-bottom=\"1.0000inch\" fo:margin-left=\"1.0000inch\" fo:margin-right=\"1.0000inch\" fo:margin-top=\"1.0000inch\"\
- fo:page-height=\"11.0000inch\" fo:page-width=\"8.5000inch\" style:print-orientation=\"portrait\">\
-<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:rel-width=\"25%\"/>\
-</style:properties>\
-</style:page-master>\
-</office:automatic-styles>\
-<office:master-styles>\
-<style:master-page style:name=\"Standard\" style:page-master-name=\"PM0\"/>\
-<style:master-page style:name=\"Endnote\" style:page-master-name=\"PM1\"/>\
-</office:master-styles>\
-</office:document-styles>";
- styles->writeBlock( (const char*) stylesstring, stylesstring.length() );
- }
-
- KoStoreDevice* out = m_chain->storageFile( "content.xml", KoStore::Write );
-
- if( out )
- out->writeBlock( (const char*) handler.documentstring.cstr(), strlen(handler.documentstring.cstr()) );
-
- return KoFilter::OK;
-}
-
-#include "wpimport.moc"
diff --git a/filters/kword/wordperfect/import/wpimport.cpp b/filters/kword/wordperfect/import/wpimport.cpp
new file mode 100644
index 000000000..12f5446e3
--- /dev/null
+++ b/filters/kword/wordperfect/import/wpimport.cpp
@@ -0,0 +1,391 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001-2005 Ariya Hidayat <ariya@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include <kdebug.h>
+#include <KoFilterChain.h>
+#include <kgenericfactory.h>
+
+#include <wpimport.h>
+
+#include <stdio.h> // debug
+
+typedef KGenericFactory<WPImport, KoFilter> WPImportFactory;
+K_EXPORT_COMPONENT_FACTORY( libwpimport, WPImportFactory( "kofficefilters" ) )
+
+#include <libwpd/libwpd.h>
+#include "DocumentHandler.h"
+#include "WordPerfectCollector.h"
+
+class _SH_MemoryInputStream : public _SH_InputStream
+{
+public:
+ _SH_MemoryInputStream(unsigned char *data, unsigned long size);
+ virtual ~_SH_MemoryInputStream();
+
+ virtual bool isOLEStream() { return false; }
+#if defined(HAVE_LIBWPD_0100) || defined(HAVE_LIBWPD_090)
+ virtual _SH_InputStream * getDocumentOLEStream(const char *name = NULL) { return NULL; }
+ const virtual unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead);
+#else
+ virtual _SH_InputStream * getDocumentOLEStream() { return NULL; }
+ const virtual uint8_t *read(size_t numBytes, size_t &numBytesRead);
+#endif
+
+ virtual int seek(long offset, _SH_SEEK_TYPE seekType);
+ virtual long tell();
+ virtual bool atEOS();
+
+#ifdef HAVE_LIBWPD_0100
+ virtual bool isStructured() { return false; }
+ virtual unsigned subStreamCount() { return 0U; }
+ virtual const char *subStreamName(unsigned id) { return NULL; }
+ virtual bool existsSubStream(const char *name) { return false; }
+ virtual RVNGInputStream *getSubStreamByName(const char *name) { return NULL; }
+ virtual RVNGInputStream *getSubStreamById(unsigned id) { return NULL; }
+ virtual bool isEnd() { return false; }
+#endif
+
+private:
+ long m_offset;
+ size_t m_size;
+ unsigned char *m_data;
+};
+
+_SH_MemoryInputStream::_SH_MemoryInputStream(unsigned char *data, unsigned long size) :
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+ _SH_InputStream(),
+#else
+ _SH_InputStream(false),
+#endif
+ m_offset(0),
+ m_size(size),
+ m_data(data)
+{
+}
+
+_SH_MemoryInputStream::~_SH_MemoryInputStream()
+{
+ if (m_data)
+ delete [] m_data;
+}
+
+#if defined(HAVE_LIBWPD_090) || defined(HAVE_LIBWPD_0100)
+const unsigned char * _SH_MemoryInputStream::read(unsigned long numBytes, unsigned long &numBytesRead)
+#else
+const uint8_t * _SH_MemoryInputStream::read(size_t numBytes, size_t &numBytesRead)
+#endif
+{
+ numBytesRead = 0;
+
+ if (numBytes == 0)
+ return 0;
+
+ int numBytesToRead;
+
+ if ((m_offset+numBytes) < m_size)
+ numBytesToRead = numBytes;
+ else
+ numBytesToRead = m_size - m_offset;
+
+ numBytesRead = numBytesToRead; // about as paranoid as we can be..
+
+ if (numBytesToRead == 0)
+ return 0;
+
+ long oldOffset = m_offset;
+ m_offset += numBytesToRead;
+
+ return &m_data[oldOffset];
+}
+
+int _SH_MemoryInputStream::seek(long offset, _SH_SEEK_TYPE seekType)
+{
+ if (seekType == _SH_SEEK_CUR)
+ m_offset += offset;
+ else if (seekType == _SH_SEEK_SET)
+ m_offset = offset;
+
+ if (m_offset < 0)
+ {
+ m_offset = 0;
+ return 1;
+ }
+ if ((long)m_offset > (long)m_size)
+ {
+ m_offset = m_size;
+ return 1;
+ }
+
+ return 0;
+}
+
+long _SH_MemoryInputStream::tell()
+{
+ return m_offset;
+}
+
+bool _SH_MemoryInputStream::atEOS()
+{
+ if ((long)m_offset == (long)m_size)
+ return true;
+
+ return false;
+}
+
+class KWordHandler : public DocumentHandler
+{
+public:
+ KWordHandler();
+ virtual ~KWordHandler() {};
+ void startDocument();
+ void endDocument();
+ void startElement(const char *psName, const _SH_PropertyList &xPropList);
+ void endElement(const char *psName);
+ void characters(const _SH_String &sCharacters);
+ _SH_String documentstring;
+private:
+ bool isTagOpened;
+ _SH_String openedTagName;
+};
+
+KWordHandler::KWordHandler() :
+ isTagOpened(false)
+{
+}
+
+void KWordHandler::startDocument()
+{
+ documentstring.clear();
+}
+
+void KWordHandler::startElement(const char *psName, const _SH_PropertyList &xPropList)
+{
+ if (isTagOpened)
+ {
+ documentstring.append( ">" );
+ isTagOpened = false;
+ }
+ _SH_String tempString;
+ tempString.sprintf("<%s", psName);
+ documentstring.append( tempString );
+ _SH_PropertyList::Iter i(xPropList);
+ for (i.rewind(); i.next(); )
+ {
+ // filter out libwpd elements
+ if (strlen(i.key()) > 6 && strncmp(i.key(), "libwpd", 6) != 0)
+ {
+ tempString.sprintf(" %s=\"%s\"", i.key(), i()->getStr().cstr());
+ documentstring.append( tempString );
+ }
+ }
+ isTagOpened = true;
+ openedTagName.sprintf("%s", psName);
+}
+
+void KWordHandler::endElement(const char *psName)
+{
+ if ((isTagOpened) && (openedTagName == psName))
+ documentstring.append( " />" );
+ else
+ {
+ _SH_String tempString;
+ tempString.sprintf("</%s>", psName);
+ documentstring.append( tempString );
+ }
+ isTagOpened = false;
+}
+
+void KWordHandler::characters(const _SH_String &sCharacters)
+{
+ if (isTagOpened)
+ {
+ documentstring.append( ">" );
+ isTagOpened = false;
+ }
+#ifdef HAVE_LIBWPD_0100
+ documentstring.append( _SH_String::escapeXML(sCharacters) );
+#else
+ documentstring.append( _SH_String(sCharacters, true) );
+#endif
+}
+
+
+void KWordHandler::endDocument()
+{
+ if (isTagOpened)
+ {
+ documentstring.append( ">" );
+ isTagOpened = false;
+ }
+}
+
+
+
+WPImport::WPImport( KoFilter *, const char *, const TQStringList& ): KoFilter()
+{
+}
+
+KoFilter::ConversionStatus WPImport::convert( const TQCString& from, const TQCString& to )
+{
+ // check for proper conversion
+ if(to!= "application/vnd.sun.xml.writer" || from != "application/wordperfect" )
+ return KoFilter::NotImplemented;
+
+ // open input file
+ const char* infile = m_chain->inputFile().latin1();
+ FILE *f = fopen( infile, "rb" );
+ if( !f )
+ return KoFilter::StupidError;
+
+ fseek( f, 0, SEEK_END );
+ long fsize = ftell( f );
+ fseek( f, 0, SEEK_SET );
+
+ unsigned char* buf = new unsigned char[fsize];
+ fread( buf, 1, fsize, f );
+ fclose( f );
+
+ // instream now owns buf, no need to delete buf later
+ _SH_MemoryInputStream instream = _SH_MemoryInputStream( buf, fsize );
+
+#if defined(HAVE_LIBWPD_0100)
+ libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&instream);
+#elif defined(HAVE_LIBWPD_090)
+ WPDConfidence confidence = WPDocument::isFileFormatSupported(&instream);
+#else
+ WPDConfidence confidence = WPDocument::isFileFormatSupported(&instream, false);
+#endif
+#if defined(HAVE_LIBWPD_0100)
+ if( confidence == libwpd::WPD_CONFIDENCE_NONE )
+#else
+ if( confidence == WPD_CONFIDENCE_NONE )
+#endif
+ {
+ fprintf(stderr, "ERROR: We have no confidence that you are giving us a valid WordPerfect document.\n");
+ return KoFilter::StupidError;
+ }
+ instream.seek(0, _SH_SEEK_SET);
+
+ // open and parse the file
+ KWordHandler handler;
+
+ WordPerfectCollector collector(&instream, &handler);
+
+ if ( !collector.filter() ) return KoFilter::StupidError;
+
+ // prepare storage
+ KoStoreDevice* manifest = m_chain->storageFile( "META-INF/manifest.xml", KoStore::Write );
+ if ( manifest )
+ {
+ TQCString manifeststring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
+<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n\
+<manifest:manifest xmlns:manifest=\"http://openoffice.org/2001/manifest\">\n\
+<manifest:file-entry manifest:media-type=\"application/vnd.sun.xml.writer\" manifest:full-path=\"/\"/>\n\
+<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n\
+<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>\n\
+</manifest:manifest>\n";
+ manifest->writeBlock( (const char*) manifeststring, manifeststring.length() );
+ }
+
+ KoStoreDevice* styles = m_chain->storageFile( "styles.xml", KoStore::Write );
+ if ( styles )
+ {
+ TQCString stylesstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
+<!DOCTYPE office:document-styles PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\" \"office.dtd\">\
+<office:document-styles xmlns:office=\"http://openoffice.org/2000/office\" xmlns:style=\"http://openoffice.org/2000/style\"\
+ xmlns:text=\"http://openoffice.org/2000/text\" xmlns:table=\"http://openoffice.org/2000/table\"\
+ xmlns:draw=\"http://openoffice.org/2000/drawing\" xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"\
+ xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:number=\"http://openoffice.org/2000/datastyle\"\
+ xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:chart=\"http://openoffice.org/2000/chart\" xmlns:dr3d=\"http://openoffice.org/2000/dr3d\"\
+ xmlns:math=\"http://www.w3.org/1998/Math/MathML\" xmlns:form=\"http://openoffice.org/2000/form\"\
+ xmlns:script=\"http://openoffice.org/2000/script\" office:version=\"1.0\">\
+<office:styles>\
+<style:default-style style:family=\"paragraph\">\
+<style:properties style:use-window-font-color=\"true\" style:text-autospace=\"ideograph-alpha\"\
+ style:punctuation-wrap=\"hanging\" style:line-break=\"strict\" style:writing-mode=\"page\"/>\
+</style:default-style>\
+<style:default-style style:family=\"table\"/>\
+<style:default-style style:family=\"table-row\"/>\
+<style:default-style style:family=\"table-column\"/>\
+<style:style style:name=\"Standard\" style:family=\"paragraph\" style:class=\"text\"/>\
+<style:style style:name=\"Text body\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"text\"/>\
+<style:style style:name=\"List\" style:family=\"paragraph\" style:parent-style-name=\"Text body\" style:class=\"list\"/>\
+<style:style style:name=\"Header\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
+<style:style style:name=\"Footer\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
+<style:style style:name=\"Caption\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
+<style:style style:name=\"Footnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
+<style:style style:name=\"Endnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>\
+<style:style style:name=\"Index\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"index\"/>\
+<style:style style:name=\"Footnote Symbol\" style:family=\"text\">\
+<style:properties style:text-position=\"super 58%\"/>\
+</style:style>\
+<style:style style:name=\"Endnote Symbol\" style:family=\"text\">\
+<style:properties style:text-position=\"super 58%\"/>\
+</style:style>\
+<style:style style:name=\"Footnote anchor\" style:family=\"text\">\
+<style:properties style:text-position=\"super 58%\"/>\
+</style:style>\
+<style:style style:name=\"Endnote anchor\" style:family=\"text\">\
+<style:properties style:text-position=\"super 58%\"/>\
+</style:style>\
+<text:footnotes-configuration text:citation-style-name=\"Footnote Symbol\" text:citation-body-style-name=\"Footnote anchor\"\
+ style:num-format=\"1\" text:start-value=\"0\" text:footnotes-position=\"page\" text:start-numbering-at=\"document\"/>\
+<text:endnotes-configuration text:citation-style-name=\"Endnote Symbol\" text:citation-body-style-name=\"Endnote anchor\"\
+ text:master-page-name=\"Endnote\" style:num-format=\"i\" text:start-value=\"0\"/>\
+<text:linenumbering-configuration text:number-lines=\"false\" text:offset=\"0.1965inch\" style:num-format=\"1\"\
+ text:number-position=\"left\" text:increment=\"5\"/>\
+</office:styles>\
+<office:automatic-styles>\
+<style:page-master style:name=\"PM0\">\
+<style:properties fo:margin-bottom=\"1.0000inch\" fo:margin-left=\"1.0000inch\" fo:margin-right=\"1.0000inch\" fo:margin-top=\"1.0000inch\"\
+ fo:page-height=\"11.0000inch\" fo:page-width=\"8.5000inch\" style:print-orientation=\"portrait\">\
+<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:distance-after-sep=\"0.0398inch\"\
+ style:distance-before-sep=\"0.0398inch\" style:rel-width=\"25%\" style:width=\"0.0071inch\"/>\
+</style:properties>\
+</style:page-master>\
+<style:page-master style:name=\"PM1\">\
+<style:properties fo:margin-bottom=\"1.0000inch\" fo:margin-left=\"1.0000inch\" fo:margin-right=\"1.0000inch\" fo:margin-top=\"1.0000inch\"\
+ fo:page-height=\"11.0000inch\" fo:page-width=\"8.5000inch\" style:print-orientation=\"portrait\">\
+<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:rel-width=\"25%\"/>\
+</style:properties>\
+</style:page-master>\
+</office:automatic-styles>\
+<office:master-styles>\
+<style:master-page style:name=\"Standard\" style:page-master-name=\"PM0\"/>\
+<style:master-page style:name=\"Endnote\" style:page-master-name=\"PM1\"/>\
+</office:master-styles>\
+</office:document-styles>";
+ styles->writeBlock( (const char*) stylesstring, stylesstring.length() );
+ }
+
+ KoStoreDevice* out = m_chain->storageFile( "content.xml", KoStore::Write );
+
+ if( out )
+ out->writeBlock( (const char*) handler.documentstring.cstr(), strlen(handler.documentstring.cstr()) );
+
+ return KoFilter::OK;
+}
+
+#include "wpimport.moc"
diff --git a/filters/liboofilter/Makefile.am b/filters/liboofilter/Makefile.am
index 22e60f13d..9a758eadb 100644
--- a/filters/liboofilter/Makefile.am
+++ b/filters/liboofilter/Makefile.am
@@ -1,5 +1,5 @@
INCLUDES = $(KOFFICE_INCLUDES) $(all_includes)
noinst_LTLIBRARIES = liboofilter.la
-liboofilter_la_SOURCES = ooutils.cc liststylestack.cc
+liboofilter_la_SOURCES = ooutils.cpp liststylestack.cpp
diff --git a/filters/liboofilter/liststylestack.cc b/filters/liboofilter/liststylestack.cpp
index b5eff1337..b5eff1337 100644
--- a/filters/liboofilter/liststylestack.cc
+++ b/filters/liboofilter/liststylestack.cpp
diff --git a/filters/liboofilter/ooutils.cc b/filters/liboofilter/ooutils.cpp
index a04633fe3..a04633fe3 100644
--- a/filters/liboofilter/ooutils.cc
+++ b/filters/liboofilter/ooutils.cpp
diff --git a/filters/olefilters/Makefile.am b/filters/olefilters/Makefile.am
index e7bd753ac..f6aadf4d6 100644
--- a/filters/olefilters/Makefile.am
+++ b/filters/olefilters/Makefile.am
@@ -14,7 +14,7 @@ SUBDIRS = lib powerpoint97
kde_module_LTLIBRARIES = libolefilter.la
-libolefilter_la_SOURCES = olefilter.cc
+libolefilter_la_SOURCES = olefilter.cpp
noinst_HEADERS = olefilter.h
diff --git a/filters/olefilters/lib/Makefile.am b/filters/olefilters/lib/Makefile.am
index 9e902fd25..0edcbd2f2 100644
--- a/filters/olefilters/lib/Makefile.am
+++ b/filters/olefilters/lib/Makefile.am
@@ -6,11 +6,11 @@ INCLUDES = -I$(srcdir) $(KOFFICE_INCLUDES) $(all_includes)
noinst_LTLIBRARIES = libfilterbase.la libklaola.la
-libfilterbase_la_SOURCES = filterbase.cc
+libfilterbase_la_SOURCES = filterbase.cpp
libfilterbase_la_METASOURCES = filterbase.moc
libfilterbase_la_LDFLAGS = $(all_libraries)
-libklaola_la_SOURCES = klaola.cc
+libklaola_la_SOURCES = klaola.cpp
libklaola_la_LDFLAGS = $(all_libraries)
noinst_HEADERS = filterbase.h klaola.h
diff --git a/filters/olefilters/lib/filterbase.cc b/filters/olefilters/lib/filterbase.cpp
index dbb7edd06..dbb7edd06 100644
--- a/filters/olefilters/lib/filterbase.cc
+++ b/filters/olefilters/lib/filterbase.cpp
diff --git a/filters/olefilters/lib/klaola.cc b/filters/olefilters/lib/klaola.cpp
index 28af157c8..28af157c8 100644
--- a/filters/olefilters/lib/klaola.cc
+++ b/filters/olefilters/lib/klaola.cpp
diff --git a/filters/olefilters/olefilter.cc b/filters/olefilters/olefilter.cpp
index ae0395a94..ae0395a94 100644
--- a/filters/olefilters/olefilter.cc
+++ b/filters/olefilters/olefilter.cpp
diff --git a/filters/olefilters/powerpoint97/Makefile.am b/filters/olefilters/powerpoint97/Makefile.am
index d0c3fc2ba..873a81e5f 100644
--- a/filters/olefilters/powerpoint97/Makefile.am
+++ b/filters/olefilters/powerpoint97/Makefile.am
@@ -6,7 +6,7 @@ INCLUDES= -I$(srcdir) -I$(srcdir)/../lib $(KOFFICE_INCLUDES) $(all_includes)
noinst_LTLIBRARIES = libpowerpoint97.la
-libpowerpoint97_la_SOURCES = powerpointfilter.cc powerpoint.cc pptdoc.cc pptxml.cc pptSlide.cpp
+libpowerpoint97_la_SOURCES = powerpointfilter.cpp powerpoint.cpp pptdoc.cpp pptxml.cpp pptSlide.cpp
libpowerpoint97_la_LDFLAGS = $(all_libraries)
noinst_HEADERS = powerpointfilter.h powerpoint.h pptdoc.h pptxml.h pptSlide.h
diff --git a/filters/olefilters/powerpoint97/powerpoint.cc b/filters/olefilters/powerpoint97/powerpoint.cpp
index 3f330fa75..3f330fa75 100644
--- a/filters/olefilters/powerpoint97/powerpoint.cc
+++ b/filters/olefilters/powerpoint97/powerpoint.cpp
diff --git a/filters/olefilters/powerpoint97/powerpointfilter.cc b/filters/olefilters/powerpoint97/powerpointfilter.cpp
index 5359dd985..5359dd985 100644
--- a/filters/olefilters/powerpoint97/powerpointfilter.cc
+++ b/filters/olefilters/powerpoint97/powerpointfilter.cpp
diff --git a/filters/olefilters/powerpoint97/pptdoc.cc b/filters/olefilters/powerpoint97/pptdoc.cpp
index 9aa10ee4f..9aa10ee4f 100644
--- a/filters/olefilters/powerpoint97/pptdoc.cc
+++ b/filters/olefilters/powerpoint97/pptdoc.cpp
diff --git a/filters/olefilters/powerpoint97/pptxml.cc b/filters/olefilters/powerpoint97/pptxml.cpp
index 42be4de5c..42be4de5c 100644
--- a/filters/olefilters/powerpoint97/pptxml.cc
+++ b/filters/olefilters/powerpoint97/pptxml.cpp
diff --git a/filters/xsltfilter/export/Makefile.am b/filters/xsltfilter/export/Makefile.am
index b62ee9c43..c1c11316e 100644
--- a/filters/xsltfilter/export/Makefile.am
+++ b/filters/xsltfilter/export/Makefile.am
@@ -8,7 +8,7 @@ CXXFLAGS += $(ICU_CXXFLAGS)
kde_module_LTLIBRARIES = libxsltexport.la
-libxsltexport_la_SOURCES = xsltexport.cc xsltexportdia.cc xsltproc.cc xsltdialog.ui
+libxsltexport_la_SOURCES = xsltexport.cpp xsltexportdia.cpp xsltproc.cpp xsltdialog.ui
libxsltexport_la_LDFLAGS = $(KDE_RPATH) $(LIBXML_RPATH) $(LIBXSLT_RPATH) $(all_libraries) -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libxsltexport_la_LIBADD = $(KOFFICE_LIBS) $(LIBXSLT_LIBS) $(LIBXML_LIBS)
@@ -16,7 +16,7 @@ noinst_HEADERS = xsltexport.h xsltexportdia.h xsltproc.h
######## Debug
#check_PROGRAMS = xsltfilter
-#xsltfilter_SOURCES = xsltfilter.cc
+#xsltfilter_SOURCES = xsltfilter.cpp
#xsltfilter_LDADD = $(LIBXSLT_LIBS) $(LIBXML_LIBS)
#xsltfilter_LDFLAGS = $(KDE_RPATH) $(LIBXML_RPATH) $(LIBXSLT_RPATH) $(all_libraries)
diff --git a/filters/xsltfilter/export/xsltexport.cc b/filters/xsltfilter/export/xsltexport.cpp
index b1d9d84e6..b1d9d84e6 100644
--- a/filters/xsltfilter/export/xsltexport.cc
+++ b/filters/xsltfilter/export/xsltexport.cpp
diff --git a/filters/xsltfilter/export/xsltexportdia.cc b/filters/xsltfilter/export/xsltexportdia.cpp
index bf141f903..bf141f903 100644
--- a/filters/xsltfilter/export/xsltexportdia.cc
+++ b/filters/xsltfilter/export/xsltexportdia.cpp
diff --git a/filters/xsltfilter/export/xsltproc.cc b/filters/xsltfilter/export/xsltproc.cpp
index 3bd20408a..3bd20408a 100644
--- a/filters/xsltfilter/export/xsltproc.cc
+++ b/filters/xsltfilter/export/xsltproc.cpp
diff --git a/filters/xsltfilter/import/Makefile.am b/filters/xsltfilter/import/Makefile.am
index 01e45a9af..4fe88b426 100644
--- a/filters/xsltfilter/import/Makefile.am
+++ b/filters/xsltfilter/import/Makefile.am
@@ -7,7 +7,7 @@ CXXFLAGS += $(ICU_CXXFLAGS)
kde_module_LTLIBRARIES = libxsltimport.la
-libxsltimport_la_SOURCES = xsltimport.cc xsltimportdia.cc xsltproc.cc xsltdialog.ui
+libxsltimport_la_SOURCES = xsltimport.cpp xsltimportdia.cpp xsltproc.cpp xsltdialog.ui
libxsltimport_la_LDFLAGS = $(KDE_RPATH) $(LIBXML_RPATH) $(LIBXSLT_RPATH) $(all_libraries) -module $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libxsltimport_la_LIBADD = $(KOFFICE_LIBS) $(LIBXSLT_LIBS) $(LIBXML_LIBS)
diff --git a/filters/xsltfilter/import/xsltimport.cc b/filters/xsltfilter/import/xsltimport.cpp
index 24dfb5477..24dfb5477 100644
--- a/filters/xsltfilter/import/xsltimport.cc
+++ b/filters/xsltfilter/import/xsltimport.cpp
diff --git a/filters/xsltfilter/import/xsltimportdia.cc b/filters/xsltfilter/import/xsltimportdia.cpp
index 9052e4ecc..9052e4ecc 100644
--- a/filters/xsltfilter/import/xsltimportdia.cc
+++ b/filters/xsltfilter/import/xsltimportdia.cpp
diff --git a/filters/xsltfilter/import/xsltproc.cc b/filters/xsltfilter/import/xsltproc.cpp
index 3bd20408a..3bd20408a 100644
--- a/filters/xsltfilter/import/xsltproc.cc
+++ b/filters/xsltfilter/import/xsltproc.cpp
diff --git a/interfaces/Makefile.am b/interfaces/Makefile.am
index e4ac9a6f1..dd523fa14 100644
--- a/interfaces/Makefile.am
+++ b/interfaces/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/kchart/kdchart -I$(interfacedir)
lib_LTLIBRARIES = libkochart.la
-libkochart_la_SOURCES = koChart.cc
+libkochart_la_SOURCES = koChart.cpp
libkochart_la_LDFLAGS = $(all_libraries) -version-info 1:0:0 -no-undefined
libkochart_la_LIBADD = $(LIB_KOFFICECORE)
METASOURCES = AUTO
diff --git a/interfaces/koChart.cc b/interfaces/koChart.cpp
index d66578ab5..d66578ab5 100644
--- a/interfaces/koChart.cc
+++ b/interfaces/koChart.cpp
diff --git a/karbon/Makefile.am b/karbon/Makefile.am
index 8faf3972a..55ab8ac5d 100644
--- a/karbon/Makefile.am
+++ b/karbon/Makefile.am
@@ -14,7 +14,7 @@ SUBDIRS = commands visitors core shapes widgets dialogs dockers render . tools p
lib_LTLIBRARIES = libkarboncommon.la
kde_module_LTLIBRARIES = libkarbonpart.la
-libkarboncommon_la_SOURCES = karbon_factory.cc karbon_resourceserver.cc karbon_part.cc karbon_part_iface.cc karbon_part_iface.skel karbon_view.cc karbon_view_iface.cc karbon_view_iface.skel karbon_drag.cpp karbon_grid_data.cpp karbon_tool_registry.cc karbon_tool_factory.cc vtoolcontroller.cc vtool.cc
+libkarboncommon_la_SOURCES = karbon_factory.cpp karbon_resourceserver.cpp karbon_part.cpp karbon_part_iface.cpp karbon_part_iface.skel karbon_view.cpp karbon_view_iface.cpp karbon_view_iface.skel karbon_drag.cpp karbon_grid_data.cpp karbon_tool_registry.cpp karbon_tool_factory.cpp vtoolcontroller.cpp vtool.cpp
libkarboncommon_la_LDFLAGS = $(KDE_RPATH) $(LIBFREETYPE_RPATH) $(LIBMAGICK_LDFLAGS) -no-undefined $(LIB_TQT)
libkarboncommon_la_LIBADD = $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) $(LIB_KOPALETTE) $(LIB_KOPAINTER) $(LIB_KOTEXT) \
@@ -32,13 +32,13 @@ libkarboncommon_la_LIBADD = $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) $(LIB_KOPALETTE)
$(LIBMAGICK_LIBS) \
$(LIBFREETYPE_LIBS)
-libkarbonpart_la_SOURCES = karbon_factory_init.cc
+libkarbonpart_la_SOURCES = karbon_factory_init.cpp
libkarbonpart_la_LDFLAGS = $(KDE_PLUGIN) $(LIBFREETYPE_RPATH) $(LIB_TQT)
libkarbonpart_la_LIBADD = libkarboncommon.la
bin_PROGRAMS =
tdeinit_LTLIBRARIES = karbon.la
-karbon_la_SOURCES = main.cc
+karbon_la_SOURCES = main.cpp
karbon_la_LDFLAGS = $(all_libraries) -module -avoid-version $(LIB_TQT)
karbon_la_LIBADD = libkarboncommon.la $(LIB_TQT) $(LIB_KOFFICECORE)
@@ -55,7 +55,7 @@ METASOURCES = AUTO
messages: rc.cpp
$(EXTRACTRC) data/*.rc >> rc.cpp
- $(XGETTEXT) rc.cpp *.cpp *.cc */*.cc tools/*.h plugins/*/*.cc -o $(podir)/karbon.pot
+ $(XGETTEXT) rc.cpp *.cpp *.cpp */*.cpp tools/*.h plugins/*/*.cpp -o $(podir)/karbon.pot
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/karbon/TODO b/karbon/TODO
index c09f9a595..d63ee979b 100644
--- a/karbon/TODO
+++ b/karbon/TODO
@@ -90,7 +90,7 @@ MAKE IT NICE:
- can't we pass VTool::draw() a painter inseatd of each tool creating a painter itself?
- remove V*Tool::refreshUnit(). call this directly via dialog() instead
- pass all dialogs a parent
-- think about using ghostscript's flatten algo (see comments in vflatten.cc)
+- think about using ghostscript's flatten algo (see comments in vflatten.cpp)
- why represent opacity as float, not as short?
- introduce our own "Color drag" class, since we have in addition to rgb also opacity,
and maybe also gradient info could be dragged later.
diff --git a/karbon/commands/Makefile.am b/karbon/commands/Makefile.am
index fb5ac24a9..bebbfd1e6 100644
--- a/karbon/commands/Makefile.am
+++ b/karbon/commands/Makefile.am
@@ -29,26 +29,26 @@ noinst_HEADERS = \
vzordercmd.h
libkarboncommands_la_SOURCES = \
- valigncmd.cc \
- vbooleancmd.cc \
- vcleanupcmd.cc \
- vclipartcmd.cc \
- vclosepathcmd.cc \
- vcommand.cc \
- vdeletecmd.cc \
- vdistributecmd.cc \
- vfillcmd.cc \
- vflattencmd.cc \
- vgroupcmd.cc \
- vdeletenodescmd.cc \
- vlayercmd.cc \
- vreplacingcmd.cc \
- vshapecmd.cc \
- vstrokecmd.cc \
- vtransformcmd.cc \
- vinsertcmd.cc \
- vungroupcmd.cc \
- vzordercmd.cc
+ valigncmd.cpp \
+ vbooleancmd.cpp \
+ vcleanupcmd.cpp \
+ vclipartcmd.cpp \
+ vclosepathcmd.cpp \
+ vcommand.cpp \
+ vdeletecmd.cpp \
+ vdistributecmd.cpp \
+ vfillcmd.cpp \
+ vflattencmd.cpp \
+ vgroupcmd.cpp \
+ vdeletenodescmd.cpp \
+ vlayercmd.cpp \
+ vreplacingcmd.cpp \
+ vshapecmd.cpp \
+ vstrokecmd.cpp \
+ vtransformcmd.cpp \
+ vinsertcmd.cpp \
+ vungroupcmd.cpp \
+ vzordercmd.cpp
libkarboncommands_la_METASOURCES = \
AUTO
diff --git a/karbon/commands/valigncmd.cc b/karbon/commands/valigncmd.cpp
index d79c8485c..d79c8485c 100644
--- a/karbon/commands/valigncmd.cc
+++ b/karbon/commands/valigncmd.cpp
diff --git a/karbon/commands/vbooleancmd.cc b/karbon/commands/vbooleancmd.cpp
index dbfccffeb..dbfccffeb 100644
--- a/karbon/commands/vbooleancmd.cc
+++ b/karbon/commands/vbooleancmd.cpp
diff --git a/karbon/commands/vcleanupcmd.cc b/karbon/commands/vcleanupcmd.cpp
index 2c9d49627..2c9d49627 100644
--- a/karbon/commands/vcleanupcmd.cc
+++ b/karbon/commands/vcleanupcmd.cpp
diff --git a/karbon/commands/vclipartcmd.cc b/karbon/commands/vclipartcmd.cpp
index a9465e4e0..a9465e4e0 100644
--- a/karbon/commands/vclipartcmd.cc
+++ b/karbon/commands/vclipartcmd.cpp
diff --git a/karbon/commands/vclosepathcmd.cc b/karbon/commands/vclosepathcmd.cpp
index 652ed2df0..652ed2df0 100644
--- a/karbon/commands/vclosepathcmd.cc
+++ b/karbon/commands/vclosepathcmd.cpp
diff --git a/karbon/commands/vcommand.cc b/karbon/commands/vcommand.cpp
index fe5e9adaf..fe5e9adaf 100644
--- a/karbon/commands/vcommand.cc
+++ b/karbon/commands/vcommand.cpp
diff --git a/karbon/commands/vdeletecmd.cc b/karbon/commands/vdeletecmd.cpp
index 2cd6a711b..2cd6a711b 100644
--- a/karbon/commands/vdeletecmd.cc
+++ b/karbon/commands/vdeletecmd.cpp
diff --git a/karbon/commands/vdeletenodescmd.cc b/karbon/commands/vdeletenodescmd.cpp
index e83c160a1..e83c160a1 100644
--- a/karbon/commands/vdeletenodescmd.cc
+++ b/karbon/commands/vdeletenodescmd.cpp
diff --git a/karbon/commands/vdistributecmd.cc b/karbon/commands/vdistributecmd.cpp
index 7a23072f8..7a23072f8 100644
--- a/karbon/commands/vdistributecmd.cc
+++ b/karbon/commands/vdistributecmd.cpp
diff --git a/karbon/commands/vfillcmd.cc b/karbon/commands/vfillcmd.cpp
index 75d5284cc..75d5284cc 100644
--- a/karbon/commands/vfillcmd.cc
+++ b/karbon/commands/vfillcmd.cpp
diff --git a/karbon/commands/vflattencmd.cc b/karbon/commands/vflattencmd.cpp
index 21d5b50c2..21d5b50c2 100644
--- a/karbon/commands/vflattencmd.cc
+++ b/karbon/commands/vflattencmd.cpp
diff --git a/karbon/commands/vgroupcmd.cc b/karbon/commands/vgroupcmd.cpp
index 70bd2933f..70bd2933f 100644
--- a/karbon/commands/vgroupcmd.cc
+++ b/karbon/commands/vgroupcmd.cpp
diff --git a/karbon/commands/vinsertcmd.cc b/karbon/commands/vinsertcmd.cpp
index fb544a0c3..fb544a0c3 100644
--- a/karbon/commands/vinsertcmd.cc
+++ b/karbon/commands/vinsertcmd.cpp
diff --git a/karbon/commands/vlayercmd.cc b/karbon/commands/vlayercmd.cpp
index 9a1fe7bdf..9a1fe7bdf 100644
--- a/karbon/commands/vlayercmd.cc
+++ b/karbon/commands/vlayercmd.cpp
diff --git a/karbon/commands/vreplacingcmd.cc b/karbon/commands/vreplacingcmd.cpp
index 427ecdcab..427ecdcab 100644
--- a/karbon/commands/vreplacingcmd.cc
+++ b/karbon/commands/vreplacingcmd.cpp
diff --git a/karbon/commands/vshapecmd.cc b/karbon/commands/vshapecmd.cpp
index 9a59fcd9f..9a59fcd9f 100644
--- a/karbon/commands/vshapecmd.cc
+++ b/karbon/commands/vshapecmd.cpp
diff --git a/karbon/commands/vstrokecmd.cc b/karbon/commands/vstrokecmd.cpp
index 7b99f2d75..7b99f2d75 100644
--- a/karbon/commands/vstrokecmd.cc
+++ b/karbon/commands/vstrokecmd.cpp
diff --git a/karbon/commands/vtextcmd.cc b/karbon/commands/vtextcmd.cpp
index fd7424ba1..fd7424ba1 100644
--- a/karbon/commands/vtextcmd.cc
+++ b/karbon/commands/vtextcmd.cpp
diff --git a/karbon/commands/vtransformcmd.cc b/karbon/commands/vtransformcmd.cpp
index ebcb443ed..ebcb443ed 100644
--- a/karbon/commands/vtransformcmd.cc
+++ b/karbon/commands/vtransformcmd.cpp
diff --git a/karbon/commands/vungroupcmd.cc b/karbon/commands/vungroupcmd.cpp
index 947c4afe3..947c4afe3 100644
--- a/karbon/commands/vungroupcmd.cc
+++ b/karbon/commands/vungroupcmd.cpp
diff --git a/karbon/commands/vzordercmd.cc b/karbon/commands/vzordercmd.cpp
index 2a25edf95..2a25edf95 100644
--- a/karbon/commands/vzordercmd.cc
+++ b/karbon/commands/vzordercmd.cpp
diff --git a/karbon/core/Makefile.am b/karbon/core/Makefile.am
index aabebf800..1f7d8312e 100644
--- a/karbon/core/Makefile.am
+++ b/karbon/core/Makefile.am
@@ -35,37 +35,37 @@ noinst_HEADERS = \
vcursor.h
libkarboncore_la_SOURCES = \
- vcolor.cc \
- vcomposite.cc \
- vcomposite_iface.cc \
+ vcolor.cpp \
+ vcomposite.cpp \
+ vcomposite_iface.cpp \
vcomposite_iface.skel \
- vdashpattern.cc \
- vdocument.cc \
- vfill.cc \
- vglobal.cc \
- vgradient.cc \
- vgroup.cc \
- vobject_iface.cc \
+ vdashpattern.cpp \
+ vdocument.cpp \
+ vfill.cpp \
+ vglobal.cpp \
+ vgradient.cpp \
+ vgroup.cpp \
+ vobject_iface.cpp \
vobject_iface.skel \
- vgroup_iface.cc \
+ vgroup_iface.cpp \
vgroup_iface.skel \
- vimage.cc \
- vkarbonplugin.cc \
- vlayer.cc \
- vobject.cc \
- vpath.cc \
- vpattern.cc \
- vsegment.cc \
- vselection.cc \
- vstroke.cc \
- vvisitor.cc \
- vlayer_iface.cc \
+ vimage.cpp \
+ vkarbonplugin.cpp \
+ vlayer.cpp \
+ vobject.cpp \
+ vpath.cpp \
+ vpattern.cpp \
+ vsegment.cpp \
+ vselection.cpp \
+ vstroke.cpp \
+ vvisitor.cpp \
+ vlayer_iface.cpp \
vlayer_iface.skel \
- vtext.cc \
- vtext_iface.cc \
+ vtext.cpp \
+ vtext_iface.cpp \
vtext_iface.skel \
- vclipgroup.cc \
- vcursor.cc
+ vclipgroup.cpp \
+ vcursor.cpp
libkarboncore_la_LIBADD = $(LIBFONTCONFIG_LIBS)
diff --git a/karbon/core/vclipgroup.cc b/karbon/core/vclipgroup.cpp
index 9a36c1c55..9a36c1c55 100644
--- a/karbon/core/vclipgroup.cc
+++ b/karbon/core/vclipgroup.cpp
diff --git a/karbon/core/vcolor.cc b/karbon/core/vcolor.cpp
index f8f237d50..f8f237d50 100644
--- a/karbon/core/vcolor.cc
+++ b/karbon/core/vcolor.cpp
diff --git a/karbon/core/vcomposite.cc b/karbon/core/vcomposite.cpp
index 256362116..256362116 100644
--- a/karbon/core/vcomposite.cc
+++ b/karbon/core/vcomposite.cpp
diff --git a/karbon/core/vcomposite_iface.cc b/karbon/core/vcomposite_iface.cpp
index 2cc07c530..2cc07c530 100644
--- a/karbon/core/vcomposite_iface.cc
+++ b/karbon/core/vcomposite_iface.cpp
diff --git a/karbon/core/vcursor.cc b/karbon/core/vcursor.cpp
index c5fb2f402..c5fb2f402 100644
--- a/karbon/core/vcursor.cc
+++ b/karbon/core/vcursor.cpp
diff --git a/karbon/core/vdashpattern.cc b/karbon/core/vdashpattern.cpp
index cc167584d..cc167584d 100644
--- a/karbon/core/vdashpattern.cc
+++ b/karbon/core/vdashpattern.cpp
diff --git a/karbon/core/vdocument.cc b/karbon/core/vdocument.cpp
index 2de51bf14..2de51bf14 100644
--- a/karbon/core/vdocument.cc
+++ b/karbon/core/vdocument.cpp
diff --git a/karbon/core/vfill.cc b/karbon/core/vfill.cpp
index dfa4d5dfb..dfa4d5dfb 100644
--- a/karbon/core/vfill.cc
+++ b/karbon/core/vfill.cpp
diff --git a/karbon/core/vglobal.cc b/karbon/core/vglobal.cpp
index b118e5e26..b118e5e26 100644
--- a/karbon/core/vglobal.cc
+++ b/karbon/core/vglobal.cpp
diff --git a/karbon/core/vgradient.cc b/karbon/core/vgradient.cpp
index 577d13735..577d13735 100644
--- a/karbon/core/vgradient.cc
+++ b/karbon/core/vgradient.cpp
diff --git a/karbon/core/vgroup.cc b/karbon/core/vgroup.cpp
index 1d18f54f5..1d18f54f5 100644
--- a/karbon/core/vgroup.cc
+++ b/karbon/core/vgroup.cpp
diff --git a/karbon/core/vgroup_iface.cc b/karbon/core/vgroup_iface.cpp
index 8a22343a8..8a22343a8 100644
--- a/karbon/core/vgroup_iface.cc
+++ b/karbon/core/vgroup_iface.cpp
diff --git a/karbon/core/vimage.cc b/karbon/core/vimage.cpp
index 4e8466613..4e8466613 100644
--- a/karbon/core/vimage.cc
+++ b/karbon/core/vimage.cpp
diff --git a/karbon/core/vkarbonplugin.cc b/karbon/core/vkarbonplugin.cpp
index 41fd47a89..41fd47a89 100644
--- a/karbon/core/vkarbonplugin.cc
+++ b/karbon/core/vkarbonplugin.cpp
diff --git a/karbon/core/vlayer.cc b/karbon/core/vlayer.cpp
index 55602598e..55602598e 100644
--- a/karbon/core/vlayer.cc
+++ b/karbon/core/vlayer.cpp
diff --git a/karbon/core/vlayer_iface.cc b/karbon/core/vlayer_iface.cpp
index 168e6a4a9..168e6a4a9 100644
--- a/karbon/core/vlayer_iface.cc
+++ b/karbon/core/vlayer_iface.cpp
diff --git a/karbon/core/vobject.cc b/karbon/core/vobject.cpp
index 897652c37..897652c37 100644
--- a/karbon/core/vobject.cc
+++ b/karbon/core/vobject.cpp
diff --git a/karbon/core/vobject_iface.cc b/karbon/core/vobject_iface.cpp
index 25f9959f7..25f9959f7 100644
--- a/karbon/core/vobject_iface.cc
+++ b/karbon/core/vobject_iface.cpp
diff --git a/karbon/core/vpath.cc b/karbon/core/vpath.cpp
index ea05fc762..ea05fc762 100644
--- a/karbon/core/vpath.cc
+++ b/karbon/core/vpath.cpp
diff --git a/karbon/core/vpattern.cc b/karbon/core/vpattern.cpp
index 3a9c181f1..3a9c181f1 100644
--- a/karbon/core/vpattern.cc
+++ b/karbon/core/vpattern.cpp
diff --git a/karbon/core/vsegment.cc b/karbon/core/vsegment.cpp
index d18baeba8..d18baeba8 100644
--- a/karbon/core/vsegment.cc
+++ b/karbon/core/vsegment.cpp
diff --git a/karbon/core/vselection.cc b/karbon/core/vselection.cpp
index 5a10373f4..5a10373f4 100644
--- a/karbon/core/vselection.cc
+++ b/karbon/core/vselection.cpp
diff --git a/karbon/core/vstroke.cc b/karbon/core/vstroke.cpp
index d0cea9c72..d0cea9c72 100644
--- a/karbon/core/vstroke.cc
+++ b/karbon/core/vstroke.cpp
diff --git a/karbon/core/vtext.cc b/karbon/core/vtext.cpp
index b8e15c4f3..b8e15c4f3 100644
--- a/karbon/core/vtext.cc
+++ b/karbon/core/vtext.cpp
diff --git a/karbon/core/vtext_iface.cc b/karbon/core/vtext_iface.cpp
index 7cbeaf377..7cbeaf377 100644
--- a/karbon/core/vtext_iface.cc
+++ b/karbon/core/vtext_iface.cpp
diff --git a/karbon/core/vvisitor.cc b/karbon/core/vvisitor.cpp
index 90085c4a0..90085c4a0 100644
--- a/karbon/core/vvisitor.cc
+++ b/karbon/core/vvisitor.cpp
diff --git a/karbon/dialogs/Makefile.am b/karbon/dialogs/Makefile.am
index 7856355a5..18bd36146 100644
--- a/karbon/dialogs/Makefile.am
+++ b/karbon/dialogs/Makefile.am
@@ -13,9 +13,9 @@ noinst_HEADERS = \
vcolortab.h
libkarbondialogs_la_SOURCES = \
- vcolordlg.cc \
- vconfiguredlg.cc \
- vcolortab.cc
+ vcolordlg.cpp \
+ vconfiguredlg.cpp \
+ vcolortab.cpp
libkarbondialogs_la_METASOURCES = \
AUTO
diff --git a/karbon/dialogs/vcolordlg.cc b/karbon/dialogs/vcolordlg.cpp
index ae8e399a5..ae8e399a5 100644
--- a/karbon/dialogs/vcolordlg.cc
+++ b/karbon/dialogs/vcolordlg.cpp
diff --git a/karbon/dialogs/vcolortab.cc b/karbon/dialogs/vcolortab.cpp
index 0b2c3bab9..0b2c3bab9 100644
--- a/karbon/dialogs/vcolortab.cc
+++ b/karbon/dialogs/vcolortab.cpp
diff --git a/karbon/dialogs/vconfiguredlg.cc b/karbon/dialogs/vconfiguredlg.cpp
index 49f874fc4..49f874fc4 100644
--- a/karbon/dialogs/vconfiguredlg.cc
+++ b/karbon/dialogs/vconfiguredlg.cpp
diff --git a/karbon/dialogs/vstrokedlg.cc b/karbon/dialogs/vstrokedlg.cpp
index 27009bf21..27009bf21 100644
--- a/karbon/dialogs/vstrokedlg.cc
+++ b/karbon/dialogs/vstrokedlg.cpp
diff --git a/karbon/dockers/Makefile.am b/karbon/dockers/Makefile.am
index 9df79e8b9..36a918adc 100644
--- a/karbon/dockers/Makefile.am
+++ b/karbon/dockers/Makefile.am
@@ -19,18 +19,18 @@ noinst_HEADERS = \
vtransformdocker.h
libkarbondockers_la_SOURCES = \
- dummy.cc \
- vcolordocker.cc \
- vdocumentdocker.cc \
- vstrokedocker.cc \
- vstyledocker.cc \
- vtransformdocker.cc
+ dummy.cpp \
+ vcolordocker.cpp \
+ vdocumentdocker.cpp \
+ vstrokedocker.cpp \
+ vstyledocker.cpp \
+ vtransformdocker.cpp
libkarbondockers_la_METASOURCES = AUTO
DISTCLEANFILES = \
- dummy.cc
+ dummy.cpp
-dummy.cc:
- echo > dummy.cc
+dummy.cpp:
+ echo > dummy.cpp
diff --git a/karbon/dockers/vcolordocker.cc b/karbon/dockers/vcolordocker.cpp
index 328f4f3ff..328f4f3ff 100644
--- a/karbon/dockers/vcolordocker.cc
+++ b/karbon/dockers/vcolordocker.cpp
diff --git a/karbon/dockers/vdocumentdocker.cc b/karbon/dockers/vdocumentdocker.cpp
index dc676a85c..dc676a85c 100644
--- a/karbon/dockers/vdocumentdocker.cc
+++ b/karbon/dockers/vdocumentdocker.cpp
diff --git a/karbon/dockers/vstrokedocker.cc b/karbon/dockers/vstrokedocker.cpp
index 13fe44c16..13fe44c16 100644
--- a/karbon/dockers/vstrokedocker.cc
+++ b/karbon/dockers/vstrokedocker.cpp
diff --git a/karbon/dockers/vstyledocker.cc b/karbon/dockers/vstyledocker.cpp
index 9f3d12e6f..9f3d12e6f 100644
--- a/karbon/dockers/vstyledocker.cc
+++ b/karbon/dockers/vstyledocker.cpp
diff --git a/karbon/dockers/vtransformdocker.cc b/karbon/dockers/vtransformdocker.cpp
index 69c9a87cb..69c9a87cb 100644
--- a/karbon/dockers/vtransformdocker.cc
+++ b/karbon/dockers/vtransformdocker.cpp
diff --git a/karbon/karbon_factory.cc b/karbon/karbon_factory.cpp
index 6dd94ed36..6dd94ed36 100644
--- a/karbon/karbon_factory.cc
+++ b/karbon/karbon_factory.cpp
diff --git a/karbon/karbon_factory_init.cc b/karbon/karbon_factory_init.cpp
index 76315b5e3..76315b5e3 100644
--- a/karbon/karbon_factory_init.cc
+++ b/karbon/karbon_factory_init.cpp
diff --git a/karbon/karbon_part.cc b/karbon/karbon_part.cpp
index a34a4da11..a34a4da11 100644
--- a/karbon/karbon_part.cc
+++ b/karbon/karbon_part.cpp
diff --git a/karbon/karbon_part_iface.cc b/karbon/karbon_part_iface.cpp
index a87b454b3..a87b454b3 100644
--- a/karbon/karbon_part_iface.cc
+++ b/karbon/karbon_part_iface.cpp
diff --git a/karbon/karbon_resourceserver.cc b/karbon/karbon_resourceserver.cpp
index 2b31e4d71..2b31e4d71 100644
--- a/karbon/karbon_resourceserver.cc
+++ b/karbon/karbon_resourceserver.cpp
diff --git a/karbon/karbon_tool_factory.cc b/karbon/karbon_tool_factory.cpp
index 081a9148b..081a9148b 100644
--- a/karbon/karbon_tool_factory.cc
+++ b/karbon/karbon_tool_factory.cpp
diff --git a/karbon/karbon_tool_registry.cc b/karbon/karbon_tool_registry.cpp
index bc699d455..bc699d455 100644
--- a/karbon/karbon_tool_registry.cc
+++ b/karbon/karbon_tool_registry.cpp
diff --git a/karbon/karbon_view.cc b/karbon/karbon_view.cpp
index 3fc8eaf5b..3fc8eaf5b 100644
--- a/karbon/karbon_view.cc
+++ b/karbon/karbon_view.cpp
diff --git a/karbon/karbon_view_iface.cc b/karbon/karbon_view_iface.cpp
index 3fdf17783..3fdf17783 100644
--- a/karbon/karbon_view_iface.cc
+++ b/karbon/karbon_view_iface.cpp
diff --git a/karbon/main.cc b/karbon/main.cpp
index 434134fee..434134fee 100644
--- a/karbon/main.cc
+++ b/karbon/main.cpp
diff --git a/karbon/plugins/flattenpath/Makefile.am b/karbon/plugins/flattenpath/Makefile.am
index e1337a7ea..8cce9268c 100644
--- a/karbon/plugins/flattenpath/Makefile.am
+++ b/karbon/plugins/flattenpath/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/co
kde_module_LTLIBRARIES = karbon_flattenpathplugin.la
-karbon_flattenpathplugin_la_SOURCES = flattenpathplugin.cc
+karbon_flattenpathplugin_la_SOURCES = flattenpathplugin.cpp
karbon_flattenpathplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/flattenpath/flattenpathplugin.cc b/karbon/plugins/flattenpath/flattenpathplugin.cpp
index 6c4a33d8d..6c4a33d8d 100644
--- a/karbon/plugins/flattenpath/flattenpathplugin.cc
+++ b/karbon/plugins/flattenpath/flattenpathplugin.cpp
diff --git a/karbon/plugins/imagetool/Makefile.am b/karbon/plugins/imagetool/Makefile.am
index 188656241..32c078961 100644
--- a/karbon/plugins/imagetool/Makefile.am
+++ b/karbon/plugins/imagetool/Makefile.am
@@ -4,7 +4,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/co
kde_module_LTLIBRARIES = karbon_imagetoolplugin.la
-karbon_imagetoolplugin_la_SOURCES = imagetoolplugin.cc vimagetool.cc
+karbon_imagetoolplugin_la_SOURCES = imagetoolplugin.cpp vimagetool.cpp
karbon_imagetoolplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/imagetool/imagetoolplugin.cc b/karbon/plugins/imagetool/imagetoolplugin.cpp
index 5a0d49a8c..5a0d49a8c 100644
--- a/karbon/plugins/imagetool/imagetoolplugin.cc
+++ b/karbon/plugins/imagetool/imagetoolplugin.cpp
diff --git a/karbon/plugins/imagetool/vimagetool.cc b/karbon/plugins/imagetool/vimagetool.cpp
index 749e07a1f..749e07a1f 100644
--- a/karbon/plugins/imagetool/vimagetool.cc
+++ b/karbon/plugins/imagetool/vimagetool.cpp
diff --git a/karbon/plugins/insertknots/Makefile.am b/karbon/plugins/insertknots/Makefile.am
index 3e5b767f8..97cb21f7f 100644
--- a/karbon/plugins/insertknots/Makefile.am
+++ b/karbon/plugins/insertknots/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/co
kde_module_LTLIBRARIES = karbon_insertknotsplugin.la
-karbon_insertknotsplugin_la_SOURCES = insertknotsplugin.cc
+karbon_insertknotsplugin_la_SOURCES = insertknotsplugin.cpp
karbon_insertknotsplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/insertknots/insertknotsplugin.cc b/karbon/plugins/insertknots/insertknotsplugin.cpp
index 19a1e4d56..19a1e4d56 100644
--- a/karbon/plugins/insertknots/insertknotsplugin.cc
+++ b/karbon/plugins/insertknots/insertknotsplugin.cpp
diff --git a/karbon/plugins/roundcorners/Makefile.am b/karbon/plugins/roundcorners/Makefile.am
index e454b2cd9..ed824ee20 100644
--- a/karbon/plugins/roundcorners/Makefile.am
+++ b/karbon/plugins/roundcorners/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/co
kde_module_LTLIBRARIES = karbon_roundcornersplugin.la
-karbon_roundcornersplugin_la_SOURCES = roundcornersplugin.cc
+karbon_roundcornersplugin_la_SOURCES = roundcornersplugin.cpp
karbon_roundcornersplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/roundcorners/roundcornersplugin.cc b/karbon/plugins/roundcorners/roundcornersplugin.cpp
index 1841c5eb1..1841c5eb1 100644
--- a/karbon/plugins/roundcorners/roundcornersplugin.cc
+++ b/karbon/plugins/roundcorners/roundcornersplugin.cpp
diff --git a/karbon/plugins/shadoweffect/Makefile.am b/karbon/plugins/shadoweffect/Makefile.am
index 9837f11e8..947a02c11 100644
--- a/karbon/plugins/shadoweffect/Makefile.am
+++ b/karbon/plugins/shadoweffect/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) $(KOPAINTER_INCLUDES) -I$(top_srcdir)/karbon -I$
kde_module_LTLIBRARIES = karbon_shadoweffectplugin.la
-karbon_shadoweffectplugin_la_SOURCES = shadoweffectplugin.cc vshadowdecorator.cc
+karbon_shadoweffectplugin_la_SOURCES = shadoweffectplugin.cpp vshadowdecorator.cpp
karbon_shadoweffectplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/shadoweffect/shadoweffectplugin.cc b/karbon/plugins/shadoweffect/shadoweffectplugin.cpp
index 019b4024a..019b4024a 100644
--- a/karbon/plugins/shadoweffect/shadoweffectplugin.cc
+++ b/karbon/plugins/shadoweffect/shadoweffectplugin.cpp
diff --git a/karbon/plugins/shadoweffect/vshadowdecorator.cc b/karbon/plugins/shadoweffect/vshadowdecorator.cpp
index 99ee8c8c3..99ee8c8c3 100644
--- a/karbon/plugins/shadoweffect/vshadowdecorator.cc
+++ b/karbon/plugins/shadoweffect/vshadowdecorator.cpp
diff --git a/karbon/plugins/whirlpinch/Makefile.am b/karbon/plugins/whirlpinch/Makefile.am
index 3dd38a1ba..a563ea08a 100644
--- a/karbon/plugins/whirlpinch/Makefile.am
+++ b/karbon/plugins/whirlpinch/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/cor
kde_module_LTLIBRARIES = karbon_whirlpinchplugin.la
-karbon_whirlpinchplugin_la_SOURCES = whirlpinchplugin.cc
+karbon_whirlpinchplugin_la_SOURCES = whirlpinchplugin.cpp
karbon_whirlpinchplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOPAINTER) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
../../libkarboncommon.la
diff --git a/karbon/plugins/whirlpinch/whirlpinchplugin.cc b/karbon/plugins/whirlpinch/whirlpinchplugin.cpp
index d2b91a185..d2b91a185 100644
--- a/karbon/plugins/whirlpinch/whirlpinchplugin.cc
+++ b/karbon/plugins/whirlpinch/whirlpinchplugin.cpp
diff --git a/karbon/plugins/zoomtool/Makefile.am b/karbon/plugins/zoomtool/Makefile.am
index 1121d54f2..a08c823de 100644
--- a/karbon/plugins/zoomtool/Makefile.am
+++ b/karbon/plugins/zoomtool/Makefile.am
@@ -4,7 +4,7 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(top_srcdir)/karbon -I$(top_srcdir)/karbon/co
kde_module_LTLIBRARIES = karbon_zoomtoolplugin.la
-karbon_zoomtoolplugin_la_SOURCES = vzoomtool.cc zoomtoolplugin.cc
+karbon_zoomtoolplugin_la_SOURCES = vzoomtool.cpp zoomtoolplugin.cpp
karbon_zoomtoolplugin_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) \
$(LIB_KOPAINTER) ../../libkarboncommon.la
diff --git a/karbon/plugins/zoomtool/vzoomtool.cc b/karbon/plugins/zoomtool/vzoomtool.cpp
index 1cecb94a8..1cecb94a8 100644
--- a/karbon/plugins/zoomtool/vzoomtool.cc
+++ b/karbon/plugins/zoomtool/vzoomtool.cpp
diff --git a/karbon/plugins/zoomtool/zoomtoolplugin.cc b/karbon/plugins/zoomtool/zoomtoolplugin.cpp
index 3ad73ee9f..3ad73ee9f 100644
--- a/karbon/plugins/zoomtool/zoomtoolplugin.cc
+++ b/karbon/plugins/zoomtool/zoomtoolplugin.cpp
diff --git a/karbon/render/Makefile.am b/karbon/render/Makefile.am
index 5f604f6cf..42c837724 100644
--- a/karbon/render/Makefile.am
+++ b/karbon/render/Makefile.am
@@ -21,14 +21,14 @@ noinst_HEADERS = \
vkopainter.h
libvpainter_la_SOURCES = \
- vpainterfactory.cc \
- vqpainter.cc \
+ vpainterfactory.cpp \
+ vqpainter.cpp \
art_render_pattern.c \
art_render_misc.c \
art_rgb_svp.c \
art_rgb.c \
art_rgba_affine.c \
- vkopainter.cc
+ vkopainter.cpp
libvpainter_la_METASOURCES = \
AUTO
diff --git a/karbon/render/vkopainter.cc b/karbon/render/vkopainter.cpp
index 3f81f3c32..3f81f3c32 100644
--- a/karbon/render/vkopainter.cc
+++ b/karbon/render/vkopainter.cpp
diff --git a/karbon/render/vpainterfactory.cc b/karbon/render/vpainterfactory.cpp
index 2d36882d9..2d36882d9 100644
--- a/karbon/render/vpainterfactory.cc
+++ b/karbon/render/vpainterfactory.cpp
diff --git a/karbon/render/vqpainter.cc b/karbon/render/vqpainter.cpp
index 51819ae30..51819ae30 100644
--- a/karbon/render/vqpainter.cc
+++ b/karbon/render/vqpainter.cpp
diff --git a/karbon/shapes/Makefile.am b/karbon/shapes/Makefile.am
index bbb7899b1..5f8ba408b 100644
--- a/karbon/shapes/Makefile.am
+++ b/karbon/shapes/Makefile.am
@@ -16,13 +16,13 @@ noinst_HEADERS = \
vstar.h
libkarbonshapes_la_SOURCES = \
- vellipse.cc \
- vpolyline.cc \
- vpolygon.cc \
- vrectangle.cc \
- vsinus.cc \
- vspiral.cc \
- vstar.cc
+ vellipse.cpp \
+ vpolyline.cpp \
+ vpolygon.cpp \
+ vrectangle.cpp \
+ vsinus.cpp \
+ vspiral.cpp \
+ vstar.cpp
libkarbonshapes_la_METASOURCES = \
AUTO
diff --git a/karbon/shapes/vellipse.cc b/karbon/shapes/vellipse.cpp
index 1a9462b81..1a9462b81 100644
--- a/karbon/shapes/vellipse.cc
+++ b/karbon/shapes/vellipse.cpp
diff --git a/karbon/shapes/vpolygon.cc b/karbon/shapes/vpolygon.cpp
index fdf0f745d..fdf0f745d 100644
--- a/karbon/shapes/vpolygon.cc
+++ b/karbon/shapes/vpolygon.cpp
diff --git a/karbon/shapes/vpolyline.cc b/karbon/shapes/vpolyline.cpp
index 519422ed9..519422ed9 100644
--- a/karbon/shapes/vpolyline.cc
+++ b/karbon/shapes/vpolyline.cpp
diff --git a/karbon/shapes/vrectangle.cc b/karbon/shapes/vrectangle.cpp
index 3190c93c9..3190c93c9 100644
--- a/karbon/shapes/vrectangle.cc
+++ b/karbon/shapes/vrectangle.cpp
diff --git a/karbon/shapes/vsinus.cc b/karbon/shapes/vsinus.cpp
index f27cee4b3..f27cee4b3 100644
--- a/karbon/shapes/vsinus.cc
+++ b/karbon/shapes/vsinus.cpp
diff --git a/karbon/shapes/vspiral.cc b/karbon/shapes/vspiral.cpp
index ff2f691e0..ff2f691e0 100644
--- a/karbon/shapes/vspiral.cc
+++ b/karbon/shapes/vspiral.cpp
diff --git a/karbon/shapes/vstar.cc b/karbon/shapes/vstar.cpp
index a43413c99..a43413c99 100644
--- a/karbon/shapes/vstar.cc
+++ b/karbon/shapes/vstar.cpp
diff --git a/karbon/tools/Makefile.am b/karbon/tools/Makefile.am
index 8aa4070f9..ee753e7e7 100644
--- a/karbon/tools/Makefile.am
+++ b/karbon/tools/Makefile.am
@@ -36,25 +36,25 @@ noinst_HEADERS = \
vdefaulttools.h
karbon_defaulttools_la_SOURCES = \
- vcurvefit.cc \
- vrotatetool.cc \
- vselectnodestool.cc \
- vselecttool.cc \
- vsheartool.cc \
- vellipsetool.cc \
- vgradienttool.cc \
- vpatterntool.cc \
- vpenciltool.cc \
- vpolygontool.cc \
- vpolylinetool.cc \
- vrectangletool.cc \
- vroundrecttool.cc \
- vshapetool.cc \
- vsinustool.cc \
- vspiraltool.cc \
- vstartool.cc \
- vtexttool.cc \
- vdefaulttools.cc
+ vcurvefit.cpp \
+ vrotatetool.cpp \
+ vselectnodestool.cpp \
+ vselecttool.cpp \
+ vsheartool.cpp \
+ vellipsetool.cpp \
+ vgradienttool.cpp \
+ vpatterntool.cpp \
+ vpenciltool.cpp \
+ vpolygontool.cpp \
+ vpolylinetool.cpp \
+ vrectangletool.cpp \
+ vroundrecttool.cpp \
+ vshapetool.cpp \
+ vsinustool.cpp \
+ vspiraltool.cpp \
+ vstartool.cpp \
+ vtexttool.cpp \
+ vdefaulttools.cpp
karbon_defaulttools_la_LIBADD = $(LIB_TDEPARTS) $(LIB_KOFFICECORE) $(LIB_KOFFICEUI) $(LIB_KOPAINTER) ../libkarboncommon.la
karbon_defaulttools_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio
diff --git a/karbon/tools/vcurvefit.cc b/karbon/tools/vcurvefit.cpp
index 40d7b7e3e..40d7b7e3e 100644
--- a/karbon/tools/vcurvefit.cc
+++ b/karbon/tools/vcurvefit.cpp
diff --git a/karbon/tools/vdefaulttools.cc b/karbon/tools/vdefaulttools.cpp
index 3be8a8bd2..3be8a8bd2 100644
--- a/karbon/tools/vdefaulttools.cc
+++ b/karbon/tools/vdefaulttools.cpp
diff --git a/karbon/tools/vellipsetool.cc b/karbon/tools/vellipsetool.cpp
index 170a51dde..170a51dde 100644
--- a/karbon/tools/vellipsetool.cc
+++ b/karbon/tools/vellipsetool.cpp
diff --git a/karbon/tools/vgradienttool.cc b/karbon/tools/vgradienttool.cpp
index e7d2db3ca..e7d2db3ca 100644
--- a/karbon/tools/vgradienttool.cc
+++ b/karbon/tools/vgradienttool.cpp
diff --git a/karbon/tools/vpatterntool.cc b/karbon/tools/vpatterntool.cpp
index 8c42d5e00..8c42d5e00 100644
--- a/karbon/tools/vpatterntool.cc
+++ b/karbon/tools/vpatterntool.cpp
diff --git a/karbon/tools/vpenciltool.cc b/karbon/tools/vpenciltool.cpp
index 1239923ea..1239923ea 100644
--- a/karbon/tools/vpenciltool.cc
+++ b/karbon/tools/vpenciltool.cpp
diff --git a/karbon/tools/vpolygontool.cc b/karbon/tools/vpolygontool.cpp
index de4756919..de4756919 100644
--- a/karbon/tools/vpolygontool.cc
+++ b/karbon/tools/vpolygontool.cpp
diff --git a/karbon/tools/vpolylinetool.cc b/karbon/tools/vpolylinetool.cpp
index 38ac9d256..38ac9d256 100644
--- a/karbon/tools/vpolylinetool.cc
+++ b/karbon/tools/vpolylinetool.cpp
diff --git a/karbon/tools/vrectangletool.cc b/karbon/tools/vrectangletool.cpp
index 4572cc237..4572cc237 100644
--- a/karbon/tools/vrectangletool.cc
+++ b/karbon/tools/vrectangletool.cpp
diff --git a/karbon/tools/vrotatetool.cc b/karbon/tools/vrotatetool.cpp
index 4230cac7f..4230cac7f 100644
--- a/karbon/tools/vrotatetool.cc
+++ b/karbon/tools/vrotatetool.cpp
diff --git a/karbon/tools/vroundrecttool.cc b/karbon/tools/vroundrecttool.cpp
index 02f694c69..02f694c69 100644
--- a/karbon/tools/vroundrecttool.cc
+++ b/karbon/tools/vroundrecttool.cpp
diff --git a/karbon/tools/vselectnodestool.cc b/karbon/tools/vselectnodestool.cpp
index 2a3c38bba..2a3c38bba 100644
--- a/karbon/tools/vselectnodestool.cc
+++ b/karbon/tools/vselectnodestool.cpp
diff --git a/karbon/tools/vselecttool.cc b/karbon/tools/vselecttool.cpp
index b2c28d661..b2c28d661 100644
--- a/karbon/tools/vselecttool.cc
+++ b/karbon/tools/vselecttool.cpp
diff --git a/karbon/tools/vshapetool.cc b/karbon/tools/vshapetool.cpp
index 9b59104d1..9b59104d1 100644
--- a/karbon/tools/vshapetool.cc
+++ b/karbon/tools/vshapetool.cpp
diff --git a/karbon/tools/vsheartool.cc b/karbon/tools/vsheartool.cpp
index 4bc80810e..4bc80810e 100644
--- a/karbon/tools/vsheartool.cc
+++ b/karbon/tools/vsheartool.cpp
diff --git a/karbon/tools/vsinustool.cc b/karbon/tools/vsinustool.cpp
index 12dbe1282..12dbe1282 100644
--- a/karbon/tools/vsinustool.cc
+++ b/karbon/tools/vsinustool.cpp
diff --git a/karbon/tools/vspiraltool.cc b/karbon/tools/vspiraltool.cpp
index c414be41f..c414be41f 100644
--- a/karbon/tools/vspiraltool.cc
+++ b/karbon/tools/vspiraltool.cpp
diff --git a/karbon/tools/vstartool.cc b/karbon/tools/vstartool.cpp
index 9a92cd376..9a92cd376 100644
--- a/karbon/tools/vstartool.cc
+++ b/karbon/tools/vstartool.cpp
diff --git a/karbon/tools/vtexttool.cc b/karbon/tools/vtexttool.cpp
index e7fa848d2..e7fa848d2 100644
--- a/karbon/tools/vtexttool.cc
+++ b/karbon/tools/vtexttool.cpp
diff --git a/karbon/usablity-review.txt b/karbon/usablity-review.txt
index 5d2eb8b44..a977c8d0b 100644
--- a/karbon/usablity-review.txt
+++ b/karbon/usablity-review.txt
@@ -1,6 +1,6 @@
Since I think the following link is closely related, I am including it here :
-http://dan.ostrowski.cc/suggestions.html
+http://dan.ostrowski.cpp/suggestions.html
Rob Buis <buis@kde.org>
17-12-2003
diff --git a/karbon/visitors/Makefile.am b/karbon/visitors/Makefile.am
index 60bc3caa2..e4ce58ccc 100644
--- a/karbon/visitors/Makefile.am
+++ b/karbon/visitors/Makefile.am
@@ -17,12 +17,12 @@ noinst_HEADERS = \
vcomputeboundingbox.h
libkarbonvisitors_la_SOURCES = \
- vselectnodes.cc \
- vselectobjects.cc \
- vdrawselection.cc \
- vselectiondesc.cc \
- vtransformnodes.cc \
- vcomputeboundingbox.cc
+ vselectnodes.cpp \
+ vselectobjects.cpp \
+ vdrawselection.cpp \
+ vselectiondesc.cpp \
+ vtransformnodes.cpp \
+ vcomputeboundingbox.cpp
libkarbonvisitors_la_METASOURCES = \
AUTO
diff --git a/karbon/visitors/vcomputeboundingbox.cc b/karbon/visitors/vcomputeboundingbox.cpp
index e303a2f97..e303a2f97 100644
--- a/karbon/visitors/vcomputeboundingbox.cc
+++ b/karbon/visitors/vcomputeboundingbox.cpp
diff --git a/karbon/visitors/vdrawselection.cc b/karbon/visitors/vdrawselection.cpp
index dbd932471..dbd932471 100644
--- a/karbon/visitors/vdrawselection.cc
+++ b/karbon/visitors/vdrawselection.cpp
diff --git a/karbon/visitors/vselectiondesc.cc b/karbon/visitors/vselectiondesc.cpp
index 8518b7b62..8518b7b62 100644
--- a/karbon/visitors/vselectiondesc.cc
+++ b/karbon/visitors/vselectiondesc.cpp
diff --git a/karbon/visitors/vselectnodes.cc b/karbon/visitors/vselectnodes.cpp
index 00f56de39..00f56de39 100644
--- a/karbon/visitors/vselectnodes.cc
+++ b/karbon/visitors/vselectnodes.cpp
diff --git a/karbon/visitors/vselectobjects.cc b/karbon/visitors/vselectobjects.cpp
index 060eeacbc..060eeacbc 100644
--- a/karbon/visitors/vselectobjects.cc
+++ b/karbon/visitors/vselectobjects.cpp
diff --git a/karbon/visitors/vtransformnodes.cc b/karbon/visitors/vtransformnodes.cpp
index 102bb33d6..102bb33d6 100644
--- a/karbon/visitors/vtransformnodes.cc
+++ b/karbon/visitors/vtransformnodes.cpp
diff --git a/karbon/vtool.cc b/karbon/vtool.cpp
index 140d65131..140d65131 100644
--- a/karbon/vtool.cc
+++ b/karbon/vtool.cpp
diff --git a/karbon/vtoolcontroller.cc b/karbon/vtoolcontroller.cpp
index 4a8eaa9fe..4a8eaa9fe 100644
--- a/karbon/vtoolcontroller.cc
+++ b/karbon/vtoolcontroller.cpp
diff --git a/karbon/widgets/Makefile.am b/karbon/widgets/Makefile.am
index c78d166c7..35828299a 100644
--- a/karbon/widgets/Makefile.am
+++ b/karbon/widgets/Makefile.am
@@ -27,27 +27,27 @@ noinst_HEADERS = \
vruler.h
libkarbonwidgets_la_SOURCES = \
- dummy.cc \
- vcanvas.cc \
- vcolorslider.cc \
- vgradientwidget.cc \
- vgradienttabwidget.cc \
- vreference.cc \
- vstrokefillpreview.cc \
- vtranslate.cc \
- vselecttoolbar.cc \
- vsmallpreview.cc \
- vstatebutton.cc \
- vtoolbox.cc \
- vtypebuttonbox.cc \
- vruler.cc
+ dummy.cpp \
+ vcanvas.cpp \
+ vcolorslider.cpp \
+ vgradientwidget.cpp \
+ vgradienttabwidget.cpp \
+ vreference.cpp \
+ vstrokefillpreview.cpp \
+ vtranslate.cpp \
+ vselecttoolbar.cpp \
+ vsmallpreview.cpp \
+ vstatebutton.cpp \
+ vtoolbox.cpp \
+ vtypebuttonbox.cpp \
+ vruler.cpp
libkarbonwidgets_la_METASOURCES = \
AUTO
DISTCLEANFILES = \
- dummy.cc
+ dummy.cpp
-dummy.cc:
- echo > dummy.cc
+dummy.cpp:
+ echo > dummy.cpp
diff --git a/karbon/widgets/vcanvas.cc b/karbon/widgets/vcanvas.cpp
index d4cd64972..d4cd64972 100644
--- a/karbon/widgets/vcanvas.cc
+++ b/karbon/widgets/vcanvas.cpp
diff --git a/karbon/widgets/vcolorslider.cc b/karbon/widgets/vcolorslider.cc
deleted file mode 100644
index 42c4f0588..000000000
--- a/karbon/widgets/vcolorslider.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-/* This file is part of the KDE project
- Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
- Copyright (C) 2002, The Karbon Developers
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/* vcolorslider.cc */
-
-#include <tqlayout.h>
-#include <tqlabel.h>
-#include <knuminput.h>
-#include <tdeselect.h>
-
-#include "vcolorslider.h"
-
-VColorSlider::VColorSlider( TQWidget* parent, const char* name )
- : TQWidget( parent, name )
-{
- init();
-}
-
-// Label, left color, right color, min, max, value ...
-VColorSlider::VColorSlider( const TQString& label, const TQColor& col1,
- const TQColor& col2, int min, int max, int value, TQWidget* parent, const char* name )
- : TQWidget( parent, name )
-{
- init();
- setLabel( label );
- setColors( col1, col2 );
- setMinValue( min );
- setMaxValue( max );
- setValue( value );
-}
-
-VColorSlider::~VColorSlider()
-{
-}
-
-void VColorSlider::init()
-{
- m_isDragging = false;
- TQHBoxLayout *layout = new TQHBoxLayout( this, 3 );
-
- m_label = new TQLabel( this );
- m_gradientSelect = new KGradientSelector( Qt::Horizontal, this );
- m_spinBox = new KIntSpinBox( this );
-
- layout->addWidget( m_label );
- layout->addWidget( m_gradientSelect, 2 );
- layout->addWidget( m_spinBox );
-
- setValue( 0 );
- setMinValue( 0 );
- setMaxValue( 255 );
-
- connect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
- connect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
-
- m_gradientSelect->installEventFilter( this );
-
- layout->activate();
-}
-
-void VColorSlider::setLabel( const TQString& label )
-{
- m_label->setText( label );
-}
-
-void VColorSlider::setColors( const TQColor& color1, const TQColor& color2 )
-{
- m_gradientSelect->setColors( color1, color2 );
-}
-
-void VColorSlider::setValue( int value )
-{
- m_spinBox->setValue( value );
- m_gradientSelect->setValue( (m_maxValue - value) + m_minValue );
-}
-
-void VColorSlider::setMinValue( int value )
-{
- m_minValue = value;
- m_spinBox->setMinValue( value );
- m_gradientSelect->setMinValue( value );
-}
-
-void VColorSlider::setMaxValue( int value )
-{
- m_maxValue = value;
- m_spinBox->setMaxValue( value );
- m_gradientSelect->setMaxValue( value );
-}
-
-int VColorSlider::value()
-{
- return( m_spinBox->value() );
-}
-
-void VColorSlider::updateFrom_spinBox( int value )
-{
- if ( value != m_gradientSelect->value() )
- {
- disconnect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
- m_gradientSelect->setValue( (m_maxValue - value) + m_minValue );
- connect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
- emit valueChanged( value );
- }
-}
-
-void VColorSlider::updateFrom_gradientSelect( int value )
-{
- value = (m_maxValue - value) + m_minValue;
- if ( value != m_spinBox->value() )
- {
- disconnect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
- m_spinBox->setValue( value );
- connect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
- emit valueChanged( value );
- }
-}
-
-bool VColorSlider::eventFilter( TQObject *obj, TQEvent *ev )
-{
- if( TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_gradientSelect) )
- {
- if ( ev->type() == TQEvent::MouseButtonPress )
- m_isDragging = true;
- else if( ev->type() == TQEvent::MouseButtonRelease )
- m_isDragging = false;
- }
- return FALSE;
-}
-
-#include "vcolorslider.moc"
-
diff --git a/karbon/widgets/vcolorslider.cpp b/karbon/widgets/vcolorslider.cpp
new file mode 100644
index 000000000..d2d0a0ab5
--- /dev/null
+++ b/karbon/widgets/vcolorslider.cpp
@@ -0,0 +1,149 @@
+/* This file is part of the KDE project
+ Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
+ Copyright (C) 2002, The Karbon Developers
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/* vcolorslider.cpp */
+
+#include <tqlayout.h>
+#include <tqlabel.h>
+#include <knuminput.h>
+#include <tdeselect.h>
+
+#include "vcolorslider.h"
+
+VColorSlider::VColorSlider( TQWidget* parent, const char* name )
+ : TQWidget( parent, name )
+{
+ init();
+}
+
+// Label, left color, right color, min, max, value ...
+VColorSlider::VColorSlider( const TQString& label, const TQColor& col1,
+ const TQColor& col2, int min, int max, int value, TQWidget* parent, const char* name )
+ : TQWidget( parent, name )
+{
+ init();
+ setLabel( label );
+ setColors( col1, col2 );
+ setMinValue( min );
+ setMaxValue( max );
+ setValue( value );
+}
+
+VColorSlider::~VColorSlider()
+{
+}
+
+void VColorSlider::init()
+{
+ m_isDragging = false;
+ TQHBoxLayout *layout = new TQHBoxLayout( this, 3 );
+
+ m_label = new TQLabel( this );
+ m_gradientSelect = new KGradientSelector( Qt::Horizontal, this );
+ m_spinBox = new KIntSpinBox( this );
+
+ layout->addWidget( m_label );
+ layout->addWidget( m_gradientSelect, 2 );
+ layout->addWidget( m_spinBox );
+
+ setValue( 0 );
+ setMinValue( 0 );
+ setMaxValue( 255 );
+
+ connect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
+ connect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
+
+ m_gradientSelect->installEventFilter( this );
+
+ layout->activate();
+}
+
+void VColorSlider::setLabel( const TQString& label )
+{
+ m_label->setText( label );
+}
+
+void VColorSlider::setColors( const TQColor& color1, const TQColor& color2 )
+{
+ m_gradientSelect->setColors( color1, color2 );
+}
+
+void VColorSlider::setValue( int value )
+{
+ m_spinBox->setValue( value );
+ m_gradientSelect->setValue( (m_maxValue - value) + m_minValue );
+}
+
+void VColorSlider::setMinValue( int value )
+{
+ m_minValue = value;
+ m_spinBox->setMinValue( value );
+ m_gradientSelect->setMinValue( value );
+}
+
+void VColorSlider::setMaxValue( int value )
+{
+ m_maxValue = value;
+ m_spinBox->setMaxValue( value );
+ m_gradientSelect->setMaxValue( value );
+}
+
+int VColorSlider::value()
+{
+ return( m_spinBox->value() );
+}
+
+void VColorSlider::updateFrom_spinBox( int value )
+{
+ if ( value != m_gradientSelect->value() )
+ {
+ disconnect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
+ m_gradientSelect->setValue( (m_maxValue - value) + m_minValue );
+ connect( m_gradientSelect, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_gradientSelect( int ) ) );
+ emit valueChanged( value );
+ }
+}
+
+void VColorSlider::updateFrom_gradientSelect( int value )
+{
+ value = (m_maxValue - value) + m_minValue;
+ if ( value != m_spinBox->value() )
+ {
+ disconnect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
+ m_spinBox->setValue( value );
+ connect( m_spinBox, TQT_SIGNAL( valueChanged ( int ) ), this, TQT_SLOT( updateFrom_spinBox( int ) ) );
+ emit valueChanged( value );
+ }
+}
+
+bool VColorSlider::eventFilter( TQObject *obj, TQEvent *ev )
+{
+ if( TQT_BASE_OBJECT(obj) == TQT_BASE_OBJECT(m_gradientSelect) )
+ {
+ if ( ev->type() == TQEvent::MouseButtonPress )
+ m_isDragging = true;
+ else if( ev->type() == TQEvent::MouseButtonRelease )
+ m_isDragging = false;
+ }
+ return FALSE;
+}
+
+#include "vcolorslider.moc"
+
diff --git a/karbon/widgets/vgradienttabwidget.cc b/karbon/widgets/vgradienttabwidget.cpp
index 5c57efaba..5c57efaba 100644
--- a/karbon/widgets/vgradienttabwidget.cc
+++ b/karbon/widgets/vgradienttabwidget.cpp
diff --git a/karbon/widgets/vgradientwidget.cc b/karbon/widgets/vgradientwidget.cpp
index 64cbf3731..64cbf3731 100644
--- a/karbon/widgets/vgradientwidget.cc
+++ b/karbon/widgets/vgradientwidget.cpp
diff --git a/karbon/widgets/vreference.cc b/karbon/widgets/vreference.cc
deleted file mode 100644
index c85800002..000000000
--- a/karbon/widgets/vreference.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-/* This file is part of the KDE project
- Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
- Copyright (C) 2002, The Karbon Developers
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/* vreference.cc */
-
-#include <tqbuttongroup.h>
-#include <tqlayout.h>
-#include <tqradiobutton.h>
-
-#include "vreference.h"
-
-VReference::VReference( TQWidget *parent, const char *name ) : TQFrame ( parent, name )
-{
- TQVBoxLayout* layout = new TQVBoxLayout( this );
- mButtonGroup = new TQButtonGroup (3,Qt::Vertical, this );
- TQRadioButton* radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, TopLeft );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, Left );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, BottomLeft );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, Top );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, Center );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, Bottom );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, TopRight );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, Right );
- radio = new TQRadioButton ( mButtonGroup );
- mButtonGroup->insert( radio, BottomRight );
-
- connect(
- mButtonGroup, TQT_SIGNAL( clicked( int ) ),
- this, TQT_SLOT( setReferencePoint( int ) ) );
-
- mButtonGroup->setButton( Center );
- layout->addWidget( mButtonGroup );
- layout->activate();
- setReferencePoint( Center );
-}
-
-void VReference::setReferencePoint ( int i )
-{
- m_referencePoint = i;
- emit referencePointChanged( m_referencePoint );
-}
-
-int VReference::referencePoint()
-{
- return( m_referencePoint );
-}
-
-#include "vreference.moc"
-
diff --git a/karbon/widgets/vreference.cpp b/karbon/widgets/vreference.cpp
new file mode 100644
index 000000000..c4e96ddff
--- /dev/null
+++ b/karbon/widgets/vreference.cpp
@@ -0,0 +1,74 @@
+/* This file is part of the KDE project
+ Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
+ Copyright (C) 2002, The Karbon Developers
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/* vreference.cpp */
+
+#include <tqbuttongroup.h>
+#include <tqlayout.h>
+#include <tqradiobutton.h>
+
+#include "vreference.h"
+
+VReference::VReference( TQWidget *parent, const char *name ) : TQFrame ( parent, name )
+{
+ TQVBoxLayout* layout = new TQVBoxLayout( this );
+ mButtonGroup = new TQButtonGroup (3,Qt::Vertical, this );
+ TQRadioButton* radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, TopLeft );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, Left );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, BottomLeft );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, Top );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, Center );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, Bottom );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, TopRight );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, Right );
+ radio = new TQRadioButton ( mButtonGroup );
+ mButtonGroup->insert( radio, BottomRight );
+
+ connect(
+ mButtonGroup, TQT_SIGNAL( clicked( int ) ),
+ this, TQT_SLOT( setReferencePoint( int ) ) );
+
+ mButtonGroup->setButton( Center );
+ layout->addWidget( mButtonGroup );
+ layout->activate();
+ setReferencePoint( Center );
+}
+
+void VReference::setReferencePoint ( int i )
+{
+ m_referencePoint = i;
+ emit referencePointChanged( m_referencePoint );
+}
+
+int VReference::referencePoint()
+{
+ return( m_referencePoint );
+}
+
+#include "vreference.moc"
+
diff --git a/karbon/widgets/vruler.cc b/karbon/widgets/vruler.cpp
index c0ff0a201..c0ff0a201 100644
--- a/karbon/widgets/vruler.cc
+++ b/karbon/widgets/vruler.cpp
diff --git a/karbon/widgets/vselecttoolbar.cc b/karbon/widgets/vselecttoolbar.cc
deleted file mode 100644
index 2e32a6773..000000000
--- a/karbon/widgets/vselecttoolbar.cc
+++ /dev/null
@@ -1,124 +0,0 @@
-/* This file is part of the KDE project
- Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
- Copyright (C) 2002, The Karbon Developers
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/* vselecttoolbar.cc */
-
-#include <tqlabel.h>
-
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include "KoUnitWidgets.h"
-#include "vselecttoolbar.h"
-#include "karbon_view.h"
-#include "karbon_part.h"
-#include "vselection.h"
-#include "vtransformcmd.h"
-#include <KoRect.h>
-
-VSelectToolBar::VSelectToolBar( KarbonView *view, const char* name ) : TDEToolBar( view, name ), m_view( view )
-{
- setCaption( i18n( "Object Properties" ) );
- TQLabel *x_label = new TQLabel( i18n( "X:" ), this, "tde toolbar widget" );
- insertWidget( 0, x_label->width(), x_label );
- m_x = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
- connect( m_x, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotXChanged( double ) ) );
- insertWidget( 1, m_x->width(), m_x );
- TQLabel *y_label = new TQLabel( i18n( "Y:" ), this, "tde toolbar widget" );
- insertWidget( 2, y_label->width(), y_label );
- m_y = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
- connect( m_y, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotYChanged( double ) ) );
- insertWidget( 3, m_y->width(), m_y );
-
- insertSeparator( 4 );
- TQLabel *w_label = new TQLabel( i18n( "selection width", "Width:" ), this, "tde toolbar widget" );
- insertWidget( 5, w_label->width(), w_label );
- m_width = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
- connect( m_width, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotWidthChanged( double ) ) );
- insertWidget( 6, m_width->width(), m_width );
- TQLabel *h_label = new TQLabel( i18n( "Height:" ), this, "tde toolbar widget" );
- insertWidget( 7, h_label->width(), h_label );
- m_height = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
- connect( m_height, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotHeightChanged( double ) ) );
- insertWidget( 8, m_height->width(), m_height );
-
- connect( m_view, TQT_SIGNAL( selectionChange() ), this, TQT_SLOT( slotSelectionChanged() ) );
-}
-
-VSelectToolBar::~VSelectToolBar()
-{
-}
-
-void
-VSelectToolBar::slotXChanged( double newval )
-{
- double dx = newval - m_view->part()->document().selection()->boundingBox().topLeft().x();
- m_view->part()->addCommand( new VTranslateCmd( &m_view->part()->document(), dx, 0.0 ), true );
-}
-
-void
-VSelectToolBar::slotYChanged( double newval )
-{
- double dy = newval - m_view->part()->document().selection()->boundingBox().topLeft().y();
- m_view->part()->addCommand( new VTranslateCmd( &m_view->part()->document(), 0.0, dy ), true );
-}
-
-void
-VSelectToolBar::slotWidthChanged( double newval )
-{
- if( newval != 0.0 )
- {
- double sx = newval / m_view->part()->document().selection()->boundingBox().width();
- KoPoint sp = m_view->part()->document().selection()->boundingBox().topLeft();
- m_view->part()->addCommand( new VScaleCmd( &m_view->part()->document(), sp, sx, 1.0 ), true );
- }
-}
-
-void
-VSelectToolBar::slotHeightChanged( double newval )
-{
- if( newval != 0.0 )
- {
- double sy = newval / m_view->part()->document().selection()->boundingBox().height();
- KoPoint sp = m_view->part()->document().selection()->boundingBox().bottomLeft();
- m_view->part()->addCommand( new VScaleCmd( &m_view->part()->document(), sp, 1.0, sy ), true );
- }
-}
-
-void
-VSelectToolBar::slotSelectionChanged()
-{
- m_x->blockSignals( true );
- m_y->blockSignals( true );
- m_width->blockSignals( true );
- m_height->blockSignals( true );
- KoRect rect = m_view->part()->document().selection()->boundingBox();
- m_x->setValue( rect.topLeft().x() );
- m_y->setValue( rect.topLeft().y() );
- m_width->setValue( rect.width() );
- m_height->setValue( rect.height() );
- m_x->blockSignals( false );
- m_y->blockSignals( false );
- m_width->blockSignals( false );
- m_height->blockSignals( false );
-}
-
-#include "vselecttoolbar.moc"
-
diff --git a/karbon/widgets/vselecttoolbar.cpp b/karbon/widgets/vselecttoolbar.cpp
new file mode 100644
index 000000000..b0dc9a7c8
--- /dev/null
+++ b/karbon/widgets/vselecttoolbar.cpp
@@ -0,0 +1,124 @@
+/* This file is part of the KDE project
+ Made by Tomislav Lukman (tomislav.lukman@ck.tel.hr)
+ Copyright (C) 2002, The Karbon Developers
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/* vselecttoolbar.cpp */
+
+#include <tqlabel.h>
+
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include "KoUnitWidgets.h"
+#include "vselecttoolbar.h"
+#include "karbon_view.h"
+#include "karbon_part.h"
+#include "vselection.h"
+#include "vtransformcmd.h"
+#include <KoRect.h>
+
+VSelectToolBar::VSelectToolBar( KarbonView *view, const char* name ) : TDEToolBar( view, name ), m_view( view )
+{
+ setCaption( i18n( "Object Properties" ) );
+ TQLabel *x_label = new TQLabel( i18n( "X:" ), this, "tde toolbar widget" );
+ insertWidget( 0, x_label->width(), x_label );
+ m_x = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
+ connect( m_x, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotXChanged( double ) ) );
+ insertWidget( 1, m_x->width(), m_x );
+ TQLabel *y_label = new TQLabel( i18n( "Y:" ), this, "tde toolbar widget" );
+ insertWidget( 2, y_label->width(), y_label );
+ m_y = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
+ connect( m_y, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotYChanged( double ) ) );
+ insertWidget( 3, m_y->width(), m_y );
+
+ insertSeparator( 4 );
+ TQLabel *w_label = new TQLabel( i18n( "selection width", "Width:" ), this, "tde toolbar widget" );
+ insertWidget( 5, w_label->width(), w_label );
+ m_width = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
+ connect( m_width, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotWidthChanged( double ) ) );
+ insertWidget( 6, m_width->width(), m_width );
+ TQLabel *h_label = new TQLabel( i18n( "Height:" ), this, "tde toolbar widget" );
+ insertWidget( 7, h_label->width(), h_label );
+ m_height = new KoUnitDoubleSpinBox( this, 0.0, 1000.0, 0.5 );
+ connect( m_height, TQT_SIGNAL( valueChanged( double ) ), this, TQT_SLOT( slotHeightChanged( double ) ) );
+ insertWidget( 8, m_height->width(), m_height );
+
+ connect( m_view, TQT_SIGNAL( selectionChange() ), this, TQT_SLOT( slotSelectionChanged() ) );
+}
+
+VSelectToolBar::~VSelectToolBar()
+{
+}
+
+void
+VSelectToolBar::slotXChanged( double newval )
+{
+ double dx = newval - m_view->part()->document().selection()->boundingBox().topLeft().x();
+ m_view->part()->addCommand( new VTranslateCmd( &m_view->part()->document(), dx, 0.0 ), true );
+}
+
+void
+VSelectToolBar::slotYChanged( double newval )
+{
+ double dy = newval - m_view->part()->document().selection()->boundingBox().topLeft().y();
+ m_view->part()->addCommand( new VTranslateCmd( &m_view->part()->document(), 0.0, dy ), true );
+}
+
+void
+VSelectToolBar::slotWidthChanged( double newval )
+{
+ if( newval != 0.0 )
+ {
+ double sx = newval / m_view->part()->document().selection()->boundingBox().width();
+ KoPoint sp = m_view->part()->document().selection()->boundingBox().topLeft();
+ m_view->part()->addCommand( new VScaleCmd( &m_view->part()->document(), sp, sx, 1.0 ), true );
+ }
+}
+
+void
+VSelectToolBar::slotHeightChanged( double newval )
+{
+ if( newval != 0.0 )
+ {
+ double sy = newval / m_view->part()->document().selection()->boundingBox().height();
+ KoPoint sp = m_view->part()->document().selection()->boundingBox().bottomLeft();
+ m_view->part()->addCommand( new VScaleCmd( &m_view->part()->document(), sp, 1.0, sy ), true );
+ }
+}
+
+void
+VSelectToolBar::slotSelectionChanged()
+{
+ m_x->blockSignals( true );
+ m_y->blockSignals( true );
+ m_width->blockSignals( true );
+ m_height->blockSignals( true );
+ KoRect rect = m_view->part()->document().selection()->boundingBox();
+ m_x->setValue( rect.topLeft().x() );
+ m_y->setValue( rect.topLeft().y() );
+ m_width->setValue( rect.width() );
+ m_height->setValue( rect.height() );
+ m_x->blockSignals( false );
+ m_y->blockSignals( false );
+ m_width->blockSignals( false );
+ m_height->blockSignals( false );
+}
+
+#include "vselecttoolbar.moc"
+
diff --git a/karbon/widgets/vsmallpreview.cc b/karbon/widgets/vsmallpreview.cc
deleted file mode 100644
index 28a8dd27d..000000000
--- a/karbon/widgets/vsmallpreview.cc
+++ /dev/null
@@ -1,282 +0,0 @@
-/* This file is part of the KDE project
- Made by Tomislav Lukman (tomislav.lukman@ck.t-com.hr)
- Copyright (C) 2005, The Karbon Developers
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-/* vsmallpreview.cc */
-#include <tqcolor.h>
-#include <tqframe.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqpixmap.h>
-
-#include <tdelocale.h>
-#include <KoPoint.h>
-
-#include "vcolor.h"
-#include "vfill.h"
-#include "vgradient.h"
-#include "vkopainter.h"
-#include "vpattern.h"
-#include "vstroke.h"
-
-#include "vsmallpreview.h"
-
-#define FRAMEWIDTH 40
-
-VSmallPreview::VSmallPreview( TQWidget* parent, const char* name )
- : TQWidget( parent, name )
-{
- /* Create widget layout */
- TQHBoxLayout *layout = new TQHBoxLayout( this, 4 );
- m_strokeLabel = new TQLabel( i18n( "Stroke: None" ), this );
- layout->addWidget( m_strokeLabel );
- m_strokeFrame = new TQFrame( this );
- m_strokeFrame->setFixedWidth ( FRAMEWIDTH );
- m_strokeFrame->setFrameStyle( TQFrame::GroupBoxPanel | TQFrame::Plain );
- layout->addWidget( m_strokeFrame );
- m_fillLabel = new TQLabel( i18n( "Fill: None" ), this );
- layout->addWidget( m_fillLabel );
- m_fillFrame = new TQFrame( this );
- m_fillFrame->setFixedWidth ( FRAMEWIDTH );
- m_fillFrame->setFrameStyle( TQFrame::GroupBoxPanel | TQFrame::Plain );
- layout->addWidget( m_fillFrame );
- layout->activate();
-
- m_fill = VFill();
- m_stroke = VStroke();
-}
-
-VSmallPreview::~VSmallPreview()
-{
-}
-
-void
-VSmallPreview::update( const VStroke &s, const VFill &f )
-{
- if( &f )
- m_fill = f;
- else
- m_fill = VFill();
- if( &s )
- m_stroke = s;
- else
- m_stroke = VStroke();
-
- drawStroke( m_stroke );
- drawFill( m_fill );
-}
-
-void
-VSmallPreview::paintEvent( TQPaintEvent* /*event*/ )
-{
- drawStroke( m_stroke );
- drawFill( m_fill );
-}
-
-void
-VSmallPreview::drawFill( const VFill &f )
-{
- VFill fill;
- VStroke stroke;
-
- TQPixmap m_pixmap;
- m_pixmap.resize( m_fillFrame->width(), m_fillFrame->height() );
- VKoPainter* m_painter = new VKoPainter( TQT_TQPAINTDEVICE(&m_pixmap), m_fillFrame->width(), m_fillFrame->height() );
-
- m_painter->begin();
- m_painter->setPen( TQt::NoPen );
- fill.setColor( TQt::white );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
-
- switch ( f.type() )
- {
- case VFill::solid:
- {
- switch ( f.color().colorSpace() )
- {
- case VColor::rgb:
- m_fillLabel->setText( i18n( "Fill: RGB") ); break;
- case VColor::cmyk:
- m_fillLabel->setText( i18n( "Fill: CMYK") ); break;
- case VColor::hsb:
- m_fillLabel->setText( i18n( "Fill: HSB") ); break;
- case VColor::gray:
- m_fillLabel->setText( i18n( "Fill: Grayscale") ); break;
- default:
- m_fillLabel->setText( i18n( "Fill: Color") );
- }
- fill.setColor( f.color() );
- break;
- }
- case VFill::grad:
- {
- fill.gradient() = f.gradient();
- fill.setType( VFill::grad );
- m_fillLabel->setText( i18n( "Fill: Gradient") );
- if( f.gradient().type() == VGradient::linear )
- {
- fill.gradient().setOrigin( KoPoint( m_fillFrame->width() * 0.5, 0 ) );
- fill.gradient().setVector( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() ) );
- }
- else if( f.gradient().type() == VGradient::radial ||
- f.gradient().type() == VGradient::conic )
- {
- fill.gradient().setOrigin( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() * 0.5 ) );
- fill.gradient().setFocalPoint( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() * 0.5 ) );
- fill.gradient().setVector( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() ) );
- }
- break;
-
- }
- case VFill::patt:
- {
- fill.pattern() = f.pattern();
- fill.pattern().setOrigin( KoPoint( 0, 0 ) );
- fill.pattern().setVector( KoPoint( m_fillFrame->width() * 0.5, 0 ) );
- fill.setType( VFill::patt );
- m_fillLabel->setText( i18n( "Fill: Pattern") );
- break;
- }
- default: //None or unknown
- {
- m_fillLabel->setText( i18n( "Fill: None") );
- fill.setColor( TQt::white );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
- stroke.setColor( TQt::red );
- stroke.setLineWidth( 2.0 );
- m_painter->setPen( stroke );
- m_painter->newPath();
- m_painter->moveTo( KoPoint( 4, m_fillFrame->height() - 4 ) );
- m_painter->lineTo( KoPoint( m_fillFrame->width() - 4, 4 ) );
- m_painter->strokePath();
- }
- }
-
- if( f.type() != VFill::none )
- {
- m_painter->setPen( stroke );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
- }
-
- m_painter->end();
-
- bitBlt( m_fillFrame, m_fillFrame->frameWidth(), m_fillFrame->frameWidth(), &m_pixmap, m_fillFrame->frameWidth(), m_fillFrame->frameWidth(), m_fillFrame->width() - m_fillFrame->frameWidth(), m_fillFrame->height() - m_fillFrame->frameWidth(), CopyROP );
-
- delete ( m_painter );
-}
-
-void
-VSmallPreview::drawStroke( const VStroke &s )
-{
- VFill fill;
- VStroke stroke;
-
- TQPixmap m_pixmap;
- m_pixmap.resize( m_fillFrame->width(), m_fillFrame->height() );
- VKoPainter* m_painter = new VKoPainter( TQT_TQPAINTDEVICE(&m_pixmap), m_fillFrame->width(), m_fillFrame->height() );
-
- m_painter->begin();
- m_painter->setPen( TQt::NoPen );
- fill.setColor( TQt::white );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
-
- switch ( s.type() )
- {
- case VStroke::solid:
- {
- switch ( s.color().colorSpace() )
- {
- case VColor::rgb:
- m_strokeLabel->setText( i18n( "Stroke: RGB") ); break;
- case VColor::cmyk:
- m_strokeLabel->setText( i18n( "Stroke: CMYK") ); break;
- case VColor::hsb:
- m_strokeLabel->setText( i18n( "Stroke: HSB") ); break;
- case VColor::gray:
- m_strokeLabel->setText( i18n( "Stroke: Grayscale") ); break;
- default:
- m_strokeLabel->setText( i18n( "Stroke: Color") );
- }
- fill.setColor( s.color() );
- break;
- }
- case VStroke::grad:
- {
- fill.gradient() = s.gradient();
- fill.setType( VFill::grad );
- m_strokeLabel->setText( i18n( "Stroke: Gradient") );
- if( s.gradient().type() == VGradient::linear )
- {
- fill.gradient().setOrigin( KoPoint( m_strokeFrame->width() * 0.5, 0 ) );
- fill.gradient().setVector( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() ) );
- }
- else if( s.gradient().type() == VGradient::radial ||
- s.gradient().type() == VGradient::conic )
- {
- fill.gradient().setOrigin( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() * 0.5 ) );
- fill.gradient().setFocalPoint( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() * 0.5 ) );
- fill.gradient().setVector( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() ) );
- }
- break;
- }
- case VStroke::patt:
- {
- fill.pattern() = s.pattern();
- fill.pattern().setOrigin( KoPoint( 0, 0 ) );
- fill.pattern().setVector( KoPoint( m_strokeFrame->width() * 0.5, 0 ) );
- fill.setType( VFill::patt );
- m_strokeLabel->setText( i18n( "Stroke: Pattern") );
- break;
- }
- default: //None or unknown
- {
- m_strokeLabel->setText( i18n( "Stroke: None") );
- fill.setColor( TQt::white );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
- stroke.setColor( TQt::red );
- stroke.setLineWidth( 2.0 );
- m_painter->setPen( stroke );
- m_painter->newPath();
- m_painter->moveTo( KoPoint( 4, m_strokeFrame->height() - 4 ) );
- m_painter->lineTo( KoPoint( m_strokeFrame->width() - 4, 4 ) );
- m_painter->strokePath();
- }
- }
-
- if( s.type() != VStroke::none )
- {
- m_painter->setPen( stroke );
- m_painter->setBrush( fill );
- m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
- }
-
- m_painter->end();
-
- bitBlt( m_strokeFrame, m_strokeFrame->frameWidth(), m_strokeFrame->frameWidth(), &m_pixmap, m_strokeFrame->frameWidth(), m_strokeFrame->frameWidth(), m_strokeFrame->width() - m_strokeFrame->frameWidth(), m_strokeFrame->height() - m_strokeFrame->frameWidth(), CopyROP );
-
- delete ( m_painter );
-}
-
-#include "vsmallpreview.moc"
-
diff --git a/karbon/widgets/vsmallpreview.cpp b/karbon/widgets/vsmallpreview.cpp
new file mode 100644
index 000000000..c422104ea
--- /dev/null
+++ b/karbon/widgets/vsmallpreview.cpp
@@ -0,0 +1,282 @@
+/* This file is part of the KDE project
+ Made by Tomislav Lukman (tomislav.lukman@ck.t-com.hr)
+ Copyright (C) 2005, The Karbon Developers
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+/* vsmallpreview.cpp */
+#include <tqcolor.h>
+#include <tqframe.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqpixmap.h>
+
+#include <tdelocale.h>
+#include <KoPoint.h>
+
+#include "vcolor.h"
+#include "vfill.h"
+#include "vgradient.h"
+#include "vkopainter.h"
+#include "vpattern.h"
+#include "vstroke.h"
+
+#include "vsmallpreview.h"
+
+#define FRAMEWIDTH 40
+
+VSmallPreview::VSmallPreview( TQWidget* parent, const char* name )
+ : TQWidget( parent, name )
+{
+ /* Create widget layout */
+ TQHBoxLayout *layout = new TQHBoxLayout( this, 4 );
+ m_strokeLabel = new TQLabel( i18n( "Stroke: None" ), this );
+ layout->addWidget( m_strokeLabel );
+ m_strokeFrame = new TQFrame( this );
+ m_strokeFrame->setFixedWidth ( FRAMEWIDTH );
+ m_strokeFrame->setFrameStyle( TQFrame::GroupBoxPanel | TQFrame::Plain );
+ layout->addWidget( m_strokeFrame );
+ m_fillLabel = new TQLabel( i18n( "Fill: None" ), this );
+ layout->addWidget( m_fillLabel );
+ m_fillFrame = new TQFrame( this );
+ m_fillFrame->setFixedWidth ( FRAMEWIDTH );
+ m_fillFrame->setFrameStyle( TQFrame::GroupBoxPanel | TQFrame::Plain );
+ layout->addWidget( m_fillFrame );
+ layout->activate();
+
+ m_fill = VFill();
+ m_stroke = VStroke();
+}
+
+VSmallPreview::~VSmallPreview()
+{
+}
+
+void
+VSmallPreview::update( const VStroke &s, const VFill &f )
+{
+ if( &f )
+ m_fill = f;
+ else
+ m_fill = VFill();
+ if( &s )
+ m_stroke = s;
+ else
+ m_stroke = VStroke();
+
+ drawStroke( m_stroke );
+ drawFill( m_fill );
+}
+
+void
+VSmallPreview::paintEvent( TQPaintEvent* /*event*/ )
+{
+ drawStroke( m_stroke );
+ drawFill( m_fill );
+}
+
+void
+VSmallPreview::drawFill( const VFill &f )
+{
+ VFill fill;
+ VStroke stroke;
+
+ TQPixmap m_pixmap;
+ m_pixmap.resize( m_fillFrame->width(), m_fillFrame->height() );
+ VKoPainter* m_painter = new VKoPainter( TQT_TQPAINTDEVICE(&m_pixmap), m_fillFrame->width(), m_fillFrame->height() );
+
+ m_painter->begin();
+ m_painter->setPen( TQt::NoPen );
+ fill.setColor( TQt::white );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
+
+ switch ( f.type() )
+ {
+ case VFill::solid:
+ {
+ switch ( f.color().colorSpace() )
+ {
+ case VColor::rgb:
+ m_fillLabel->setText( i18n( "Fill: RGB") ); break;
+ case VColor::cmyk:
+ m_fillLabel->setText( i18n( "Fill: CMYK") ); break;
+ case VColor::hsb:
+ m_fillLabel->setText( i18n( "Fill: HSB") ); break;
+ case VColor::gray:
+ m_fillLabel->setText( i18n( "Fill: Grayscale") ); break;
+ default:
+ m_fillLabel->setText( i18n( "Fill: Color") );
+ }
+ fill.setColor( f.color() );
+ break;
+ }
+ case VFill::grad:
+ {
+ fill.gradient() = f.gradient();
+ fill.setType( VFill::grad );
+ m_fillLabel->setText( i18n( "Fill: Gradient") );
+ if( f.gradient().type() == VGradient::linear )
+ {
+ fill.gradient().setOrigin( KoPoint( m_fillFrame->width() * 0.5, 0 ) );
+ fill.gradient().setVector( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() ) );
+ }
+ else if( f.gradient().type() == VGradient::radial ||
+ f.gradient().type() == VGradient::conic )
+ {
+ fill.gradient().setOrigin( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() * 0.5 ) );
+ fill.gradient().setFocalPoint( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() * 0.5 ) );
+ fill.gradient().setVector( KoPoint( m_fillFrame->width() * 0.5, m_fillFrame->height() ) );
+ }
+ break;
+
+ }
+ case VFill::patt:
+ {
+ fill.pattern() = f.pattern();
+ fill.pattern().setOrigin( KoPoint( 0, 0 ) );
+ fill.pattern().setVector( KoPoint( m_fillFrame->width() * 0.5, 0 ) );
+ fill.setType( VFill::patt );
+ m_fillLabel->setText( i18n( "Fill: Pattern") );
+ break;
+ }
+ default: //None or unknown
+ {
+ m_fillLabel->setText( i18n( "Fill: None") );
+ fill.setColor( TQt::white );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
+ stroke.setColor( TQt::red );
+ stroke.setLineWidth( 2.0 );
+ m_painter->setPen( stroke );
+ m_painter->newPath();
+ m_painter->moveTo( KoPoint( 4, m_fillFrame->height() - 4 ) );
+ m_painter->lineTo( KoPoint( m_fillFrame->width() - 4, 4 ) );
+ m_painter->strokePath();
+ }
+ }
+
+ if( f.type() != VFill::none )
+ {
+ m_painter->setPen( stroke );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_fillFrame->width(), m_fillFrame->height() ) );
+ }
+
+ m_painter->end();
+
+ bitBlt( m_fillFrame, m_fillFrame->frameWidth(), m_fillFrame->frameWidth(), &m_pixmap, m_fillFrame->frameWidth(), m_fillFrame->frameWidth(), m_fillFrame->width() - m_fillFrame->frameWidth(), m_fillFrame->height() - m_fillFrame->frameWidth(), CopyROP );
+
+ delete ( m_painter );
+}
+
+void
+VSmallPreview::drawStroke( const VStroke &s )
+{
+ VFill fill;
+ VStroke stroke;
+
+ TQPixmap m_pixmap;
+ m_pixmap.resize( m_fillFrame->width(), m_fillFrame->height() );
+ VKoPainter* m_painter = new VKoPainter( TQT_TQPAINTDEVICE(&m_pixmap), m_fillFrame->width(), m_fillFrame->height() );
+
+ m_painter->begin();
+ m_painter->setPen( TQt::NoPen );
+ fill.setColor( TQt::white );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
+
+ switch ( s.type() )
+ {
+ case VStroke::solid:
+ {
+ switch ( s.color().colorSpace() )
+ {
+ case VColor::rgb:
+ m_strokeLabel->setText( i18n( "Stroke: RGB") ); break;
+ case VColor::cmyk:
+ m_strokeLabel->setText( i18n( "Stroke: CMYK") ); break;
+ case VColor::hsb:
+ m_strokeLabel->setText( i18n( "Stroke: HSB") ); break;
+ case VColor::gray:
+ m_strokeLabel->setText( i18n( "Stroke: Grayscale") ); break;
+ default:
+ m_strokeLabel->setText( i18n( "Stroke: Color") );
+ }
+ fill.setColor( s.color() );
+ break;
+ }
+ case VStroke::grad:
+ {
+ fill.gradient() = s.gradient();
+ fill.setType( VFill::grad );
+ m_strokeLabel->setText( i18n( "Stroke: Gradient") );
+ if( s.gradient().type() == VGradient::linear )
+ {
+ fill.gradient().setOrigin( KoPoint( m_strokeFrame->width() * 0.5, 0 ) );
+ fill.gradient().setVector( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() ) );
+ }
+ else if( s.gradient().type() == VGradient::radial ||
+ s.gradient().type() == VGradient::conic )
+ {
+ fill.gradient().setOrigin( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() * 0.5 ) );
+ fill.gradient().setFocalPoint( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() * 0.5 ) );
+ fill.gradient().setVector( KoPoint( m_strokeFrame->width() * 0.5, m_strokeFrame->height() ) );
+ }
+ break;
+ }
+ case VStroke::patt:
+ {
+ fill.pattern() = s.pattern();
+ fill.pattern().setOrigin( KoPoint( 0, 0 ) );
+ fill.pattern().setVector( KoPoint( m_strokeFrame->width() * 0.5, 0 ) );
+ fill.setType( VFill::patt );
+ m_strokeLabel->setText( i18n( "Stroke: Pattern") );
+ break;
+ }
+ default: //None or unknown
+ {
+ m_strokeLabel->setText( i18n( "Stroke: None") );
+ fill.setColor( TQt::white );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
+ stroke.setColor( TQt::red );
+ stroke.setLineWidth( 2.0 );
+ m_painter->setPen( stroke );
+ m_painter->newPath();
+ m_painter->moveTo( KoPoint( 4, m_strokeFrame->height() - 4 ) );
+ m_painter->lineTo( KoPoint( m_strokeFrame->width() - 4, 4 ) );
+ m_painter->strokePath();
+ }
+ }
+
+ if( s.type() != VStroke::none )
+ {
+ m_painter->setPen( stroke );
+ m_painter->setBrush( fill );
+ m_painter->drawRect( KoRect( 0, 0, m_strokeFrame->width(), m_strokeFrame->height() ) );
+ }
+
+ m_painter->end();
+
+ bitBlt( m_strokeFrame, m_strokeFrame->frameWidth(), m_strokeFrame->frameWidth(), &m_pixmap, m_strokeFrame->frameWidth(), m_strokeFrame->frameWidth(), m_strokeFrame->width() - m_strokeFrame->frameWidth(), m_strokeFrame->height() - m_strokeFrame->frameWidth(), CopyROP );
+
+ delete ( m_painter );
+}
+
+#include "vsmallpreview.moc"
+
diff --git a/karbon/widgets/vstatebutton.cc b/karbon/widgets/vstatebutton.cpp
index 1ea8e27a7..1ea8e27a7 100644
--- a/karbon/widgets/vstatebutton.cc
+++ b/karbon/widgets/vstatebutton.cpp
diff --git a/karbon/widgets/vstrokefillpreview.cc b/karbon/widgets/vstrokefillpreview.cpp
index f69d5d855..f69d5d855 100644
--- a/karbon/widgets/vstrokefillpreview.cc
+++ b/karbon/widgets/vstrokefillpreview.cpp
diff --git a/karbon/widgets/vtoolbox.cc b/karbon/widgets/vtoolbox.cpp
index e048555cb..e048555cb 100644
--- a/karbon/widgets/vtoolbox.cc
+++ b/karbon/widgets/vtoolbox.cpp
diff --git a/karbon/widgets/vtranslate.cc b/karbon/widgets/vtranslate.cpp
index 35a25a719..35a25a719 100644
--- a/karbon/widgets/vtranslate.cc
+++ b/karbon/widgets/vtranslate.cpp
diff --git a/karbon/widgets/vtypebuttonbox.cc b/karbon/widgets/vtypebuttonbox.cpp
index 9a98a125a..9a98a125a 100644
--- a/karbon/widgets/vtypebuttonbox.cc
+++ b/karbon/widgets/vtypebuttonbox.cpp
diff --git a/kchart/ChangeLog b/kchart/ChangeLog
index 5d38df2f5..1d9263a9b 100644
--- a/kchart/ChangeLog
+++ b/kchart/ChangeLog
@@ -13,16 +13,16 @@
Start on bug 134194: Impossible to change the data range.
Step 1: Actually set and read the data area.
* kchart_params.h: store the data area in the params.
- * kchartDataConfigPage.cc (init): Set dataArea lineEdit.
+ * kchartDataConfigPage.cpp (init): Set dataArea lineEdit.
(defaults): clear it
(apply): set dataArea from the lineEdit
- * kchartWizardSelectDataFormatPage.cc (constructor): set dataArea lineEdit
+ * kchartWizardSelectDataFormatPage.cpp (constructor): set dataArea lineEdit
(apply): set dataArea from the lineEdit
2006-11-06 Inge Wallin <inge@lysator.liu.se>
Fix bug 128758: misinterpretation of the checkbox "first row as label"
- * kchart_part.cc (createLabelsAndLegend): Pass parameters as
+ * kchart_part.cpp (createLabelsAndLegend): Pass parameters as
references.
2006-10-29 Inge Wallin <inge@lysator.liu.se>
@@ -31,38 +31,38 @@
2006-10-10 Inge Wallin <inge@lysator.liu.se>
- * kchart_params.cc (saveOasisAxis): Add saving of axis titles.
+ * kchart_params.cpp (saveOasisAxis): Add saving of axis titles.
2006-10-06 ---- Version 1.6.0 tagged ----
2006-10-03 Inge Wallin <inge@lysator.liu.se>
- * kchart_params.cc (loadOasisPlotarea): Fix bug. Pie charts use
+ * kchart_params.cpp (loadOasisPlotarea): Fix bug. Pie charts use
only the y axis, not only the x axis.
2006-09-28 Inge Wallin <inge@lysator.liu.se>
- * kchart_params.cc (loadOasisPlotarea): Add support for
+ * kchart_params.cpp (loadOasisPlotarea): Add support for
chart:series-source (row or column):
2006-08-11 Inge Wallin <inge@lysator.liu.se>
Only show checkboxes in config dialog if applicable.
* kchart_params.h (KChartParams::part): new method
- * kchartDataConfigPage.cc: Only show the checkboxes "First row/col
+ * kchartDataConfigPage.cpp: Only show the checkboxes "First row/col
as headers" if we have external data.
2006-08-06 Inge Wallin <inge@lysator.liu.se>
Disable "First row/col as label in the data editor.
- * kchartDataEditor.cc (kchartDataEditor): Disable checkboxes
+ * kchartDataEditor.cpp (kchartDataEditor): Disable checkboxes
2006-08-04 Inge Wallin <inge@lysator.liu.se>
Let the Data Editor use icons for it's buttons.
- * kchartDataEditor.cc (kchartDataEditor): Make the insert / delete
+ * kchartDataEditor.cpp (kchartDataEditor): Make the insert / delete
row / col buttons show an icon instead of text.
- * kchartDataEditor.cc (addDocs): Add ToolTips to the buttons.
+ * kchartDataEditor.cpp (addDocs): Add ToolTips to the buttons.
2006-07-18 Inge Wallin <inge@lysator.liu.se>
@@ -71,7 +71,7 @@
* kchartDataEditor.{h,cc} (currentChanged): New method
(m_insertRowButton, m_removeRowButton, m_insertRowButton,
m_removeRowButton): New members
- * kchartDataEditor.cc (removeCurrentRow, removeCurrentCol): Don't
+ * kchartDataEditor.cpp (removeCurrentRow, removeCurrentCol): Don't
allow to remove a row or column if it's the first column or if
there are only 2 of them.
@@ -80,9 +80,9 @@
2006-07-17 Inge Wallin <inge@lysator.liu.se>
Add "first row/col as legend" checkboxes to data editor.
- * kchartDataEditor.cc (kchartDataEditor): Enable existing code
- * kchartDataEditor.cc (setData): Enable existing code
- * kchartDataEditor.cc (getData): Enable existing code
+ * kchartDataEditor.cpp (kchartDataEditor): Enable existing code
+ * kchartDataEditor.cpp (setData): Enable existing code
+ * kchartDataEditor.cpp (getData): Enable existing code
Simplify paintContent():
* kchart_part.{h,cc} (createLabelsAndLegend): New function
@@ -99,7 +99,7 @@
Fix bug 108770: [PATCH] kchart should have a format menu
* kchart.rc (Format): New menu
(KChartTypes toolbar): place to the left
- * kchart_view.cc (KChartView::KChartView): change strings for some
+ * kchart_view.cpp (KChartView::KChartView): change strings for some
actions.
2005-08-08 Inge Wallin <inge@lysator.liu.se>
@@ -110,7 +110,7 @@
2005-07-28 Inge Wallin <inge@lysator.liu.se>
Fix bug 108461: Bug in generation of HiLo charts
- * kchart_part.cc (paintContent): Add code to handle HiLo chart
+ * kchart_part.cpp (paintContent): Add code to handle HiLo chart
separately.
General code cleaning.
@@ -153,7 +153,7 @@
* kdchart/KDChartParams.h (lineColor): return _lineColor again.
* kdchart/KDChartParams_io.h (saveXML): Only save the line color
if it is non-null.
- * kchart_part.cc (setAxisDefaults): Always set lineColor to
+ * kchart_part.cpp (setAxisDefaults): Always set lineColor to
null. This compensates for the (now fixed) bug in saving when
reading back old charts.
@@ -169,7 +169,7 @@
Fix bug 99995: KChart should be able to import CSV data
* kchart_part.{h,cc} (doSetData): new method broken out of setData()
(setData): Call doSetData
- kchart_view.cc (importData): Get data from the dialog and call
+ kchart_view.cpp (importData): Get data from the dialog and call
KChartPart::doSetData()
Code cleaning
@@ -195,7 +195,7 @@
negative numbers in a 3D bar chart. If all bars are <= 0 the bars
with value 0 will still have an arrow.
- * kchart_part.cc (KChartPart), kchart_params.cc (KChartParams):
+ * kchart_part.cpp (KChartPart), kchart_params.cpp (KChartParams):
Make sure the excess arrow is solid by calling
setDrawSolidExcessArrows(true) after a chart has been loaded or
created.
@@ -203,7 +203,7 @@
2005-04-13 Inge Wallin <inge@lysator.liu.se>
CSV import: Disable irrelevant formats
- * csvimportdialog.cc (CSVImportDialog): Disable formats Currency
+ * csvimportdialog.cpp (CSVImportDialog): Disable formats Currency
and Date.
Disable "Import Data" if inside KSpread
@@ -214,7 +214,7 @@
Get a file name for "Import Data" and actually read data.
(No new strings).
- * kchart_view.cc (importData): Open a file dialog, and read data.
+ * kchart_view.cpp (importData): Open a file dialog, and read data.
----------------------------------------------------------------
@@ -224,31 +224,31 @@
* csvimportdialogui.ui: new file
* Makefile.am: Add files above
* kchart.rc (File menu): Add Action import_data
- * kchart_view.cc (import_data): new TDEAction
+ * kchart_view.cpp (import_data): new TDEAction
(importData): new slot
2005-04-10 Inge Wallin <inge@lysator.liu.se>
Fix the margins on the pie config page.
- * kchartParameterPieConfigPage.cc (KChartParameterPieConfigPage):
+ * kchartParameterPieConfigPage.cpp (KChartParameterPieConfigPage):
Added a toplevel layout.
2005-04-07 Fredrik Edemar <f_edemar@linux.se>
- * kchart_part.cc (KChartPart): Set modified when the chart type is
+ * kchart_part.cpp (KChartPart): Set modified when the chart type is
changed.
2005-04-07 Inge Wallin <inge@lysator.liu.se>
- * kchartWizardLabelsLegendPage.cc (KChartWizardLabelsLegendPage):
+ * kchartWizardLabelsLegendPage.cpp (KChartWizardLabelsLegendPage):
Reenable titles for X and Y axis.
2005-04-07 Fredrik Edemar <f_edemar@linux.se>
- * kchart_part.cc (KChartPart): The decimal symbol and thousends
+ * kchart_part.cpp (KChartPart): The decimal symbol and thousends
separator is the same as the rest of KDE.
- * kchart_params.cc (KChartParams): Revert my last change: use
+ * kchart_params.cpp (KChartParams): Revert my last change: use
KDChart's default precision instead.
* KDChart (KDChartAxesPainter.cpp): The axis label: Use at most 6
digits after the decimal point.
@@ -258,7 +258,7 @@
Fix bug 103267: Unreasonable precison in axis values
* kchartParameterConfigPage.{h,cc} (KChartParameterConfigPage):
Add settings for decimal precision for the left axis.
- * kchart_params.cc (KChartParams): Set 2 as default decimal
+ * kchart_params.cpp (KChartParams): Set 2 as default decimal
precision.
* KDChart: If the totalLen property is >0, the text label should
be truncated at the position of totalLen.
@@ -268,7 +268,7 @@
2005-04-06 Inge Wallin <inge@lysator.liu.se>
Enable axis titles again.
- * kchartParameterConfigPage.cc (KChartParameterConfigPage): Don't
+ * kchartParameterConfigPage.cpp (KChartParameterConfigPage): Don't
disable xtitle and ytitle.
----------------------------------------------------------------
@@ -276,15 +276,15 @@
Fix line specific settings
* kchartConfigDialog.{h,cc} (linepage3d): resurrected page
(all members except
- * kchartLine3dConfigPage.cc (lineMarkers): new method
+ * kchartLine3dConfigPage.cpp (lineMarkers): new method
(all 3d stuff): disabled
- * kchartParameterConfigPage.cc (lineMarker): moved to the line
+ * kchartParameterConfigPage.cpp (lineMarker): moved to the line
page.
----------------------------------------------------------------
Fix pie specific settings.
- * kchartConfigDialog.cc (constructor): Move all type specific
+ * kchartConfigDialog.cpp (constructor): Move all type specific
settings immediately after the subtype page.
(constructor): disable the piepage.
* kchartParameterPieConfigPage.{h,cc} (explode): new member
@@ -292,10 +292,10 @@
* kchartPieConfigPage (explose): Moved to kchartParameterPieConfigPage.
Code cleaning
- * kchartConfigDialog.cc (constructor): order initializations
+ * kchartConfigDialog.cpp (constructor): order initializations
logically
(all): Fix indentation and other smaller stuff.
- * kchart_view.cc: Remove reduntant variable actionExtraCreateTemplate.
+ * kchart_view.cpp: Remove reduntant variable actionExtraCreateTemplate.
2005-04-05 Fredrik Edemar <f_edemar@linux.se>
* Use a better layout in KChartParameterPieConfigPage and KChartParameterPolarConfigPage.
@@ -328,7 +328,7 @@
Fix bug 102414: KChart shows the startup dialog even when embedded
into a spreadsheet.
- * kchart_part.cc (constructor): Initialize members but don't call
+ * kchart_part.cpp (constructor): Initialize members but don't call
initDoc().
(initDoc): don't initialize members, and return immediately if
called for an embedded chart.
@@ -342,14 +342,14 @@
(misc): set m_modified if data changed, including headers.
* kchart_part.{h,cc} (slotModified): new slot
(setData): connect wizard::finished() with slotModified
- * kchart_view.cc (edit, apply, wizard): call setModified() in document
+ * kchart_view.cpp (edit, apply, wizard): call setModified() in document
2005-03-23 Inge Wallin <inge@lysator.liu.se>
Implement wish 45358: KChart start up dialog?
- * kchart_part.cc (initNullChart): New method
+ * kchart_part.cpp (initNullChart): New method
(initDoc): Call KoTemplateChooseDia().
- * kchart_view.cc (KChartView): Don't initialize the standard chart.
+ * kchart_view.cpp (KChartView): Don't initialize the standard chart.
----------------------------------------------------------------
@@ -361,7 +361,7 @@
----------------------------------------------------------------
Bug fix.
- * kchartDataEditor.cc (setCols): Set width for all new columns.
+ * kchartDataEditor.cpp (setCols): Set width for all new columns.
(misc): Code cleaning
Code cleaning
@@ -382,22 +382,22 @@
2005-03-18 Inge Wallin <inge@lysator.liu.se>
Improve layout for 3D bar chart parameters.
- * kchartParameter3dConfigPage.cc (KChartParameter3dConfigPage):
+ * kchartParameter3dConfigPage.cpp (KChartParameter3dConfigPage):
Improve layout.
2005-03-17 Inge Wallin <inge@lysator.liu.se>
Remove the 3D Line Parameters page from the config dialog due to
general uselessness and uglyness.
- * kchartConfigDialog.cc (KChartConfigDialog): Disabled 3D Line
+ * kchartConfigDialog.cpp (KChartConfigDialog): Disabled 3D Line
page.
- * kchartLine3dConfigPage.cc (constructor): Changed layout
+ * kchartLine3dConfigPage.cpp (constructor): Changed layout
somewhat, during the experiments.
----------------------------------------------------------------
Fix the uglyness of the font config dialog.
- * kchartFontConfigPage.cc (KChartFontConfigPage): Add some stretch
+ * kchartFontConfigPage.cpp (KChartFontConfigPage): Add some stretch
in suitable places.
----------------------------------------------------------------
@@ -432,13 +432,13 @@
----------------------------------------------------------------
Don't include kchartDataEditor.h where is shouldn't be included.
- * kchartBarConfigDialog.cc, kchartColorConfigPage.cc,
- kchartDataConfigPage.cc: remove it, and include koChart.h instead
+ * kchartBarConfigDialog.cpp, kchartColorConfigPage.cpp,
+ kchartDataConfigPage.cpp: remove it, and include koChart.h instead
2005-03-13 Inge Wallin <inge@lysator.liu.se>
Make the page layout dialog better looking.
- * kchartPageLayout.cc (constructor): Place settings inside a
+ * kchartPageLayout.cpp (constructor): Place settings inside a
button box.
----------------------------------------------------------------
@@ -450,21 +450,21 @@
(getXLabel): removed
* kchart_part.h (axisLabelText{short,long}): removed
(m_longLabels, m_shortLabels): removed
- * kchart_view.cc (edit): remove all stuff within #if 0 - #endif
+ * kchart_view.cpp (edit): remove all stuff within #if 0 - #endif
----------------------------------------------------------------
Fix problem with mixed plurals/singulars in chart names.
- * kchart_view.cc (KChartView): Rename some actions.
+ * kchart_view.cpp (KChartView): Rename some actions.
The default chart is marked as modified even when it's not.
- * kchart_part.cc (KChartPart): Remove call to setModified().
+ * kchart_part.cpp (KChartPart): Remove call to setModified().
2005-03-12 Inge Wallin <inge@lysator.liu.se>
Remove the defaults button from the config dialog. It wasn't
working anyway.
- * kchartConfigDialog.cc (KChartConfigDialog): Disable the Defaults
+ * kchartConfigDialog.cpp (KChartConfigDialog): Disable the Defaults
button.
----------------------------------------------------------------
@@ -473,7 +473,7 @@
logarithmic axes.
* kchartParameterConfigPage.h (KChartParameterConfigPage::lin and
log): new members
- * kchartParameterConfigPage.cc (KChartParameterConfigPage): Add
+ * kchartParameterConfigPage.cpp (KChartParameterConfigPage): Add
new widgets to the Settings buttonbox (used to be Title)
(init): initialize the members from the params.
(apply): store the parameters from the values of the widgets
@@ -481,13 +481,13 @@
----------------------------------------------------------------
Fix the bad layout of the title buttonbox.
- * kchartParameterConfigPage.cc (KChartParameterConfigPage): Change
+ * kchartParameterConfigPage.cpp (KChartParameterConfigPage): Change
the layout slightly, and add row and col stretch.
----------------------------------------------------------------
Load row and column headers from XML file.
- * kchart_part.cc (loadXML): Get the legend and axis label strings
+ * kchart_part.cpp (loadXML): Get the legend and axis label strings
from the KDChart parameters and store in the column and row
headers.
@@ -497,8 +497,8 @@
Clean up the data editor and remove old cruft.
* kchartDataEditor.{h,cc}: Remove all #if 0:ed code.
- * Makefile.am (libkchartpart_la_SOURCES): Removed parser.cc,
- sheet.cc, sheetdlg.cc, table.cc qttableview.cpp
+ * Makefile.am (libkchartpart_la_SOURCES): Removed parser.cpp,
+ sheet.cpp, sheetdlg.cpp, table.cpp qttableview.cpp
(noinst_HEADERS): Removed parser.h sheet.h sheetdlg.h table.h
qttableview.h
Files mentioned above: Removed.
@@ -507,20 +507,20 @@
Move Tooltips and Whatsthis help from the old data editor to the
new one.
- * kchartDataEditor.cc (addDocs): New method
+ * kchartDataEditor.cpp (addDocs): New method
(constructor): Clean up by moving all help generation to addDocs().
----------------------------------------------------------------
Enable "Finish" button for all pages in the wizard.
- * kchartWizard.cc (KChartWizard): Enable Finish button for
+ * kchartWizard.cpp (KChartWizard): Enable Finish button for
"Subtypes" and "Labels & Legend" pages.
2005-03-10 Inge Wallin <inge@lysator.liu.se>
Make the table in the data editor shrink when number of rows/cols
are decreased in the spinboxes.
- * kchartDataEditor.cc (askUserForConfirmation): new static
+ * kchartDataEditor.cpp (askUserForConfirmation): new static
function.
(setRows, setCols): Handle shrinking
@@ -546,25 +546,25 @@
----------------------------------------------------------------
Cleaning
- * kchart_part.cc (paintContent): break out common code out of an
+ * kchart_part.cpp (paintContent): break out common code out of an
if/else construction.
----------------------------------------------------------------
More experiments with visual appearance of the data editor
- * kchartDataEditor.cc (setData): Set size of the table widget to
+ * kchartDataEditor.cpp (setData): Set size of the table widget to
(600,300)
----------------------------------------------------------------
Experiment with visual appearance of the new data editor
- * kchartDataEditor.cc (setData): Set column widths to 80.
+ * kchartDataEditor.cpp (setData): Set column widths to 80.
----------------------------------------------------------------
Fix bug introduced by patch to fix bug 14971: Axes label handling
in connection with KSpread was broken.
- * kchart_part.cc (setData): set m_rowLabels and m_colLabels
+ * kchart_part.cpp (setData): set m_rowLabels and m_colLabels
instead of storing axes labels to the params.
2005-03-08 Inge Wallin <inge@lysator.liu.se>
@@ -580,13 +580,13 @@
This fixes bug 14971.
* kchart_part.h (m_rowLabels, m_colLabels): new members
(rowLabelTexts, colLabelTexts): new methods
- * kchart_part.cc (paintContent): Paint using the new labels, both
+ * kchart_part.cpp (paintContent): Paint using the new labels, both
for ordinary and transposed tables.
* kchartDataEditor.{h,cc} (setRowLabels): new method
(getRowLabels): new method
(setColLabels): new method
(getColLabels): new method
- * kchart_view.cc (edit): call new methods above in data editor,
+ * kchart_view.cpp (edit): call new methods above in data editor,
and don't call old methods setLegend, getLegend, setXLabel, etc.
2005-03-07 Inge Wallin <inge@lysator.liu.se>
@@ -608,18 +608,18 @@
----------------------------------------------------------------
Cleaning:
- * kchart_part.cc (loadOasis): remove parameter names to remove
+ * kchart_part.cpp (loadOasis): remove parameter names to remove
warnings.
Reorder chart types to make it more logical order
* kchart.rc (Toolbar): Reorder chart types
- * kchartWizardSelectChartTypePage.cc (constructor): Reorder chart
+ * kchartWizardSelectChartTypePage.cpp (constructor): Reorder chart
types into same order.
2005-03-06 Inge Wallin <inge@lysator.liu.se>
Begin to support the Apply button in the data editor.
- * kchartDataEditor.cc (kchartDataEditor): connect applyClicked()
+ * kchartDataEditor.cpp (kchartDataEditor): connect applyClicked()
to apply()
* kchartDataEditor.{h,cc} (apply): new method.
@@ -630,11 +630,11 @@
author.
Continue with the new data editor.
- * kchartDataEditor.cc (setLegend): Always initialize the row
+ * kchartDataEditor.cpp (setLegend): Always initialize the row
headers, not only the first time.
Start fixing default handling in the config dialog.
- * kchartConfigDialog.cc (defaults): Call datapage->defaults()
+ * kchartConfigDialog.cpp (defaults): Call datapage->defaults()
instead of init.
* kchartDataConfigPage.{h,cc} (defaults): New method.
@@ -649,13 +649,13 @@
* kchartDataEditor.{h,cc}: First prototype of a new data editor.
Code cleaning.
- * kchartFontConfigPage.cc (class KChartFontListBoxItem): Move from
+ * kchartFontConfigPage.cpp (class KChartFontListBoxItem): Move from
kchartDataConfigPage.h. That used to be an error.
2005-02-25 Inge Wallin <inge@lysator.liu.se>
Fix bug 99998: KChart: 3d Depth parameter has ludicrous max value
- * kchartParameter3dConfigPage.cc (KChartParameter3dConfigPage):
+ * kchartParameter3dConfigPage.cpp (KChartParameter3dConfigPage):
Make the depth parameter go from 0 to 2.0 instead of 0 to 40.
2005-02-24 Inge Wallin <inge@lysator.liu.se>
@@ -689,7 +689,7 @@
Fix bug 99765: "Chart Subtype" config page is missing for Pie,
Ring, Box&Whisker chart types.
- * kchartConfigDialog.cc (initSubtypePage): Don't create a
+ * kchartConfigDialog.cpp (initSubtypePage): Don't create a
configuration page for subtype if the type doesn't have a
subtype. Applicable to Pie, Ring and Box&Whiskers.
@@ -698,9 +698,9 @@
Start of a new page in the config dialog for configuring Data.
This is not yet finished.
* kchartDataConfigPage.h: New file
- * kchartDataConfigPage.cc: New file
+ * kchartDataConfigPage.cpp: New file
* kchartConfigDialog.h (KChartConfigDialog::m_datapage): New member
- * kchartConfigDialog.cc (KChartConfigDialog): Create the data page
+ * kchartConfigDialog.cpp (KChartConfigDialog): Create the data page
2005-01-07 Raphael Langerhorst <raphael-langerhorst@gmx.at>
@@ -711,10 +711,10 @@
2005-01-06 Raphael Langerhorst <raphael-langerhorst@gmx.at>
Improve Data Editor usability:
- * sheet.cc: Add tooltips and what's this help.
- * sheet.cc: Use a different color for first row and column
- * sheetdlg.cc: Add tooltips and what's this help.
- * sheetdlg.cc: Change order of widget initialization (better tab order).
+ * sheet.cpp: Add tooltips and what's this help.
+ * sheet.cpp: Use a different color for first row and column
+ * sheetdlg.cpp: Add tooltips and what's this help.
+ * sheetdlg.cpp: Change order of widget initialization (better tab order).
2004-11-16 Inge Wallin <inge@lysator.liu.se>
@@ -725,7 +725,7 @@
2004-11-05 Inge Wallin <inge@lysator.liu.se>
Fix bug 90895: save config is not needed
- * kchart_view.cc (KChartView): Remove actions "loadconfig",
+ * kchart_view.cpp (KChartView): Remove actions "loadconfig",
"saveconfig" and "defaultconfig".
* kchart.rc: Remove reference to them in the definition of the
Settings menu.
@@ -733,26 +733,26 @@
Fix bug 90904: edit/configure is confusingly named
* kchart.rc: Add a sub menu for editing only one aspect of the
chart.
- * kchart_view.cc: Change shortcut for Edit Data
- * kchart_view.cc: Change string for Configure Chart
+ * kchart_view.cpp: Change shortcut for Edit Data
+ * kchart_view.cpp: Change string for Configure Chart
2004-10-07 Inge Wallin <inge@lysator.liu.se>
* Cleanup of the following files. Made the code more readable,
fixed indentation, added some comments:
- sheet.h
- - sheet.cc
+ - sheet.cpp
2004-10-06 Inge Wallin <inge@lysator.liu.se>
Fix bug 55603: Pressing Enter in Data Editor doesn't update any
changes.
- * sheetdlg.cc (SheetDlg): Make the OK button the default.
+ * sheetdlg.cpp (SheetDlg): Make the OK button the default.
* Cleanup of the following files. Made the code more readable,
fixed indentation, added some comments:
- parser.h
- - parser.cc
+ - parser.cpp
2004-10-04 Inge Wallin <inge@lysator.liu.se>
@@ -760,19 +760,19 @@
readable, fixed indentation, added (a few) comments:
(Man, there are a lot of coding styles in there...)
- kchart_part.h
- - kchart_part.cc
+ - kchart_part.cpp
* Cleaned the following files a little. Made the code more
readable, fixed indentation, added (a few) comments:
- - kchart.la.cc
- - main.cc
- - kchart_dummy.cc
+ - kchart.la.cpp
+ - main.cpp
+ - kchart_dummy.cpp
- kchart_aboutdata.h
- kchart_factory.h
- - kchart_factory.cc
+ - kchart_factory.cpp
- kchart_params.h
- - kchart_params.cc
+ - kchart_params.cpp
- kchart_view.h
- - kchart_view.cc
+ - kchart_view.cpp
diff --git a/kchart/KChartParamsIface.cc b/kchart/KChartParamsIface.cpp
index 794c46790..794c46790 100644
--- a/kchart/KChartParamsIface.cc
+++ b/kchart/KChartParamsIface.cpp
diff --git a/kchart/KChartViewIface.cc b/kchart/KChartViewIface.cpp
index c9c2cbadb..c9c2cbadb 100644
--- a/kchart/KChartViewIface.cc
+++ b/kchart/KChartViewIface.cpp
diff --git a/kchart/Makefile.am b/kchart/Makefile.am
index a2cb355df..1008b17c7 100644
--- a/kchart/Makefile.am
+++ b/kchart/Makefile.am
@@ -3,34 +3,34 @@ INCLUDES = $(KOFFICE_INCLUDES) -I$(srcdir)/kdchart -I$(top_srcdir)/interfaces -
## The lib with most of the code (shared with the kchart filters)
lib_LTLIBRARIES = libkchartcommon.la
-libkchartcommon_la_SOURCES = kchart_part.cc \
- kchart_view.cc kchart_factory.cc \
- kchartColorConfigPage.cc \
- kchartParameterConfigPage.cc \
- kchartParameter3dConfigPage.cc \
- kchartBackgroundPixmapConfigPage.cc \
- kchartSubTypeChartPage.cc \
- kchartComboConfigPage.cc \
- kchartFontConfigPage.cc \
- kchartDataConfigPage.cc \
- kchartPieConfigPage.cc \
- kchartParameterPieConfigPage.cc \
- kchartConfigDialog.cc \
- kchartWizard.cc \
- kchartWizardLabelsLegendPage.cc \
- kchartWizardSelectChartSubTypePage.cc \
- kchartWizardSelectChartTypePage.cc \
- kchartWizardSelectDataPage.cc \
- kchartWizardSetupAxesPage.cc \
- kchartWizardSetupDataPage.cc \
- kchartWizardSelectDataFormatPage.cc \
- kchartDataEditor.cc \
- KChartViewIface.skel KChartViewIface.cc \
- kchartLegendConfigPage.cc kchart_params.cc KChartParamsIface.skel \
- KChartParamsIface.cc kchartHeaderFooterConfigPage.cc \
- kchartLine3dConfigPage.cc kchartParameterPolarConfigPage.cc kchartPageLayout.cc \
- kchartPrinterDlg.cc \
- csvimportdialog.cc csvimportdialogui.ui
+libkchartcommon_la_SOURCES = kchart_part.cpp \
+ kchart_view.cpp kchart_factory.cpp \
+ kchartColorConfigPage.cpp \
+ kchartParameterConfigPage.cpp \
+ kchartParameter3dConfigPage.cpp \
+ kchartBackgroundPixmapConfigPage.cpp \
+ kchartSubTypeChartPage.cpp \
+ kchartComboConfigPage.cpp \
+ kchartFontConfigPage.cpp \
+ kchartDataConfigPage.cpp \
+ kchartPieConfigPage.cpp \
+ kchartParameterPieConfigPage.cpp \
+ kchartConfigDialog.cpp \
+ kchartWizard.cpp \
+ kchartWizardLabelsLegendPage.cpp \
+ kchartWizardSelectChartSubTypePage.cpp \
+ kchartWizardSelectChartTypePage.cpp \
+ kchartWizardSelectDataPage.cpp \
+ kchartWizardSetupAxesPage.cpp \
+ kchartWizardSetupDataPage.cpp \
+ kchartWizardSelectDataFormatPage.cpp \
+ kchartDataEditor.cpp \
+ KChartViewIface.skel KChartViewIface.cpp \
+ kchartLegendConfigPage.cpp kchart_params.cpp KChartParamsIface.skel \
+ KChartParamsIface.cpp kchartHeaderFooterConfigPage.cpp \
+ kchartLine3dConfigPage.cpp kchartParameterPolarConfigPage.cpp kchartPageLayout.cpp \
+ kchartPrinterDlg.cpp \
+ csvimportdialog.cpp csvimportdialogui.ui
libkchartcommon_la_LIBADD = $(top_builddir)/interfaces/libkochart.la \
$(LIB_KOFFICEUI) \
@@ -39,14 +39,14 @@ libkchartcommon_la_LDFLAGS = $(KDE_RPATH) -version-info 2:0:0 -no-undefined $(LI
## The part
kde_module_LTLIBRARIES = libkchartpart.la
-libkchartpart_la_SOURCES = kchart_factory_init.cc
+libkchartpart_la_SOURCES = kchart_factory_init.cpp
libkchartpart_la_LDFLAGS = $(KDE_PLUGIN) $(LIB_TQT)
libkchartpart_la_LIBADD = libkchartcommon.la
## The tdeinit loadable module and executable
tdeinit_LTLIBRARIES = kchart.la
bin_PROGRAMS =
-kchart_la_SOURCES = main.cc
+kchart_la_SOURCES = main.cpp
kchart_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT)
kchart_la_LIBADD = $(LIB_KOFFICECORE)
@@ -91,7 +91,7 @@ xdg_apps_DATA = kchart.desktop
SUBDIRS = kdchart . toolbar pics templates
messages: rc.cpp
- $(XGETTEXT) rc.cpp *.cc kchart_aboutdata.h kdchart/*.cpp -o $(podir)/kchart.pot
+ $(XGETTEXT) rc.cpp *.cpp kchart_aboutdata.h kdchart/*.cpp -o $(podir)/kchart.pot
kde_services_DATA = kchartpart.desktop
diff --git a/kchart/csvimportdialog.cc b/kchart/csvimportdialog.cpp
index cf13c1b5e..cf13c1b5e 100644
--- a/kchart/csvimportdialog.cc
+++ b/kchart/csvimportdialog.cpp
diff --git a/kchart/kchartBackgroundPixmapConfigPage.cc b/kchart/kchartBackgroundPixmapConfigPage.cc
deleted file mode 100644
index d7716d311..000000000
--- a/kchart/kchartBackgroundPixmapConfigPage.cc
+++ /dev/null
@@ -1,548 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 Matthias Kalle Dalheimer <kalle@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include "kchartBackgroundPixmapConfigPage.h"
-#include "kchartBackgroundPixmapConfigPage.moc"
-
-#include <tdelocale.h>
-#include <tdeglobal.h>
-#include <kstandarddirs.h>
-#include <tdefiledialog.h>
-#include <tdemessagebox.h>
-#include <kdebug.h>
-#include <tdefilemetainfo.h>
-#include <kstringhandler.h>
-
-#include <tqcombobox.h>
-#include <tqradiobutton.h>
-#include <tqbuttongroup.h>
-#include <tqspinbox.h>
-#include <tqlayout.h>
-#include <tqhbox.h>
-#include <tqpushbutton.h>
-#include <tqlabel.h>
-#include <tqwhatsthis.h>
-#include <tqlistbox.h>
-#include <kcolorbutton.h>
-
-#include "kchart_params.h"
-
-namespace KChart
-{
-
-KChartBackgroundPixmapConfigPage::KChartBackgroundPixmapConfigPage( KChartParams* params, TQWidget* parent )
- : TQWidget( parent, "KChartBackgroundPixmapConfigPage" ),
- _params( params )
-{
- TQWhatsThis::add( this,
- i18n( "On this page, you can select colors or images "
- "to be displayed behind the different areas. You "
- "can also select whether the images should be "
- "stretched or scaled or centered or used as "
- "background tiles." ) );
-
- TQHBoxLayout* toplevel = new TQHBoxLayout( this, 10 );
-
-#if 0
- TQVBoxLayout* left=new TQVBoxLayout(10);
- toplevel->addLayout(left,2);
- regionList=new TQListBox(this);
- left->addWidget(regionList);
-#endif
-
- TQVBoxLayout* center = new TQVBoxLayout( 10 );
- toplevel->addLayout( center, 2 );
-
-
- TQLabel* backgroundLA = new TQLabel( i18n( "&Background color:" ), this );
- center->addWidget( backgroundLA );
- _backgroundCB = new KColorButton( this );
- backgroundLA->setBuddy( _backgroundCB );
- center->addWidget( _backgroundCB);
- TQString wtstr = i18n( "Here you set the color in which the background "
- "of the chart is painted." );
- TQWhatsThis::add( backgroundLA, wtstr );
- TQWhatsThis::add( _backgroundCB, wtstr );
-
-
- TQLabel* wallpaperLA = new TQLabel( i18n( "Background wallpaper:" ), this );
- center->addWidget( wallpaperLA );
-
- wallCB = new TQComboBox( false, this, "wallCombo" );
- wallpaperLA->setBuddy(wallCB);
- TQWhatsThis::add( wallCB, i18n( "You can select a background image from "
- "this list. Initially, the installed TDE "
- "wallpapers will be offered. If you do not "
- "find what you are looking for here, you can "
- "select any image file by clicking on the "
- "<i>Browse</i> button below." ) );
- center->addWidget( wallCB );
- wallCB->insertItem( i18n("None") );
-
- loadWallpaperFilesList();
- TQPushButton* browsePB = new TQPushButton( i18n("&Browse..."), this );
- TQWhatsThis::add( browsePB, i18n( "Click this button to select a background "
- "image not yet present in the list above. " ) );
- center->addWidget( browsePB );
- connect( browsePB, TQT_SIGNAL( clicked() ), TQT_SLOT( slotBrowse() ) );
-
- wallWidget = new TQWidget( this );
- TQWhatsThis::add( wallWidget, i18n( "This area will always display the "
- "currently selected background image. "
- "Note that the image will be scaled and "
- "thus might have a different ratio than "
- "it originally had." ) );
- center->addWidget( wallWidget );
-
- connect( wallCB, TQT_SIGNAL( activated( int ) ),
- this, TQT_SLOT( slotWallPaperChanged( int ) ) );
-
- right = new TQVGroupBox( i18n( "Wallpaper Configuration" ), this );
- TQWhatsThis::add( right, i18n( "In this box, you can set various settings "
- "that control how the background image is "
- "displayed." ) );
- toplevel->addWidget( right );
-
- TQHBox* intensityHB = new TQHBox( right );
- intensityHB->setSpacing( 10 );
- TQLabel* intensityLA = new TQLabel(
- // xgettext:no-c-format
- i18n( "&Intensity in %:" ), intensityHB );
- intensitySB = new TQSpinBox( 1, 100, 1, intensityHB );
- intensityLA->setBuddy( intensitySB );
- // xgettext:no-c-format
- TQString ttstr = i18n( "Here you can select how much the image should be "
- "brightened up so that it does not disturb the "
- "selected area too much.<br> Different images require "
- "different settings, but 25% is a good value to start "
- "with." );
- TQWhatsThis::add( intensityLA, ttstr );
- TQWhatsThis::add( intensitySB, ttstr );
-
-
- stretchedRB = new TQRadioButton( i18n( "Stretched" ), right );
- TQWhatsThis::add( stretchedRB,
- i18n( "If you check this box, the selected image will "
- "be scaled to fit the total size of the selected "
- "area. Image ratio will be adjusted to match "
- "the area size and height if necessary." ) );
- stretchedRB->setChecked( true );
- scaledRB = new TQRadioButton( i18n( "Scaled" ), right );
- TQWhatsThis::add( scaledRB,
- i18n( "If you check this box, the selected image will "
- "be scaled to match the height or width of the "
- "selected area - whichever is reached first." ) );
- centeredRB = new TQRadioButton( i18n( "Centered" ), right );
- TQWhatsThis::add( centeredRB,
- i18n( "If you check this box, the selected image will "
- "be centered over the selected area. If the image "
- "is larger then the area, you will only see the "
- "middle part of it." ) );
-
- tiledRB = new TQRadioButton( i18n( "Tiled" ), right );
- TQWhatsThis::add( tiledRB,
- i18n( "If you check this box, the selected image will "
- "be used as a background tile. If the image is "
- "larger then the selected area, you will only see "
- "the upper left part of it." ) );
- TQButtonGroup* alignmentBG;
- alignmentBG = new TQButtonGroup( right, "GroupBox_Alignment" );
- alignmentBG->setFrameStyle( TQFrame::NoFrame );
- alignmentBG->insert( stretchedRB );
- alignmentBG->insert( scaledRB );
- alignmentBG->insert( centeredRB );
- alignmentBG->insert( tiledRB );
-
- intensitySB->hide(); //the property doesn't work atm
-}
-
-//Code from kcontrol/background/bgdialog.cc
-void KChartBackgroundPixmapConfigPage::loadWallpaperFilesList()
-{
- // Wallpapers
- // the following TQMap is lower cased names mapped to cased names and URLs
- // this way we get case insensitive sorting
- TQMap<TQString, TQPair<TQString, TQString> > papers;
-
- //search for .desktop files before searching for images without .desktop files
- TQStringList lst = TDEGlobal::dirs()->findAllResources("wallpaper", "*desktop", false, true);
- TQStringList files;
- for (TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
- {
- KSimpleConfig fileConfig(*it);
- fileConfig.setGroup("Wallpaper");
-
- TQString imageCaption = fileConfig.readEntry("Name");
- TQString fileName = fileConfig.readEntry("File");
-
- if (imageCaption.isEmpty())
- {
- imageCaption = fileName;
- imageCaption.replace('_', ' ');
- imageCaption = KStringHandler::capwords(imageCaption);
- }
-
- // avoid name collisions
- TQString rs = imageCaption;
- TQString lrs = rs.lower();
- for (int n = 1; papers.find(lrs) != papers.end(); ++n)
- {
- rs = imageCaption + " (" + TQString::number(n) + ')';
- lrs = rs.lower();
- }
- int slash = (*it).findRev('/') + 1;
- TQString directory = (*it).left(slash);
- bool canLoadScaleable = false;
-#ifdef HAVE_LIBART
- canLoadScaleable = true;
-#endif
- if ( fileConfig.readEntry("ImageType") == "pixmap" || canLoadScaleable ) {
- papers[lrs] = tqMakePair(rs, directory + fileName);
- files.append(directory + fileName);
- }
- }
-
- //now find any wallpapers that don't have a .desktop file
- lst = TDEGlobal::dirs()->findAllResources("wallpaper", "*", false, true);
- for (TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
- {
- if ( !(*it).endsWith(".desktop") && files.grep(*it).empty() ) {
- // First try to see if we have a comment describing the image. If we do
- // just use the first line of said comment.
- KFileMetaInfo metaInfo(*it);
- TQString imageCaption;
-
- if (metaInfo.isValid() && metaInfo.item("Comment").isValid())
- imageCaption = metaInfo.item("Comment").string().section('\n', 0, 0);
-
- if (imageCaption.isEmpty())
- {
- int slash = (*it).findRev('/') + 1;
- int endDot = (*it).findRev('.');
-
- // strip the extension if it exists
- if (endDot != -1 && endDot > slash)
- imageCaption = (*it).mid(slash, endDot - slash);
- else
- imageCaption = (*it).mid(slash);
-
- imageCaption.replace('_', ' ');
- imageCaption = KStringHandler::capwords(imageCaption);
- }
-
- // avoid name collisions
- TQString rs = imageCaption;
- TQString lrs = rs.lower();
- for (int n = 1; papers.find(lrs) != papers.end(); ++n)
- {
- rs = imageCaption + " (" + TQString::number(n) + ')';
- lrs = rs.lower();
- }
- papers[lrs] = tqMakePair(rs, *it);
- }
- }
-
- m_wallpaper.clear();
- //don't start to 0, we have None element
- int i = 1;
- for (TQMap<TQString, TQPair<TQString, TQString> >::Iterator it = papers.begin();
- it != papers.end();
- ++it)
- {
- wallCB->insertItem(it.data().first);
- m_wallpaper[it.data().second] = i;
- i++;
- }
-}
-
-void KChartBackgroundPixmapConfigPage::init()
-{
-#if 0
- TQStringList lst;
- lst.append(i18n( "Outermost Region" ));
- lst.append(i18n( "Innermost Region" ));
- lst.append(i18n( "Header+Title+Subtitle" ));
- lst.append(i18n( "Footers" ));
- lst.append(i18n( "Data+Axes+Legend" ));
- lst.append(i18n( "Data+Axes" ));
- lst.append(i18n( "Data" ));
- lst.append(i18n( "Legend" ));
- lst.append(i18n( "Left Axis" ));
- lst.append(i18n( "Bottom Axis" ));
- lst.append(i18n( "Right Axis" ));
- lst.append(i18n( "Header A" ));
- lst.append(i18n( "Header B" ));
- lst.append(i18n( "Header C" ));
- lst.append(i18n( "Title A" ));
- lst.append(i18n( "Title B" ));
- lst.append(i18n( "Title C" ));
- lst.append(i18n( "Subtitle A" ));
- lst.append(i18n( "Subtitle B" ));
- lst.append(i18n( "Subtitle C" ));
- lst.append(i18n( "Footer 1 A" ));
- lst.append(i18n( "Footer 1 B" ));
- lst.append(i18n( "Footer 1 C" ));
- lst.append(i18n( "Footer 2 A" ));
- lst.append(i18n( "Footer 2 B" ));
- lst.append(i18n( "Footer 2 C" ));
- lst.append(i18n( "Footer 3 A" ));
- lst.append(i18n( "Footer 3 B" ));
- lst.append(i18n( "Footer 3 C" ));
- regionList->insertStringList(lst);
-#endif
- // PENDING(kalle) Readapt
- // showSettings( _params->backgroundPixmapName );
-// intensitySB->setValue( (int)(_params->backgroundPixmapIntensity * 100.0) );
-// scaledCB->setChecked( _params->backgroundPixmapScaled );
-// centeredCB->setChecked( _params->backgroundPixmapCentered );
-
- bool bFound;
- const KDChartParams::KDChartFrameSettings * innerFrame =
- _params->frameSettings( KDChartEnums::AreaInnermost, bFound );
- if( bFound )
- {
- const TQPixmap* backPixmap;
- bool isTiledMode = false;
- KDFrame::BackPixmapMode backPixmapMode;
- const TQBrush& background = innerFrame->frame().background( backPixmap, backPixmapMode );
- const TQColor backColor( background.color() );
-
- // Bg color has to be be set in any case,
- // even when a (tiled) pixmap is specified:
- _backgroundCB->setColor( backColor );
-
-
- if( !backPixmap || backPixmap->isNull() )
- {
- // A pixmap can be in the brush, if used as Tile.
- backPixmap = background.pixmap();
- if( backPixmap )
- isTiledMode = true;
- }
-
- if( !backPixmap || backPixmap->isNull() ) //color as background
- {
- right->setEnabled( false );
- wallCB->setCurrentItem( 0 );
- }
- else //pixmap as background
- {
- _backgroundCB->setEnabled( false );
- wallWidget->setPaletteBackgroundPixmap( *backPixmap );
- wallCB->setCurrentItem( 1 );
- if( isTiledMode )
- {
- tiledRB->setChecked( true );
- }
- else
- {
- switch( backPixmapMode ){
- case KDFrame::PixCentered:
- centeredRB->setChecked( true );
- break;
- case KDFrame::PixScaled:
- scaledRB->setChecked( true );
- break;
- default:
- stretchedRB->setChecked( true );
- }
- }
- }
- }
- else
- _backgroundCB->setColor(TQColor(230, 222, 222) );
-}
-
-void KChartBackgroundPixmapConfigPage::apply()
-{
- // PENDING(kalle) Readapt
- // if( wallCB->currentText() != _params->backgroundPixmapName ) {
-// bool load=true;
-// if(wallCB->currentText()==i18n("None")) {
-// load=false;
-// } else {
-// _params->backgroundPixmapName = wallCB->currentText();
-// bool load=_params->backgroundPixmap.load( locate( "wallpaper", _params->backgroundPixmapName ) );
-// if(load)
-// _params->backgroundPixmapIsDirty = true;
-// }
-
-// if( !load ) {
-// _params->backgroundPixmapName = "";
-// _params->backgroundPixmap=TQPixmap("");
-// _params->backgroundPixmapIsDirty = false;
-// }
-// }
-// if( (int)(_params->backgroundPixmapIntensity * 100.0) !=
-// intensitySB->value() ) {
-// _params->backgroundPixmapIntensity = (float)(intensitySB->value()) / 100.0;
-// _params->backgroundPixmapIsDirty = true;
-// }
-
-// if( _params->backgroundPixmapScaled !=
-// scaledCB->isChecked() ) {
-// _params->backgroundPixmapScaled = scaledCB->isChecked();
-// _params->backgroundPixmapIsDirty = true;
-// }
-// if( _params->backgroundPixmapCentered !=
-// centeredCB->isChecked() ) {
-// _params->backgroundPixmapCentered = centeredCB->isChecked();
-// _params->backgroundPixmapIsDirty = true;
-// }
-
- //
- // temp. hack: the background is removed if "None" is selected in the combo box
- //
- // For KOffice 1.5/2.0 this is to be removed by a checkbox.
- bool bFound;
- const KDChartParams::KDChartFrameSettings * innerFrame =
- _params->frameSettings( KDChartEnums::AreaInnermost, bFound );
- if( bFound )
- {
- const TQColor backColor( _backgroundCB->color() );
- KDFrame& frame( const_cast<KDFrame&>(innerFrame->frame()) );
- if ( wallCB->currentItem() == 0 )
- {
- frame.setBackPixmap( 0 );
- frame.setBackground( backColor );
- }
- else
- {
- const TQPixmap* pixmap = wallWidget->paletteBackgroundPixmap();
- if ( tiledRB->isChecked() ){
- // We remove the frame's extra pixmap,
- frame.setBackPixmap( 0 );
- // because a tiled image is set via a TQBrush.
- if( pixmap )
- frame.setBackground( TQBrush( backColor, *pixmap ) );
- else
- frame.setBackground( backColor );
- }else{
- KDFrame::BackPixmapMode backPixmapMode;
- if ( centeredRB->isChecked() )
- backPixmapMode = KDFrame::PixCentered;
- else if ( scaledRB->isChecked() )
- backPixmapMode = KDFrame::PixScaled;
- else
- backPixmapMode = KDFrame::PixStretched;
- // We reset the background color, removing any tiled brush,
- frame.setBackground( backColor );
- // because we specify an extra pixmap instead.
- frame.setBackPixmap( pixmap, backPixmapMode );
- }
- }
- }
-}
-
-
-void KChartBackgroundPixmapConfigPage::showSettings( const TQString& fileName )
-{
- wallCB->blockSignals(true);
-
- if (m_wallpaper.find(fileName) == m_wallpaper.end())
- {
- int i = wallCB->count();
- TQString imageCaption;
- int slash = fileName.findRev('/') + 1;
- int endDot = fileName.findRev('.');
-
- // strip the extension if it exists
- if (endDot != -1 && endDot > slash)
- imageCaption = fileName.mid(slash, endDot - slash);
- else
- imageCaption = fileName.mid(slash);
- if (wallCB->text(i-1) == imageCaption)
- {
- i--;
- wallCB->removeItem(i);
- }
- wallCB->insertItem(imageCaption);
- m_wallpaper[fileName] = i;
- wallCB->setCurrentItem(i);
- }
- else
- {
- wallCB->setCurrentItem(m_wallpaper[fileName]);
- }
- wallCB->blockSignals(false);
- loadWallPaper();
-}
-
-
-void KChartBackgroundPixmapConfigPage::slotBrowse()
-{
- //TODO: Support non-local wallpapers
- KURL url = KFileDialog::getOpenFileName( 0 );
- if( url.isEmpty() )
- return;
- showSettings( url.path() );
-}
-
-void KChartBackgroundPixmapConfigPage::slotWallPaperChanged( int index )
-{
- if ( index != 0 && loadWallPaper() )
- {
- _backgroundCB->setEnabled( false );
- right->setEnabled( true );
- }
- else
- {
- wallWidget->setPaletteBackgroundPixmap( 0 );
- _backgroundCB->setEnabled( true );
- right->setEnabled( false );
- }
-}
-
-
-bool KChartBackgroundPixmapConfigPage::loadWallPaper()
-{
- int i = wallCB->currentItem();
- if ( i == -1 || i == 0 ) { // 0 is 'None'
- wallPixmap.resize(0,0);
- wallFile = "";
- } else {
- for(TQMap<TQString,int>::ConstIterator it = m_wallpaper.begin();
- it != m_wallpaper.end();
- ++it)
- {
- if (it.data() == i)
- {
- wallFile = it.key();
- break;
- }
- }
- TQString file = locate("wallpaper", wallFile);
- if( file.isEmpty() ) {
- kdWarning(35001) << "Couldn't locate wallpaper " << wallFile << endl;
- wallPixmap.resize(0,0);
- wallFile = "";
- return false;
- } else {
- wallPixmap.load( file );
-
- if( wallPixmap.isNull() )
- return false;
-// kdWarning(35001) << "Could not load wallpaper " << file << endl;
- }
- }
- wallWidget->setPaletteBackgroundPixmap( wallPixmap );
- return true;
-}
-
-} //KChart namespace
diff --git a/kchart/kchartBackgroundPixmapConfigPage.cpp b/kchart/kchartBackgroundPixmapConfigPage.cpp
new file mode 100644
index 000000000..c92131166
--- /dev/null
+++ b/kchart/kchartBackgroundPixmapConfigPage.cpp
@@ -0,0 +1,548 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 Matthias Kalle Dalheimer <kalle@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "kchartBackgroundPixmapConfigPage.h"
+#include "kchartBackgroundPixmapConfigPage.moc"
+
+#include <tdelocale.h>
+#include <tdeglobal.h>
+#include <kstandarddirs.h>
+#include <tdefiledialog.h>
+#include <tdemessagebox.h>
+#include <kdebug.h>
+#include <tdefilemetainfo.h>
+#include <kstringhandler.h>
+
+#include <tqcombobox.h>
+#include <tqradiobutton.h>
+#include <tqbuttongroup.h>
+#include <tqspinbox.h>
+#include <tqlayout.h>
+#include <tqhbox.h>
+#include <tqpushbutton.h>
+#include <tqlabel.h>
+#include <tqwhatsthis.h>
+#include <tqlistbox.h>
+#include <kcolorbutton.h>
+
+#include "kchart_params.h"
+
+namespace KChart
+{
+
+KChartBackgroundPixmapConfigPage::KChartBackgroundPixmapConfigPage( KChartParams* params, TQWidget* parent )
+ : TQWidget( parent, "KChartBackgroundPixmapConfigPage" ),
+ _params( params )
+{
+ TQWhatsThis::add( this,
+ i18n( "On this page, you can select colors or images "
+ "to be displayed behind the different areas. You "
+ "can also select whether the images should be "
+ "stretched or scaled or centered or used as "
+ "background tiles." ) );
+
+ TQHBoxLayout* toplevel = new TQHBoxLayout( this, 10 );
+
+#if 0
+ TQVBoxLayout* left=new TQVBoxLayout(10);
+ toplevel->addLayout(left,2);
+ regionList=new TQListBox(this);
+ left->addWidget(regionList);
+#endif
+
+ TQVBoxLayout* center = new TQVBoxLayout( 10 );
+ toplevel->addLayout( center, 2 );
+
+
+ TQLabel* backgroundLA = new TQLabel( i18n( "&Background color:" ), this );
+ center->addWidget( backgroundLA );
+ _backgroundCB = new KColorButton( this );
+ backgroundLA->setBuddy( _backgroundCB );
+ center->addWidget( _backgroundCB);
+ TQString wtstr = i18n( "Here you set the color in which the background "
+ "of the chart is painted." );
+ TQWhatsThis::add( backgroundLA, wtstr );
+ TQWhatsThis::add( _backgroundCB, wtstr );
+
+
+ TQLabel* wallpaperLA = new TQLabel( i18n( "Background wallpaper:" ), this );
+ center->addWidget( wallpaperLA );
+
+ wallCB = new TQComboBox( false, this, "wallCombo" );
+ wallpaperLA->setBuddy(wallCB);
+ TQWhatsThis::add( wallCB, i18n( "You can select a background image from "
+ "this list. Initially, the installed TDE "
+ "wallpapers will be offered. If you do not "
+ "find what you are looking for here, you can "
+ "select any image file by clicking on the "
+ "<i>Browse</i> button below." ) );
+ center->addWidget( wallCB );
+ wallCB->insertItem( i18n("None") );
+
+ loadWallpaperFilesList();
+ TQPushButton* browsePB = new TQPushButton( i18n("&Browse..."), this );
+ TQWhatsThis::add( browsePB, i18n( "Click this button to select a background "
+ "image not yet present in the list above. " ) );
+ center->addWidget( browsePB );
+ connect( browsePB, TQT_SIGNAL( clicked() ), TQT_SLOT( slotBrowse() ) );
+
+ wallWidget = new TQWidget( this );
+ TQWhatsThis::add( wallWidget, i18n( "This area will always display the "
+ "currently selected background image. "
+ "Note that the image will be scaled and "
+ "thus might have a different ratio than "
+ "it originally had." ) );
+ center->addWidget( wallWidget );
+
+ connect( wallCB, TQT_SIGNAL( activated( int ) ),
+ this, TQT_SLOT( slotWallPaperChanged( int ) ) );
+
+ right = new TQVGroupBox( i18n( "Wallpaper Configuration" ), this );
+ TQWhatsThis::add( right, i18n( "In this box, you can set various settings "
+ "that control how the background image is "
+ "displayed." ) );
+ toplevel->addWidget( right );
+
+ TQHBox* intensityHB = new TQHBox( right );
+ intensityHB->setSpacing( 10 );
+ TQLabel* intensityLA = new TQLabel(
+ // xgettext:no-c-format
+ i18n( "&Intensity in %:" ), intensityHB );
+ intensitySB = new TQSpinBox( 1, 100, 1, intensityHB );
+ intensityLA->setBuddy( intensitySB );
+ // xgettext:no-c-format
+ TQString ttstr = i18n( "Here you can select how much the image should be "
+ "brightened up so that it does not disturb the "
+ "selected area too much.<br> Different images require "
+ "different settings, but 25% is a good value to start "
+ "with." );
+ TQWhatsThis::add( intensityLA, ttstr );
+ TQWhatsThis::add( intensitySB, ttstr );
+
+
+ stretchedRB = new TQRadioButton( i18n( "Stretched" ), right );
+ TQWhatsThis::add( stretchedRB,
+ i18n( "If you check this box, the selected image will "
+ "be scaled to fit the total size of the selected "
+ "area. Image ratio will be adjusted to match "
+ "the area size and height if necessary." ) );
+ stretchedRB->setChecked( true );
+ scaledRB = new TQRadioButton( i18n( "Scaled" ), right );
+ TQWhatsThis::add( scaledRB,
+ i18n( "If you check this box, the selected image will "
+ "be scaled to match the height or width of the "
+ "selected area - whichever is reached first." ) );
+ centeredRB = new TQRadioButton( i18n( "Centered" ), right );
+ TQWhatsThis::add( centeredRB,
+ i18n( "If you check this box, the selected image will "
+ "be centered over the selected area. If the image "
+ "is larger then the area, you will only see the "
+ "middle part of it." ) );
+
+ tiledRB = new TQRadioButton( i18n( "Tiled" ), right );
+ TQWhatsThis::add( tiledRB,
+ i18n( "If you check this box, the selected image will "
+ "be used as a background tile. If the image is "
+ "larger then the selected area, you will only see "
+ "the upper left part of it." ) );
+ TQButtonGroup* alignmentBG;
+ alignmentBG = new TQButtonGroup( right, "GroupBox_Alignment" );
+ alignmentBG->setFrameStyle( TQFrame::NoFrame );
+ alignmentBG->insert( stretchedRB );
+ alignmentBG->insert( scaledRB );
+ alignmentBG->insert( centeredRB );
+ alignmentBG->insert( tiledRB );
+
+ intensitySB->hide(); //the property doesn't work atm
+}
+
+//Code from kcontrol/background/bgdialog.cpp
+void KChartBackgroundPixmapConfigPage::loadWallpaperFilesList()
+{
+ // Wallpapers
+ // the following TQMap is lower cased names mapped to cased names and URLs
+ // this way we get case insensitive sorting
+ TQMap<TQString, TQPair<TQString, TQString> > papers;
+
+ //search for .desktop files before searching for images without .desktop files
+ TQStringList lst = TDEGlobal::dirs()->findAllResources("wallpaper", "*desktop", false, true);
+ TQStringList files;
+ for (TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
+ {
+ KSimpleConfig fileConfig(*it);
+ fileConfig.setGroup("Wallpaper");
+
+ TQString imageCaption = fileConfig.readEntry("Name");
+ TQString fileName = fileConfig.readEntry("File");
+
+ if (imageCaption.isEmpty())
+ {
+ imageCaption = fileName;
+ imageCaption.replace('_', ' ');
+ imageCaption = KStringHandler::capwords(imageCaption);
+ }
+
+ // avoid name collisions
+ TQString rs = imageCaption;
+ TQString lrs = rs.lower();
+ for (int n = 1; papers.find(lrs) != papers.end(); ++n)
+ {
+ rs = imageCaption + " (" + TQString::number(n) + ')';
+ lrs = rs.lower();
+ }
+ int slash = (*it).findRev('/') + 1;
+ TQString directory = (*it).left(slash);
+ bool canLoadScaleable = false;
+#ifdef HAVE_LIBART
+ canLoadScaleable = true;
+#endif
+ if ( fileConfig.readEntry("ImageType") == "pixmap" || canLoadScaleable ) {
+ papers[lrs] = tqMakePair(rs, directory + fileName);
+ files.append(directory + fileName);
+ }
+ }
+
+ //now find any wallpapers that don't have a .desktop file
+ lst = TDEGlobal::dirs()->findAllResources("wallpaper", "*", false, true);
+ for (TQStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
+ {
+ if ( !(*it).endsWith(".desktop") && files.grep(*it).empty() ) {
+ // First try to see if we have a comment describing the image. If we do
+ // just use the first line of said comment.
+ KFileMetaInfo metaInfo(*it);
+ TQString imageCaption;
+
+ if (metaInfo.isValid() && metaInfo.item("Comment").isValid())
+ imageCaption = metaInfo.item("Comment").string().section('\n', 0, 0);
+
+ if (imageCaption.isEmpty())
+ {
+ int slash = (*it).findRev('/') + 1;
+ int endDot = (*it).findRev('.');
+
+ // strip the extension if it exists
+ if (endDot != -1 && endDot > slash)
+ imageCaption = (*it).mid(slash, endDot - slash);
+ else
+ imageCaption = (*it).mid(slash);
+
+ imageCaption.replace('_', ' ');
+ imageCaption = KStringHandler::capwords(imageCaption);
+ }
+
+ // avoid name collisions
+ TQString rs = imageCaption;
+ TQString lrs = rs.lower();
+ for (int n = 1; papers.find(lrs) != papers.end(); ++n)
+ {
+ rs = imageCaption + " (" + TQString::number(n) + ')';
+ lrs = rs.lower();
+ }
+ papers[lrs] = tqMakePair(rs, *it);
+ }
+ }
+
+ m_wallpaper.clear();
+ //don't start to 0, we have None element
+ int i = 1;
+ for (TQMap<TQString, TQPair<TQString, TQString> >::Iterator it = papers.begin();
+ it != papers.end();
+ ++it)
+ {
+ wallCB->insertItem(it.data().first);
+ m_wallpaper[it.data().second] = i;
+ i++;
+ }
+}
+
+void KChartBackgroundPixmapConfigPage::init()
+{
+#if 0
+ TQStringList lst;
+ lst.append(i18n( "Outermost Region" ));
+ lst.append(i18n( "Innermost Region" ));
+ lst.append(i18n( "Header+Title+Subtitle" ));
+ lst.append(i18n( "Footers" ));
+ lst.append(i18n( "Data+Axes+Legend" ));
+ lst.append(i18n( "Data+Axes" ));
+ lst.append(i18n( "Data" ));
+ lst.append(i18n( "Legend" ));
+ lst.append(i18n( "Left Axis" ));
+ lst.append(i18n( "Bottom Axis" ));
+ lst.append(i18n( "Right Axis" ));
+ lst.append(i18n( "Header A" ));
+ lst.append(i18n( "Header B" ));
+ lst.append(i18n( "Header C" ));
+ lst.append(i18n( "Title A" ));
+ lst.append(i18n( "Title B" ));
+ lst.append(i18n( "Title C" ));
+ lst.append(i18n( "Subtitle A" ));
+ lst.append(i18n( "Subtitle B" ));
+ lst.append(i18n( "Subtitle C" ));
+ lst.append(i18n( "Footer 1 A" ));
+ lst.append(i18n( "Footer 1 B" ));
+ lst.append(i18n( "Footer 1 C" ));
+ lst.append(i18n( "Footer 2 A" ));
+ lst.append(i18n( "Footer 2 B" ));
+ lst.append(i18n( "Footer 2 C" ));
+ lst.append(i18n( "Footer 3 A" ));
+ lst.append(i18n( "Footer 3 B" ));
+ lst.append(i18n( "Footer 3 C" ));
+ regionList->insertStringList(lst);
+#endif
+ // PENDING(kalle) Readapt
+ // showSettings( _params->backgroundPixmapName );
+// intensitySB->setValue( (int)(_params->backgroundPixmapIntensity * 100.0) );
+// scaledCB->setChecked( _params->backgroundPixmapScaled );
+// centeredCB->setChecked( _params->backgroundPixmapCentered );
+
+ bool bFound;
+ const KDChartParams::KDChartFrameSettings * innerFrame =
+ _params->frameSettings( KDChartEnums::AreaInnermost, bFound );
+ if( bFound )
+ {
+ const TQPixmap* backPixmap;
+ bool isTiledMode = false;
+ KDFrame::BackPixmapMode backPixmapMode;
+ const TQBrush& background = innerFrame->frame().background( backPixmap, backPixmapMode );
+ const TQColor backColor( background.color() );
+
+ // Bg color has to be be set in any case,
+ // even when a (tiled) pixmap is specified:
+ _backgroundCB->setColor( backColor );
+
+
+ if( !backPixmap || backPixmap->isNull() )
+ {
+ // A pixmap can be in the brush, if used as Tile.
+ backPixmap = background.pixmap();
+ if( backPixmap )
+ isTiledMode = true;
+ }
+
+ if( !backPixmap || backPixmap->isNull() ) //color as background
+ {
+ right->setEnabled( false );
+ wallCB->setCurrentItem( 0 );
+ }
+ else //pixmap as background
+ {
+ _backgroundCB->setEnabled( false );
+ wallWidget->setPaletteBackgroundPixmap( *backPixmap );
+ wallCB->setCurrentItem( 1 );
+ if( isTiledMode )
+ {
+ tiledRB->setChecked( true );
+ }
+ else
+ {
+ switch( backPixmapMode ){
+ case KDFrame::PixCentered:
+ centeredRB->setChecked( true );
+ break;
+ case KDFrame::PixScaled:
+ scaledRB->setChecked( true );
+ break;
+ default:
+ stretchedRB->setChecked( true );
+ }
+ }
+ }
+ }
+ else
+ _backgroundCB->setColor(TQColor(230, 222, 222) );
+}
+
+void KChartBackgroundPixmapConfigPage::apply()
+{
+ // PENDING(kalle) Readapt
+ // if( wallCB->currentText() != _params->backgroundPixmapName ) {
+// bool load=true;
+// if(wallCB->currentText()==i18n("None")) {
+// load=false;
+// } else {
+// _params->backgroundPixmapName = wallCB->currentText();
+// bool load=_params->backgroundPixmap.load( locate( "wallpaper", _params->backgroundPixmapName ) );
+// if(load)
+// _params->backgroundPixmapIsDirty = true;
+// }
+
+// if( !load ) {
+// _params->backgroundPixmapName = "";
+// _params->backgroundPixmap=TQPixmap("");
+// _params->backgroundPixmapIsDirty = false;
+// }
+// }
+// if( (int)(_params->backgroundPixmapIntensity * 100.0) !=
+// intensitySB->value() ) {
+// _params->backgroundPixmapIntensity = (float)(intensitySB->value()) / 100.0;
+// _params->backgroundPixmapIsDirty = true;
+// }
+
+// if( _params->backgroundPixmapScaled !=
+// scaledCB->isChecked() ) {
+// _params->backgroundPixmapScaled = scaledCB->isChecked();
+// _params->backgroundPixmapIsDirty = true;
+// }
+// if( _params->backgroundPixmapCentered !=
+// centeredCB->isChecked() ) {
+// _params->backgroundPixmapCentered = centeredCB->isChecked();
+// _params->backgroundPixmapIsDirty = true;
+// }
+
+ //
+ // temp. hack: the background is removed if "None" is selected in the combo box
+ //
+ // For KOffice 1.5/2.0 this is to be removed by a checkbox.
+ bool bFound;
+ const KDChartParams::KDChartFrameSettings * innerFrame =
+ _params->frameSettings( KDChartEnums::AreaInnermost, bFound );
+ if( bFound )
+ {
+ const TQColor backColor( _backgroundCB->color() );
+ KDFrame& frame( const_cast<KDFrame&>(innerFrame->frame()) );
+ if ( wallCB->currentItem() == 0 )
+ {
+ frame.setBackPixmap( 0 );
+ frame.setBackground( backColor );
+ }
+ else
+ {
+ const TQPixmap* pixmap = wallWidget->paletteBackgroundPixmap();
+ if ( tiledRB->isChecked() ){
+ // We remove the frame's extra pixmap,
+ frame.setBackPixmap( 0 );
+ // because a tiled image is set via a TQBrush.
+ if( pixmap )
+ frame.setBackground( TQBrush( backColor, *pixmap ) );
+ else
+ frame.setBackground( backColor );
+ }else{
+ KDFrame::BackPixmapMode backPixmapMode;
+ if ( centeredRB->isChecked() )
+ backPixmapMode = KDFrame::PixCentered;
+ else if ( scaledRB->isChecked() )
+ backPixmapMode = KDFrame::PixScaled;
+ else
+ backPixmapMode = KDFrame::PixStretched;
+ // We reset the background color, removing any tiled brush,
+ frame.setBackground( backColor );
+ // because we specify an extra pixmap instead.
+ frame.setBackPixmap( pixmap, backPixmapMode );
+ }
+ }
+ }
+}
+
+
+void KChartBackgroundPixmapConfigPage::showSettings( const TQString& fileName )
+{
+ wallCB->blockSignals(true);
+
+ if (m_wallpaper.find(fileName) == m_wallpaper.end())
+ {
+ int i = wallCB->count();
+ TQString imageCaption;
+ int slash = fileName.findRev('/') + 1;
+ int endDot = fileName.findRev('.');
+
+ // strip the extension if it exists
+ if (endDot != -1 && endDot > slash)
+ imageCaption = fileName.mid(slash, endDot - slash);
+ else
+ imageCaption = fileName.mid(slash);
+ if (wallCB->text(i-1) == imageCaption)
+ {
+ i--;
+ wallCB->removeItem(i);
+ }
+ wallCB->insertItem(imageCaption);
+ m_wallpaper[fileName] = i;
+ wallCB->setCurrentItem(i);
+ }
+ else
+ {
+ wallCB->setCurrentItem(m_wallpaper[fileName]);
+ }
+ wallCB->blockSignals(false);
+ loadWallPaper();
+}
+
+
+void KChartBackgroundPixmapConfigPage::slotBrowse()
+{
+ //TODO: Support non-local wallpapers
+ KURL url = KFileDialog::getOpenFileName( 0 );
+ if( url.isEmpty() )
+ return;
+ showSettings( url.path() );
+}
+
+void KChartBackgroundPixmapConfigPage::slotWallPaperChanged( int index )
+{
+ if ( index != 0 && loadWallPaper() )
+ {
+ _backgroundCB->setEnabled( false );
+ right->setEnabled( true );
+ }
+ else
+ {
+ wallWidget->setPaletteBackgroundPixmap( 0 );
+ _backgroundCB->setEnabled( true );
+ right->setEnabled( false );
+ }
+}
+
+
+bool KChartBackgroundPixmapConfigPage::loadWallPaper()
+{
+ int i = wallCB->currentItem();
+ if ( i == -1 || i == 0 ) { // 0 is 'None'
+ wallPixmap.resize(0,0);
+ wallFile = "";
+ } else {
+ for(TQMap<TQString,int>::ConstIterator it = m_wallpaper.begin();
+ it != m_wallpaper.end();
+ ++it)
+ {
+ if (it.data() == i)
+ {
+ wallFile = it.key();
+ break;
+ }
+ }
+ TQString file = locate("wallpaper", wallFile);
+ if( file.isEmpty() ) {
+ kdWarning(35001) << "Couldn't locate wallpaper " << wallFile << endl;
+ wallPixmap.resize(0,0);
+ wallFile = "";
+ return false;
+ } else {
+ wallPixmap.load( file );
+
+ if( wallPixmap.isNull() )
+ return false;
+// kdWarning(35001) << "Could not load wallpaper " << file << endl;
+ }
+ }
+ wallWidget->setPaletteBackgroundPixmap( wallPixmap );
+ return true;
+}
+
+} //KChart namespace
diff --git a/kchart/kchartColorConfigPage.cc b/kchart/kchartColorConfigPage.cpp
index 921b42c47..921b42c47 100644
--- a/kchart/kchartColorConfigPage.cc
+++ b/kchart/kchartColorConfigPage.cpp
diff --git a/kchart/kchartComboConfigPage.cc b/kchart/kchartComboConfigPage.cpp
index dcf99e4ac..dcf99e4ac 100644
--- a/kchart/kchartComboConfigPage.cc
+++ b/kchart/kchartComboConfigPage.cpp
diff --git a/kchart/kchartConfigDialog.cc b/kchart/kchartConfigDialog.cpp
index f0f57d625..f0f57d625 100644
--- a/kchart/kchartConfigDialog.cc
+++ b/kchart/kchartConfigDialog.cpp
diff --git a/kchart/kchartDataConfigPage.cc b/kchart/kchartDataConfigPage.cc
deleted file mode 100644
index f9cc7e25d..000000000
--- a/kchart/kchartDataConfigPage.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001,2002,2003,2004 Laurent Montel <montel@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include "kchartDataConfigPage.h"
-
-#include "kchartDataConfigPage.moc"
-
-#include <tdeapplication.h>
-#include <tdelocale.h>
-#include <kcolorbutton.h>
-#include <kdebug.h>
-
-#include <tqhbox.h>
-#include <tqlayout.h>
-#include <tqlabel.h>
-#include <tqlineedit.h>
-#include <tqlistbox.h>
-#include <tqbuttongroup.h>
-#include <tqvbuttongroup.h>
-#include <tqpushbutton.h>
-#include <tqradiobutton.h>
-#include <tqcheckbox.h>
-#include <tqpainter.h>
-#include <tqwhatsthis.h>
-
-#include <tdefontdialog.h>
-
-// For IRIX
-namespace std {}
-
-using namespace std;
-
-#include "kchart_params.h"
-#include "kchart_part.h"
-
-namespace KChart
-{
-
-KChartDataConfigPage::KChartDataConfigPage( KChartParams* params,
- TQWidget* parent,
- KDChartTableData *dat)
- : TQWidget( parent ), m_params( params ), data(dat),
- m_firstRowAsLabel(0), m_firstColAsLabel(0)
-{
- TQGridLayout *grid1 = new TQGridLayout(this, 4, 1, KDialog::marginHint(),
- KDialog::spacingHint());
-
- // The Data Area
- if ( !m_params->part()->canChangeValue() ) {
- TQButtonGroup *gb1 = new TQVButtonGroup( i18n( "Data Area" ), this );
-
- // ================================================================
- // This code is copied from kchartWizardSelectDataFormatPage.cc
- TQHBox *hbox = new TQHBox( gb1 );
- (void) new TQLabel( i18n("Area: "), hbox);
- m_dataArea = new TQLineEdit( hbox );
-
- // The row/column as label checkboxes.
- m_firstRowAsLabel = new TQCheckBox( i18n( "First row as label" ), gb1);
- m_firstColAsLabel = new TQCheckBox( i18n( "First column as label" ), gb1);
-
- grid1->addWidget(gb1, 0, 0);
- }
-
- // The Data Format button group
- TQButtonGroup *gb = new TQVButtonGroup( i18n( "Data Format" ), this );
-
- m_rowMajor = new TQRadioButton( i18n( "Data in rows" ), gb );
- m_rowMajor->resize( m_rowMajor->sizeHint() );
-
- m_colMajor = new TQRadioButton( i18n( "Data in columns" ), gb );
- m_colMajor->resize( m_colMajor->sizeHint() );
-
- grid1->addWidget(gb, 2, 0);
-
- TQWhatsThis::add(this, i18n("This configuration page can be used to swap the interpretation of rows and columns."));
- TQWhatsThis::add(m_rowMajor, i18n("By default one row is considered to be a data set and each column holds the individual values of the data series. This sets the data in rows on your chart."));
-
- TQWhatsThis::add(m_colMajor, i18n("Here you can choose to have each column hold one data set. Note that the values are not really swapped but only their interpretation."));
- m_colMajor->resize( m_colMajor->sizeHint() );
- grid1->addWidget(gb, 1, 0);
- grid1->setColStretch(3, 0);
-
- grid1->activate();
-}
-
-
-void KChartDataConfigPage::init()
-{
- if (m_params->dataDirection() == KChartParams::DataRows)
- m_rowMajor->setChecked(true);
- else
- m_colMajor->setChecked(true);
-
- if ( !m_params->part()->canChangeValue() ) {
- m_firstRowAsLabel->setChecked( m_params->firstRowAsLabel() );
- m_firstColAsLabel->setChecked( m_params->firstColAsLabel() );
-
- m_dataArea->setText( m_params->dataArea() );
- }
-}
-
-
-void KChartDataConfigPage::defaults()
-{
- m_colMajor->setChecked( true );
-
- if ( !m_params->part()->canChangeValue() ) {
- m_firstRowAsLabel->setChecked( false );
- m_firstColAsLabel->setChecked( false );
-
- m_dataArea->setText( "" );
- }
-}
-
-
-void KChartDataConfigPage::apply()
-{
- if (m_rowMajor->isChecked())
- m_params->setDataDirection( KChartParams::DataRows );
- else
- m_params->setDataDirection( KChartParams::DataColumns );
-
- if ( !m_params->part()->canChangeValue() ) {
- m_params->setFirstRowAsLabel( m_firstRowAsLabel->isChecked() );
- m_params->setFirstColAsLabel( m_firstColAsLabel->isChecked() );
-
- m_params->setDataArea( m_dataArea->text() );
- }
-}
-
-
-} //KChart namespace
diff --git a/kchart/kchartDataConfigPage.cpp b/kchart/kchartDataConfigPage.cpp
new file mode 100644
index 000000000..3a3968e40
--- /dev/null
+++ b/kchart/kchartDataConfigPage.cpp
@@ -0,0 +1,149 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001,2002,2003,2004 Laurent Montel <montel@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "kchartDataConfigPage.h"
+
+#include "kchartDataConfigPage.moc"
+
+#include <tdeapplication.h>
+#include <tdelocale.h>
+#include <kcolorbutton.h>
+#include <kdebug.h>
+
+#include <tqhbox.h>
+#include <tqlayout.h>
+#include <tqlabel.h>
+#include <tqlineedit.h>
+#include <tqlistbox.h>
+#include <tqbuttongroup.h>
+#include <tqvbuttongroup.h>
+#include <tqpushbutton.h>
+#include <tqradiobutton.h>
+#include <tqcheckbox.h>
+#include <tqpainter.h>
+#include <tqwhatsthis.h>
+
+#include <tdefontdialog.h>
+
+// For IRIX
+namespace std {}
+
+using namespace std;
+
+#include "kchart_params.h"
+#include "kchart_part.h"
+
+namespace KChart
+{
+
+KChartDataConfigPage::KChartDataConfigPage( KChartParams* params,
+ TQWidget* parent,
+ KDChartTableData *dat)
+ : TQWidget( parent ), m_params( params ), data(dat),
+ m_firstRowAsLabel(0), m_firstColAsLabel(0)
+{
+ TQGridLayout *grid1 = new TQGridLayout(this, 4, 1, KDialog::marginHint(),
+ KDialog::spacingHint());
+
+ // The Data Area
+ if ( !m_params->part()->canChangeValue() ) {
+ TQButtonGroup *gb1 = new TQVButtonGroup( i18n( "Data Area" ), this );
+
+ // ================================================================
+ // This code is copied from kchartWizardSelectDataFormatPage.cpp
+ TQHBox *hbox = new TQHBox( gb1 );
+ (void) new TQLabel( i18n("Area: "), hbox);
+ m_dataArea = new TQLineEdit( hbox );
+
+ // The row/column as label checkboxes.
+ m_firstRowAsLabel = new TQCheckBox( i18n( "First row as label" ), gb1);
+ m_firstColAsLabel = new TQCheckBox( i18n( "First column as label" ), gb1);
+
+ grid1->addWidget(gb1, 0, 0);
+ }
+
+ // The Data Format button group
+ TQButtonGroup *gb = new TQVButtonGroup( i18n( "Data Format" ), this );
+
+ m_rowMajor = new TQRadioButton( i18n( "Data in rows" ), gb );
+ m_rowMajor->resize( m_rowMajor->sizeHint() );
+
+ m_colMajor = new TQRadioButton( i18n( "Data in columns" ), gb );
+ m_colMajor->resize( m_colMajor->sizeHint() );
+
+ grid1->addWidget(gb, 2, 0);
+
+ TQWhatsThis::add(this, i18n("This configuration page can be used to swap the interpretation of rows and columns."));
+ TQWhatsThis::add(m_rowMajor, i18n("By default one row is considered to be a data set and each column holds the individual values of the data series. This sets the data in rows on your chart."));
+
+ TQWhatsThis::add(m_colMajor, i18n("Here you can choose to have each column hold one data set. Note that the values are not really swapped but only their interpretation."));
+ m_colMajor->resize( m_colMajor->sizeHint() );
+ grid1->addWidget(gb, 1, 0);
+ grid1->setColStretch(3, 0);
+
+ grid1->activate();
+}
+
+
+void KChartDataConfigPage::init()
+{
+ if (m_params->dataDirection() == KChartParams::DataRows)
+ m_rowMajor->setChecked(true);
+ else
+ m_colMajor->setChecked(true);
+
+ if ( !m_params->part()->canChangeValue() ) {
+ m_firstRowAsLabel->setChecked( m_params->firstRowAsLabel() );
+ m_firstColAsLabel->setChecked( m_params->firstColAsLabel() );
+
+ m_dataArea->setText( m_params->dataArea() );
+ }
+}
+
+
+void KChartDataConfigPage::defaults()
+{
+ m_colMajor->setChecked( true );
+
+ if ( !m_params->part()->canChangeValue() ) {
+ m_firstRowAsLabel->setChecked( false );
+ m_firstColAsLabel->setChecked( false );
+
+ m_dataArea->setText( "" );
+ }
+}
+
+
+void KChartDataConfigPage::apply()
+{
+ if (m_rowMajor->isChecked())
+ m_params->setDataDirection( KChartParams::DataRows );
+ else
+ m_params->setDataDirection( KChartParams::DataColumns );
+
+ if ( !m_params->part()->canChangeValue() ) {
+ m_params->setFirstRowAsLabel( m_firstRowAsLabel->isChecked() );
+ m_params->setFirstColAsLabel( m_firstColAsLabel->isChecked() );
+
+ m_params->setDataArea( m_dataArea->text() );
+ }
+}
+
+
+} //KChart namespace
diff --git a/kchart/kchartDataEditor.cc b/kchart/kchartDataEditor.cpp
index 8f08dd78b..8f08dd78b 100644
--- a/kchart/kchartDataEditor.cc
+++ b/kchart/kchartDataEditor.cpp
diff --git a/kchart/kchartFontConfigPage.cc b/kchart/kchartFontConfigPage.cpp
index 27f91581d..27f91581d 100644
--- a/kchart/kchartFontConfigPage.cc
+++ b/kchart/kchartFontConfigPage.cpp
diff --git a/kchart/kchartHeaderFooterConfigPage.cc b/kchart/kchartHeaderFooterConfigPage.cpp
index 8e11184ed..8e11184ed 100644
--- a/kchart/kchartHeaderFooterConfigPage.cc
+++ b/kchart/kchartHeaderFooterConfigPage.cpp
diff --git a/kchart/kchartLegendConfigPage.cc b/kchart/kchartLegendConfigPage.cpp
index dc18d7176..dc18d7176 100644
--- a/kchart/kchartLegendConfigPage.cc
+++ b/kchart/kchartLegendConfigPage.cpp
diff --git a/kchart/kchartLine3dConfigPage.cc b/kchart/kchartLine3dConfigPage.cpp
index f3750f739..f3750f739 100644
--- a/kchart/kchartLine3dConfigPage.cc
+++ b/kchart/kchartLine3dConfigPage.cpp
diff --git a/kchart/kchartPageLayout.cc b/kchart/kchartPageLayout.cpp
index e2587b9ff..e2587b9ff 100644
--- a/kchart/kchartPageLayout.cc
+++ b/kchart/kchartPageLayout.cpp
diff --git a/kchart/kchartParameter3dConfigPage.cc b/kchart/kchartParameter3dConfigPage.cpp
index 1b37b8cca..1b37b8cca 100644
--- a/kchart/kchartParameter3dConfigPage.cc
+++ b/kchart/kchartParameter3dConfigPage.cpp
diff --git a/kchart/kchartParameterConfigPage.cc b/kchart/kchartParameterConfigPage.cpp
index da6c8017f..da6c8017f 100644
--- a/kchart/kchartParameterConfigPage.cc
+++ b/kchart/kchartParameterConfigPage.cpp
diff --git a/kchart/kchartParameterPieConfigPage.cc b/kchart/kchartParameterPieConfigPage.cpp
index d640333ee..d640333ee 100644
--- a/kchart/kchartParameterPieConfigPage.cc
+++ b/kchart/kchartParameterPieConfigPage.cpp
diff --git a/kchart/kchartParameterPolarConfigPage.cc b/kchart/kchartParameterPolarConfigPage.cpp
index b6e1fe59d..b6e1fe59d 100644
--- a/kchart/kchartParameterPolarConfigPage.cc
+++ b/kchart/kchartParameterPolarConfigPage.cpp
diff --git a/kchart/kchartPieConfigPage.cc b/kchart/kchartPieConfigPage.cpp
index 31ec42a6b..31ec42a6b 100644
--- a/kchart/kchartPieConfigPage.cc
+++ b/kchart/kchartPieConfigPage.cpp
diff --git a/kchart/kchartPrinterDlg.cc b/kchart/kchartPrinterDlg.cpp
index a02592ded..a02592ded 100644
--- a/kchart/kchartPrinterDlg.cc
+++ b/kchart/kchartPrinterDlg.cpp
diff --git a/kchart/kchartSubTypeChartPage.cc b/kchart/kchartSubTypeChartPage.cpp
index 9ccad59eb..9ccad59eb 100644
--- a/kchart/kchartSubTypeChartPage.cc
+++ b/kchart/kchartSubTypeChartPage.cpp
diff --git a/kchart/kchartWizard.cc b/kchart/kchartWizard.cpp
index 01e5bf456..01e5bf456 100644
--- a/kchart/kchartWizard.cc
+++ b/kchart/kchartWizard.cpp
diff --git a/kchart/kchartWizardLabelsLegendPage.cc b/kchart/kchartWizardLabelsLegendPage.cpp
index 3899a2766..3899a2766 100644
--- a/kchart/kchartWizardLabelsLegendPage.cc
+++ b/kchart/kchartWizardLabelsLegendPage.cpp
diff --git a/kchart/kchartWizardSelectChartSubTypePage.cc b/kchart/kchartWizardSelectChartSubTypePage.cpp
index 2c86549a8..2c86549a8 100644
--- a/kchart/kchartWizardSelectChartSubTypePage.cc
+++ b/kchart/kchartWizardSelectChartSubTypePage.cpp
diff --git a/kchart/kchartWizardSelectChartTypePage.cc b/kchart/kchartWizardSelectChartTypePage.cpp
index 8ea02100b..8ea02100b 100644
--- a/kchart/kchartWizardSelectChartTypePage.cc
+++ b/kchart/kchartWizardSelectChartTypePage.cpp
diff --git a/kchart/kchartWizardSelectChartTypePage.h b/kchart/kchartWizardSelectChartTypePage.h
index 16c289440..91b62da34 100644
--- a/kchart/kchartWizardSelectChartTypePage.h
+++ b/kchart/kchartWizardSelectChartTypePage.h
@@ -18,7 +18,7 @@ class KChartPart;
// Contains a button with a text label below it
//
-// FIXME: Move to kchartWizardSelectChartTypePage.cc
+// FIXME: Move to kchartWizardSelectChartTypePage.cpp
class KChartButton : public TQVBox
{
Q_OBJECT
diff --git a/kchart/kchartWizardSelectDataFormatPage.cc b/kchart/kchartWizardSelectDataFormatPage.cpp
index d40e95fe7..d40e95fe7 100644
--- a/kchart/kchartWizardSelectDataFormatPage.cc
+++ b/kchart/kchartWizardSelectDataFormatPage.cpp
diff --git a/kchart/kchartWizardSelectDataPage.cc b/kchart/kchartWizardSelectDataPage.cpp
index 40dafc123..40dafc123 100644
--- a/kchart/kchartWizardSelectDataPage.cc
+++ b/kchart/kchartWizardSelectDataPage.cpp
diff --git a/kchart/kchartWizardSetupAxesPage.cc b/kchart/kchartWizardSetupAxesPage.cpp
index 5514e82b8..5514e82b8 100644
--- a/kchart/kchartWizardSetupAxesPage.cc
+++ b/kchart/kchartWizardSetupAxesPage.cpp
diff --git a/kchart/kchartWizardSetupDataPage.cc b/kchart/kchartWizardSetupDataPage.cpp
index 1d057d4ca..1d057d4ca 100644
--- a/kchart/kchartWizardSetupDataPage.cc
+++ b/kchart/kchartWizardSetupDataPage.cpp
diff --git a/kchart/kchart_factory.cc b/kchart/kchart_factory.cc
deleted file mode 100644
index 053627387..000000000
--- a/kchart/kchart_factory.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * $Id: kchart_factory.cc 483001 2005-11-24 18:27:18Z dfaure $
- *
- * Kalle Dalheimer <kalle@kde.org>
- */
-
-
-#include "kchart_factory.h"
-#include "kchart_aboutdata.h"
-#include "kchart_part.h"
-#include <tdelocale.h>
-#include <kinstance.h>
-#include <kdebug.h>
-#include <kiconloader.h>
-#include <kstandarddirs.h>
-
-namespace KChart
-{
-
-TDEInstance *KChartFactory::s_global = 0;
-TDEAboutData *KChartFactory::s_aboutData = 0;
-
-
-KChartFactory::KChartFactory( TQObject* parent, const char* name )
- : KoFactory( parent, name )
-{
- global();
-}
-
-
-KChartFactory::~KChartFactory()
-{
- delete s_aboutData;
- s_aboutData = 0;
- delete s_global;
- s_global = 0;
-}
-
-
-KParts::Part* KChartFactory::createPartObject( TQWidget *parentWidget,
- const char *widgetName,
- TQObject* parent,
- const char* name,
- const char *classname,
- const TQStringList & )
-{
- bool bWantKoDocument = ( strcmp( classname, "KoDocument" ) == 0 );
-
- KChartPart *part = new KChartPart( parentWidget, widgetName, parent, name,
- !bWantKoDocument );
-
- if ( !bWantKoDocument )
- part->setReadWrite( false );
-
- return part;
-}
-
-
-TDEAboutData* KChartFactory::aboutData()
-{
- if( !s_aboutData )
- s_aboutData = newKChartAboutData();
- return s_aboutData;
-}
-
-
-TDEInstance* KChartFactory::global()
-{
- if ( !s_global )
- {
- s_global = new TDEInstance(aboutData());
- s_global->dirs()->addResourceType( "kchart_template",
- TDEStandardDirs::kde_default("data") + "kchart/templates/");
- // Tell the iconloader about share/apps/koffice/icons
- s_global->iconLoader()->addAppDir("koffice");
- }
- return s_global;
-}
-
-} //namespace KChart
-
-#include <kchart_factory.moc>
diff --git a/kchart/kchart_factory.cpp b/kchart/kchart_factory.cpp
new file mode 100644
index 000000000..ff00f2058
--- /dev/null
+++ b/kchart/kchart_factory.cpp
@@ -0,0 +1,82 @@
+/**
+ * $Id: kchart_factory.cpp 483001 2005-11-24 18:27:18Z dfaure $
+ *
+ * Kalle Dalheimer <kalle@kde.org>
+ */
+
+
+#include "kchart_factory.h"
+#include "kchart_aboutdata.h"
+#include "kchart_part.h"
+#include <tdelocale.h>
+#include <kinstance.h>
+#include <kdebug.h>
+#include <kiconloader.h>
+#include <kstandarddirs.h>
+
+namespace KChart
+{
+
+TDEInstance *KChartFactory::s_global = 0;
+TDEAboutData *KChartFactory::s_aboutData = 0;
+
+
+KChartFactory::KChartFactory( TQObject* parent, const char* name )
+ : KoFactory( parent, name )
+{
+ global();
+}
+
+
+KChartFactory::~KChartFactory()
+{
+ delete s_aboutData;
+ s_aboutData = 0;
+ delete s_global;
+ s_global = 0;
+}
+
+
+KParts::Part* KChartFactory::createPartObject( TQWidget *parentWidget,
+ const char *widgetName,
+ TQObject* parent,
+ const char* name,
+ const char *classname,
+ const TQStringList & )
+{
+ bool bWantKoDocument = ( strcmp( classname, "KoDocument" ) == 0 );
+
+ KChartPart *part = new KChartPart( parentWidget, widgetName, parent, name,
+ !bWantKoDocument );
+
+ if ( !bWantKoDocument )
+ part->setReadWrite( false );
+
+ return part;
+}
+
+
+TDEAboutData* KChartFactory::aboutData()
+{
+ if( !s_aboutData )
+ s_aboutData = newKChartAboutData();
+ return s_aboutData;
+}
+
+
+TDEInstance* KChartFactory::global()
+{
+ if ( !s_global )
+ {
+ s_global = new TDEInstance(aboutData());
+ s_global->dirs()->addResourceType( "kchart_template",
+ TDEStandardDirs::kde_default("data") + "kchart/templates/");
+ // Tell the iconloader about share/apps/koffice/icons
+ s_global->iconLoader()->addAppDir("koffice");
+ }
+ return s_global;
+}
+
+} //namespace KChart
+
+#include <kchart_factory.moc>
diff --git a/kchart/kchart_factory_init.cc b/kchart/kchart_factory_init.cpp
index 42b2b2caf..42b2b2caf 100644
--- a/kchart/kchart_factory_init.cc
+++ b/kchart/kchart_factory_init.cpp
diff --git a/kchart/kchart_params.cc b/kchart/kchart_params.cpp
index 2cd8da51d..2cd8da51d 100644
--- a/kchart/kchart_params.cc
+++ b/kchart/kchart_params.cpp
diff --git a/kchart/kchart_part.cc b/kchart/kchart_part.cpp
index fb6a64143..fb6a64143 100644
--- a/kchart/kchart_part.cc
+++ b/kchart/kchart_part.cpp
diff --git a/kchart/kchart_view.cc b/kchart/kchart_view.cpp
index ba2d1321e..ba2d1321e 100644
--- a/kchart/kchart_view.cc
+++ b/kchart/kchart_view.cpp
diff --git a/kchart/main.cc b/kchart/main.cpp
index 97d046d1a..97d046d1a 100644
--- a/kchart/main.cc
+++ b/kchart/main.cpp
diff --git a/kexi/3rdparty/kexisql/Makefile.msvc b/kexi/3rdparty/kexisql/Makefile.msvc
index e6fae4775..01e3028f6 100644
--- a/kexi/3rdparty/kexisql/Makefile.msvc
+++ b/kexi/3rdparty/kexisql/Makefile.msvc
@@ -107,18 +107,13 @@ TARGET = $(TDEDIR)/bin/kexisql2_d.dll
####### Implicit rules
-.SUFFIXES: .c .cpp .cc .cxx .C
+.SUFFIXES: .c .cpp .cxx .C
{.}.cpp{obj\}.obj::
$(CXX) -c $(CXXFLAGS) $(INCPATH) -Foobj\ @<<
$<
<<
-{.}.cc{obj\}.obj::
- $(CXX) -c $(CXXFLAGS) $(INCPATH) -Foobj\ @<<
- $<
-<<
-
{.}.cxx{obj\}.obj::
$(CXX) -c $(CXXFLAGS) $(INCPATH) -Foobj\ @<<
$<
diff --git a/kexi/3rdparty/kolibs/Makefile.am b/kexi/3rdparty/kolibs/Makefile.am
index 05d3fbd31..c5b1cf7b2 100644
--- a/kexi/3rdparty/kolibs/Makefile.am
+++ b/kexi/3rdparty/kolibs/Makefile.am
@@ -3,10 +3,10 @@ include $(top_srcdir)/kexi/Makefile.global
noinst_LTLIBRARIES = libkexikolibs.la
libkexikolibs_la_SOURCES = \
-koGlobal.cc \
-koUnit.cc \
-koUnitWidgets.cc \
-koPageLayoutDia.cc \
+koGlobal.cpp \
+koUnit.cpp \
+koUnitWidgets.cpp \
+koPageLayoutDia.cpp \
KoPageLayoutColumnsBase.ui \
KoPageLayoutColumns.cpp \
koPageLayout.cpp \
diff --git a/kexi/3rdparty/kolibs/koGlobal.cc b/kexi/3rdparty/kolibs/koGlobal.cpp
index a375327fd..a375327fd 100644
--- a/kexi/3rdparty/kolibs/koGlobal.cc
+++ b/kexi/3rdparty/kolibs/koGlobal.cpp
diff --git a/kexi/3rdparty/kolibs/koPageLayoutDia.cc b/kexi/3rdparty/kolibs/koPageLayoutDia.cpp
index 2f0db91a3..2f0db91a3 100644
--- a/kexi/3rdparty/kolibs/koPageLayoutDia.cc
+++ b/kexi/3rdparty/kolibs/koPageLayoutDia.cpp
diff --git a/kexi/3rdparty/kolibs/koUnit.cc b/kexi/3rdparty/kolibs/koUnit.cpp
index a2eb289a1..a2eb289a1 100644
--- a/kexi/3rdparty/kolibs/koUnit.cc
+++ b/kexi/3rdparty/kolibs/koUnit.cpp
diff --git a/kexi/3rdparty/kolibs/koUnitWidgets.cc b/kexi/3rdparty/kolibs/koUnitWidgets.cpp
index 097dfc250..097dfc250 100644
--- a/kexi/3rdparty/kolibs/koUnitWidgets.cc
+++ b/kexi/3rdparty/kolibs/koUnitWidgets.cpp
diff --git a/kexi/doc/dev/TODO-Kexi-js b/kexi/doc/dev/TODO-Kexi-js
index 880c0d138..90b7d5f6e 100644
--- a/kexi/doc/dev/TODO-Kexi-js
+++ b/kexi/doc/dev/TODO-Kexi-js
@@ -607,7 +607,7 @@ for blobs...The client has to read the _entire_ blob into memory."; use:
- port to libpq
- set version information in drv_useDatabase()
There's connection_base::server_version() in libpqxx trunk -
- http://thaiopensource.org/development/libpqxx/file/trunk/include/pqxx/connection_base.hxx
+ http://thaiopensource.org/development/libpqxx/file/trunk/include/pqxx/connection_base.h
=== KEXIDB TESTS===
- add tests for DatabaseProperties
diff --git a/kexi/plugins/importexport/csv/kexicsvimportdialog.cpp b/kexi/plugins/importexport/csv/kexicsvimportdialog.cpp
index a1b1c6ea7..cf6604779 100644
--- a/kexi/plugins/importexport/csv/kexicsvimportdialog.cpp
+++ b/kexi/plugins/importexport/csv/kexicsvimportdialog.cpp
@@ -1,7 +1,7 @@
/* This file is part of the KDE project
Copyright (C) 2005-2006 Jaroslaw Staniek <js@iidea.pl>
- This work is based on kspread/dialogs/kspread_dlg_csv.cc
+ This work is based on kspread/dialogs/kspread_dlg_csv.cpp
and will be merged back with KOffice libraries.
Copyright (C) 2002-2003 Norbert Andres <nandres@web.de>
diff --git a/kexi/plugins/importexport/csv/kexicsvimportdialog.h b/kexi/plugins/importexport/csv/kexicsvimportdialog.h
index 4df8a621a..52724ca69 100644
--- a/kexi/plugins/importexport/csv/kexicsvimportdialog.h
+++ b/kexi/plugins/importexport/csv/kexicsvimportdialog.h
@@ -1,7 +1,7 @@
/* This file is part of the KDE project
Copyright (C) 2005-2006 Jaroslaw Staniek <js@iidea.pl>
- This work is based on kspread/dialogs/kspread_dlg_csv.cc
+ This work is based on kspread/dialogs/kspread_dlg_csv.cpp
and will be merged back with KOffice libraries.
Copyright (C) 2002-2003 Norbert Andres <nandres@web.de>
diff --git a/kexi/tools/build_tarball/build_kexi_tarball.sh b/kexi/tools/build_tarball/build_kexi_tarball.sh
index efc607df9..3159d815e 100755
--- a/kexi/tools/build_tarball/build_kexi_tarball.sh
+++ b/kexi/tools/build_tarball/build_kexi_tarball.sh
@@ -187,7 +187,7 @@ for dir in $EXC; do
mkdir $dir
done
#fix exectutable bits for sources:
-find . -name \*.h -o -name \*.cpp -o -name \*.c -o -name \*.cc -o -name \*.1 | xargs chmod a-x
+find . -name \*.h -o -name \*.cpp -o -name \*.c -o -name \*.1 | xargs chmod a-x
#other app-specific fixes:
fixAppSpecific
diff --git a/kformula/Makefile.am b/kformula/Makefile.am
index dd4338b65..9f7263cc2 100644
--- a/kformula/Makefile.am
+++ b/kformula/Makefile.am
@@ -3,16 +3,16 @@ KDE_CXXFLAGS = $(USE_RTTI)
## The part
kde_module_LTLIBRARIES = libkformulapart.la
-libkformulapart_la_SOURCES = kformula_doc.cc \
- kformula_view.cc kformula_factory.cc kformulawidget.cc kfconfig.cc \
- kformula_view_iface.skel kformula_view_iface.cc formulastring.cc fsparser.cc
+libkformulapart_la_SOURCES = kformula_doc.cpp \
+ kformula_view.cpp kformula_factory.cpp kformulawidget.cpp kfconfig.cpp \
+ kformula_view_iface.skel kformula_view_iface.cpp formulastring.cpp fsparser.cpp
libkformulapart_la_LDFLAGS = $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio $(KDE_PLUGIN) -lDCOP -ltdeparts
libkformulapart_la_LIBADD = $(KOFFICE_LIBS) $(LIB_KFORMULA) $(LIB_KOTEXT)
libkformulapart_la_METASOURCES = AUTO
## The tdeinit loadable module
tdeinit_LTLIBRARIES = kformula.la
-kformula_la_SOURCES = main.cc
+kformula_la_SOURCES = main.cpp
kformula_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT)
kformula_la_LIBADD = $(LIB_KOFFICECORE)
@@ -35,7 +35,7 @@ tip_DATA = tips
messages: rc.cpp
$(PREPARETIPS) >> rc.cpp
- $(XGETTEXT) rc.cpp *.cc kformula_aboutdata.h -o $(podir)/kformula.pot
+ $(XGETTEXT) rc.cpp *.cpp kformula_aboutdata.h -o $(podir)/kformula.pot
kde_services_DATA = kformulapart.desktop
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kformula/formulastring.cc b/kformula/formulastring.cpp
index f86b113a4..f86b113a4 100644
--- a/kformula/formulastring.cc
+++ b/kformula/formulastring.cpp
diff --git a/kformula/fsparser.cc b/kformula/fsparser.cpp
index b6bdd787c..b6bdd787c 100644
--- a/kformula/fsparser.cc
+++ b/kformula/fsparser.cpp
diff --git a/kformula/kfconfig.cc b/kformula/kfconfig.cpp
index 82e3ae65f..82e3ae65f 100644
--- a/kformula/kfconfig.cc
+++ b/kformula/kfconfig.cpp
diff --git a/kformula/kformula_doc.cc b/kformula/kformula_doc.cpp
index 5eeb59f4b..5eeb59f4b 100644
--- a/kformula/kformula_doc.cc
+++ b/kformula/kformula_doc.cpp
diff --git a/kformula/kformula_factory.cc b/kformula/kformula_factory.cpp
index 1aebcfbd7..1aebcfbd7 100644
--- a/kformula/kformula_factory.cc
+++ b/kformula/kformula_factory.cpp
diff --git a/kformula/kformula_view.cc b/kformula/kformula_view.cpp
index 2d93ce5d8..2d93ce5d8 100644
--- a/kformula/kformula_view.cc
+++ b/kformula/kformula_view.cpp
diff --git a/kformula/kformula_view_iface.cc b/kformula/kformula_view_iface.cpp
index c3b859087..c3b859087 100644
--- a/kformula/kformula_view_iface.cc
+++ b/kformula/kformula_view_iface.cpp
diff --git a/kformula/kformulawidget.cc b/kformula/kformulawidget.cpp
index b505d817d..b505d817d 100644
--- a/kformula/kformulawidget.cc
+++ b/kformula/kformulawidget.cpp
diff --git a/kformula/main.cc b/kformula/main.cpp
index a2337241d..a2337241d 100644
--- a/kformula/main.cc
+++ b/kformula/main.cpp
diff --git a/kivio/kiviopart/KIvioDocIface.cc b/kivio/kiviopart/KIvioDocIface.cpp
index e9ab089f1..e9ab089f1 100644
--- a/kivio/kiviopart/KIvioDocIface.cc
+++ b/kivio/kiviopart/KIvioDocIface.cpp
diff --git a/kivio/kiviopart/KIvioLayerIface.cc b/kivio/kiviopart/KIvioLayerIface.cpp
index c2e667afe..c2e667afe 100644
--- a/kivio/kiviopart/KIvioLayerIface.cc
+++ b/kivio/kiviopart/KIvioLayerIface.cpp
diff --git a/kivio/kiviopart/KIvioMapIface.cc b/kivio/kiviopart/KIvioMapIface.cpp
index 99397692e..99397692e 100644
--- a/kivio/kiviopart/KIvioMapIface.cc
+++ b/kivio/kiviopart/KIvioMapIface.cpp
diff --git a/kivio/kiviopart/KIvioPageIface.cc b/kivio/kiviopart/KIvioPageIface.cpp
index 26ba9a2e4..26ba9a2e4 100644
--- a/kivio/kiviopart/KIvioPageIface.cc
+++ b/kivio/kiviopart/KIvioPageIface.cpp
diff --git a/kivio/kiviopart/KIvioStencilIface.cc b/kivio/kiviopart/KIvioStencilIface.cpp
index 61c5542e1..61c5542e1 100644
--- a/kivio/kiviopart/KIvioStencilIface.cc
+++ b/kivio/kiviopart/KIvioStencilIface.cpp
diff --git a/kivio/kiviopart/KIvioViewIface.cc b/kivio/kiviopart/KIvioViewIface.cpp
index f8d7477c8..f8d7477c8 100644
--- a/kivio/kiviopart/KIvioViewIface.cc
+++ b/kivio/kiviopart/KIvioViewIface.cpp
diff --git a/kivio/kiviopart/Makefile.am b/kivio/kiviopart/Makefile.am
index 39bae3fb0..8eb5a7ec0 100644
--- a/kivio/kiviopart/Makefile.am
+++ b/kivio/kiviopart/Makefile.am
@@ -30,17 +30,17 @@ libkiviocommon_la_SOURCES = kivio_canvas.cpp kivio_doc.cpp kivio_factory.cpp \
kivio_view.cpp kivio_map.cpp kivio_page.cpp kivio_dlg_pageshow.cpp \
kivio_zoomaction.cpp kivio_icon_view.cpp kivio_spawner_drag.cpp kivio_intra_stencil_data.cpp \
kivio_stackbar.cpp stencilbarbutton.cpp stencilbardockmanager.cpp kivio_grid_data.cpp \
- kivio_stencil_geometry_panel.cpp KIvioViewIface.skel KIvioViewIface.cc KIvioDocIface.skel \
- KIvioDocIface.cc KIvioMapIface.skel KIvioMapIface.cc KIvioPageIface.skel \
- KIvioPageIface.cc kivio_command.cc KIvioLayerIface.skel KIvioLayerIface.cc \
+ kivio_stencil_geometry_panel.cpp KIvioViewIface.skel KIvioViewIface.cpp KIvioDocIface.skel \
+ KIvioDocIface.cpp KIvioMapIface.skel KIvioMapIface.cpp KIvioPageIface.skel \
+ KIvioPageIface.cpp kivio_command.cpp KIvioLayerIface.skel KIvioLayerIface.cpp \
kivioglobal.cpp kiviostencilsetaction.cpp kivioarrowheadaction.cpp \
- KIvioStencilIface.skel KIvioStencilIface.cc kiviodragobject.cpp kiviostencilsetinstaller.cpp \
+ KIvioStencilIface.skel KIvioStencilIface.cpp kiviodragobject.cpp kiviostencilsetinstaller.cpp \
addstenciltool.cpp
kde_module_LTLIBRARIES = libkiviopart.la
libkiviopart_la_LDFLAGS = -avoid-version $(all_libraries) -module
libkiviopart_la_LIBADD = libkiviocommon.la
-libkiviopart_la_SOURCES = kivio_part_init.cc
+libkiviopart_la_SOURCES = kivio_part_init.cpp
dummy.cpp:
echo > dummy.cpp
diff --git a/kivio/kiviopart/kivio_command.cc b/kivio/kiviopart/kivio_command.cpp
index 4633a60fe..4633a60fe 100644
--- a/kivio/kiviopart/kivio_command.cc
+++ b/kivio/kiviopart/kivio_command.cpp
diff --git a/kivio/kiviopart/kivio_part_init.cc b/kivio/kiviopart/kivio_part_init.cpp
index 9800fb0f6..9800fb0f6 100644
--- a/kivio/kiviopart/kivio_part_init.cc
+++ b/kivio/kiviopart/kivio_part_init.cpp
diff --git a/koshell/Makefile.am b/koshell/Makefile.am
index a8bd72883..927df925a 100644
--- a/koshell/Makefile.am
+++ b/koshell/Makefile.am
@@ -5,7 +5,7 @@ INCLUDES = $(KOFFICE_INCLUDES) $(all_includes)
lib_LTLIBRARIES =
tdeinit_LTLIBRARIES = koshell.la
bin_PROGRAMS =
-koshell_la_SOURCES = koshell_main.cc koshell_shell.cc iconsidepane.cpp koshellsettings.kcfgc
+koshell_la_SOURCES = koshell_main.cpp koshell_shell.cpp iconsidepane.cpp koshellsettings.kcfgc
koshell_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(LIB_TQT)
koshell_la_LIBADD = $(LIB_KOFFICEUI)
kde_kcfg_DATA = koshell.kcfg
@@ -20,7 +20,7 @@ rc_DATA = koshellui.rc
xdg_apps_DATA = koshell.desktop
messages: rc.cpp
- $(XGETTEXT) rc.cpp *.cc *.cpp -o $(podir)/koshell.pot
+ $(XGETTEXT) rc.cpp *.cpp *.cpp -o $(podir)/koshell.pot
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/koshell/koshell_main.cc b/koshell/koshell_main.cpp
index e816cd9e1..e816cd9e1 100644
--- a/koshell/koshell_main.cc
+++ b/koshell/koshell_main.cpp
diff --git a/koshell/koshell_shell.cc b/koshell/koshell_shell.cpp
index aaff3c02b..aaff3c02b 100644
--- a/koshell/koshell_shell.cc
+++ b/koshell/koshell_shell.cpp
diff --git a/kounavail/Makefile.am b/kounavail/Makefile.am
index 472fa1cc8..b0cba4ee3 100644
--- a/kounavail/Makefile.am
+++ b/kounavail/Makefile.am
@@ -2,7 +2,7 @@ INCLUDES = $(KOFFICE_INCLUDES) $(all_includes)
## The part
kde_module_LTLIBRARIES = libkounavailpart.la
-libkounavailpart_la_SOURCES = kounavail.cc
+libkounavailpart_la_SOURCES = kounavail.cpp
libkounavailpart_la_LDFLAGS = $(KDE_PLUGIN) $(all_libraries) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkounavailpart_la_LIBADD = $(LIB_KOFFICECORE)
@@ -13,4 +13,4 @@ kdelnk_DATA = kounavail.desktop
kdelnkdir = $(kde_servicesdir)
messages:
- $(XGETTEXT) *.cc -o $(podir)/kounavail.pot
+ $(XGETTEXT) *.cpp -o $(podir)/kounavail.pot
diff --git a/kounavail/kounavail.cc b/kounavail/kounavail.cpp
index 47bfd5036..47bfd5036 100644
--- a/kounavail/kounavail.cc
+++ b/kounavail/kounavail.cpp
diff --git a/kplato/KPtViewIface.cc b/kplato/KPtViewIface.cpp
index dafd718d3..dafd718d3 100644
--- a/kplato/KPtViewIface.cc
+++ b/kplato/KPtViewIface.cpp
diff --git a/kplato/Makefile.am b/kplato/Makefile.am
index 42d936a97..146a789b0 100644
--- a/kplato/Makefile.am
+++ b/kplato/Makefile.am
@@ -6,56 +6,56 @@ INCLUDES = $(KOFFICE_INCLUDES) $(KOTEXT_INCLUDES) \
libkplatopart_la_SOURCES = \
kptsummarytaskgeneralpanelbase.ui \
- kptsummarytaskdialog.cc \
- kptsummarytaskgeneralpanel.cc \
- kptschedule.cc \
- kptappointment.cc \
+ kptsummarytaskdialog.cpp \
+ kptsummarytaskgeneralpanel.cpp \
+ kptschedule.cpp \
+ kptappointment.cpp \
kptcalendarlistpanel.ui \
- kptresourceappointmentsview.cc \
- kpttaskappointmentsview.cc \
- kptdoublelistviewbase.cc \
- kptaccountsviewconfigdialog.cc \
+ kptresourceappointmentsview.cpp \
+ kpttaskappointmentsview.cpp \
+ kptdoublelistviewbase.cpp \
+ kptaccountsviewconfigdialog.cpp \
kptaccountsviewconfigurepanelbase.ui \
- kptaccountsview.cc \
+ kptaccountsview.cpp \
kpttaskcostpanelbase.ui \
- kpttaskcostpanel.cc \
- kptmilestoneprogresspanel.cc \
+ kpttaskcostpanel.cpp \
+ kptmilestoneprogresspanel.cpp \
kptmilestoneprogresspanelbase.ui \
- kptmilestoneprogressdialog.cc \
- kptaccount.cc kptaccountsdialog.cc kptaccountspanel.cc kptaccountspanelbase.ui \
- kptnode.cc kptproject.cc \
- kptrelation.cc kptresource.cc kpttask.cc \
- kptduration.cc kptfactory.cc kptpart.cc kptview.cc \
+ kptmilestoneprogressdialog.cpp \
+ kptaccount.cpp kptaccountsdialog.cpp kptaccountspanel.cpp kptaccountspanelbase.ui \
+ kptnode.cpp kptproject.cpp \
+ kptrelation.cpp kptresource.cpp kpttask.cpp \
+ kptduration.cpp kptfactory.cpp kptpart.cpp kptview.cpp \
kptdurationwidget.ui relationpanel.ui\
- kptprojectdialog.cc kpttaskdialog.cc \
- kptmainprojectdialog.cc kptmainprojectpanel.cc kptmainprojectpanelbase.ui \
- kptganttview.cc kptresourcespanel.cc \
- kptpertview.cc kptpertcanvas.cc kptrelationdialog.cc \
- kptcanvasitem.cc kptprojectdialogbase.ui \
+ kptprojectdialog.cpp kpttaskdialog.cpp \
+ kptmainprojectdialog.cpp kptmainprojectpanel.cpp kptmainprojectpanelbase.ui \
+ kptganttview.cpp kptresourcespanel.cpp \
+ kptpertview.cpp kptpertcanvas.cpp kptrelationdialog.cpp \
+ kptcanvasitem.cpp kptprojectdialogbase.ui \
resourcespanelbase.ui \
- kptresourceview.cc \
- kpttastderesourcespanelbase.ui kptrequestresourcespanel.cc \
- resourcedialogbase.ui kptresourcedialog.cc \
+ kptresourceview.cpp \
+ kpttastderesourcespanelbase.ui kptrequestresourcespanel.cpp \
+ resourcedialogbase.ui kptresourcedialog.cpp \
kpttaskgeneralpanelbase.ui \
kpttasknotespanelbase.ui \
- kptdatetime.cc \
- kptcalendar.cc kptcalendaredit.cc kptcalendarlistdialog.cc \
- kptcalendarpanel.cc kptdatetable.cc \
- kptcalendarlistdialogbase.cc kptcalendareditbase.cc \
- kptcommand.cc KPtViewIface.cc KPtViewIface.skel \
- standardworktimedialogbase.ui kptstandardworktimedialog.cc \
- kptintervaleditbase.ui kptintervaledit.cc \
- kpttaskgeneralpanel.cc kpttaskdefaultpanel.cc \
+ kptdatetime.cpp \
+ kptcalendar.cpp kptcalendaredit.cpp kptcalendarlistdialog.cpp \
+ kptcalendarpanel.cpp kptdatetable.cpp \
+ kptcalendarlistdialogbase.cpp kptcalendareditbase.cpp \
+ kptcommand.cpp KPtViewIface.cpp KPtViewIface.skel \
+ standardworktimedialogbase.ui kptstandardworktimedialog.cpp \
+ kptintervaleditbase.ui kptintervaledit.cpp \
+ kpttaskgeneralpanel.cpp kpttaskdefaultpanel.cpp \
kptconfigtaskpanelbase.ui \
- kptconfigdialog.cc \
- kpttaskprogresspanel.cc kpttaskprogresspanelbase.ui \
- kpttaskprogressdialog.cc \
- kptconfig.cc kptcontext.cc \
- kptresourcesdialog.cc \
- kptwbsdefinitiondialog.cc kptwbsdefinitionpanel.cc kptwbsdefinitionpanelbase.ui \
- kptwbsdefinition.cc
-## kptconfigbehaviorpanel.cc kptconfigbehaviorpanelbase.ui \
-## kptreportview.cc
+ kptconfigdialog.cpp \
+ kpttaskprogresspanel.cpp kpttaskprogresspanelbase.ui \
+ kpttaskprogressdialog.cpp \
+ kptconfig.cpp kptcontext.cpp \
+ kptresourcesdialog.cpp \
+ kptwbsdefinitiondialog.cpp kptwbsdefinitionpanel.cpp kptwbsdefinitionpanelbase.ui \
+ kptwbsdefinition.cpp
+## kptconfigbehaviorpanel.cpp kptconfigbehaviorpanelbase.ui \
+## kptreportview.cpp
# (this is not used)
noinst_HEADERS = \
@@ -112,7 +112,7 @@ libkplatopart_la_METASOURCES = AUTO
## The tdeinit loadable module and executable
tdeinit_LTLIBRARIES = kplato.la
bin_PROGRAMS =
-kplato_la_SOURCES = main.cc
+kplato_la_SOURCES = main.cpp
kplato_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts -ltdeprint
kplato_la_LIBADD = $(KOFFICE_LIBS)
@@ -124,7 +124,7 @@ rc_DATA = kplato.rc kplato_readonly.rc
## NOTE: extractattr needs <Label & Text on same line!
messages: rc.cpp
$(EXTRACTATTR) --attr=Label,Text reports/*.ktf >>rc.cpp
- $(XGETTEXT) rc.cpp *.cc kptaboutdata.h -o $(podir)/kplato.pot
+ $(XGETTEXT) rc.cpp *.cpp kptaboutdata.h -o $(podir)/kplato.pot
kde_services_DATA = kplatopart.desktop
diff --git a/kplato/TODO b/kplato/TODO
index 746a4a272..0526cf557 100644
--- a/kplato/TODO
+++ b/kplato/TODO
@@ -97,7 +97,7 @@ Taken User manual (contact: raphael.langerhorst@kdemail.net)
Taskjuggler???
Change source filenames to 'classname'.cpp and d:o .h
- Eg: kpttask.cc -> Task.cpp kpttask.h -> Task.h
+ Eg: kpttask.cpp -> Task.cpp kpttask.h -> Task.h
Also remove the .ui filename prefix.
------------------------------------------------------------------
Done Remove Networkview.
diff --git a/kplato/kplato.tdevelop b/kplato/kplato.tdevelop
index cae30836d..2be3b5395 100644
--- a/kplato/kplato.tdevelop
+++ b/kplato/kplato.tdevelop
@@ -17,7 +17,7 @@
</general>
<kdevfileview>
<groups>
- <group pattern="*.cpp;*.cxx;*.h" name="Sources" />
+ <group pattern="*.cpp;*.h" name="Sources" />
<group pattern="*.ui" name="User Interface" />
<group pattern="*.png" name="Icons" />
<group pattern="*.po;*.ts" name="Translations" />
diff --git a/kplato/kptaccount.cc b/kplato/kptaccount.cpp
index f6016ff45..f6016ff45 100644
--- a/kplato/kptaccount.cc
+++ b/kplato/kptaccount.cpp
diff --git a/kplato/kptaccountsdialog.cc b/kplato/kptaccountsdialog.cpp
index 7ecc7bf1e..7ecc7bf1e 100644
--- a/kplato/kptaccountsdialog.cc
+++ b/kplato/kptaccountsdialog.cpp
diff --git a/kplato/kptaccountspanel.cc b/kplato/kptaccountspanel.cpp
index 3a6015d8b..3a6015d8b 100644
--- a/kplato/kptaccountspanel.cc
+++ b/kplato/kptaccountspanel.cpp
diff --git a/kplato/kptaccountsview.cc b/kplato/kptaccountsview.cpp
index 3352a87de..3352a87de 100644
--- a/kplato/kptaccountsview.cc
+++ b/kplato/kptaccountsview.cpp
diff --git a/kplato/kptaccountsviewconfigdialog.cc b/kplato/kptaccountsviewconfigdialog.cpp
index 18e63fb66..18e63fb66 100644
--- a/kplato/kptaccountsviewconfigdialog.cc
+++ b/kplato/kptaccountsviewconfigdialog.cpp
diff --git a/kplato/kptappointment.cc b/kplato/kptappointment.cpp
index f09b4bcc6..f09b4bcc6 100644
--- a/kplato/kptappointment.cc
+++ b/kplato/kptappointment.cpp
diff --git a/kplato/kptcalendar.cc b/kplato/kptcalendar.cpp
index 461950410..461950410 100644
--- a/kplato/kptcalendar.cc
+++ b/kplato/kptcalendar.cpp
diff --git a/kplato/kptcalendaredit.cc b/kplato/kptcalendaredit.cpp
index a29eb8c09..a29eb8c09 100644
--- a/kplato/kptcalendaredit.cc
+++ b/kplato/kptcalendaredit.cpp
diff --git a/kplato/kptcalendareditbase.cc b/kplato/kptcalendareditbase.cpp
index 6349c273e..6349c273e 100644
--- a/kplato/kptcalendareditbase.cc
+++ b/kplato/kptcalendareditbase.cpp
diff --git a/kplato/kptcalendarlistdialog.cc b/kplato/kptcalendarlistdialog.cpp
index 496cc786b..496cc786b 100644
--- a/kplato/kptcalendarlistdialog.cc
+++ b/kplato/kptcalendarlistdialog.cpp
diff --git a/kplato/kptcalendarlistdialogbase.cc b/kplato/kptcalendarlistdialogbase.cpp
index bc59788ff..bc59788ff 100644
--- a/kplato/kptcalendarlistdialogbase.cc
+++ b/kplato/kptcalendarlistdialogbase.cpp
diff --git a/kplato/kptcalendarpanel.cc b/kplato/kptcalendarpanel.cpp
index 8717f187b..8717f187b 100644
--- a/kplato/kptcalendarpanel.cc
+++ b/kplato/kptcalendarpanel.cpp
diff --git a/kplato/kptcanvasitem.cc b/kplato/kptcanvasitem.cpp
index 152fd837f..152fd837f 100644
--- a/kplato/kptcanvasitem.cc
+++ b/kplato/kptcanvasitem.cpp
diff --git a/kplato/kptcommand.cc b/kplato/kptcommand.cpp
index 11c920006..11c920006 100644
--- a/kplato/kptcommand.cc
+++ b/kplato/kptcommand.cpp
diff --git a/kplato/kptconfig.cc b/kplato/kptconfig.cpp
index 358b57978..358b57978 100644
--- a/kplato/kptconfig.cc
+++ b/kplato/kptconfig.cpp
diff --git a/kplato/kptconfigbehaviorpanel.cc b/kplato/kptconfigbehaviorpanel.cpp
index f721ae234..f721ae234 100644
--- a/kplato/kptconfigbehaviorpanel.cc
+++ b/kplato/kptconfigbehaviorpanel.cpp
diff --git a/kplato/kptconfigdialog.cc b/kplato/kptconfigdialog.cpp
index 384c4abde..384c4abde 100644
--- a/kplato/kptconfigdialog.cc
+++ b/kplato/kptconfigdialog.cpp
diff --git a/kplato/kptcontext.cc b/kplato/kptcontext.cpp
index 830c6c957..830c6c957 100644
--- a/kplato/kptcontext.cc
+++ b/kplato/kptcontext.cpp
diff --git a/kplato/kptdatetable.cc b/kplato/kptdatetable.cpp
index ea8e16afb..ea8e16afb 100644
--- a/kplato/kptdatetable.cc
+++ b/kplato/kptdatetable.cpp
diff --git a/kplato/kptdatetime.cc b/kplato/kptdatetime.cpp
index 2a05ace5c..2a05ace5c 100644
--- a/kplato/kptdatetime.cc
+++ b/kplato/kptdatetime.cpp
diff --git a/kplato/kptdoublelistviewbase.cc b/kplato/kptdoublelistviewbase.cpp
index d6bc73d4f..d6bc73d4f 100644
--- a/kplato/kptdoublelistviewbase.cc
+++ b/kplato/kptdoublelistviewbase.cpp
diff --git a/kplato/kptduration.cc b/kplato/kptduration.cpp
index 87e0e54a0..87e0e54a0 100644
--- a/kplato/kptduration.cc
+++ b/kplato/kptduration.cpp
diff --git a/kplato/kptfactory.cc b/kplato/kptfactory.cpp
index 7d66a7406..7d66a7406 100644
--- a/kplato/kptfactory.cc
+++ b/kplato/kptfactory.cpp
diff --git a/kplato/kptganttview.cc b/kplato/kptganttview.cpp
index b84bbbc49..b84bbbc49 100644
--- a/kplato/kptganttview.cc
+++ b/kplato/kptganttview.cpp
diff --git a/kplato/kptintervaledit.cc b/kplato/kptintervaledit.cpp
index a37ec064c..a37ec064c 100644
--- a/kplato/kptintervaledit.cc
+++ b/kplato/kptintervaledit.cpp
diff --git a/kplato/kptmainprojectdialog.cc b/kplato/kptmainprojectdialog.cpp
index 3d9065e20..3d9065e20 100644
--- a/kplato/kptmainprojectdialog.cc
+++ b/kplato/kptmainprojectdialog.cpp
diff --git a/kplato/kptmainprojectpanel.cc b/kplato/kptmainprojectpanel.cpp
index 375b04f12..375b04f12 100644
--- a/kplato/kptmainprojectpanel.cc
+++ b/kplato/kptmainprojectpanel.cpp
diff --git a/kplato/kptmilestoneprogressdialog.cc b/kplato/kptmilestoneprogressdialog.cpp
index f9bf729e9..f9bf729e9 100644
--- a/kplato/kptmilestoneprogressdialog.cc
+++ b/kplato/kptmilestoneprogressdialog.cpp
diff --git a/kplato/kptmilestoneprogresspanel.cc b/kplato/kptmilestoneprogresspanel.cpp
index 977878f10..977878f10 100644
--- a/kplato/kptmilestoneprogresspanel.cc
+++ b/kplato/kptmilestoneprogresspanel.cpp
diff --git a/kplato/kptnode.cc b/kplato/kptnode.cpp
index b56146094..b56146094 100644
--- a/kplato/kptnode.cc
+++ b/kplato/kptnode.cpp
diff --git a/kplato/kptpart.cc b/kplato/kptpart.cpp
index 53ed107f0..53ed107f0 100644
--- a/kplato/kptpart.cc
+++ b/kplato/kptpart.cpp
diff --git a/kplato/kptpertcanvas.cc b/kplato/kptpertcanvas.cpp
index 9d12945cf..9d12945cf 100644
--- a/kplato/kptpertcanvas.cc
+++ b/kplato/kptpertcanvas.cpp
diff --git a/kplato/kptpertview.cc b/kplato/kptpertview.cpp
index f68d9eb8e..f68d9eb8e 100644
--- a/kplato/kptpertview.cc
+++ b/kplato/kptpertview.cpp
diff --git a/kplato/kptproject.cc b/kplato/kptproject.cpp
index 97eb82028..97eb82028 100644
--- a/kplato/kptproject.cc
+++ b/kplato/kptproject.cpp
diff --git a/kplato/kptprojectdialog.cc b/kplato/kptprojectdialog.cpp
index 1b547629b..1b547629b 100644
--- a/kplato/kptprojectdialog.cc
+++ b/kplato/kptprojectdialog.cpp
diff --git a/kplato/kptrelation.cc b/kplato/kptrelation.cpp
index e84b72a29..e84b72a29 100644
--- a/kplato/kptrelation.cc
+++ b/kplato/kptrelation.cpp
diff --git a/kplato/kptrelationdialog.cc b/kplato/kptrelationdialog.cpp
index 4de50c110..4de50c110 100644
--- a/kplato/kptrelationdialog.cc
+++ b/kplato/kptrelationdialog.cpp
diff --git a/kplato/kptreportview.cc b/kplato/kptreportview.cpp
index dbbae9a17..dbbae9a17 100644
--- a/kplato/kptreportview.cc
+++ b/kplato/kptreportview.cpp
diff --git a/kplato/kptrequestresourcespanel.cc b/kplato/kptrequestresourcespanel.cpp
index 790a61777..790a61777 100644
--- a/kplato/kptrequestresourcespanel.cc
+++ b/kplato/kptrequestresourcespanel.cpp
diff --git a/kplato/kptresource.cc b/kplato/kptresource.cpp
index 763c0c86c..763c0c86c 100644
--- a/kplato/kptresource.cc
+++ b/kplato/kptresource.cpp
diff --git a/kplato/kptresourceappointmentsview.cc b/kplato/kptresourceappointmentsview.cpp
index a251eddba..a251eddba 100644
--- a/kplato/kptresourceappointmentsview.cc
+++ b/kplato/kptresourceappointmentsview.cpp
diff --git a/kplato/kptresourcedialog.cc b/kplato/kptresourcedialog.cpp
index 8e2c24fd8..8e2c24fd8 100644
--- a/kplato/kptresourcedialog.cc
+++ b/kplato/kptresourcedialog.cpp
diff --git a/kplato/kptresourcesdialog.cc b/kplato/kptresourcesdialog.cpp
index 37ce45298..37ce45298 100644
--- a/kplato/kptresourcesdialog.cc
+++ b/kplato/kptresourcesdialog.cpp
diff --git a/kplato/kptresourcespanel.cc b/kplato/kptresourcespanel.cpp
index 86275cd73..86275cd73 100644
--- a/kplato/kptresourcespanel.cc
+++ b/kplato/kptresourcespanel.cpp
diff --git a/kplato/kptresourceview.cc b/kplato/kptresourceview.cpp
index c20b9fd26..c20b9fd26 100644
--- a/kplato/kptresourceview.cc
+++ b/kplato/kptresourceview.cpp
diff --git a/kplato/kptschedule.cc b/kplato/kptschedule.cpp
index 7581312e0..7581312e0 100644
--- a/kplato/kptschedule.cc
+++ b/kplato/kptschedule.cpp
diff --git a/kplato/kptstandardworktimedialog.cc b/kplato/kptstandardworktimedialog.cpp
index 31fcae494..31fcae494 100644
--- a/kplato/kptstandardworktimedialog.cc
+++ b/kplato/kptstandardworktimedialog.cpp
diff --git a/kplato/kptsummarytaskdialog.cc b/kplato/kptsummarytaskdialog.cpp
index adf152a19..adf152a19 100644
--- a/kplato/kptsummarytaskdialog.cc
+++ b/kplato/kptsummarytaskdialog.cpp
diff --git a/kplato/kptsummarytaskgeneralpanel.cc b/kplato/kptsummarytaskgeneralpanel.cpp
index 8fff18211..8fff18211 100644
--- a/kplato/kptsummarytaskgeneralpanel.cc
+++ b/kplato/kptsummarytaskgeneralpanel.cpp
diff --git a/kplato/kpttask.cc b/kplato/kpttask.cpp
index 4e41e6bc8..4e41e6bc8 100644
--- a/kplato/kpttask.cc
+++ b/kplato/kpttask.cpp
diff --git a/kplato/kpttaskappointmentsview.cc b/kplato/kpttaskappointmentsview.cpp
index 669bf0654..669bf0654 100644
--- a/kplato/kpttaskappointmentsview.cc
+++ b/kplato/kpttaskappointmentsview.cpp
diff --git a/kplato/kpttaskcostpanel.cc b/kplato/kpttaskcostpanel.cpp
index d33e2c7cb..d33e2c7cb 100644
--- a/kplato/kpttaskcostpanel.cc
+++ b/kplato/kpttaskcostpanel.cpp
diff --git a/kplato/kpttaskdefaultpanel.cc b/kplato/kpttaskdefaultpanel.cpp
index d3fb322ed..d3fb322ed 100644
--- a/kplato/kpttaskdefaultpanel.cc
+++ b/kplato/kpttaskdefaultpanel.cpp
diff --git a/kplato/kpttaskdialog.cc b/kplato/kpttaskdialog.cpp
index 65aa917f2..65aa917f2 100644
--- a/kplato/kpttaskdialog.cc
+++ b/kplato/kpttaskdialog.cpp
diff --git a/kplato/kpttaskgeneralpanel.cc b/kplato/kpttaskgeneralpanel.cpp
index 854197e39..854197e39 100644
--- a/kplato/kpttaskgeneralpanel.cc
+++ b/kplato/kpttaskgeneralpanel.cpp
diff --git a/kplato/kpttaskprogressdialog.cc b/kplato/kpttaskprogressdialog.cpp
index 180d3a53d..180d3a53d 100644
--- a/kplato/kpttaskprogressdialog.cc
+++ b/kplato/kpttaskprogressdialog.cpp
diff --git a/kplato/kpttaskprogresspanel.cc b/kplato/kpttaskprogresspanel.cpp
index 00de2b225..00de2b225 100644
--- a/kplato/kpttaskprogresspanel.cc
+++ b/kplato/kpttaskprogresspanel.cpp
diff --git a/kplato/kptview.cc b/kplato/kptview.cpp
index 238ff733f..238ff733f 100644
--- a/kplato/kptview.cc
+++ b/kplato/kptview.cpp
diff --git a/kplato/kptwbsdefinition.cc b/kplato/kptwbsdefinition.cc
deleted file mode 100644
index fcf2d41f2..000000000
--- a/kplato/kptwbsdefinition.cc
+++ /dev/null
@@ -1,188 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2005 Dag Andersen <danders@get2net.dk>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation;
- version 2 of the License.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include "kptwbsdefinition.h"
-
-
-#include <tdelocale.h>
-#include <kdebug.h>
-
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqpair.h>
-
-namespace KPlato
-{
-
-
-WBSDefinition::WBSDefinition() {
- m_levelsEnabled = false;
-
- m_defaultDef.code = "Number";
- m_defaultDef.separator = ".";
-
- m_codeLists.append(tqMakePair(TQString("Number"), i18n("Number")));
- m_codeLists.append(tqMakePair(TQString("Roman, upper case"), i18n("Roman, Upper Case")));
- m_codeLists.append(tqMakePair(TQString("Roman, lower case"), i18n("Roman, Lower Case")));
- m_codeLists.append(tqMakePair(TQString("Letter, upper case"), i18n("Letter, Upper Case")));
- m_codeLists.append(tqMakePair(TQString("Letter, lower case"), i18n("Letter, Lower Case")));
-}
-
-WBSDefinition::~WBSDefinition() {
-}
-
-void WBSDefinition::clear() {
- m_defaultDef.clear();
- m_levelsDef.clear();
-}
-
-TQString WBSDefinition::wbs(uint index, int level) {
- if (isLevelsDefEnabled()) {
- CodeDef def = levelsDef(level);
- if (!def.isEmpty()) {
- return code(def, index) + def.separator;
- }
- }
- return code(m_defaultDef, index) + m_defaultDef.separator;
-}
-
-
-TQString WBSDefinition::code(uint index, int level) {
- if (isLevelsDefEnabled()) {
- CodeDef def = levelsDef(level);
- if (!def.isEmpty()) {
- return code(def, index);
- }
- }
- return code(m_defaultDef, index);
-}
-
-TQString WBSDefinition::separator(int level) {
- if (isLevelsDefEnabled()) {
- CodeDef def = levelsDef(level);
- if (!def.isEmpty()) {
- return def.separator;
- }
- }
- return m_defaultDef.separator;
-}
-
-void WBSDefinition::setLevelsDef(TQMap<int, CodeDef> def) {
- m_levelsDef.clear();
- m_levelsDef = def;
-}
-
-WBSDefinition::CodeDef WBSDefinition::levelsDef(int level) const {
- return m_levelsDef.contains(level) ? m_levelsDef[level] : CodeDef();
-}
-
-void WBSDefinition::setLevelsDef(int level, CodeDef def) {
- m_levelsDef.insert(level, def);
-}
-
-void WBSDefinition::setLevelsDef(int level, TQString c, TQString s) {
- m_levelsDef.insert(level, CodeDef(c, s));
-}
-
-bool WBSDefinition::level0Enabled() {
- return m_levelsEnabled && !levelsDef(0).isEmpty();
-}
-
-const TQChar Letters[] = { '?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
-
-TQString WBSDefinition::code(CodeDef &def, uint index) {
- if (def.code == "Number") {
- return TQString("%1").arg(index);
- }
- if (def.code == "Roman, lower case") {
- return TQString("%1").arg(toRoman(index));
- }
- if (def.code == "Roman, upper case") {
- return TQString("%1").arg(toRoman(index, true));
- }
- if (def.code == "Letter, lower case") {
- if (index > 26) {
- index = 0;
- }
- return TQString("%1").arg(Letters[index]);
- }
- if (def.code == "Letter, upper case") {
- if (index > 26) {
- index = 0;
- }
- return TQString("%1").arg(Letters[index].upper());
- }
- return TQString();
-}
-
-// Nicked from koparagcounter.cc
-const TQCString RNUnits[] = {"", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};
-const TQCString RNTens[] = {"", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"};
-const TQCString RNHundreds[] = {"", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"};
-const TQCString RNThousands[] = {"", "m", "mm", "mmm"};
-
-TQString WBSDefinition::toRoman( int n, bool upper )
-{
- if ( n >= 0 ) {
- TQString s = TQString::fromLatin1( RNThousands[ ( n / 1000 ) ] +
- RNHundreds[ ( n / 100 ) % 10 ] +
- RNTens[ ( n / 10 ) % 10 ] +
- RNUnits[ ( n ) % 10 ] );
- return upper ? s.upper() : s;
-
- } else { // should never happen, but better not crash if it does
- kdWarning()<< k_funcinfo << " n=" << n << endl;
- return TQString::number( n );
- }
-}
-
-TQStringList WBSDefinition::codeList() {
- TQStringList cl;
- TQValueList<TQPair<TQString, TQString> >::Iterator it;
- for (it = m_codeLists.begin(); it != m_codeLists.end(); ++it) {
- cl.append((*it).second);
- }
- return cl;
-}
-
-int WBSDefinition::defaultCodeIndex() const {
- TQValueList<TQPair<TQString, TQString> >::const_iterator it;
- int i = -1;
- for(it = m_codeLists.begin(); it != m_codeLists.end(); ++it) {
- ++i;
- if (m_defaultDef.code == (*it).first)
- break;
- }
- return i;
-}
-
-bool WBSDefinition::setDefaultCode(uint index) {
- TQValueList<TQPair<TQString, TQString> >::const_iterator it = m_codeLists.at(index);
- if (it == m_codeLists.end()) {
- return false;
- }
- m_defaultDef.code = (*it).first;
- return true;
-}
-
-void WBSDefinition::setDefaultSeparator(TQString s) {
- m_defaultDef.separator = s;
-}
-
-} //namespace KPlato
diff --git a/kplato/kptwbsdefinition.cpp b/kplato/kptwbsdefinition.cpp
new file mode 100644
index 000000000..4c1465334
--- /dev/null
+++ b/kplato/kptwbsdefinition.cpp
@@ -0,0 +1,188 @@
+/* This file is part of the KDE project
+ Copyright (C) 2005 Dag Andersen <danders@get2net.dk>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation;
+ version 2 of the License.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "kptwbsdefinition.h"
+
+
+#include <tdelocale.h>
+#include <kdebug.h>
+
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqpair.h>
+
+namespace KPlato
+{
+
+
+WBSDefinition::WBSDefinition() {
+ m_levelsEnabled = false;
+
+ m_defaultDef.code = "Number";
+ m_defaultDef.separator = ".";
+
+ m_codeLists.append(tqMakePair(TQString("Number"), i18n("Number")));
+ m_codeLists.append(tqMakePair(TQString("Roman, upper case"), i18n("Roman, Upper Case")));
+ m_codeLists.append(tqMakePair(TQString("Roman, lower case"), i18n("Roman, Lower Case")));
+ m_codeLists.append(tqMakePair(TQString("Letter, upper case"), i18n("Letter, Upper Case")));
+ m_codeLists.append(tqMakePair(TQString("Letter, lower case"), i18n("Letter, Lower Case")));
+}
+
+WBSDefinition::~WBSDefinition() {
+}
+
+void WBSDefinition::clear() {
+ m_defaultDef.clear();
+ m_levelsDef.clear();
+}
+
+TQString WBSDefinition::wbs(uint index, int level) {
+ if (isLevelsDefEnabled()) {
+ CodeDef def = levelsDef(level);
+ if (!def.isEmpty()) {
+ return code(def, index) + def.separator;
+ }
+ }
+ return code(m_defaultDef, index) + m_defaultDef.separator;
+}
+
+
+TQString WBSDefinition::code(uint index, int level) {
+ if (isLevelsDefEnabled()) {
+ CodeDef def = levelsDef(level);
+ if (!def.isEmpty()) {
+ return code(def, index);
+ }
+ }
+ return code(m_defaultDef, index);
+}
+
+TQString WBSDefinition::separator(int level) {
+ if (isLevelsDefEnabled()) {
+ CodeDef def = levelsDef(level);
+ if (!def.isEmpty()) {
+ return def.separator;
+ }
+ }
+ return m_defaultDef.separator;
+}
+
+void WBSDefinition::setLevelsDef(TQMap<int, CodeDef> def) {
+ m_levelsDef.clear();
+ m_levelsDef = def;
+}
+
+WBSDefinition::CodeDef WBSDefinition::levelsDef(int level) const {
+ return m_levelsDef.contains(level) ? m_levelsDef[level] : CodeDef();
+}
+
+void WBSDefinition::setLevelsDef(int level, CodeDef def) {
+ m_levelsDef.insert(level, def);
+}
+
+void WBSDefinition::setLevelsDef(int level, TQString c, TQString s) {
+ m_levelsDef.insert(level, CodeDef(c, s));
+}
+
+bool WBSDefinition::level0Enabled() {
+ return m_levelsEnabled && !levelsDef(0).isEmpty();
+}
+
+const TQChar Letters[] = { '?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
+
+TQString WBSDefinition::code(CodeDef &def, uint index) {
+ if (def.code == "Number") {
+ return TQString("%1").arg(index);
+ }
+ if (def.code == "Roman, lower case") {
+ return TQString("%1").arg(toRoman(index));
+ }
+ if (def.code == "Roman, upper case") {
+ return TQString("%1").arg(toRoman(index, true));
+ }
+ if (def.code == "Letter, lower case") {
+ if (index > 26) {
+ index = 0;
+ }
+ return TQString("%1").arg(Letters[index]);
+ }
+ if (def.code == "Letter, upper case") {
+ if (index > 26) {
+ index = 0;
+ }
+ return TQString("%1").arg(Letters[index].upper());
+ }
+ return TQString();
+}
+
+// Nicked from koparagcounter.cpp
+const TQCString RNUnits[] = {"", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};
+const TQCString RNTens[] = {"", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"};
+const TQCString RNHundreds[] = {"", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"};
+const TQCString RNThousands[] = {"", "m", "mm", "mmm"};
+
+TQString WBSDefinition::toRoman( int n, bool upper )
+{
+ if ( n >= 0 ) {
+ TQString s = TQString::fromLatin1( RNThousands[ ( n / 1000 ) ] +
+ RNHundreds[ ( n / 100 ) % 10 ] +
+ RNTens[ ( n / 10 ) % 10 ] +
+ RNUnits[ ( n ) % 10 ] );
+ return upper ? s.upper() : s;
+
+ } else { // should never happen, but better not crash if it does
+ kdWarning()<< k_funcinfo << " n=" << n << endl;
+ return TQString::number( n );
+ }
+}
+
+TQStringList WBSDefinition::codeList() {
+ TQStringList cl;
+ TQValueList<TQPair<TQString, TQString> >::Iterator it;
+ for (it = m_codeLists.begin(); it != m_codeLists.end(); ++it) {
+ cl.append((*it).second);
+ }
+ return cl;
+}
+
+int WBSDefinition::defaultCodeIndex() const {
+ TQValueList<TQPair<TQString, TQString> >::const_iterator it;
+ int i = -1;
+ for(it = m_codeLists.begin(); it != m_codeLists.end(); ++it) {
+ ++i;
+ if (m_defaultDef.code == (*it).first)
+ break;
+ }
+ return i;
+}
+
+bool WBSDefinition::setDefaultCode(uint index) {
+ TQValueList<TQPair<TQString, TQString> >::const_iterator it = m_codeLists.at(index);
+ if (it == m_codeLists.end()) {
+ return false;
+ }
+ m_defaultDef.code = (*it).first;
+ return true;
+}
+
+void WBSDefinition::setDefaultSeparator(TQString s) {
+ m_defaultDef.separator = s;
+}
+
+} //namespace KPlato
diff --git a/kplato/kptwbsdefinitiondialog.cc b/kplato/kptwbsdefinitiondialog.cpp
index 181cbd43a..181cbd43a 100644
--- a/kplato/kptwbsdefinitiondialog.cc
+++ b/kplato/kptwbsdefinitiondialog.cpp
diff --git a/kplato/kptwbsdefinitionpanel.cc b/kplato/kptwbsdefinitionpanel.cpp
index 3843a98c8..3843a98c8 100644
--- a/kplato/kptwbsdefinitionpanel.cc
+++ b/kplato/kptwbsdefinitionpanel.cpp
diff --git a/kplato/main.cc b/kplato/main.cpp
index 75af7b84b..75af7b84b 100644
--- a/kplato/main.cc
+++ b/kplato/main.cpp
diff --git a/kpresenter/KPrMSPresentationSetup.cpp b/kpresenter/KPrMSPresentationSetup.cpp
index de0f888ca..557b87c48 100644
--- a/kpresenter/KPrMSPresentationSetup.cpp
+++ b/kpresenter/KPrMSPresentationSetup.cpp
@@ -1,6 +1,6 @@
/* This file is part of the KDE project
Copyright 2004 Brad Hards <bradh@frogmouth.net>
- Loosely based on webpresention.cc, which is:
+ Loosely based on webpresention.cpp, which is:
Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
Copyright 2001, 2002 Nicolas GOUTTE <goutte@kde.org>
Copyright 2002 Ariya Hidayat <ariya@kde.org>
diff --git a/kpresenter/KPrMarginWidget.cpp b/kpresenter/KPrMarginWidget.cpp
index a67fa96ec..a8aa403e3 100644
--- a/kpresenter/KPrMarginWidget.cpp
+++ b/kpresenter/KPrMarginWidget.cpp
@@ -1,7 +1,7 @@
/* This file is part of the KDE project
Copyright (C) 2005 Thorsten Zachmann <zachmann@kde.org>
- The code is mostly a copy from kword/framedia.cc
+ The code is mostly a copy from kword/framedia.cpp
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
diff --git a/kpresenter/KPrSoundPlayer.cpp b/kpresenter/KPrSoundPlayer.cpp
index ff4b1ffd3..22b986735 100644
--- a/kpresenter/KPrSoundPlayer.cpp
+++ b/kpresenter/KPrSoundPlayer.cpp
@@ -4,7 +4,7 @@ base code from kaudioplayer.h, kaudioplayer.cpp
Copyright (C) 2000 Stefan Westerfeld
stefan@space.twc.de
-and konq_sound.h konq_sound.cc
+and konq_sound.h konq_sound.cpp
Copyright (c) 2001 Malte Starostik <malte@kde.org>
This file's authors :
diff --git a/kpresenter/KPrSoundPlayer.h b/kpresenter/KPrSoundPlayer.h
index 384ee0666..4ef27a20a 100644
--- a/kpresenter/KPrSoundPlayer.h
+++ b/kpresenter/KPrSoundPlayer.h
@@ -4,7 +4,7 @@ base code from kaudioplayer.h, kaudioplayer.cpp
Copyright (C) 2000 Stefan Westerfeld
stefan@space.twc.de
-and konq_sound.h konq_sound.cc
+and konq_sound.h konq_sound.cpp
Copyright (c) 2001 Malte Starostik <malte@kde.org>
This file's authors :
diff --git a/kpresenter/KPrTextObject.cpp b/kpresenter/KPrTextObject.cpp
index 4c7f6bdd1..461015faf 100644
--- a/kpresenter/KPrTextObject.cpp
+++ b/kpresenter/KPrTextObject.cpp
@@ -439,7 +439,7 @@ void KPrTextObject::paint( TQPainter *_painter, KoTextZoomHandler*_zoomHandler,
}
if ( !editingTextObj || !onlyChanged )
{
- /// #### Port this to KoBorder, see e.g. kword/kwframe.cc:590
+ /// #### Port this to KoBorder, see e.g. kword/kwframe.cpp:590
// (so that the border gets drawn OUTSIDE of the object area)
_painter->drawRect( _zoomHandler->zoomItX(pw), _zoomHandler->zoomItX(pw), _zoomHandler->zoomItX( ow - 2 * pw),
_zoomHandler->zoomItY( oh - 2 * pw) );
diff --git a/kpresenter/KPrTextProperty.cpp b/kpresenter/KPrTextProperty.cpp
index bb5073ff0..e10fd701a 100644
--- a/kpresenter/KPrTextProperty.cpp
+++ b/kpresenter/KPrTextProperty.cpp
@@ -1,7 +1,7 @@
/* This file is part of the KDE project
Copyright (C) 2005 Thorsten Zachmann <zachmann@kde.org>
- The code is mostly a copy from kword/framedia.cc
+ The code is mostly a copy from kword/framedia.cpp
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
diff --git a/kpresenter/KPrTextProperty.h b/kpresenter/KPrTextProperty.h
index dd018c2fc..2a33b56f7 100644
--- a/kpresenter/KPrTextProperty.h
+++ b/kpresenter/KPrTextProperty.h
@@ -1,7 +1,7 @@
/* This file is part of the KDE project
Copyright (C) 2005 Thorsten Zachmann <zachmann@kde.org>
- The code is mostly a copy from kword/framedia.cc
+ The code is mostly a copy from kword/framedia.cpp
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
diff --git a/kpresenter/KPrView.cpp b/kpresenter/KPrView.cpp
index cfbe5f231..220dc91b6 100644
--- a/kpresenter/KPrView.cpp
+++ b/kpresenter/KPrView.cpp
@@ -2894,7 +2894,7 @@ void KPrView::setupActions()
actionCollection(), "insert_link" );
#if 0
- //code from page.cc
+ //code from page.cpp
//not implemented
picResizeMenu->insertSeparator();
picResizeMenu->insertItem( i18n( "Enter Custom Factor..." ), TQT_TQOBJECT(this), TQT_SLOT( picViewOrigFactor() ) );
diff --git a/kpresenter/KPrWebPresentation.cpp b/kpresenter/KPrWebPresentation.cpp
index 00c0dbf4e..5d8998474 100644
--- a/kpresenter/KPrWebPresentation.cpp
+++ b/kpresenter/KPrWebPresentation.cpp
@@ -76,7 +76,7 @@
#include "KoDocumentInfo.h"
-// Comes from koffice/filters/libexport/KWEFUtils.cc
+// Comes from koffice/filters/libexport/KWEFUtils.cpp
static TQString EscapeSgmlText(const TQTextCodec* codec, const TQString& strIn,
const bool quot = false , const bool apos = false )
{
diff --git a/kspread/CHANGES b/kspread/CHANGES
index 9b9b654ef..514e7bf8b 100644
--- a/kspread/CHANGES
+++ b/kspread/CHANGES
@@ -386,7 +386,7 @@ Until beta1:
- many new built-in functions (see detailed list below)
- function name is now case-insensitive
- "Related Function" in formula editor
-- move functions in kspread_interpreter into several kspread_functions_*.cc
+- move functions in kspread_interpreter into several kspread_functions_*.cpp
New functions added:
conversion:
diff --git a/kspread/DESIGN.html b/kspread/DESIGN.html
index 3cd509e21..f1aef8cf3 100644
--- a/kspread/DESIGN.html
+++ b/kspread/DESIGN.html
@@ -684,7 +684,7 @@ existing tester and modify it. Basically, it must be a subclass of class Tester
(see <tt>koffice/kspread/tests/tester.h</tt>). Just reimplement the virtual
function <tt>run()</tt> and it is ready. In order to make it possible to run
the new tester, add an instance of the class in TestRunner
-(for details, see <tt>koffice/kspread/tests/testrunner.cc</tt>).</p>
+(for details, see <tt>koffice/kspread/tests/testrunner.cpp</tt>).</p>
<p>A tester must be self-contained, it should not use any test data from
current document. If necessary, it must create (or hard code) the data by
@@ -739,7 +739,7 @@ would not cause tons of recompile.</p>
<p>When creating a new class, use namespace KSpread. Do not use KSpread prefix
anymore. Example: use <tt>KSpread::Foo</tt> instead of <tt>KSpreadFoo</tt>.
Also source file name should not contain kspread prefix anymore, i.e.
-<tt>foo.h</tt> and <tt>foo.cc</tt> (but not <tt>kspread_foo.h</tt> and
-<tt>kspread_foo.cc</tt>) for the above example.</p>
+<tt>foo.h</tt> and <tt>foo.cpp</tt> (but not <tt>kspread_foo.h</tt> and
+<tt>kspread_foo.cpp</tt>) for the above example.</p>
</body></html>
diff --git a/kspread/Doxyfile b/kspread/Doxyfile
index 38131dfba..bb39c7ba8 100644
--- a/kspread/Doxyfile
+++ b/kspread/Doxyfile
@@ -397,12 +397,11 @@ INPUT =
# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
# and *.h) to filter out the source-files in the directories. If left
# blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp
+# *.c *.cpp *.cxx *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp
# *.h++ *.idl *.odl *.cs *.php *.php3 *.inc
FILE_PATTERNS = *.h \
*.cpp \
- *.cc \
*.hpp \
*.dox \
*.c++ \
diff --git a/kspread/KSpreadAppIface.cc b/kspread/KSpreadAppIface.cpp
index 6f0c8362e..6f0c8362e 100644
--- a/kspread/KSpreadAppIface.cc
+++ b/kspread/KSpreadAppIface.cpp
diff --git a/kspread/KSpreadCellIface.cc b/kspread/KSpreadCellIface.cpp
index 4188a1e4e..4188a1e4e 100644
--- a/kspread/KSpreadCellIface.cc
+++ b/kspread/KSpreadCellIface.cpp
diff --git a/kspread/KSpreadColumnIface.cc b/kspread/KSpreadColumnIface.cpp
index c0fc813f4..c0fc813f4 100644
--- a/kspread/KSpreadColumnIface.cc
+++ b/kspread/KSpreadColumnIface.cpp
diff --git a/kspread/KSpreadDocIface.cc b/kspread/KSpreadDocIface.cpp
index e8f1df462..e8f1df462 100644
--- a/kspread/KSpreadDocIface.cc
+++ b/kspread/KSpreadDocIface.cpp
diff --git a/kspread/KSpreadLayoutIface.cc b/kspread/KSpreadLayoutIface.cpp
index d3c5e1b75..d3c5e1b75 100644
--- a/kspread/KSpreadLayoutIface.cc
+++ b/kspread/KSpreadLayoutIface.cpp
diff --git a/kspread/KSpreadMapIface.cc b/kspread/KSpreadMapIface.cpp
index ba8071f9c..ba8071f9c 100644
--- a/kspread/KSpreadMapIface.cc
+++ b/kspread/KSpreadMapIface.cpp
diff --git a/kspread/KSpreadRowIface.cc b/kspread/KSpreadRowIface.cpp
index 69db292f6..69db292f6 100644
--- a/kspread/KSpreadRowIface.cc
+++ b/kspread/KSpreadRowIface.cpp
diff --git a/kspread/KSpreadTableIface.cc b/kspread/KSpreadTableIface.cpp
index cbf37f202..cbf37f202 100644
--- a/kspread/KSpreadTableIface.cc
+++ b/kspread/KSpreadTableIface.cpp
diff --git a/kspread/KSpreadViewIface.cc b/kspread/KSpreadViewIface.cpp
index 1fb76f460..1fb76f460 100644
--- a/kspread/KSpreadViewIface.cc
+++ b/kspread/KSpreadViewIface.cpp
diff --git a/kspread/Makefile.am b/kspread/Makefile.am
index df50d89dc..da52cf90c 100644
--- a/kspread/Makefile.am
+++ b/kspread/Makefile.am
@@ -8,24 +8,24 @@ INCLUDES = $(KOFFICE_INCLUDES) $(KOTEXT_INCLUDES) -I$(interfacedir) \
lib_LTLIBRARIES = libkspreadcommon.la
kde_module_LTLIBRARIES = libkspreadpart.la
-libkspreadcommon_la_SOURCES = digest.cc commands.cc damages.cc dependencies.cc \
- formula.cc functions.cc kspread_autofill.cc kspread_canvas.cc \
- kspread_cell.cc kspread_cluster.cc kspread_condition.cc kspread_doc.cc \
- kspread_editors.cc kspread_events.cc kspread_factory.cc kspread_format.cc \
- kspread_functions_conversion.cc kspread_functions_database.cc kspread_functions_datetime.cc \
- kspread_functions_engineering.cc kspread_functions_financial.cc kspread_functions_helper.cc \
- kspread_functions_information.cc kspread_functions_logic.cc kspread_functions_math.cc \
- kspread_functions_reference.cc kspread_functions_statistical.cc kspread_functions_text.cc \
- kspread_functions_trig.cc kspread_handler.cc kspread_locale.cc kspread_map.cc \
- kspread_numformat.cc kspread_object.cc kspread_style.cc kspread_style_manager.cc \
- kspread_undo.cc kspread_value.cc kspread_view.cc kspread_sheet.cc kspread_sheetprint.cc \
- kspread_util.cc kspread_toolbox.cc valuecalc.cc valueconverter.cc valueformatter.cc \
- valueparser.cc KSpreadAppIface.cc KSpreadAppIface.skel KSpreadCellIface.cc \
- KSpreadCellIface.skel KSpreadColumnIface.skel KSpreadColumnIface.cc KSpreadDocIface.cc \
- KSpreadDocIface.skel KSpreadLayoutIface.skel KSpreadLayoutIface.cc KSpreadMapIface.cc \
- KSpreadMapIface.skel KSpreadRowIface.skel KSpreadRowIface.cc KSpreadTableIface.cc \
- KSpreadTableIface.skel KSpreadViewIface.skel KSpreadViewIface.cc \
- kspread_genvalidationstyle.cc region.cc selection.cc manipulator.cc manipulator_data.cc \
+libkspreadcommon_la_SOURCES = digest.cpp commands.cpp damages.cpp dependencies.cpp \
+ formula.cpp functions.cpp kspread_autofill.cpp kspread_canvas.cpp \
+ kspread_cell.cpp kspread_cluster.cpp kspread_condition.cpp kspread_doc.cpp \
+ kspread_editors.cpp kspread_events.cpp kspread_factory.cpp kspread_format.cpp \
+ kspread_functions_conversion.cpp kspread_functions_database.cpp kspread_functions_datetime.cpp \
+ kspread_functions_engineering.cpp kspread_functions_financial.cpp kspread_functions_helper.cpp \
+ kspread_functions_information.cpp kspread_functions_logic.cpp kspread_functions_math.cpp \
+ kspread_functions_reference.cpp kspread_functions_statistical.cpp kspread_functions_text.cpp \
+ kspread_functions_trig.cpp kspread_handler.cpp kspread_locale.cpp kspread_map.cpp \
+ kspread_numformat.cpp kspread_object.cpp kspread_style.cpp kspread_style_manager.cpp \
+ kspread_undo.cpp kspread_value.cpp kspread_view.cpp kspread_sheet.cpp kspread_sheetprint.cpp \
+ kspread_util.cpp kspread_toolbox.cpp valuecalc.cpp valueconverter.cpp valueformatter.cpp \
+ valueparser.cpp KSpreadAppIface.cpp KSpreadAppIface.skel KSpreadCellIface.cpp \
+ KSpreadCellIface.skel KSpreadColumnIface.skel KSpreadColumnIface.cpp KSpreadDocIface.cpp \
+ KSpreadDocIface.skel KSpreadLayoutIface.skel KSpreadLayoutIface.cpp KSpreadMapIface.cpp \
+ KSpreadMapIface.skel KSpreadRowIface.skel KSpreadRowIface.cpp KSpreadTableIface.cpp \
+ KSpreadTableIface.skel KSpreadViewIface.skel KSpreadViewIface.cpp \
+ kspread_genvalidationstyle.cpp region.cpp selection.cpp manipulator.cpp manipulator_data.cpp \
kspread_generalProperty.cpp kspread_propertyEditor.cpp
libkspreadcommon_la_LDFLAGS = $(all_libraries) $(KDE_RPATH) -no-undefined -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts -ltdeutils
@@ -35,7 +35,7 @@ libkspreadcommon_la_LIBADD = $(top_builddir)/interfaces/libkochart.la \
libkspreadpart_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
libkspreadpart_la_LIBADD = libkspreadcommon.la
-libkspreadpart_la_SOURCES = kspread_factory_init.cc
+libkspreadpart_la_SOURCES = kspread_factory_init.cpp
METASOURCES = AUTO
@@ -43,7 +43,7 @@ METASOURCES = AUTO
## The tdeinit loadable module and the executable
tdeinit_LTLIBRARIES = kspread.la
bin_PROGRAMS =
-kspread_la_SOURCES = main.cc
+kspread_la_SOURCES = main.cpp
kspread_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) -ltdecore -ltdeui $(LIB_TQT) -lkjs -ltdefx -ltdeio -ltdeparts
kspread_la_LIBADD = $(LIB_KOFFICECORE)
@@ -63,10 +63,10 @@ parser:
bison -p dep -b dep -d yacc.dep.y
messages: rc.cpp
- $(EXTRACTRC) --tag-group=koffice extensions/*.xml > xml_doc.cc
+ $(EXTRACTRC) --tag-group=koffice extensions/*.xml > xml_doc.cpp
$(EXTRACTRC) dialogs/*.ui >> rc.cpp
- $(XGETTEXT) rc.cpp *.cc kspread_aboutdata.h dialogs/*.cc tests/*.cc -o $(podir)/kspread.pot
- -rm xml_doc.cc
+ $(XGETTEXT) rc.cpp *.cpp kspread_aboutdata.h dialogs/*.cpp tests/*.cpp -o $(podir)/kspread.pot
+ -rm xml_doc.cpp
include ../admin/Doxyfile.am
diff --git a/kspread/TODO b/kspread/TODO
index 575d8c8d0..0769dc6f4 100644
--- a/kspread/TODO
+++ b/kspread/TODO
@@ -160,7 +160,7 @@ Things to do after the release of KOffice 1.4
+ code cleanups 3 ----
- Merge Cell::checkForNamedAreas(.) into Oasis::decodeFormula(.).
- Move Cell::convertFormulaToOasisFormat(..) to
- Oasis::encodeFormula to reduce the size of kspread_cell.cc
+ Oasis::encodeFormula to reduce the size of kspread_cell.cpp
and to have encoding/decoding in one place.
- Check if all logic of Point and Range is materialized in Region.
Replace all occurences of Point and Range by Region.
diff --git a/kspread/commands.cc b/kspread/commands.cpp
index 490bee81b..490bee81b 100644
--- a/kspread/commands.cc
+++ b/kspread/commands.cpp
diff --git a/kspread/damages.cc b/kspread/damages.cpp
index 291db4087..291db4087 100644
--- a/kspread/damages.cc
+++ b/kspread/damages.cpp
diff --git a/kspread/dependencies.cc b/kspread/dependencies.cpp
index 66bbe61a1..66bbe61a1 100644
--- a/kspread/dependencies.cc
+++ b/kspread/dependencies.cpp
diff --git a/kspread/dialogs/Makefile.am b/kspread/dialogs/Makefile.am
index 71d7a476e..6f2dce6dc 100644
--- a/kspread/dialogs/Makefile.am
+++ b/kspread/dialogs/Makefile.am
@@ -10,38 +10,38 @@ noinst_LTLIBRARIES = \
libdialogs.la
libdialogs_la_SOURCES = \
- kspread_dlg_angle.cc \
- kspread_dlg_area.cc \
- kspread_dlg_comment.cc \
- kspread_dlg_conditional.cc \
- kspread_dlg_cons.cc \
- kspread_dlg_csv.cc \
- kspread_dlg_database.cc \
- kspread_dlg_format.cc \
- kspread_dlg_formula.cc \
- kspread_dlg_goalseek.cc \
- kspread_dlg_goto.cc \
- kspread_dlg_insert.cc \
- kspread_dlg_layout.cc \
- kspread_dlg_list.cc \
- kspread_dlg_paperlayout.cc \
- kspread_dlg_pasteinsert.cc \
- kspread_dlg_preference.cc \
- kspread_dlg_reference.cc \
- kspread_dlg_resize2.cc \
- kspread_dlg_series.cc \
- kspread_dlg_show.cc \
- kspread_dlg_showColRow.cc \
- kspread_dlg_sort.cc \
- kspread_dlg_special.cc \
- kspread_dlg_styles.cc \
- kspread_dlg_subtotal.cc \
- kspread_dlg_validity.cc \
+ kspread_dlg_angle.cpp \
+ kspread_dlg_area.cpp \
+ kspread_dlg_comment.cpp \
+ kspread_dlg_conditional.cpp \
+ kspread_dlg_cons.cpp \
+ kspread_dlg_csv.cpp \
+ kspread_dlg_database.cpp \
+ kspread_dlg_format.cpp \
+ kspread_dlg_formula.cpp \
+ kspread_dlg_goalseek.cpp \
+ kspread_dlg_goto.cpp \
+ kspread_dlg_insert.cpp \
+ kspread_dlg_layout.cpp \
+ kspread_dlg_list.cpp \
+ kspread_dlg_paperlayout.cpp \
+ kspread_dlg_pasteinsert.cpp \
+ kspread_dlg_preference.cpp \
+ kspread_dlg_reference.cpp \
+ kspread_dlg_resize2.cpp \
+ kspread_dlg_series.cpp \
+ kspread_dlg_show.cpp \
+ kspread_dlg_showColRow.cpp \
+ kspread_dlg_sort.cpp \
+ kspread_dlg_special.cpp \
+ kspread_dlg_styles.cpp \
+ kspread_dlg_subtotal.cpp \
+ kspread_dlg_validity.cpp \
kspreadsubtotal.ui \
- link.cc \
+ link.cpp \
sheet_properties_base.ui \
- sheet_properties.cc \
- kspread_dlg_find.cc \
+ sheet_properties.cpp \
+ kspread_dlg_find.cpp \
position_cell_format.ui \
font_cell_format.ui \
protection_cell_format.ui \
diff --git a/kspread/dialogs/kspread_dlg_angle.cc b/kspread/dialogs/kspread_dlg_angle.cpp
index 763e47a59..763e47a59 100644
--- a/kspread/dialogs/kspread_dlg_angle.cc
+++ b/kspread/dialogs/kspread_dlg_angle.cpp
diff --git a/kspread/dialogs/kspread_dlg_area.cc b/kspread/dialogs/kspread_dlg_area.cpp
index 108511ad0..108511ad0 100644
--- a/kspread/dialogs/kspread_dlg_area.cc
+++ b/kspread/dialogs/kspread_dlg_area.cpp
diff --git a/kspread/dialogs/kspread_dlg_comment.cc b/kspread/dialogs/kspread_dlg_comment.cpp
index 2494959c2..2494959c2 100644
--- a/kspread/dialogs/kspread_dlg_comment.cc
+++ b/kspread/dialogs/kspread_dlg_comment.cpp
diff --git a/kspread/dialogs/kspread_dlg_conditional.cc b/kspread/dialogs/kspread_dlg_conditional.cpp
index a75bd5bd0..a75bd5bd0 100644
--- a/kspread/dialogs/kspread_dlg_conditional.cc
+++ b/kspread/dialogs/kspread_dlg_conditional.cpp
diff --git a/kspread/dialogs/kspread_dlg_cons.cc b/kspread/dialogs/kspread_dlg_cons.cpp
index 139113c79..139113c79 100644
--- a/kspread/dialogs/kspread_dlg_cons.cc
+++ b/kspread/dialogs/kspread_dlg_cons.cpp
diff --git a/kspread/dialogs/kspread_dlg_csv.cc b/kspread/dialogs/kspread_dlg_csv.cpp
index c068810b0..c068810b0 100644
--- a/kspread/dialogs/kspread_dlg_csv.cc
+++ b/kspread/dialogs/kspread_dlg_csv.cpp
diff --git a/kspread/dialogs/kspread_dlg_database.cc b/kspread/dialogs/kspread_dlg_database.cpp
index 34e680cdb..34e680cdb 100644
--- a/kspread/dialogs/kspread_dlg_database.cc
+++ b/kspread/dialogs/kspread_dlg_database.cpp
diff --git a/kspread/dialogs/kspread_dlg_find.cc b/kspread/dialogs/kspread_dlg_find.cpp
index aa1c7f71e..aa1c7f71e 100644
--- a/kspread/dialogs/kspread_dlg_find.cc
+++ b/kspread/dialogs/kspread_dlg_find.cpp
diff --git a/kspread/dialogs/kspread_dlg_format.cc b/kspread/dialogs/kspread_dlg_format.cpp
index 501d8bf36..501d8bf36 100644
--- a/kspread/dialogs/kspread_dlg_format.cc
+++ b/kspread/dialogs/kspread_dlg_format.cpp
diff --git a/kspread/dialogs/kspread_dlg_formula.cc b/kspread/dialogs/kspread_dlg_formula.cpp
index 8e53c5254..8e53c5254 100644
--- a/kspread/dialogs/kspread_dlg_formula.cc
+++ b/kspread/dialogs/kspread_dlg_formula.cpp
diff --git a/kspread/dialogs/kspread_dlg_goalseek.cc b/kspread/dialogs/kspread_dlg_goalseek.cpp
index b45525ad2..b45525ad2 100644
--- a/kspread/dialogs/kspread_dlg_goalseek.cc
+++ b/kspread/dialogs/kspread_dlg_goalseek.cpp
diff --git a/kspread/dialogs/kspread_dlg_goto.cc b/kspread/dialogs/kspread_dlg_goto.cpp
index 2d9935ac2..2d9935ac2 100644
--- a/kspread/dialogs/kspread_dlg_goto.cc
+++ b/kspread/dialogs/kspread_dlg_goto.cpp
diff --git a/kspread/dialogs/kspread_dlg_insert.cc b/kspread/dialogs/kspread_dlg_insert.cpp
index 454a43ba4..454a43ba4 100644
--- a/kspread/dialogs/kspread_dlg_insert.cc
+++ b/kspread/dialogs/kspread_dlg_insert.cpp
diff --git a/kspread/dialogs/kspread_dlg_layout.cc b/kspread/dialogs/kspread_dlg_layout.cpp
index ad876b3b4..ad876b3b4 100644
--- a/kspread/dialogs/kspread_dlg_layout.cc
+++ b/kspread/dialogs/kspread_dlg_layout.cpp
diff --git a/kspread/dialogs/kspread_dlg_list.cc b/kspread/dialogs/kspread_dlg_list.cpp
index 254470e19..254470e19 100644
--- a/kspread/dialogs/kspread_dlg_list.cc
+++ b/kspread/dialogs/kspread_dlg_list.cpp
diff --git a/kspread/dialogs/kspread_dlg_paperlayout.cc b/kspread/dialogs/kspread_dlg_paperlayout.cpp
index 3305963e2..3305963e2 100644
--- a/kspread/dialogs/kspread_dlg_paperlayout.cc
+++ b/kspread/dialogs/kspread_dlg_paperlayout.cpp
diff --git a/kspread/dialogs/kspread_dlg_pasteinsert.cc b/kspread/dialogs/kspread_dlg_pasteinsert.cpp
index 93d67b06a..93d67b06a 100644
--- a/kspread/dialogs/kspread_dlg_pasteinsert.cc
+++ b/kspread/dialogs/kspread_dlg_pasteinsert.cpp
diff --git a/kspread/dialogs/kspread_dlg_preference.cc b/kspread/dialogs/kspread_dlg_preference.cpp
index d82af591b..d82af591b 100644
--- a/kspread/dialogs/kspread_dlg_preference.cc
+++ b/kspread/dialogs/kspread_dlg_preference.cpp
diff --git a/kspread/dialogs/kspread_dlg_reference.cc b/kspread/dialogs/kspread_dlg_reference.cpp
index 9e747dfbb..9e747dfbb 100644
--- a/kspread/dialogs/kspread_dlg_reference.cc
+++ b/kspread/dialogs/kspread_dlg_reference.cpp
diff --git a/kspread/dialogs/kspread_dlg_resize2.cc b/kspread/dialogs/kspread_dlg_resize2.cpp
index e6d74d26d..e6d74d26d 100644
--- a/kspread/dialogs/kspread_dlg_resize2.cc
+++ b/kspread/dialogs/kspread_dlg_resize2.cpp
diff --git a/kspread/dialogs/kspread_dlg_series.cc b/kspread/dialogs/kspread_dlg_series.cpp
index ee241617d..ee241617d 100644
--- a/kspread/dialogs/kspread_dlg_series.cc
+++ b/kspread/dialogs/kspread_dlg_series.cpp
diff --git a/kspread/dialogs/kspread_dlg_show.cc b/kspread/dialogs/kspread_dlg_show.cpp
index 11f55e6d0..11f55e6d0 100644
--- a/kspread/dialogs/kspread_dlg_show.cc
+++ b/kspread/dialogs/kspread_dlg_show.cpp
diff --git a/kspread/dialogs/kspread_dlg_showColRow.cc b/kspread/dialogs/kspread_dlg_showColRow.cpp
index 32c4c631a..32c4c631a 100644
--- a/kspread/dialogs/kspread_dlg_showColRow.cc
+++ b/kspread/dialogs/kspread_dlg_showColRow.cpp
diff --git a/kspread/dialogs/kspread_dlg_sort.cc b/kspread/dialogs/kspread_dlg_sort.cpp
index 52cda9b64..52cda9b64 100644
--- a/kspread/dialogs/kspread_dlg_sort.cc
+++ b/kspread/dialogs/kspread_dlg_sort.cpp
diff --git a/kspread/dialogs/kspread_dlg_special.cc b/kspread/dialogs/kspread_dlg_special.cpp
index 2fbeb7ebe..2fbeb7ebe 100644
--- a/kspread/dialogs/kspread_dlg_special.cc
+++ b/kspread/dialogs/kspread_dlg_special.cpp
diff --git a/kspread/dialogs/kspread_dlg_styles.cc b/kspread/dialogs/kspread_dlg_styles.cpp
index bf8f4de26..bf8f4de26 100644
--- a/kspread/dialogs/kspread_dlg_styles.cc
+++ b/kspread/dialogs/kspread_dlg_styles.cpp
diff --git a/kspread/dialogs/kspread_dlg_subtotal.cc b/kspread/dialogs/kspread_dlg_subtotal.cpp
index 054cc1f76..054cc1f76 100644
--- a/kspread/dialogs/kspread_dlg_subtotal.cc
+++ b/kspread/dialogs/kspread_dlg_subtotal.cpp
diff --git a/kspread/dialogs/kspread_dlg_validity.cc b/kspread/dialogs/kspread_dlg_validity.cpp
index ea4625272..ea4625272 100644
--- a/kspread/dialogs/kspread_dlg_validity.cc
+++ b/kspread/dialogs/kspread_dlg_validity.cpp
diff --git a/kspread/dialogs/link.cc b/kspread/dialogs/link.cpp
index e0c1be217..e0c1be217 100644
--- a/kspread/dialogs/link.cc
+++ b/kspread/dialogs/link.cpp
diff --git a/kspread/dialogs/sheet_properties.cc b/kspread/dialogs/sheet_properties.cpp
index c4b79a9d4..c4b79a9d4 100644
--- a/kspread/dialogs/sheet_properties.cc
+++ b/kspread/dialogs/sheet_properties.cpp
diff --git a/kspread/digest.cc b/kspread/digest.cpp
index c4aa90c6d..c4aa90c6d 100644
--- a/kspread/digest.cc
+++ b/kspread/digest.cpp
diff --git a/kspread/formula.cc b/kspread/formula.cpp
index 3522f06b1..3522f06b1 100644
--- a/kspread/formula.cc
+++ b/kspread/formula.cpp
diff --git a/kspread/functions.cc b/kspread/functions.cc
deleted file mode 100644
index f6bc16e2f..000000000
--- a/kspread/functions.cc
+++ /dev/null
@@ -1,526 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2003,2004 Ariya Hidayat <ariya@kde.org>
- Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include "formula.h"
-#include "functions.h"
-#include "valuecalc.h"
-
-#include <tqdict.h>
-#include <tqdom.h>
-#include <tqfile.h>
-#include <tqvaluevector.h>
-
-#include <kdebug.h>
-#include <tdelocale.h>
-#include <kstandarddirs.h>
-#include <kstaticdeleter.h>
-
-#include "kspread_factory.h"
-
-namespace KSpread
-{
-
-class Function::Private
-{
-public:
- TQString name;
- FunctionPtr ptr;
- int paramMin, paramMax;
- bool acceptArray;
- bool ne; // need FunctionExtra* when called ?
-};
-
-class FunctionRepository::Private
-{
-public:
- TQDict<Function> functions;
- TQDict<FunctionDescription> funcs;
-};
-
-} // namespace KSpread
-
-
-using namespace KSpread;
-
-Function::Function( const TQString& name, FunctionPtr ptr )
-{
- d = new Private;
- d->name = name;
- d->ptr = ptr;
- d->acceptArray = false;
- d->paramMin = 1;
- d->paramMax = 1;
- d->ne = false;
-}
-
-Function::~Function()
-{
- delete d;
-}
-
-TQString Function::name() const
-{
- return d->name;
-}
-
-void Function::setParamCount (int min, int max)
-{
- d->paramMin = min;
- d->paramMax = (max == 0) ? min : max;
-}
-
-bool Function::paramCountOkay (int count)
-{
- // less than needed
- if (count < d->paramMin) return false;
- // no upper limit
- if (d->paramMax == -1) return true;
- // more than needed
- if (count > d->paramMax) return false;
- // okay otherwise
- return true;
-}
-
-void Function::setAcceptArray (bool accept) {
- d->acceptArray = accept;
-}
-
-bool Function::needsExtra () {
- return d->ne;
-}
-void Function::setNeedsExtra (bool extra) {
- d->ne = extra;
-}
-
-Value Function::exec (valVector args, ValueCalc *calc, FuncExtra *extra)
-{
- // check number of parameters
- if (!paramCountOkay (args.count()))
- return Value::errorVALUE();
-
- // do we need to perform array expansion ?
- bool mustExpandArray = false;
- if (!d->acceptArray)
- for (unsigned int i = 0; i < args.count(); ++i) {
- if (args[i].isArray())
- mustExpandArray = true;
- }
-
- if( !d->ptr ) return Value::errorVALUE();
-
- // perform the actual array expansion if need be
-
- if (mustExpandArray) {
- // compute number of rows/cols of the result
- int rows = 0;
- int cols = 0;
- for (unsigned int i = 0; i < args.count(); ++i) {
- int x = (args[i].type() == Value::Array) ? args[i].rows() : 1;
- if (x > rows) rows = x;
- x = (args[i].type() == Value::Array) ? args[i].columns() : 1;
- if (x > cols) cols = x;
- }
- // allocate the resulting array
- Value res (cols, rows);
- // perform the actual computation for each element of the array
- for (int row = 0; row < rows; ++row)
- for (int col = 0; col < cols; ++col) {
- // fill in the parameter vector
- valVector vals (args.count());
- for (unsigned int i = 0; i < args.count(); ++i) {
- int r = args[i].rows();
- int c = args[i].columns();
- vals[i] = args[i].isArray() ?
- args[i].element (col % c, row % r): args[i];
- }
-
- // execute the function on each element
- res.setElement (col, row, exec (vals, calc, extra));
- }
- return res;
- }
- else
- // call the function
- return (*d->ptr) (args, calc, extra);
-}
-
-
-// these are defined in kspread_function_*.cc
-void RegisterConversionFunctions();
-void RegisterDatabaseFunctions();
-void RegisterDateTimeFunctions();
-void RegisterEngineeringFunctions();
-void RegisterFinancialFunctions();
-void RegisterInformationFunctions();
-void RegisterLogicFunctions();
-void RegisterMathFunctions();
-void RegisterReferenceFunctions();
-void RegisterStatisticalFunctions();
-void RegisterTextFunctions();
-void RegisterTrigFunctions();
-
-
-static KStaticDeleter<FunctionRepository> fr_sd;
-FunctionRepository* FunctionRepository::s_self = 0;
-
-FunctionRepository* FunctionRepository::self()
-{
- if( !s_self )
- {
- kdDebug() << "Creating function repository" << endl;
-
- fr_sd.setObject( s_self, new FunctionRepository() );
-
- kdDebug() << "Registering functions" << endl;
-
- // register all existing functions
- RegisterConversionFunctions();
- RegisterDatabaseFunctions();
- RegisterDateTimeFunctions();
- RegisterEngineeringFunctions();
- RegisterFinancialFunctions();
- RegisterInformationFunctions();
- RegisterLogicFunctions();
- RegisterMathFunctions();
- RegisterReferenceFunctions();
- RegisterStatisticalFunctions();
- RegisterTextFunctions();
- RegisterTrigFunctions();
-
- kdDebug() << "Functions registered, loading descriptions" << endl;
-
- // find all XML description files
- TQStringList files = Factory::global()->dirs()->findAllResources
- ("extensions", "*.xml", TRUE);
-
- // load desc/help from XML file
- for( TQStringList::Iterator it = files.begin(); it != files.end(); ++it )
- s_self->loadFile (*it);
-
- kdDebug() << "All ok, repository ready" << endl;
-
- }
- return s_self;
-}
-
-FunctionRepository::FunctionRepository()
-{
- d = new Private;
-
- d->functions.setAutoDelete( true );
- d->funcs.setAutoDelete( true );
-}
-
-FunctionRepository::~FunctionRepository()
-{
- delete d;
- s_self = 0;
-}
-
-void FunctionRepository::add( Function* function )
-{
- if( !function ) return;
- d->functions.insert( function->name().upper(), function );
-}
-
-Function *FunctionRepository::function (const TQString& name)
-{
- return d->functions.find (name.upper());
-}
-
-FunctionDescription *FunctionRepository::functionInfo (const TQString& name)
-{
- return d->funcs.find (name.upper());
-}
-
-// returns names of function in certain group
-TQStringList FunctionRepository::functionNames( const TQString& group )
-{
- TQStringList lst;
-
- TQDictIterator<FunctionDescription> it (d->funcs);
- for(; it.current(); ++it) {
- if (group.isNull() || (it.current()->group() == group))
- lst.append (it.current()->name());
- }
-
- lst.sort();
- return lst;
-}
-
-void FunctionRepository::loadFile (const TQString& filename)
-{
- TQFile file (filename);
- if (!file.open (IO_ReadOnly))
- return;
-
- TQDomDocument doc;
- doc.setContent( &file );
- file.close();
-
- TQString group = "";
-
- TQDomNode n = doc.documentElement().firstChild();
- for (; !n.isNull(); n = n.nextSibling())
- {
- if (!n.isElement())
- continue;
- TQDomElement e = n.toElement();
- if (e.tagName() == "Group")
- {
- group = i18n (e.namedItem ("GroupName").toElement().text().utf8());
- m_groups.append( group );
- m_groups.sort();
-
- TQDomNode n2 = e.firstChild();
- for (; !n2.isNull(); n2 = n2.nextSibling())
- {
- if (!n2.isElement())
- continue;
- TQDomElement e2 = n2.toElement();
- if (e2.tagName() == "Function")
- {
- FunctionDescription* desc = new FunctionDescription( e2 );
- desc->setGroup (group);
- if (d->functions.find (desc->name()))
- d->funcs.insert (desc->name(), desc);
- }
- }
- group = "";
- }
- }
-}
-
-// ------------------------------------------------------------
-
-static ParameterType toType( const TQString& type )
-{
- if ( type == "Boolean" )
- return KSpread_Boolean;
- if ( type == "Int" )
- return KSpread_Int;
- if ( type == "String" )
- return KSpread_String;
- if ( type == "Any" )
- return KSpread_Any;
-
- return KSpread_Float;
-}
-
-static TQString toString (ParameterType type, bool range = FALSE)
-{
- if ( !range )
- {
- switch(type) {
- case KSpread_String:
- return i18n("Text");
- case KSpread_Int:
- return i18n("Whole number (like 1, 132, 2344)");
- case KSpread_Boolean:
- return i18n("A truth value (TRUE or FALSE)" );
- case KSpread_Float:
- return i18n("A floating point value (like 1.3, 0.343, 253 )" );
- case KSpread_Any:
- return i18n("Any kind of value");
- }
- }
- else
- {
- switch(type) {
- case KSpread_String:
- return i18n("A range of strings");
- case KSpread_Int:
- return i18n("A range of whole numbers (like 1, 132, 2344)");
- case KSpread_Boolean:
- return i18n("A range of truth values (TRUE or FALSE)" );
- case KSpread_Float:
- return i18n("A range of floating point values (like 1.3, 0.343, 253 )" );
- case KSpread_Any:
- return i18n("A range of any kind of values");
- }
- }
-
- return TQString();
-}
-
-FunctionParameter::FunctionParameter()
-{
- m_type = KSpread_Float;
- m_range = FALSE;
-}
-
-FunctionParameter::FunctionParameter (const FunctionParameter& param)
-{
- m_help = param.m_help;
- m_type = param.m_type;
- m_range = param.m_range;
-}
-
-FunctionParameter::FunctionParameter (const TQDomElement& element)
-{
- m_type = KSpread_Float;
- m_range = FALSE;
-
- TQDomNode n = element.firstChild();
- for( ; !n.isNull(); n = n.nextSibling() )
- if ( n.isElement() )
- {
- TQDomElement e = n.toElement();
- if ( e.tagName() == "Comment" )
- m_help = i18n( e.text().utf8() );
- else if ( e.tagName() == "Type" )
- {
- m_type = toType( e.text() );
- if ( e.hasAttribute( "range" ))
- {
- if (e.attribute("range").lower() == "true")
- m_range = TRUE;
- }
- }
- }
-}
-
-FunctionDescription::FunctionDescription()
-{
- m_type = KSpread_Float;
-}
-
-FunctionDescription::FunctionDescription (const TQDomElement& element)
-{
- TQDomNode n = element.firstChild();
- for( ; !n.isNull(); n = n.nextSibling() )
- {
- if (!n.isElement())
- continue;
- TQDomElement e = n.toElement();
- if ( e.tagName() == "Name" )
- m_name = e.text();
- else if ( e.tagName() == "Type" )
- m_type = toType( e.text() );
- else if ( e.tagName() == "Parameter" )
- m_params.append (FunctionParameter (e));
- else if ( e.tagName() == "Help" )
- {
- TQDomNode n2 = e.firstChild();
- for( ; !n2.isNull(); n2 = n2.nextSibling() )
- {
- if (!n2.isElement())
- continue;
- TQDomElement e2 = n2.toElement();
- if ( e2.tagName() == "Text" )
- m_help.append ( i18n( e2.text().utf8() ) );
- else if ( e2.tagName() == "Syntax" )
- m_syntax.append( i18n( e2.text().utf8() ) );
- else if ( e2.tagName() == "Example" )
- m_examples.append( i18n( e2.text().utf8() ) );
- else if ( e2.tagName() == "Related" )
- m_related.append( i18n( e2.text().utf8() ) );
- }
- }
- }
-}
-
-FunctionDescription::FunctionDescription( const FunctionDescription& desc )
-{
- m_examples = desc.m_examples;
- m_related = desc.m_related;
- m_syntax = desc.m_syntax;
- m_help = desc.m_help;
- m_name = desc.m_name;
- m_type = desc.m_type;
-}
-
-TQString FunctionDescription::toTQML() const
-{
- TQString text( "<qt><h1>" );
- text += name();
- text += "</h1>";
-
- if( !m_help.isEmpty() )
- {
- text += i18n("<p>");
- TQStringList::ConstIterator it = m_help.begin();
- for( ; it != m_help.end(); ++it )
- {
- text += *it;
- text += "<p>";
- }
- text += "</p>";
- }
-
- text += i18n("<p><b>Return type: </b>");
- text += toString( type() );
- text += "</p>";
-
- if ( !m_syntax.isEmpty() )
- {
- text += i18n("<h2>Syntax</h2><ul>");
- TQStringList::ConstIterator it = m_syntax.begin();
- for( ; it != m_syntax.end(); ++it )
- {
- text += "<li>";
- text += *it;
- }
- text += "</ul>";
- }
-
- if ( !m_params.isEmpty() )
- {
- text += i18n("<h2>Parameters</h2><ul>");
- TQValueList<FunctionParameter>::ConstIterator it = m_params.begin();
- for( ; it != m_params.end(); ++it )
- {
- text += i18n("<li><b>Comment:</b> ");
- text += (*it).helpText();
- text += i18n("<br><b>Type:</b> ");
- text += toString( (*it).type(), (*it).hasRange() );
- }
- text += "</ul>";
- }
-
- if ( !m_examples.isEmpty() )
- {
- text += i18n("<h2>Examples</h2><ul>");
- TQStringList::ConstIterator it = m_examples.begin();
- for( ; it != m_examples.end(); ++it )
- {
- text += "<li>";
- text += *it;
- }
- text += "</ul>";
- }
-
- if ( !m_related.isEmpty() )
- {
- text += i18n("<h2>Related Functions</h2><ul>");
- TQStringList::ConstIterator it = m_related.begin();
- for( ; it != m_related.end(); ++it )
- {
- text += "<li>";
- text += "<a href=\"" + *it + "\">";
- text += *it;
- text += "</a>";
- }
- text += "</ul>";
- }
-
- text += "</qt>";
- return text;
-}
diff --git a/kspread/functions.cpp b/kspread/functions.cpp
new file mode 100644
index 000000000..fa485171a
--- /dev/null
+++ b/kspread/functions.cpp
@@ -0,0 +1,526 @@
+/* This file is part of the KDE project
+ Copyright (C) 2003,2004 Ariya Hidayat <ariya@kde.org>
+ Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "formula.h"
+#include "functions.h"
+#include "valuecalc.h"
+
+#include <tqdict.h>
+#include <tqdom.h>
+#include <tqfile.h>
+#include <tqvaluevector.h>
+
+#include <kdebug.h>
+#include <tdelocale.h>
+#include <kstandarddirs.h>
+#include <kstaticdeleter.h>
+
+#include "kspread_factory.h"
+
+namespace KSpread
+{
+
+class Function::Private
+{
+public:
+ TQString name;
+ FunctionPtr ptr;
+ int paramMin, paramMax;
+ bool acceptArray;
+ bool ne; // need FunctionExtra* when called ?
+};
+
+class FunctionRepository::Private
+{
+public:
+ TQDict<Function> functions;
+ TQDict<FunctionDescription> funcs;
+};
+
+} // namespace KSpread
+
+
+using namespace KSpread;
+
+Function::Function( const TQString& name, FunctionPtr ptr )
+{
+ d = new Private;
+ d->name = name;
+ d->ptr = ptr;
+ d->acceptArray = false;
+ d->paramMin = 1;
+ d->paramMax = 1;
+ d->ne = false;
+}
+
+Function::~Function()
+{
+ delete d;
+}
+
+TQString Function::name() const
+{
+ return d->name;
+}
+
+void Function::setParamCount (int min, int max)
+{
+ d->paramMin = min;
+ d->paramMax = (max == 0) ? min : max;
+}
+
+bool Function::paramCountOkay (int count)
+{
+ // less than needed
+ if (count < d->paramMin) return false;
+ // no upper limit
+ if (d->paramMax == -1) return true;
+ // more than needed
+ if (count > d->paramMax) return false;
+ // okay otherwise
+ return true;
+}
+
+void Function::setAcceptArray (bool accept) {
+ d->acceptArray = accept;
+}
+
+bool Function::needsExtra () {
+ return d->ne;
+}
+void Function::setNeedsExtra (bool extra) {
+ d->ne = extra;
+}
+
+Value Function::exec (valVector args, ValueCalc *calc, FuncExtra *extra)
+{
+ // check number of parameters
+ if (!paramCountOkay (args.count()))
+ return Value::errorVALUE();
+
+ // do we need to perform array expansion ?
+ bool mustExpandArray = false;
+ if (!d->acceptArray)
+ for (unsigned int i = 0; i < args.count(); ++i) {
+ if (args[i].isArray())
+ mustExpandArray = true;
+ }
+
+ if( !d->ptr ) return Value::errorVALUE();
+
+ // perform the actual array expansion if need be
+
+ if (mustExpandArray) {
+ // compute number of rows/cols of the result
+ int rows = 0;
+ int cols = 0;
+ for (unsigned int i = 0; i < args.count(); ++i) {
+ int x = (args[i].type() == Value::Array) ? args[i].rows() : 1;
+ if (x > rows) rows = x;
+ x = (args[i].type() == Value::Array) ? args[i].columns() : 1;
+ if (x > cols) cols = x;
+ }
+ // allocate the resulting array
+ Value res (cols, rows);
+ // perform the actual computation for each element of the array
+ for (int row = 0; row < rows; ++row)
+ for (int col = 0; col < cols; ++col) {
+ // fill in the parameter vector
+ valVector vals (args.count());
+ for (unsigned int i = 0; i < args.count(); ++i) {
+ int r = args[i].rows();
+ int c = args[i].columns();
+ vals[i] = args[i].isArray() ?
+ args[i].element (col % c, row % r): args[i];
+ }
+
+ // execute the function on each element
+ res.setElement (col, row, exec (vals, calc, extra));
+ }
+ return res;
+ }
+ else
+ // call the function
+ return (*d->ptr) (args, calc, extra);
+}
+
+
+// these are defined in kspread_function_*.cpp
+void RegisterConversionFunctions();
+void RegisterDatabaseFunctions();
+void RegisterDateTimeFunctions();
+void RegisterEngineeringFunctions();
+void RegisterFinancialFunctions();
+void RegisterInformationFunctions();
+void RegisterLogicFunctions();
+void RegisterMathFunctions();
+void RegisterReferenceFunctions();
+void RegisterStatisticalFunctions();
+void RegisterTextFunctions();
+void RegisterTrigFunctions();
+
+
+static KStaticDeleter<FunctionRepository> fr_sd;
+FunctionRepository* FunctionRepository::s_self = 0;
+
+FunctionRepository* FunctionRepository::self()
+{
+ if( !s_self )
+ {
+ kdDebug() << "Creating function repository" << endl;
+
+ fr_sd.setObject( s_self, new FunctionRepository() );
+
+ kdDebug() << "Registering functions" << endl;
+
+ // register all existing functions
+ RegisterConversionFunctions();
+ RegisterDatabaseFunctions();
+ RegisterDateTimeFunctions();
+ RegisterEngineeringFunctions();
+ RegisterFinancialFunctions();
+ RegisterInformationFunctions();
+ RegisterLogicFunctions();
+ RegisterMathFunctions();
+ RegisterReferenceFunctions();
+ RegisterStatisticalFunctions();
+ RegisterTextFunctions();
+ RegisterTrigFunctions();
+
+ kdDebug() << "Functions registered, loading descriptions" << endl;
+
+ // find all XML description files
+ TQStringList files = Factory::global()->dirs()->findAllResources
+ ("extensions", "*.xml", TRUE);
+
+ // load desc/help from XML file
+ for( TQStringList::Iterator it = files.begin(); it != files.end(); ++it )
+ s_self->loadFile (*it);
+
+ kdDebug() << "All ok, repository ready" << endl;
+
+ }
+ return s_self;
+}
+
+FunctionRepository::FunctionRepository()
+{
+ d = new Private;
+
+ d->functions.setAutoDelete( true );
+ d->funcs.setAutoDelete( true );
+}
+
+FunctionRepository::~FunctionRepository()
+{
+ delete d;
+ s_self = 0;
+}
+
+void FunctionRepository::add( Function* function )
+{
+ if( !function ) return;
+ d->functions.insert( function->name().upper(), function );
+}
+
+Function *FunctionRepository::function (const TQString& name)
+{
+ return d->functions.find (name.upper());
+}
+
+FunctionDescription *FunctionRepository::functionInfo (const TQString& name)
+{
+ return d->funcs.find (name.upper());
+}
+
+// returns names of function in certain group
+TQStringList FunctionRepository::functionNames( const TQString& group )
+{
+ TQStringList lst;
+
+ TQDictIterator<FunctionDescription> it (d->funcs);
+ for(; it.current(); ++it) {
+ if (group.isNull() || (it.current()->group() == group))
+ lst.append (it.current()->name());
+ }
+
+ lst.sort();
+ return lst;
+}
+
+void FunctionRepository::loadFile (const TQString& filename)
+{
+ TQFile file (filename);
+ if (!file.open (IO_ReadOnly))
+ return;
+
+ TQDomDocument doc;
+ doc.setContent( &file );
+ file.close();
+
+ TQString group = "";
+
+ TQDomNode n = doc.documentElement().firstChild();
+ for (; !n.isNull(); n = n.nextSibling())
+ {
+ if (!n.isElement())
+ continue;
+ TQDomElement e = n.toElement();
+ if (e.tagName() == "Group")
+ {
+ group = i18n (e.namedItem ("GroupName").toElement().text().utf8());
+ m_groups.append( group );
+ m_groups.sort();
+
+ TQDomNode n2 = e.firstChild();
+ for (; !n2.isNull(); n2 = n2.nextSibling())
+ {
+ if (!n2.isElement())
+ continue;
+ TQDomElement e2 = n2.toElement();
+ if (e2.tagName() == "Function")
+ {
+ FunctionDescription* desc = new FunctionDescription( e2 );
+ desc->setGroup (group);
+ if (d->functions.find (desc->name()))
+ d->funcs.insert (desc->name(), desc);
+ }
+ }
+ group = "";
+ }
+ }
+}
+
+// ------------------------------------------------------------
+
+static ParameterType toType( const TQString& type )
+{
+ if ( type == "Boolean" )
+ return KSpread_Boolean;
+ if ( type == "Int" )
+ return KSpread_Int;
+ if ( type == "String" )
+ return KSpread_String;
+ if ( type == "Any" )
+ return KSpread_Any;
+
+ return KSpread_Float;
+}
+
+static TQString toString (ParameterType type, bool range = FALSE)
+{
+ if ( !range )
+ {
+ switch(type) {
+ case KSpread_String:
+ return i18n("Text");
+ case KSpread_Int:
+ return i18n("Whole number (like 1, 132, 2344)");
+ case KSpread_Boolean:
+ return i18n("A truth value (TRUE or FALSE)" );
+ case KSpread_Float:
+ return i18n("A floating point value (like 1.3, 0.343, 253 )" );
+ case KSpread_Any:
+ return i18n("Any kind of value");
+ }
+ }
+ else
+ {
+ switch(type) {
+ case KSpread_String:
+ return i18n("A range of strings");
+ case KSpread_Int:
+ return i18n("A range of whole numbers (like 1, 132, 2344)");
+ case KSpread_Boolean:
+ return i18n("A range of truth values (TRUE or FALSE)" );
+ case KSpread_Float:
+ return i18n("A range of floating point values (like 1.3, 0.343, 253 )" );
+ case KSpread_Any:
+ return i18n("A range of any kind of values");
+ }
+ }
+
+ return TQString();
+}
+
+FunctionParameter::FunctionParameter()
+{
+ m_type = KSpread_Float;
+ m_range = FALSE;
+}
+
+FunctionParameter::FunctionParameter (const FunctionParameter& param)
+{
+ m_help = param.m_help;
+ m_type = param.m_type;
+ m_range = param.m_range;
+}
+
+FunctionParameter::FunctionParameter (const TQDomElement& element)
+{
+ m_type = KSpread_Float;
+ m_range = FALSE;
+
+ TQDomNode n = element.firstChild();
+ for( ; !n.isNull(); n = n.nextSibling() )
+ if ( n.isElement() )
+ {
+ TQDomElement e = n.toElement();
+ if ( e.tagName() == "Comment" )
+ m_help = i18n( e.text().utf8() );
+ else if ( e.tagName() == "Type" )
+ {
+ m_type = toType( e.text() );
+ if ( e.hasAttribute( "range" ))
+ {
+ if (e.attribute("range").lower() == "true")
+ m_range = TRUE;
+ }
+ }
+ }
+}
+
+FunctionDescription::FunctionDescription()
+{
+ m_type = KSpread_Float;
+}
+
+FunctionDescription::FunctionDescription (const TQDomElement& element)
+{
+ TQDomNode n = element.firstChild();
+ for( ; !n.isNull(); n = n.nextSibling() )
+ {
+ if (!n.isElement())
+ continue;
+ TQDomElement e = n.toElement();
+ if ( e.tagName() == "Name" )
+ m_name = e.text();
+ else if ( e.tagName() == "Type" )
+ m_type = toType( e.text() );
+ else if ( e.tagName() == "Parameter" )
+ m_params.append (FunctionParameter (e));
+ else if ( e.tagName() == "Help" )
+ {
+ TQDomNode n2 = e.firstChild();
+ for( ; !n2.isNull(); n2 = n2.nextSibling() )
+ {
+ if (!n2.isElement())
+ continue;
+ TQDomElement e2 = n2.toElement();
+ if ( e2.tagName() == "Text" )
+ m_help.append ( i18n( e2.text().utf8() ) );
+ else if ( e2.tagName() == "Syntax" )
+ m_syntax.append( i18n( e2.text().utf8() ) );
+ else if ( e2.tagName() == "Example" )
+ m_examples.append( i18n( e2.text().utf8() ) );
+ else if ( e2.tagName() == "Related" )
+ m_related.append( i18n( e2.text().utf8() ) );
+ }
+ }
+ }
+}
+
+FunctionDescription::FunctionDescription( const FunctionDescription& desc )
+{
+ m_examples = desc.m_examples;
+ m_related = desc.m_related;
+ m_syntax = desc.m_syntax;
+ m_help = desc.m_help;
+ m_name = desc.m_name;
+ m_type = desc.m_type;
+}
+
+TQString FunctionDescription::toTQML() const
+{
+ TQString text( "<qt><h1>" );
+ text += name();
+ text += "</h1>";
+
+ if( !m_help.isEmpty() )
+ {
+ text += i18n("<p>");
+ TQStringList::ConstIterator it = m_help.begin();
+ for( ; it != m_help.end(); ++it )
+ {
+ text += *it;
+ text += "<p>";
+ }
+ text += "</p>";
+ }
+
+ text += i18n("<p><b>Return type: </b>");
+ text += toString( type() );
+ text += "</p>";
+
+ if ( !m_syntax.isEmpty() )
+ {
+ text += i18n("<h2>Syntax</h2><ul>");
+ TQStringList::ConstIterator it = m_syntax.begin();
+ for( ; it != m_syntax.end(); ++it )
+ {
+ text += "<li>";
+ text += *it;
+ }
+ text += "</ul>";
+ }
+
+ if ( !m_params.isEmpty() )
+ {
+ text += i18n("<h2>Parameters</h2><ul>");
+ TQValueList<FunctionParameter>::ConstIterator it = m_params.begin();
+ for( ; it != m_params.end(); ++it )
+ {
+ text += i18n("<li><b>Comment:</b> ");
+ text += (*it).helpText();
+ text += i18n("<br><b>Type:</b> ");
+ text += toString( (*it).type(), (*it).hasRange() );
+ }
+ text += "</ul>";
+ }
+
+ if ( !m_examples.isEmpty() )
+ {
+ text += i18n("<h2>Examples</h2><ul>");
+ TQStringList::ConstIterator it = m_examples.begin();
+ for( ; it != m_examples.end(); ++it )
+ {
+ text += "<li>";
+ text += *it;
+ }
+ text += "</ul>";
+ }
+
+ if ( !m_related.isEmpty() )
+ {
+ text += i18n("<h2>Related Functions</h2><ul>");
+ TQStringList::ConstIterator it = m_related.begin();
+ for( ; it != m_related.end(); ++it )
+ {
+ text += "<li>";
+ text += "<a href=\"" + *it + "\">";
+ text += *it;
+ text += "</a>";
+ }
+ text += "</ul>";
+ }
+
+ text += "</qt>";
+ return text;
+}
diff --git a/kspread/kspread_autofill.cc b/kspread/kspread_autofill.cpp
index e110e1adb..e110e1adb 100644
--- a/kspread/kspread_autofill.cc
+++ b/kspread/kspread_autofill.cpp
diff --git a/kspread/kspread_brush.cc b/kspread/kspread_brush.cpp
index d585950b7..d585950b7 100644
--- a/kspread/kspread_brush.cc
+++ b/kspread/kspread_brush.cpp
diff --git a/kspread/kspread_canvas.cc b/kspread/kspread_canvas.cpp
index 0518e2740..0518e2740 100644
--- a/kspread/kspread_canvas.cc
+++ b/kspread/kspread_canvas.cpp
diff --git a/kspread/kspread_cell.cc b/kspread/kspread_cell.cpp
index fca76bbe0..fca76bbe0 100644
--- a/kspread/kspread_cell.cc
+++ b/kspread/kspread_cell.cpp
diff --git a/kspread/kspread_cluster.cc b/kspread/kspread_cluster.cpp
index 318ee7582..318ee7582 100644
--- a/kspread/kspread_cluster.cc
+++ b/kspread/kspread_cluster.cpp
diff --git a/kspread/kspread_condition.cc b/kspread/kspread_condition.cpp
index 876dfbf07..876dfbf07 100644
--- a/kspread/kspread_condition.cc
+++ b/kspread/kspread_condition.cpp
diff --git a/kspread/kspread_doc.cc b/kspread/kspread_doc.cpp
index 7643b31d8..7643b31d8 100644
--- a/kspread/kspread_doc.cc
+++ b/kspread/kspread_doc.cpp
diff --git a/kspread/kspread_editors.cc b/kspread/kspread_editors.cpp
index 4af76159e..4af76159e 100644
--- a/kspread/kspread_editors.cc
+++ b/kspread/kspread_editors.cpp
diff --git a/kspread/kspread_events.cc b/kspread/kspread_events.cpp
index 7026be1df..7026be1df 100644
--- a/kspread/kspread_events.cc
+++ b/kspread/kspread_events.cpp
diff --git a/kspread/kspread_factory.cc b/kspread/kspread_factory.cpp
index 861b9d962..861b9d962 100644
--- a/kspread/kspread_factory.cc
+++ b/kspread/kspread_factory.cpp
diff --git a/kspread/kspread_factory_init.cc b/kspread/kspread_factory_init.cpp
index d62e304f6..d62e304f6 100644
--- a/kspread/kspread_factory_init.cc
+++ b/kspread/kspread_factory_init.cpp
diff --git a/kspread/kspread_format.cc b/kspread/kspread_format.cpp
index 430e23869..430e23869 100644
--- a/kspread/kspread_format.cc
+++ b/kspread/kspread_format.cpp
diff --git a/kspread/kspread_functions_conversion.cc b/kspread/kspread_functions_conversion.cpp
index 23f2ca015..23f2ca015 100644
--- a/kspread/kspread_functions_conversion.cc
+++ b/kspread/kspread_functions_conversion.cpp
diff --git a/kspread/kspread_functions_database.cc b/kspread/kspread_functions_database.cpp
index a294914d6..a294914d6 100644
--- a/kspread/kspread_functions_database.cc
+++ b/kspread/kspread_functions_database.cpp
diff --git a/kspread/kspread_functions_datetime.cc b/kspread/kspread_functions_datetime.cpp
index d322b6a49..d322b6a49 100644
--- a/kspread/kspread_functions_datetime.cc
+++ b/kspread/kspread_functions_datetime.cpp
diff --git a/kspread/kspread_functions_engineering.cc b/kspread/kspread_functions_engineering.cpp
index bca81ec8d..bca81ec8d 100644
--- a/kspread/kspread_functions_engineering.cc
+++ b/kspread/kspread_functions_engineering.cpp
diff --git a/kspread/kspread_functions_financial.cc b/kspread/kspread_functions_financial.cpp
index daccb6408..daccb6408 100644
--- a/kspread/kspread_functions_financial.cc
+++ b/kspread/kspread_functions_financial.cpp
diff --git a/kspread/kspread_functions_helper.cc b/kspread/kspread_functions_helper.cpp
index 92f7b1ae9..92f7b1ae9 100644
--- a/kspread/kspread_functions_helper.cc
+++ b/kspread/kspread_functions_helper.cpp
diff --git a/kspread/kspread_functions_information.cc b/kspread/kspread_functions_information.cpp
index 30d64263c..30d64263c 100644
--- a/kspread/kspread_functions_information.cc
+++ b/kspread/kspread_functions_information.cpp
diff --git a/kspread/kspread_functions_logic.cc b/kspread/kspread_functions_logic.cpp
index 87dd26d48..87dd26d48 100644
--- a/kspread/kspread_functions_logic.cc
+++ b/kspread/kspread_functions_logic.cpp
diff --git a/kspread/kspread_functions_math.cc b/kspread/kspread_functions_math.cpp
index 06b6da2b5..06b6da2b5 100644
--- a/kspread/kspread_functions_math.cc
+++ b/kspread/kspread_functions_math.cpp
diff --git a/kspread/kspread_functions_reference.cc b/kspread/kspread_functions_reference.cpp
index 7dacb0548..7dacb0548 100644
--- a/kspread/kspread_functions_reference.cc
+++ b/kspread/kspread_functions_reference.cpp
diff --git a/kspread/kspread_functions_statistical.cc b/kspread/kspread_functions_statistical.cpp
index 26c9d4834..26c9d4834 100644
--- a/kspread/kspread_functions_statistical.cc
+++ b/kspread/kspread_functions_statistical.cpp
diff --git a/kspread/kspread_functions_text.cc b/kspread/kspread_functions_text.cpp
index 5a8dccf69..5a8dccf69 100644
--- a/kspread/kspread_functions_text.cc
+++ b/kspread/kspread_functions_text.cpp
diff --git a/kspread/kspread_functions_trig.cc b/kspread/kspread_functions_trig.cpp
index f79d7f814..f79d7f814 100644
--- a/kspread/kspread_functions_trig.cc
+++ b/kspread/kspread_functions_trig.cpp
diff --git a/kspread/kspread_genvalidationstyle.cc b/kspread/kspread_genvalidationstyle.cpp
index 613be1769..613be1769 100644
--- a/kspread/kspread_genvalidationstyle.cc
+++ b/kspread/kspread_genvalidationstyle.cpp
diff --git a/kspread/kspread_handler.cc b/kspread/kspread_handler.cpp
index 262774ffe..262774ffe 100644
--- a/kspread/kspread_handler.cc
+++ b/kspread/kspread_handler.cpp
diff --git a/kspread/kspread_locale.cc b/kspread/kspread_locale.cpp
index fc665f0a5..fc665f0a5 100644
--- a/kspread/kspread_locale.cc
+++ b/kspread/kspread_locale.cpp
diff --git a/kspread/kspread_map.cc b/kspread/kspread_map.cpp
index d54c340a1..d54c340a1 100644
--- a/kspread/kspread_map.cc
+++ b/kspread/kspread_map.cpp
diff --git a/kspread/kspread_numformat.cc b/kspread/kspread_numformat.cpp
index e3a0bee7a..e3a0bee7a 100644
--- a/kspread/kspread_numformat.cc
+++ b/kspread/kspread_numformat.cpp
diff --git a/kspread/kspread_object.cc b/kspread/kspread_object.cpp
index 2fce26968..2fce26968 100644
--- a/kspread/kspread_object.cc
+++ b/kspread/kspread_object.cpp
diff --git a/kspread/kspread_pen.cc b/kspread/kspread_pen.cpp
index 52a0ada6b..52a0ada6b 100644
--- a/kspread/kspread_pen.cc
+++ b/kspread/kspread_pen.cpp
diff --git a/kspread/kspread_sheet.cc b/kspread/kspread_sheet.cpp
index a8965b9e7..a8965b9e7 100644
--- a/kspread/kspread_sheet.cc
+++ b/kspread/kspread_sheet.cpp
diff --git a/kspread/kspread_sheet.h b/kspread/kspread_sheet.h
index 2b2ed21cd..a99024529 100644
--- a/kspread/kspread_sheet.h
+++ b/kspread/kspread_sheet.h
@@ -787,7 +787,7 @@ public:
void setFirstLetterUpper(bool _firstUpper);
- // TODO Stefan: remove after kspread_undo.cc|h and commands.cc|h are obsolete
+ // TODO Stefan: remove after kspread_undo.cpp|h and commands.cpp|h are obsolete
void changeMergedCell( int /*m_iCol*/, int /*m_iRow*/, int /*m_iExtraX*/, int /*m_iExtraY*/) {}
/**
@@ -1317,7 +1317,7 @@ protected:
static TQIntDict<Sheet>* s_mapSheets;
public:
- // see kspread_sheet.cc for an explanation of this
+ // see kspread_sheet.cpp for an explanation of this
// this is for type B and also for type A (better use CellWorkerTypeA for that)
struct CellWorker
{
diff --git a/kspread/kspread_sheetprint.cc b/kspread/kspread_sheetprint.cc
deleted file mode 100644
index 3cc26bf3e..000000000
--- a/kspread/kspread_sheetprint.cc
+++ /dev/null
@@ -1,1807 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>,
- 2003 Philipp Mller <philipp.mueller@gmx.de>
- 2005 Raphael Langerhorst <raphael.langerhorst@kdemail.net>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include "kspread_sheet.h"
-#include "selection.h"
-#include "kspread_locale.h"
-#include "kspread_doc.h"
-#include "kspread_undo.h"
-
-#include "kspread_sheetprint.h"
-
-#include "commands.h"
-#include <KoDocumentInfo.h>
-
-#include <tdemessagebox.h>
-#include <kprinter.h>
-#include <kdebug.h>
-
-#include <tqregexp.h>
-
-#include <pwd.h>
-#include <unistd.h>
-
-#include "kspread_sheetprint.moc"
-
-#define NO_MODIFICATION_POSSIBLE \
-do { \
- KMessageBox::error( 0, i18n ( "You cannot change a protected sheet" ) ); return; \
-} while(0)
-
-using namespace KSpread;
-
-SheetPrint::SheetPrint( Sheet* sheet )
-{
- m_pSheet = sheet;
- m_pDoc = m_pSheet->doc();
-
- m_bPrintGrid = false;
- m_bPrintCommentIndicator = false;
- m_bPrintFormulaIndicator = false;
- m_bPrintObjects = true;
- m_bPrintCharts = true;
- m_bPrintGraphics = true;
-
- m_leftBorder = 20.0;
- m_rightBorder = 20.0;
- m_topBorder = 20.0;
- m_bottomBorder = 20.0;
-
- m_paperFormat = KoPageFormat::defaultFormat();
- m_orientation = PG_PORTRAIT;
- m_paperWidth = MM_TO_POINT( KoPageFormat::width( m_paperFormat, m_orientation ) );
- m_paperHeight = MM_TO_POINT( KoPageFormat::height( m_paperFormat, m_orientation ) );
- m_printRange = TQRect( TQPoint( 1, 1 ), TQPoint( KS_colMax, KS_rowMax ) );
- m_lnewPageListX.append( 1 );
- m_lnewPageListY.append( 1 );
- m_maxCheckedNewPageX = 1;
- m_maxCheckedNewPageY = 1;
- m_dPrintRepeatColumnsWidth = 0.0;
- m_dPrintRepeatRowsHeight = 0.0;
- m_printRepeatColumns = tqMakePair( 0, 0 );
- m_printRepeatRows = tqMakePair( 0, 0 );
- m_dZoom = 1.0;
- m_iPageLimitX = 0;
- m_iPageLimitY = 0;
-
- calcPaperSize();
-}
-
-SheetPrint::~SheetPrint()
-{
- // nothing todo yet
-}
-
-TQString SheetPrint::saveOasisSheetStyleLayout( KoGenStyles &mainStyles )
-{
- KoGenStyle pageLayout( KoGenStyle::STYLE_PAGELAYOUT );
- //pageLayout.addAttribute( "style:page-usage", "all" ); FIXME
- pageLayout.addPropertyPt( "fo:page-width", MM_TO_POINT( paperWidth() ) );
- pageLayout.addPropertyPt( "fo:page-height", MM_TO_POINT( paperHeight() ) );
- pageLayout.addProperty( "style:print-orientation", orientation() == PG_LANDSCAPE ? "landscape" : "portrait" );
- pageLayout.addPropertyPt( "fo:margin-left", MM_TO_POINT(leftBorder() ) );
- pageLayout.addPropertyPt( "fo:margin-top", MM_TO_POINT(topBorder() ) );
- pageLayout.addPropertyPt( "fo:margin-right", MM_TO_POINT(rightBorder() ) );
- pageLayout.addPropertyPt( "fo:margin-bottom", MM_TO_POINT(bottomBorder() ) );
- //necessary for print setup
- m_pSheet->saveOasisPrintStyleLayout( pageLayout );
-
- return mainStyles.lookup( pageLayout, "pm" );
-}
-
-
-TQRect SheetPrint::cellsPrintRange()
-{
- // Find maximum right/bottom cell with content
- TQRect cell_range;
- cell_range.setCoords( 1, 1, 1, 1 );
-
- Cell* c = m_pSheet->firstCell();
- for( ;c; c = c->nextCell() )
- {
- if ( c->needsPrinting() )
- {
- if ( c->column() > cell_range.right() )
- cell_range.setRight( c->column() );
- if ( c->row() > cell_range.bottom() )
- cell_range.setBottom( c->row() );
- }
- }
-
- // Now look at the children
- TQPtrListIterator<KoDocumentChild> cit( m_pDoc->children() );
- double dummy;
- int i;
- for( ; cit.current(); ++cit )
- {
- //TQRect, because KoChild doesn't use KoRect yet
- TQRect bound = cit.current()->boundingRect();
-
- i = m_pSheet->leftColumn( bound.right(), dummy );
- if ( i > cell_range.right() )
- cell_range.setRight( i );
-
- i = m_pSheet->topRow( bound.bottom(), dummy );
- if ( i > cell_range.bottom() )
- cell_range.setBottom( i );
- }
- cell_range = cell_range.intersect( m_printRange );
-
- return cell_range;
-}
-
-int SheetPrint::pagesX( const TQRect& cellsPrintRange )
-{
- int pages = 0;
-
- updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( cellsPrintRange.right() ) + prinsheetWidthPts() ) );
-
- for( int i = cellsPrintRange.left(); i <= cellsPrintRange.right(); i++ )
- {
- if( isOnNewPageX( i ) )
- pages++;
- }
- return pages;
-}
-
-int SheetPrint::pagesY( const TQRect& cellsPrintRange )
-{
- int pages = 0;
-
- updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( cellsPrintRange.bottom() ) + prinsheetHeightPts() ) );
-
- for( int i = cellsPrintRange.top(); i <= cellsPrintRange.bottom(); i++ )
- {
- if( isOnNewPageY( i ) )
- pages++;
- }
- return pages;
-}
-
-
-bool SheetPrint::pageNeedsPrinting( TQRect& page_range )
-{
- // bool filled = false;
-
- // Look at the cells
- for( int r = page_range.top(); r <= page_range.bottom() ; ++r )
- for( int c = page_range.left(); c <= page_range.right() ; ++c )
- if ( m_pSheet->cellAt( c, r )->needsPrinting() )
- {
- return true;
- }
- // filled = true;
-
- //Page empty, but maybe children on it?
-
- TQRect intView = TQRect( TQPoint( m_pDoc->zoomItX( m_pSheet->dblColumnPos( page_range.left() ) ),
- m_pDoc->zoomItY( m_pSheet->dblRowPos( page_range.top() ) ) ),
- TQPoint( m_pDoc->zoomItX( m_pSheet->dblColumnPos( page_range.right() ) +
- m_pSheet->columnFormat( page_range.right() )->dblWidth() ),
- m_pDoc->zoomItY( m_pSheet->dblRowPos( page_range.bottom() ) +
- m_pSheet->rowFormat( page_range.bottom() )->dblHeight() ) ) );
-
- TQPtrListIterator<KoDocumentChild> it( m_pDoc->children() );
- for( ;it.current(); ++it )
- {
- TQRect bound = it.current()->boundingRect();
- if ( bound.intersects( intView ) )
- {
- return true;
- }
- //filled = true;
- }
-
-
- //Page has no visible content on it, so we don't need to paint it
- return false;
-}
-
-bool SheetPrint::print( TQPainter &painter, KPrinter *_printer )
-{
- kdDebug(36001)<<"PRINTING ...."<<endl;
-
- // Override the current grid pen setting, when set to disable
- TQPen gridPen;
- bool oldShowGrid = m_pSheet->getShowGrid();
- m_pSheet->setShowGrid( m_bPrintGrid );
- if ( !m_bPrintGrid )
- {
- gridPen = TQPen( m_pDoc->gridColor(), 1, TQt::SolidLine );
- TQPen nopen;
- nopen.setStyle( Qt::NoPen );
- m_pDoc->setGridColor( TQt::white );
- }
-
- //Update m_dPrintRepeatColumnsWidth for repeated columns
- //just in case it isn't done yet
- if ( !m_pSheet->isShowPageBorders() && m_printRepeatColumns.first != 0 )
- updatePrintRepeatColumnsWidth();
-
- //Update m_dPrintRepeatRowsHeight for repeated rows
- //just in case it isn't done yet
- if ( !m_pSheet->isShowPageBorders() && m_printRepeatRows.first != 0 )
- updatePrintRepeatRowsHeight();
-
- //Calculate the range to be printed
- TQRect cell_range = cellsPrintRange();
- kdDebug()<<"cellsPrintRange() :"<<cellsPrintRange()<<endl;
- //Ensure, that our newPage lists are generated for the whole sheet to print
- //For this we add to the lists the width/height of 1 page
- updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( cell_range.right() ) + prinsheetWidthPts() ) );
- updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( cell_range.bottom() ) + prinsheetHeightPts() ) );
-
- // Find out how many pages need printing
- // and which cells to print on which page.
- TQValueList<TQRect> page_list; //contains the cols and rows of a page
- TQValueList<KoRect> page_frame_list; //contains the coordinate range of a page
- TQValueList<KoPoint> page_frame_list_offset; //contains the offset of the not repeated area
-
- TQValueList<PrintNewPageEntry>::iterator itX;
- TQValueList<PrintNewPageEntry>::iterator itY;
- for( itX = m_lnewPageListX.begin(); itX != m_lnewPageListX.end(); ++itX )
- {
- for( itY = m_lnewPageListY.begin(); itY != m_lnewPageListY.end(); ++itY )
- {
- TQRect page_range( TQPoint( (*itX).startItem(), (*itY).startItem() ),
- TQPoint( (*itX).endItem(), (*itY).endItem() ) );
- kdDebug()<<" page_range :"<<page_range<<endl;
- //Append page when there is something to print
- if ( pageNeedsPrinting( page_range ) )
- {
- KoRect view = KoRect( KoPoint( m_pSheet->dblColumnPos( page_range.left() ),
- m_pSheet->dblRowPos( page_range.top() ) ),
- KoPoint( m_pSheet->dblColumnPos( page_range.right() ) +
- m_pSheet->columnFormat( page_range.right() )->dblWidth(),
- m_pSheet->dblRowPos( page_range.bottom() ) +
- m_pSheet->rowFormat( page_range.bottom() )->dblHeight() ) );
- page_list.append( page_range );
- page_frame_list.append( view );
- page_frame_list_offset.append( KoPoint( (*itX).offset(), (*itY).offset() ) );
- }
- }
- }
-
-
- kdDebug(36001) << "PRINTING " << page_list.count() << " pages" << endl;
- m_uprintPages = page_list.count();
-
-
- //Cache all object so they only need to be repainted once.
- TQPtrListIterator<EmbeddedObject> itObject( m_pDoc->embeddedObjects() );
- for ( ; itObject.current(); ++itObject )
- {
- EmbeddedObject *obj = itObject.current();
- if ( obj->sheet() != m_pSheet ||
- !( (( obj->getType() == OBJECT_KOFFICE_PART || obj->getType() == OBJECT_PICTURE ) && m_bPrintObjects) ||
- ( obj->getType() == OBJECT_CHART && m_bPrintCharts ) ) )
- continue;
-
- TQRect zoomRect = m_pDoc->zoomRect( itObject.current()->geometry() );
- TQPixmap *p = new TQPixmap( zoomRect.size() );
- TQPainter painter(p);
- painter.fillRect( p->rect(), TQColor("white") );
- painter.translate( -zoomRect.x(), -zoomRect.y() ); //we cant to paint at (0,0)
- bool const isSelected = itObject.current()->isSelected();
- itObject.current()->setSelected( false );
- itObject.current()->draw( &painter );
- painter.end();
- itObject.current()->setSelected( isSelected );
-
- PrintObject *po = new PrintObject();
- m_printObjects.append( po );
- po->obj = itObject.current();
- po->p = p;
- }
-
- if ( page_list.count() == 0 )
- {
- // nothing to print
- painter.setPen( TQPen( TQt::black, 1 ) );
- painter.drawPoint( 1, 1 );
- }
- else
- {
-
- int pageNo = 1;
-
- //
- // Print all pages in the list
- //
- TQValueList<TQRect>::Iterator it = page_list.begin();
- TQValueList<KoRect>::Iterator fit = page_frame_list.begin();
- TQValueList<KoPoint>::Iterator fito = page_frame_list_offset.begin();
-
- for( ; it != page_list.end(); ++it, ++fit, ++fito, ++pageNo )
- {
- painter.setClipRect( 0, 0, m_pDoc->zoomItX( paperWidthPts() ),
- m_pDoc->zoomItY( paperHeightPts() ) );
- printHeaderFooter( painter, pageNo );
-
- painter.translate( m_pDoc->zoomItX( leftBorderPts() ),
- m_pDoc->zoomItY( topBorderPts() ) );
-
- // Print the page
- printPage( painter, *it, *fit, *fito );
-
- painter.translate( - m_pDoc->zoomItX( leftBorderPts() ),
- - m_pDoc->zoomItY( topBorderPts() ) );
-
- if ( pageNo < (int)page_list.count() )
- _printer->newPage();
- }
- }
-
- if ( !m_bPrintGrid )
- {
- // Restore the grid pen
- m_pDoc->setGridColor( gridPen.color() );
- }
- m_pSheet->setShowGrid( oldShowGrid );
-
- TQValueList<PrintObject *>::iterator it;
- for ( it = m_printObjects.begin(); it != m_printObjects.end(); ++it )
- delete (*it)->p;
- m_printObjects.clear();
-
- return ( page_list.count() > 0 );
-}
-
-void SheetPrint::printPage( TQPainter &_painter, const TQRect& page_range,
- const KoRect& view, const KoPoint _childOffset )
-{
- kdDebug(36001) << "Rect x=" << page_range.left() << " y=" << page_range.top() << ", r="
- << page_range.right() << " b=" << page_range.bottom() << " offsetx: "<< _childOffset.x()
- << " offsety: " << _childOffset.y() <<" view-x: "<<view.x()<< endl;
-
- //Don't paint on the page borders
- TQRegion clipRegion( m_pDoc->zoomItX( leftBorderPts() ),
- m_pDoc->zoomItY( topBorderPts() ),
- m_pDoc->zoomItX( view.width() + _childOffset.x() ),
- m_pDoc->zoomItY( view.height() + _childOffset.y() ) );
- _painter.setClipRegion( clipRegion );
-
- //
- // Draw the cells.
- //
- //Check if we have to repeat some rows and columns (top left rect)
- if ( ( _childOffset.x() != 0.0 ) && ( _childOffset.y() != 0.0 ) )
- {
- //TQRect(left,top,width,height) <<<< WIDTH AND HEIGHT!!!
- TQRect _printRect( m_printRepeatColumns.first, m_printRepeatRows.first,
- m_printRepeatColumns.second - m_printRepeatColumns.first + 1,
- m_printRepeatRows.second - m_printRepeatRows.first + 1);
- KoPoint _topLeft( 0.0, 0.0 );
-
- printRect( _painter, _topLeft, _printRect, view, clipRegion );
- }
-
- //Check if we have to repeat some rows (left rect)
- if ( _childOffset.y() != 0 )
- {
- TQRect _printRect( page_range.left(), m_printRepeatRows.first,
- page_range.right() - page_range.left() + 1,
- m_printRepeatRows.second - m_printRepeatRows.first + 1);
- KoPoint _topLeft( _childOffset.x(), 0.0 );
-
- printRect( _painter, _topLeft, _printRect, view, clipRegion );
- }
-
- //Check if we have to repeat some columns (top right rect)
- if ( _childOffset.x() != 0 )
- {
- TQRect _printRect( m_printRepeatColumns.first, page_range.top(),
- m_printRepeatColumns.second - m_printRepeatColumns.first + 1,
- page_range.bottom() - page_range.top() + 1);
- KoPoint _topLeft( 0.0, _childOffset.y() );
-
- printRect( _painter, _topLeft, _printRect, view, clipRegion );
- }
-
-
- //Print the cells (right data rect)
- KoPoint _topLeft( _childOffset.x(), _childOffset.y() );
-
- printRect( _painter, _topLeft, page_range, view, clipRegion );
-}
-
-
-void SheetPrint::printRect( TQPainter& painter, const KoPoint& topLeft,
- const TQRect& printRect, const KoRect& view,
- TQRegion &clipRegion )
-{
- //
- // Draw the cells.
- //
- Cell *cell;
- RowFormat *row_lay;
- ColumnFormat *col_lay;
-
- double xpos = 0;
- double ypos = topLeft.y();
-
- int regionBottom = printRect.bottom();
- int regionRight = printRect.right();
- int regionLeft = printRect.left();
- int regionTop = printRect.top();
-
- //Calculate the output rect
- KoPoint bottomRight( topLeft );
- for ( int x = regionLeft; x <= regionRight; ++x )
- bottomRight.setX( bottomRight.x()
- + m_pSheet->columnFormat( x )->dblWidth() );
- for ( int y = regionTop; y <= regionBottom; ++y )
- bottomRight.setY( bottomRight.y()
- + m_pSheet->rowFormat( y )->dblHeight() );
- KoRect rect( topLeft, bottomRight );
-
- TQValueList<TQPoint> mergedCellsPainted;
- for ( int y = regionTop; y <= regionBottom; ++y )
- {
- row_lay = m_pSheet->rowFormat( y );
- xpos = topLeft.x();
-
- for ( int x = regionLeft; x <= regionRight; ++x )
- {
- col_lay = m_pSheet->columnFormat( x );
-
- cell = m_pSheet->cellAt( x, y );
-
- bool paintBordersBottom = false;
- bool paintBordersRight = false;
- bool paintBordersLeft = false;
- bool paintBordersTop = false;
-
- TQPen rightPen = cell->effRightBorderPen( x, y );
- TQPen leftPen = cell->effLeftBorderPen( x, y );
- TQPen bottomPen = cell->effBottomBorderPen( x, y );
- TQPen topPen = cell->effTopBorderPen( x, y );
-
- // paint right border if rightmost cell or if the pen is more "worth" than the left border pen
- // of the cell on the left or if the cell on the right is not painted. In the latter case get
- // the pen that is of more "worth"
- if ( x >= KS_colMax )
- paintBordersRight = true;
- else
- if ( x == regionRight )
- {
- paintBordersRight = true;
- if ( cell->effRightBorderValue( x, y ) < m_pSheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
- rightPen = m_pSheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
- }
- else
- {
- paintBordersRight = true;
- if ( cell->effRightBorderValue( x, y ) < m_pSheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
- rightPen = m_pSheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
- }
-
- // similiar for other borders...
- // bottom border:
- if ( y >= KS_rowMax )
- paintBordersBottom = true;
- else
- if ( y == regionBottom )
- {
- paintBordersBottom = true;
- if ( cell->effBottomBorderValue( x, y ) < m_pSheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
- bottomPen = m_pSheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
- }
- else
- {
- paintBordersBottom = true;
- if ( cell->effBottomBorderValue( x, y ) < m_pSheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
- bottomPen = m_pSheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
- }
-
- // left border:
- if ( x == 1 )
- paintBordersLeft = true;
- else
- if ( x == regionLeft )
- {
- paintBordersLeft = true;
- if ( cell->effLeftBorderValue( x, y ) < m_pSheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
- leftPen = m_pSheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
- }
- else
- {
- paintBordersLeft = true;
- if ( cell->effLeftBorderValue( x, y ) < m_pSheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
- leftPen = m_pSheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
- }
-
- // top border:
- if ( y == 1 )
- paintBordersTop = true;
- else
- if ( y == regionTop )
- {
- paintBordersTop = true;
- if ( cell->effTopBorderValue( x, y ) < m_pSheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
- topPen = m_pSheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
- }
- else
- {
- paintBordersTop = true;
- if ( cell->effTopBorderValue( x, y ) < m_pSheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
- topPen = m_pSheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
- }
-
- int paintBorder=Cell::Border_None;
- if (paintBordersLeft) paintBorder |= Cell::Border_Left;
- if (paintBordersRight) paintBorder |= Cell::Border_Right;
- if (paintBordersTop) paintBorder |= Cell::Border_Top;
- if (paintBordersBottom) paintBorder |= Cell::Border_Bottom;
-
- TQPen highlightPen;
-
- if ( m_pSheet->layoutDirection()==Sheet::RightToLeft )
- cell->paintCell( rect, painter, NULL,
- KoPoint( view.width() - xpos -
- col_lay->dblWidth(), ypos ), TQPoint( x, y ),
- paintBorder,
- rightPen, bottomPen, leftPen, topPen,
- mergedCellsPainted);
- else
- cell->paintCell( rect, painter, NULL,
- KoPoint( xpos, ypos ), TQPoint( x, y ),
- paintBorder,
- rightPen, bottomPen, leftPen, topPen,
- mergedCellsPainted);
-
- xpos += col_lay->dblWidth();
- }
-
- ypos += row_lay->dblHeight();
- }
-
- //
- // Draw the children
- //
- TQRect zoomedView = m_pDoc->zoomRect( view );
- //TQPtrListIterator<KoDocumentChild> it( m_pDoc->children() );
- //TQPtrListIterator<EmbeddedObject> itObject( m_pDoc->embeddedObjects() );
-
- TQValueList<PrintObject *>::iterator itObject;
- for ( itObject = m_printObjects.begin(); itObject != m_printObjects.end(); ++itObject ) {
- EmbeddedObject *obj = (*itObject)->obj;
-// TQString tmp=TQString("Testing child %1/%2 %3/%4 against view %5/%6 %7/%8")
-// .arg(it.current()->contentRect().left())
-// .arg(it.current()->contentRect().top())
-// .arg(it.current()->contentRect().right())
-// .arg(it.current()->contentRect().bottom())
-// .arg(view.left()).arg(view.top()).arg(zoomedView.right()).arg(zoomedView.bottom());
-// kdDebug(36001)<<tmp<<" offset "<<_childOffset.x()<<"/"<<_childOffset.y()<<endl;
-
- KoRect const bound = obj->geometry();
- TQRect zoomedBound = m_pDoc->zoomRect( KoRect(bound.left(), bound.top(),
- bound.width(),
- bound.height() ) );
-#if 1
-// kdDebug(36001) << "printRect(): Bounding rect of view: " << view
-// << endl;
-// kdDebug(36001) << "printRect(): Bounding rect of zoomed view: "
-// << zoomedView << endl;
-// kdDebug(36001) << "printRect(): Bounding rect of child: " << bound
-// << endl;
-// kdDebug(36001) << "printRect(): Bounding rect of zoomed child: "
-// << zoomedBound << endl;
-#endif
- if ( obj->sheet() == m_pSheet && zoomedBound.intersects( zoomedView ) )
- {
- painter.save();
-
- painter.translate( -zoomedView.left() + m_pDoc->zoomItX( topLeft.x() ),
- -zoomedView.top() + m_pDoc->zoomItY( topLeft.y() ) );
-
- //obj->draw( &painter );
- painter.drawPixmap( m_pDoc->zoomRect( obj->geometry() ).topLeft(), *(*itObject)->p ); //draw the cached object
-
- //painter.fillRect(zoomedBound, TQBrush("red")); //for debug purpose
- painter.restore();
- }
- }
-
- //Don't let obscuring cells and children overpaint this area
- clipRegion -= TQRegion ( m_pDoc->zoomItX( leftBorderPts() + topLeft.x() ),
- m_pDoc->zoomItY( topBorderPts() + topLeft.y() ),
- m_pDoc->zoomItX( xpos ),
- m_pDoc->zoomItY( ypos ) );
- painter.setClipRegion( clipRegion );
-}
-
-
-void SheetPrint::printHeaderFooter( TQPainter &painter, int pageNo )
-{
- double w;
- double headFootDistance = MM_TO_POINT( 10.0 /*mm*/ ) / m_dZoom;
- TQFont font( "Times" );
- font.setPointSizeFloat( 0.01 * m_pDoc->zoom() *
- /* Font size of 10 */ 10.0 / m_dZoom );
- painter.setFont( font );
- TQFontMetrics fm = painter.fontMetrics();
-
- // print head line left
- w = fm.width( headLeft( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( m_pDoc->zoomItX( leftBorderPts() ),
- m_pDoc->zoomItY( headFootDistance ),
- headLeft( pageNo, m_pSheet->sheetName() ) );
- // print head line middle
- w = fm.width( headMid( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( (int) ( m_pDoc->zoomItX( leftBorderPts() ) +
- ( m_pDoc->zoomItX( prinsheetWidthPts() ) -
- w ) / 2.0 ),
- m_pDoc->zoomItY( headFootDistance ),
- headMid( pageNo, m_pSheet->sheetName() ) );
- // print head line right
- w = fm.width( headRight( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( m_pDoc->zoomItX( leftBorderPts() +
- prinsheetWidthPts() ) - (int) w,
- m_pDoc->zoomItY( headFootDistance ),
- headRight( pageNo, m_pSheet->sheetName() ) );
-
- // print foot line left
- w = fm.width( footLeft( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( m_pDoc->zoomItX( leftBorderPts() ),
- m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
- footLeft( pageNo, m_pSheet->sheetName() ) );
- // print foot line middle
- w = fm.width( footMid( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( (int) ( m_pDoc->zoomItX( leftBorderPts() ) +
- ( m_pDoc->zoomItX( prinsheetWidthPts() ) -
- w ) / 2.0 ),
- m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
- footMid( pageNo, m_pSheet->sheetName() ) );
- // print foot line right
- w = fm.width( footRight( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
- if ( w > 0 )
- painter.drawText( m_pDoc->zoomItX( leftBorderPts() +
- prinsheetWidthPts() ) -
- (int) w,
- m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
- footRight( pageNo, m_pSheet->sheetName() ) );
-}
-
-
-bool SheetPrint::isOnNewPageX( int _column )
-{
- if( _column > m_maxCheckedNewPageX )
- updateNewPageX( _column );
-
- //Are these the edges of the print range?
- if ( _column == m_printRange.left() || _column == m_printRange.right() + 1 )
- {
- return true;
- }
-
- //beyond the print range it's always false
- if ( _column < m_printRange.left() || _column > m_printRange.right() )
- {
- return false;
- }
-
- //Now check if we find the column already in the list
- if ( m_lnewPageListX.findIndex( _column ) != -1 )
- {
- if( _column > m_maxCheckedNewPageX )
- m_maxCheckedNewPageX = _column;
- return true;
- }
- return false;
-}
-
-
-void SheetPrint::updateNewPageX( int _column )
-{
- float offset = 0.0;
-
- //Are these the edges of the print range?
- if ( _column == m_printRange.left() || _column == m_printRange.right() + 1 )
- {
- if( _column > m_maxCheckedNewPageX )
- m_maxCheckedNewPageX = _column;
- return;
- }
-
- //We don't check beyond the print range
- if ( _column < m_printRange.left() || _column > m_printRange.right() )
- {
- if( _column > m_maxCheckedNewPageX )
- m_maxCheckedNewPageX = _column;
- if ( _column > m_printRange.right() )
- {
- if ( m_lnewPageListX.last().endItem()==0 )
- m_lnewPageListX.last().setEndItem( m_printRange.right() );
- }
- return;
- }
-
- //If we start, then add the left printrange
- if ( m_lnewPageListX.empty() )
- m_lnewPageListX.append( m_printRange.left() ); //Add the first entry
-
- //If _column is greater than the last entry, we need to calculate the result
- if ( _column > m_lnewPageListX.last().startItem() &&
- _column > m_maxCheckedNewPageX ) //this columns hasn't been calculated before
- {
- int startCol = m_lnewPageListX.last().startItem();
- int col = startCol;
- double x = m_pSheet->columnFormat( col )->dblWidth();
-
- //Add repeated column width, when necessary
- if ( col > m_printRepeatColumns.first )
- {
- x += m_dPrintRepeatColumnsWidth;
- offset = m_dPrintRepeatColumnsWidth;
- }
-
- while ( ( col <= _column ) && ( col < m_printRange.right() ) )
- {
- if ( x > prinsheetWidthPts() ) //end of page?
- {
- //We found a new page, so add it to the list
- m_lnewPageListX.append( col );
-
- //Now store into the previous entry the enditem and the width
- TQValueList<PrintNewPageEntry>::iterator it;
- it = findNewPageColumn( startCol );
- (*it).setEndItem( col - 1 );
- (*it).setSize( x - m_pSheet->columnFormat( col )->dblWidth() );
- (*it).setOffset( offset );
-
- //start a new page
- startCol = col;
- if ( col == _column )
- {
- if( _column > m_maxCheckedNewPageX )
- m_maxCheckedNewPageX = _column;
- return;
- }
- else
- {
- x = m_pSheet->columnFormat( col )->dblWidth();
- if ( col >= m_printRepeatColumns.first )
- {
- x += m_dPrintRepeatColumnsWidth;
- offset = m_dPrintRepeatColumnsWidth;
- }
- }
- }
-
- col++;
- x += m_pSheet->columnFormat( col )->dblWidth();
- }
- }
-
- if( _column > m_maxCheckedNewPageX )
- m_maxCheckedNewPageX = _column;
-}
-
-
-bool SheetPrint::isOnNewPageY( int _row )
-{
- if( _row > m_maxCheckedNewPageY )
- updateNewPageY( _row );
-
- //Are these the edges of the print range?
- if ( _row == m_printRange.top() || _row == m_printRange.bottom() + 1 )
- {
- return true;
- }
-
- //beyond the print range it's always false
- if ( _row < m_printRange.top() || _row > m_printRange.bottom() )
- {
- return false;
- }
-
- //Now check if we find the row already in the list
- if ( m_lnewPageListY.findIndex( _row ) != -1 )
- {
- if( _row > m_maxCheckedNewPageY )
- m_maxCheckedNewPageY = _row;
- return true;
- }
-
- return false;
-}
-
-
-void SheetPrint::updateNewPageY( int _row )
-{
- float offset = 0.0;
-
- //Are these the edges of the print range?
- if ( _row == m_printRange.top() || _row == m_printRange.bottom() + 1 )
- {
- if( _row > m_maxCheckedNewPageY )
- m_maxCheckedNewPageY = _row;
- return;
- }
-
- //beyond the print range it's always false
- if ( _row < m_printRange.top() || _row > m_printRange.bottom() )
- {
- if( _row > m_maxCheckedNewPageY )
- m_maxCheckedNewPageY = _row;
- if ( _row > m_printRange.bottom() )
- {
- if ( m_lnewPageListY.last().endItem()==0 )
- m_lnewPageListY.last().setEndItem( m_printRange.bottom() );
- }
- return;
- }
-
- //If we start, then add the top printrange
- if ( m_lnewPageListY.empty() )
- m_lnewPageListY.append( m_printRange.top() ); //Add the first entry
-
- //If _column is greater than the last entry, we need to calculate the result
- if ( _row > m_lnewPageListY.last().startItem() &&
- _row > m_maxCheckedNewPageY ) //this columns hasn't been calculated before
- {
- int startRow = m_lnewPageListY.last().startItem();
- int row = startRow;
- double y = m_pSheet->rowFormat( row )->dblHeight();
-
- //Add repeated row height, when necessary
- if ( row > m_printRepeatRows.first )
- {
- y += m_dPrintRepeatRowsHeight;
- offset = m_dPrintRepeatRowsHeight;
- }
-
- while ( ( row <= _row ) && ( row < m_printRange.bottom() ) )
- {
- if ( y > prinsheetHeightPts() )
- {
- //We found a new page, so add it to the list
- m_lnewPageListY.append( row );
-
- //Now store into the previous entry the enditem and the width
- TQValueList<PrintNewPageEntry>::iterator it;
- it = findNewPageRow( startRow );
- (*it).setEndItem( row - 1 );
- (*it).setSize( y - m_pSheet->rowFormat( row )->dblHeight() );
- (*it).setOffset( offset );
-
- //start a new page
- startRow = row;
- if ( row == _row )
- {
- if( _row > m_maxCheckedNewPageY )
- m_maxCheckedNewPageY = _row;
- return;
- }
- else
- {
- y = m_pSheet->rowFormat( row )->dblHeight();
- if ( row >= m_printRepeatRows.first )
- {
- y += m_dPrintRepeatRowsHeight;
- offset = m_dPrintRepeatRowsHeight;
- }
- }
- }
-
- row++;
- y += m_pSheet->rowFormat( row )->dblHeight();
- }
- }
-
- if( _row > m_maxCheckedNewPageY )
- m_maxCheckedNewPageY = _row;
-}
-
-
-void SheetPrint::updateNewPageListX( int _col )
-{
- //If the new range is after the first entry, we need to delete the whole list
- if ( m_lnewPageListX.first().startItem() != m_printRange.left() ||
- _col == 0 )
- {
- m_lnewPageListX.clear();
- m_maxCheckedNewPageX = m_printRange.left();
- m_lnewPageListX.append( m_printRange.left() );
- return;
- }
-
- if ( _col < m_lnewPageListX.last().startItem() )
- {
- //Find the page entry for this column
- TQValueList<PrintNewPageEntry>::iterator it;
- it = m_lnewPageListX.find( _col );
- while ( ( it == m_lnewPageListX.end() ) && _col > 0 )
- {
- _col--;
- it = m_lnewPageListX.find( _col );
- }
-
- //Remove later pages
- while ( it != m_lnewPageListX.end() )
- it = m_lnewPageListX.remove( it );
-
- //Add default page when list is now empty
- if ( m_lnewPageListX.empty() )
- m_lnewPageListX.append( m_printRange.left() );
- }
-
- m_maxCheckedNewPageX = _col;
-}
-
-void SheetPrint::updateNewPageListY( int _row )
-{
- //If the new range is after the first entry, we need to delete the whole list
- if ( m_lnewPageListY.first().startItem() != m_printRange.top() ||
- _row == 0 )
- {
- m_lnewPageListY.clear();
- m_maxCheckedNewPageY = m_printRange.top();
- m_lnewPageListY.append( m_printRange.top() );
- return;
- }
-
- if ( _row < m_lnewPageListY.last().startItem() )
- {
- //Find the page entry for this row
- TQValueList<PrintNewPageEntry>::iterator it;
- it = m_lnewPageListY.find( _row );
- while ( ( it == m_lnewPageListY.end() ) && _row > 0 )
- {
- _row--;
- it = m_lnewPageListY.find( _row );
- }
-
- //Remove later pages
- while ( it != m_lnewPageListY.end() )
- it = m_lnewPageListY.remove( it );
-
- //Add default page when list is now empty
- if ( m_lnewPageListY.empty() )
- m_lnewPageListY.append( m_printRange.top() );
- }
-
- m_maxCheckedNewPageY = _row;
-}
-
-void SheetPrint::definePrintRange( Selection* selectionInfo )
-{
- if ( !selectionInfo->isSingular() )
- {
- KCommand* command = new DefinePrintRangeCommand( m_pSheet );
- m_pDoc->addCommand( command );
- setPrintRange( selectionInfo->selection() );
- }
-}
-
-void SheetPrint::resetPrintRange ()
-{
- KCommand* command = new DefinePrintRangeCommand( m_pSheet );
- m_pDoc->addCommand( command );
- setPrintRange( TQRect( TQPoint( 1, 1 ), TQPoint( KS_colMax, KS_rowMax ) ) );
-}
-
-void SheetPrint::replaceHeadFootLineMacro ( TQString &_text, const TQString &_search, const TQString &_replace )
-{
- if ( _search != _replace )
- _text.replace ( TQString( "<" + _search + ">" ), "<" + _replace + ">" );
-}
-
-TQString SheetPrint::localizeHeadFootLine ( const TQString &_text )
-{
- TQString tmp = _text;
-
- /*
- i18n:
- Please use the same words (even upper/lower case) as in
- KoPageLayoutDia.cc function setupTab2(), without the brakets "<" and ">"
- */
- replaceHeadFootLineMacro ( tmp, "page", i18n("page") );
- replaceHeadFootLineMacro ( tmp, "pages", i18n("pages") );
- replaceHeadFootLineMacro ( tmp, "file", i18n("file") );
- replaceHeadFootLineMacro ( tmp, "name", i18n("name") );
- replaceHeadFootLineMacro ( tmp, "time", i18n("time") );
- replaceHeadFootLineMacro ( tmp, "date", i18n("date") );
- replaceHeadFootLineMacro ( tmp, "author", i18n("author") );
- replaceHeadFootLineMacro ( tmp, "email", i18n("email") );
- replaceHeadFootLineMacro ( tmp, "org", i18n("org") );
- replaceHeadFootLineMacro ( tmp, "sheet", i18n("sheet") );
-
- return tmp;
-}
-
-
-TQString SheetPrint::delocalizeHeadFootLine ( const TQString &_text )
-{
- TQString tmp = _text;
-
- /*
- i18n:
- Please use the same words (even upper/lower case) as in
- KoPageLayoutDia.cc function setupTab2(), without the brakets "<" and ">"
- */
- replaceHeadFootLineMacro ( tmp, i18n("page"), "page" );
- replaceHeadFootLineMacro ( tmp, i18n("pages"), "pages" );
- replaceHeadFootLineMacro ( tmp, i18n("file"), "file" );
- replaceHeadFootLineMacro ( tmp, i18n("name"), "name" );
- replaceHeadFootLineMacro ( tmp, i18n("time"), "time" );
- replaceHeadFootLineMacro ( tmp, i18n("date"), "date" );
- replaceHeadFootLineMacro ( tmp, i18n("author"), "author" );
- replaceHeadFootLineMacro ( tmp, i18n("email"), "email" );
- replaceHeadFootLineMacro ( tmp, i18n("org"), "org" );
- replaceHeadFootLineMacro ( tmp, i18n("sheet"), "sheet" );
-
- return tmp;
-}
-
-
-KoHeadFoot SheetPrint::headFootLine() const
-{
- KoHeadFoot hf;
- hf.headLeft = m_headLeft;
- hf.headRight = m_headRight;
- hf.headMid = m_headMid;
- hf.footLeft = m_footLeft;
- hf.footRight = m_footRight;
- hf.footMid = m_footMid;
-
- return hf;
-}
-
-
-void SheetPrint::setHeadFootLine( const TQString &_headl, const TQString &_headm, const TQString &_headr,
- const TQString &_footl, const TQString &_footm, const TQString &_footr )
-{
- if ( m_pSheet->isProtected() )
- NO_MODIFICATION_POSSIBLE;
-
- m_headLeft = _headl;
- m_headRight = _headr;
- m_headMid = _headm;
- m_footLeft = _footl;
- m_footRight = _footr;
- m_footMid = _footm;
-
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPaperOrientation( KoOrientation _orient )
-{
- if ( m_pSheet->isProtected() )
- NO_MODIFICATION_POSSIBLE;
-
- m_orientation = _orient;
- calcPaperSize();
- updatePrintRepeatColumnsWidth();
- updatePrintRepeatRowsHeight();
- updateNewPageListX( m_printRange.left() ); //Reset the list
- updateNewPageListY( m_printRange.top() ); //Reset the list
-
- if( m_pSheet->isShowPageBorders() )
- emit sig_updateView( m_pSheet );
-}
-
-
-KoPageLayout SheetPrint::paperLayout() const
-{
- KoPageLayout pl;
- pl.format = m_paperFormat;
- pl.orientation = m_orientation;
- pl.ptWidth = m_paperWidth;
- pl.ptHeight = m_paperHeight;
- pl.ptLeft = m_leftBorder;
- pl.ptRight = m_rightBorder;
- pl.ptTop = m_topBorder;
- pl.ptBottom = m_bottomBorder;
- return pl;
-}
-
-
-void SheetPrint::setPaperLayout( float _leftBorder, float _topBorder,
- float _rightBorder, float _bottomBorder,
- KoFormat _paper,
- KoOrientation _orientation )
-{
- if ( m_pSheet->isProtected() )
- NO_MODIFICATION_POSSIBLE;
-
- m_leftBorder = _leftBorder;
- m_rightBorder = _rightBorder;
- m_topBorder = _topBorder;
- m_bottomBorder = _bottomBorder;
- m_paperFormat = _paper;
-
- setPaperOrientation( _orientation ); //calcPaperSize() is done here already
-
-// TQPtrListIterator<KoView> it( views() );
-// for( ;it.current(); ++it )
-// {
-// View *v = static_cast<View *>( it.current() );
- // We need to trigger the appropriate repaintings in the cells near the
- // border of the page. The easiest way for this is to turn the borders
- // off and on (or on and off if they were off).
-// bool bBorderWasShown = v->activeSheet()->isShowPageBorders();
-// v->activeSheet()->setShowPageBorders( !bBorderWasShown );
-// v->activeSheet()->setShowPageBorders( bBorderWasShown );
-// }
-
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPaperLayout( float _leftBorder, float _topBorder,
- float _rightBorder, float _bottomBorder,
- const TQString& _paper,
- const TQString& _orientation )
-{
- if ( m_pSheet->isProtected() )
- NO_MODIFICATION_POSSIBLE;
-
- KoFormat f = paperFormat();
- KoOrientation newOrientation = orientation();
-
- if ( _orientation == "Portrait" )
- newOrientation = PG_PORTRAIT;
- else if ( _orientation == "Landscape" )
- newOrientation = PG_LANDSCAPE;
-
-
- TQString paper( _paper );
- if ( paper[0].isDigit() ) // Custom format
- {
- const int i = paper.find( 'x' );
- if ( i < 0 )
- {
- // We have nothing useful, so assume ISO A4
- f = PG_DIN_A4;
- }
- else
- {
- f = PG_CUSTOM;
- m_paperWidth = paper.left(i).toFloat();
- m_paperHeight = paper.mid(i+1).toFloat();
- if ( m_paperWidth < 10.0 )
- m_paperWidth = KoPageFormat::width( PG_DIN_A4, newOrientation );
- if ( m_paperHeight < 10.0 )
- m_paperHeight = KoPageFormat::height( PG_DIN_A4, newOrientation );
- }
- }
- else
- {
- f = KoPageFormat::formatFromString( paper );
- if ( f == PG_CUSTOM )
- // We have no idea about height or width, therefore assume ISO A4
- f = PG_DIN_A4;
- }
- setPaperLayout( _leftBorder, _topBorder, _rightBorder, _bottomBorder, f, newOrientation );
-}
-
-void SheetPrint::calcPaperSize()
-{
- if ( m_paperFormat != PG_CUSTOM )
- {
- m_paperWidth = KoPageFormat::width( m_paperFormat, m_orientation );
- m_paperHeight = KoPageFormat::height( m_paperFormat, m_orientation );
- }
-}
-
-TQValueList<PrintNewPageEntry>::iterator SheetPrint::findNewPageColumn( int col )
-{
- TQValueList<PrintNewPageEntry>::iterator it;
- for( it = m_lnewPageListX.begin(); it != m_lnewPageListX.end(); ++it )
- {
- if( (*it).startItem() == col )
- return it;
- }
- return it;
-// TQValueList<PrintNewPageEntry>::iterator it;
-// it = m_lnewPageListX.find( startCol );
-}
-
-TQValueList<PrintNewPageEntry>::iterator SheetPrint::findNewPageRow( int row )
-{
- TQValueList<PrintNewPageEntry>::iterator it;
- for( it = m_lnewPageListY.begin(); it != m_lnewPageListY.end(); ++it )
- {
- if( (*it).startItem() == row )
- return it;
- }
- return it;
-}
-
-
-TQString SheetPrint::paperFormatString()const
-{
- if ( m_paperFormat == PG_CUSTOM )
- {
- TQString tmp;
- tmp.sprintf( "%fx%f", m_paperWidth, m_paperHeight );
- return tmp;
- }
-
- return KoPageFormat::formatString( m_paperFormat );
-}
-
-const char* SheetPrint::orientationString() const
-{
- switch( m_orientation )
- {
- case KPrinter::Portrait:
- return "Portrait";
- case KPrinter::Landscape:
- return "Landscape";
- }
-
- kdWarning(36001)<<"SheetPrint: Unknown orientation, using now portrait"<<endl;
- return 0;
-}
-
-TQString SheetPrint::completeHeading( const TQString &_data, int _page, const TQString &_sheet ) const
-{
- TQString page( TQString::number( _page) );
- TQString pages( TQString::number( m_uprintPages ) );
-
- TQString pathFileName(m_pDoc->url().path());
- if ( pathFileName.isNull() )
- pathFileName="";
-
- TQString fileName(m_pDoc->url().fileName());
- if( fileName.isNull())
- fileName="";
-
- TQString t(TQTime::currentTime().toString());
- TQString d(TQDate::currentDate().toString());
- TQString ta;
- if ( !_sheet.isEmpty() )
- ta = _sheet;
-
- KoDocumentInfo * info = m_pDoc->documentInfo();
- KoDocumentInfoAuthor * authorPage = static_cast<KoDocumentInfoAuthor *>(info->page( "author" ));
- TQString full_name;
- TQString email_addr;
- TQString organization;
- TQString tmp;
- if ( !authorPage )
- kdWarning() << "Author information not found in Document Info !" << endl;
- else
- {
- full_name = authorPage->fullName();
- email_addr = authorPage->email();
- organization = authorPage->company();
- }
-
- char hostname[80];
- struct passwd *p;
-
- p = getpwuid(getuid());
- gethostname(hostname, sizeof(hostname));
-
- if(full_name.isEmpty())
- full_name=p->pw_gecos;
-
- if( email_addr.isEmpty())
- email_addr = TQString("%1@%2").arg(p->pw_name).arg(hostname);
-
- tmp = _data;
- int pos = 0;
- while ( ( pos = tmp.find( "<page>", pos ) ) != -1 )
- tmp.replace( pos, 6, page );
- pos = 0;
- while ( ( pos = tmp.find( "<pages>", pos ) ) != -1 )
- tmp.replace( pos, 7, pages );
- pos = 0;
- while ( ( pos = tmp.find( "<file>", pos ) ) != -1 )
- tmp.replace( pos, 6, pathFileName );
- pos = 0;
- while ( ( pos = tmp.find( "<name>", pos ) ) != -1 )
- tmp.replace( pos, 6, fileName );
- pos = 0;
- while ( ( pos = tmp.find( "<time>", pos ) ) != -1 )
- tmp.replace( pos, 6, t );
- pos = 0;
- while ( ( pos = tmp.find( "<date>", pos ) ) != -1 )
- tmp.replace( pos, 6, d );
- pos = 0;
- while ( ( pos = tmp.find( "<author>", pos ) ) != -1 )
- tmp.replace( pos, 8, full_name );
- pos = 0;
- while ( ( pos = tmp.find( "<email>", pos ) ) != -1 )
- tmp.replace( pos, 7, email_addr );
- pos = 0;
- while ( ( pos = tmp.find( "<org>", pos ) ) != -1 )
- tmp.replace( pos, 5, organization );
- pos = 0;
- while ( ( pos = tmp.find( "<sheet>", pos ) ) != -1 )
- tmp.replace( pos, 7, ta );
-
- return tmp;
-}
-
-void SheetPrint::setPrintRange( const TQRect &_printRange )
-{
- if ( m_pSheet->isProtected() )
- NO_MODIFICATION_POSSIBLE;
-
-
- if ( m_printRange == _printRange )
- return;
-
- int oldLeft = m_printRange.left();
- int oldTop = m_printRange.top();
- m_printRange = _printRange;
-
- //Refresh calculation of stored page breaks, the lower one of old and new
- if ( oldLeft != _printRange.left() )
- updateNewPageListX( TQMIN( oldLeft, _printRange.left() ) );
- if ( oldTop != _printRange.top() )
- updateNewPageListY( TQMIN( oldTop, _printRange.top() ) );
-
- m_pDoc->setModified( true );
-
- emit sig_updateView( m_pSheet );
-
-}
-
-void SheetPrint::setPageLimitX( int pages )
-{
- //We do want an update in any case because the sheet content
- //could have changed, thus we need to recalculate although
- //it's the same setting!
-// if( m_iPageLimitX == pages )
-// return;
-
- m_iPageLimitX = pages;
-
- if( pages == 0 )
- return;
-
- calculateZoomForPageLimitX();
-}
-
-void SheetPrint::setPageLimitY( int pages )
-{
- //We do want an update in any case because the sheet content
- //could have changed, thus we need to recalculate although
- //it's the same setting!
-// if( m_iPageLimitY == pages )
-// return;
-
- m_iPageLimitY = pages;
-
- if( pages == 0 )
- return;
-
- calculateZoomForPageLimitY();
-}
-
-void SheetPrint::calculateZoomForPageLimitX()
-{
- kdDebug() << "Calculating zoom for X limit" << endl;
- if( m_iPageLimitX == 0 )
- return;
-
- double origZoom = m_dZoom;
-
- if( m_dZoom < 1.0 )
- m_dZoom = 1.0;
-
- TQRect printRange = cellsPrintRange();
- updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
- int currentPages = pagesX( printRange );
-
- if (currentPages <= m_iPageLimitX)
- return;
-
- //calculating a factor for scaling the zoom down makes it lots faster
- double factor = (double)m_iPageLimitX/(double)currentPages +
- 1-(double)currentPages/((double)currentPages+1); //add possible error;
- kdDebug() << "Calculated factor for scaling m_dZoom: " << factor << endl;
- m_dZoom = m_dZoom*factor;
-
- kdDebug() << "New exact zoom: " << m_dZoom << endl;
-
- if (m_dZoom < 0.01)
- m_dZoom = 0.01;
- if (m_dZoom > 1.0)
- m_dZoom = 1.0;
-
- m_dZoom = (((int)(m_dZoom*100 + 0.5))/100.0);
-
- kdDebug() << "New rounded zoom: " << m_dZoom << endl;
-
- updatePrintRepeatColumnsWidth();
- updateNewPageListX( 0 );
- updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
- currentPages = pagesX( printRange );
-
- kdDebug() << "Number of pages with this zoom: " << currentPages << endl;
-
- while( ( currentPages > m_iPageLimitX ) && ( m_dZoom > 0.01 ) )
- {
- m_dZoom -= 0.01;
- updatePrintRepeatColumnsWidth();
- updateNewPageListX( 0 );
- updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
- currentPages = pagesX( printRange );
- kdDebug() << "Looping -0.01; current zoom: " << m_dZoom << endl;
- }
-
- if ( m_dZoom < origZoom )
- {
- double newZoom = m_dZoom;
- m_dZoom += 1.0; //set it to something different
- setZoom( newZoom, false );
- }
- else
- m_dZoom = origZoom;
-}
-
-void SheetPrint::calculateZoomForPageLimitY()
-{
- kdDebug() << "Calculating zoom for Y limit" << endl;
- if( m_iPageLimitY == 0 )
- return;
-
- double origZoom = m_dZoom;
-
- if( m_dZoom < 1.0 )
- m_dZoom = 1.0;
-
- TQRect printRange = cellsPrintRange();
- updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
- int currentPages = pagesY( printRange );
-
- if (currentPages <= m_iPageLimitY)
- return;
-
- double factor = (double)m_iPageLimitY/(double)currentPages +
- 1-(double)currentPages/((double)currentPages+1); //add possible error
- kdDebug() << "Calculated factor for scaling m_dZoom: " << factor << endl;
- m_dZoom = m_dZoom*factor;
-
- kdDebug() << "New exact zoom: " << m_dZoom << endl;
-
- if (m_dZoom < 0.01)
- m_dZoom = 0.01;
- if (m_dZoom > 1.0)
- m_dZoom = 1.0;
-
- m_dZoom = (((int)(m_dZoom*100 + 0.5))/100.0);
-
- kdDebug() << "New rounded zoom: " << m_dZoom << endl;
-
- updatePrintRepeatRowsHeight();
- updateNewPageListY( 0 );
- updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
- currentPages = pagesY( printRange );
-
- kdDebug() << "Number of pages with this zoom: " << currentPages << endl;
-
- while( ( currentPages > m_iPageLimitY ) && ( m_dZoom > 0.01 ) )
- {
- m_dZoom -= 0.01;
- updatePrintRepeatRowsHeight();
- updateNewPageListY( 0 );
- updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
- currentPages = pagesY( printRange );
- kdDebug() << "Looping -0.01; current zoom: " << m_dZoom << endl;
- }
-
- if ( m_dZoom < origZoom )
- {
- double newZoom = m_dZoom;
- m_dZoom += 1.0; //set it to something different
- setZoom( newZoom, false );
- }
- else
- m_dZoom = origZoom;
-}
-
-void SheetPrint::setPrintGrid( bool _printGrid )
-{
- if ( m_bPrintGrid == _printGrid )
- return;
-
- m_bPrintGrid = _printGrid;
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintObjects( bool _printObjects )
-{
- if ( m_bPrintObjects == _printObjects )
- return;
-
- m_bPrintObjects = _printObjects;
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintCharts( bool _printCharts )
-{
- if ( m_bPrintCharts == _printCharts )
- return;
-
- m_bPrintCharts = _printCharts;
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintGraphics( bool _printGraphics )
-{
- if ( m_bPrintGraphics == _printGraphics )
- return;
-
- m_bPrintGraphics = _printGraphics;
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintCommentIndicator( bool _printCommentIndicator )
-{
- if ( m_bPrintCommentIndicator == _printCommentIndicator )
- return;
-
- m_bPrintCommentIndicator = _printCommentIndicator;
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintFormulaIndicator( bool _printFormulaIndicator )
-{
- if( m_bPrintFormulaIndicator == _printFormulaIndicator )
- return;
-
- m_bPrintFormulaIndicator = _printFormulaIndicator;
- m_pDoc->setModified( true );
-}
-void SheetPrint::updatePrintRepeatColumnsWidth()
-{
- m_dPrintRepeatColumnsWidth = 0.0;
- if( m_printRepeatColumns.first != 0 )
- {
- for( int i = m_printRepeatColumns.first; i <= m_printRepeatColumns.second; i++ )
- {
- m_dPrintRepeatColumnsWidth += m_pSheet->columnFormat( i )->dblWidth();
- }
- }
-}
-
-void SheetPrint::updatePrintRepeatRowsHeight()
-{
- m_dPrintRepeatRowsHeight = 0.0;
- if ( m_printRepeatRows.first != 0 )
- {
- for ( int i = m_printRepeatRows.first; i <= m_printRepeatRows.second; i++)
- {
- m_dPrintRepeatRowsHeight += m_pSheet->rowFormat( i )->dblHeight();
- }
- }
-}
-
-
-void SheetPrint::setPrintRepeatColumns( TQPair<int, int> _printRepeatColumns )
-{
- //Bring arguments in order
- if ( _printRepeatColumns.first > _printRepeatColumns.second )
- {
- int tmp = _printRepeatColumns.first;
- _printRepeatColumns.first = _printRepeatColumns.second;
- _printRepeatColumns.second = tmp;
- }
-
- //If old are equal to the new setting, nothing is to be done at all
- if ( m_printRepeatColumns == _printRepeatColumns )
- return;
-
- int oldFirst = m_printRepeatColumns.first;
- m_printRepeatColumns = _printRepeatColumns;
-
- //Recalcualte the space needed for the repeated columns
- updatePrintRepeatColumnsWidth();
-
- //Refresh calculation of stored page breaks, the lower one of old and new
- updateNewPageListX( TQMIN( oldFirst, _printRepeatColumns.first ) );
-
- //Refresh view, if page borders are shown
- if ( m_pSheet->isShowPageBorders() )
- emit sig_updateView( m_pSheet );
-
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::setPrintRepeatRows( TQPair<int, int> _printRepeatRows )
-{
- //Bring arguments in order
- if ( _printRepeatRows.first > _printRepeatRows.second )
- {
- int tmp = _printRepeatRows.first;
- _printRepeatRows.first = _printRepeatRows.second;
- _printRepeatRows.second = tmp;
- }
-
- //If old are equal to the new setting, nothing is to be done at all
- if ( m_printRepeatRows == _printRepeatRows )
- return;
-
- int oldFirst = m_printRepeatRows.first;
- m_printRepeatRows = _printRepeatRows;
-
- //Recalcualte the space needed for the repeated rows
- updatePrintRepeatRowsHeight();
-
- //Refresh calculation of stored page breaks, the lower one of old and new
- updateNewPageListY( TQMIN( oldFirst, _printRepeatRows.first ) );
-
- //Refresh view, if page borders are shown
- if ( m_pSheet->isShowPageBorders() )
- emit sig_updateView( m_pSheet );
-
- m_pDoc->setModified( true );
-}
-
-void SheetPrint::insertColumn( int col, int nbCol )
-{
- //update print range, when it has been defined
- if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
- {
- int left = m_printRange.left();
- int right = m_printRange.right();
-
- for( int i = 0; i <= nbCol; i++ )
- {
- if ( left >= col ) left++;
- if ( right >= col ) right++;
- }
- //Validity checks
- if ( left > KS_colMax ) left = KS_colMax;
- if ( right > KS_colMax ) right = KS_colMax;
- setPrintRange( TQRect( TQPoint( left, m_printRange.top() ),
- TQPoint( right, m_printRange.bottom() ) ) );
- }
-}
-
-void SheetPrint::insertRow( int row, int nbRow )
-{
- //update print range, when it has been defined
- if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
- {
- int top = m_printRange.top();
- int bottom = m_printRange.bottom();
-
- for( int i = 0; i <= nbRow; i++ )
- {
- if ( top >= row ) top++;
- if ( bottom >= row ) bottom++;
- }
- //Validity checks
- if ( top > KS_rowMax ) top = KS_rowMax;
- if ( bottom > KS_rowMax ) bottom = KS_rowMax;
- setPrintRange( TQRect( TQPoint( m_printRange.left(), top ),
- TQPoint( m_printRange.right(), bottom ) ) );
- }
-}
-
-void SheetPrint::removeColumn( int col, int nbCol )
-{
- //update print range, when it has been defined
- if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
- {
- int left = m_printRange.left();
- int right = m_printRange.right();
-
- for( int i = 0; i <= nbCol; i++ )
- {
- if ( left > col ) left--;
- if ( right >= col ) right--;
- }
- //Validity checks
- if ( left < 1 ) left = 1;
- if ( right < 1 ) right = 1;
- setPrintRange( TQRect( TQPoint( left, m_printRange.top() ),
- TQPoint( right, m_printRange.bottom() ) ) );
- }
-
- //update repeat columns, when it has been defined
- if ( m_printRepeatColumns.first != 0 )
- {
- int left = m_printRepeatColumns.first;
- int right = m_printRepeatColumns.second;
-
- for( int i = 0; i <= nbCol; i++ )
- {
- if ( left > col ) left--;
- if ( right >= col ) right--;
- }
- //Validity checks
- if ( left < 1 ) left = 1;
- if ( right < 1 ) right = 1;
- setPrintRepeatColumns ( tqMakePair( left, right ) );
- }
-}
-
-void SheetPrint::removeRow( int row, int nbRow )
-{
- //update print range, when it has been defined
- if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
- {
- int top = m_printRange.top();
- int bottom = m_printRange.bottom();
-
- for( int i = 0; i <= nbRow; i++ )
- {
- if ( top > row ) top--;
- if ( bottom >= row ) bottom--;
- }
- //Validity checks
- if ( top < 1 ) top = 1;
- if ( bottom < 1 ) bottom = 1;
- setPrintRange( TQRect( TQPoint( m_printRange.left(), top ),
- TQPoint( m_printRange.right(), bottom ) ) );
- }
-
- //update repeat rows, when it has been defined
- if ( m_printRepeatRows.first != 0 )
- {
- int top = m_printRepeatRows.first;
- int bottom = m_printRepeatRows.second;
-
- for( int i = 0; i <= nbRow; i++ )
- {
- if ( top > row ) top--;
- if ( bottom >= row ) bottom--;
- }
- //Validity checks
- if ( top < 1 ) top = 1;
- if ( bottom < 1 ) bottom = 1;
- setPrintRepeatRows( tqMakePair( top, bottom ) );
- }
-}
-
-void SheetPrint::setZoom( double _zoom, bool checkPageLimit )
-{
- if( m_dZoom == _zoom )
- {
- return;
- }
-
- m_dZoom = _zoom;
- updatePrintRepeatColumnsWidth();
- updatePrintRepeatRowsHeight();
- updateNewPageListX( 0 );
- updateNewPageListY( 0 );
- if( m_pSheet->isShowPageBorders() )
- emit sig_updateView( m_pSheet );
-
- if( checkPageLimit )
- {
- calculateZoomForPageLimitX();
- calculateZoomForPageLimitY();
- }
-
- m_pDoc->setModified( true );
-}
-
-bool PrintNewPageEntry::operator==( PrintNewPageEntry const & entry ) const
-{
- return m_iStartItem == entry.m_iStartItem;
-}
-
diff --git a/kspread/kspread_sheetprint.cpp b/kspread/kspread_sheetprint.cpp
new file mode 100644
index 000000000..974e89945
--- /dev/null
+++ b/kspread/kspread_sheetprint.cpp
@@ -0,0 +1,1807 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>,
+ 2003 Philipp Mller <philipp.mueller@gmx.de>
+ 2005 Raphael Langerhorst <raphael.langerhorst@kdemail.net>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "kspread_sheet.h"
+#include "selection.h"
+#include "kspread_locale.h"
+#include "kspread_doc.h"
+#include "kspread_undo.h"
+
+#include "kspread_sheetprint.h"
+
+#include "commands.h"
+#include <KoDocumentInfo.h>
+
+#include <tdemessagebox.h>
+#include <kprinter.h>
+#include <kdebug.h>
+
+#include <tqregexp.h>
+
+#include <pwd.h>
+#include <unistd.h>
+
+#include "kspread_sheetprint.moc"
+
+#define NO_MODIFICATION_POSSIBLE \
+do { \
+ KMessageBox::error( 0, i18n ( "You cannot change a protected sheet" ) ); return; \
+} while(0)
+
+using namespace KSpread;
+
+SheetPrint::SheetPrint( Sheet* sheet )
+{
+ m_pSheet = sheet;
+ m_pDoc = m_pSheet->doc();
+
+ m_bPrintGrid = false;
+ m_bPrintCommentIndicator = false;
+ m_bPrintFormulaIndicator = false;
+ m_bPrintObjects = true;
+ m_bPrintCharts = true;
+ m_bPrintGraphics = true;
+
+ m_leftBorder = 20.0;
+ m_rightBorder = 20.0;
+ m_topBorder = 20.0;
+ m_bottomBorder = 20.0;
+
+ m_paperFormat = KoPageFormat::defaultFormat();
+ m_orientation = PG_PORTRAIT;
+ m_paperWidth = MM_TO_POINT( KoPageFormat::width( m_paperFormat, m_orientation ) );
+ m_paperHeight = MM_TO_POINT( KoPageFormat::height( m_paperFormat, m_orientation ) );
+ m_printRange = TQRect( TQPoint( 1, 1 ), TQPoint( KS_colMax, KS_rowMax ) );
+ m_lnewPageListX.append( 1 );
+ m_lnewPageListY.append( 1 );
+ m_maxCheckedNewPageX = 1;
+ m_maxCheckedNewPageY = 1;
+ m_dPrintRepeatColumnsWidth = 0.0;
+ m_dPrintRepeatRowsHeight = 0.0;
+ m_printRepeatColumns = tqMakePair( 0, 0 );
+ m_printRepeatRows = tqMakePair( 0, 0 );
+ m_dZoom = 1.0;
+ m_iPageLimitX = 0;
+ m_iPageLimitY = 0;
+
+ calcPaperSize();
+}
+
+SheetPrint::~SheetPrint()
+{
+ // nothing todo yet
+}
+
+TQString SheetPrint::saveOasisSheetStyleLayout( KoGenStyles &mainStyles )
+{
+ KoGenStyle pageLayout( KoGenStyle::STYLE_PAGELAYOUT );
+ //pageLayout.addAttribute( "style:page-usage", "all" ); FIXME
+ pageLayout.addPropertyPt( "fo:page-width", MM_TO_POINT( paperWidth() ) );
+ pageLayout.addPropertyPt( "fo:page-height", MM_TO_POINT( paperHeight() ) );
+ pageLayout.addProperty( "style:print-orientation", orientation() == PG_LANDSCAPE ? "landscape" : "portrait" );
+ pageLayout.addPropertyPt( "fo:margin-left", MM_TO_POINT(leftBorder() ) );
+ pageLayout.addPropertyPt( "fo:margin-top", MM_TO_POINT(topBorder() ) );
+ pageLayout.addPropertyPt( "fo:margin-right", MM_TO_POINT(rightBorder() ) );
+ pageLayout.addPropertyPt( "fo:margin-bottom", MM_TO_POINT(bottomBorder() ) );
+ //necessary for print setup
+ m_pSheet->saveOasisPrintStyleLayout( pageLayout );
+
+ return mainStyles.lookup( pageLayout, "pm" );
+}
+
+
+TQRect SheetPrint::cellsPrintRange()
+{
+ // Find maximum right/bottom cell with content
+ TQRect cell_range;
+ cell_range.setCoords( 1, 1, 1, 1 );
+
+ Cell* c = m_pSheet->firstCell();
+ for( ;c; c = c->nextCell() )
+ {
+ if ( c->needsPrinting() )
+ {
+ if ( c->column() > cell_range.right() )
+ cell_range.setRight( c->column() );
+ if ( c->row() > cell_range.bottom() )
+ cell_range.setBottom( c->row() );
+ }
+ }
+
+ // Now look at the children
+ TQPtrListIterator<KoDocumentChild> cit( m_pDoc->children() );
+ double dummy;
+ int i;
+ for( ; cit.current(); ++cit )
+ {
+ //TQRect, because KoChild doesn't use KoRect yet
+ TQRect bound = cit.current()->boundingRect();
+
+ i = m_pSheet->leftColumn( bound.right(), dummy );
+ if ( i > cell_range.right() )
+ cell_range.setRight( i );
+
+ i = m_pSheet->topRow( bound.bottom(), dummy );
+ if ( i > cell_range.bottom() )
+ cell_range.setBottom( i );
+ }
+ cell_range = cell_range.intersect( m_printRange );
+
+ return cell_range;
+}
+
+int SheetPrint::pagesX( const TQRect& cellsPrintRange )
+{
+ int pages = 0;
+
+ updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( cellsPrintRange.right() ) + prinsheetWidthPts() ) );
+
+ for( int i = cellsPrintRange.left(); i <= cellsPrintRange.right(); i++ )
+ {
+ if( isOnNewPageX( i ) )
+ pages++;
+ }
+ return pages;
+}
+
+int SheetPrint::pagesY( const TQRect& cellsPrintRange )
+{
+ int pages = 0;
+
+ updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( cellsPrintRange.bottom() ) + prinsheetHeightPts() ) );
+
+ for( int i = cellsPrintRange.top(); i <= cellsPrintRange.bottom(); i++ )
+ {
+ if( isOnNewPageY( i ) )
+ pages++;
+ }
+ return pages;
+}
+
+
+bool SheetPrint::pageNeedsPrinting( TQRect& page_range )
+{
+ // bool filled = false;
+
+ // Look at the cells
+ for( int r = page_range.top(); r <= page_range.bottom() ; ++r )
+ for( int c = page_range.left(); c <= page_range.right() ; ++c )
+ if ( m_pSheet->cellAt( c, r )->needsPrinting() )
+ {
+ return true;
+ }
+ // filled = true;
+
+ //Page empty, but maybe children on it?
+
+ TQRect intView = TQRect( TQPoint( m_pDoc->zoomItX( m_pSheet->dblColumnPos( page_range.left() ) ),
+ m_pDoc->zoomItY( m_pSheet->dblRowPos( page_range.top() ) ) ),
+ TQPoint( m_pDoc->zoomItX( m_pSheet->dblColumnPos( page_range.right() ) +
+ m_pSheet->columnFormat( page_range.right() )->dblWidth() ),
+ m_pDoc->zoomItY( m_pSheet->dblRowPos( page_range.bottom() ) +
+ m_pSheet->rowFormat( page_range.bottom() )->dblHeight() ) ) );
+
+ TQPtrListIterator<KoDocumentChild> it( m_pDoc->children() );
+ for( ;it.current(); ++it )
+ {
+ TQRect bound = it.current()->boundingRect();
+ if ( bound.intersects( intView ) )
+ {
+ return true;
+ }
+ //filled = true;
+ }
+
+
+ //Page has no visible content on it, so we don't need to paint it
+ return false;
+}
+
+bool SheetPrint::print( TQPainter &painter, KPrinter *_printer )
+{
+ kdDebug(36001)<<"PRINTING ...."<<endl;
+
+ // Override the current grid pen setting, when set to disable
+ TQPen gridPen;
+ bool oldShowGrid = m_pSheet->getShowGrid();
+ m_pSheet->setShowGrid( m_bPrintGrid );
+ if ( !m_bPrintGrid )
+ {
+ gridPen = TQPen( m_pDoc->gridColor(), 1, TQt::SolidLine );
+ TQPen nopen;
+ nopen.setStyle( Qt::NoPen );
+ m_pDoc->setGridColor( TQt::white );
+ }
+
+ //Update m_dPrintRepeatColumnsWidth for repeated columns
+ //just in case it isn't done yet
+ if ( !m_pSheet->isShowPageBorders() && m_printRepeatColumns.first != 0 )
+ updatePrintRepeatColumnsWidth();
+
+ //Update m_dPrintRepeatRowsHeight for repeated rows
+ //just in case it isn't done yet
+ if ( !m_pSheet->isShowPageBorders() && m_printRepeatRows.first != 0 )
+ updatePrintRepeatRowsHeight();
+
+ //Calculate the range to be printed
+ TQRect cell_range = cellsPrintRange();
+ kdDebug()<<"cellsPrintRange() :"<<cellsPrintRange()<<endl;
+ //Ensure, that our newPage lists are generated for the whole sheet to print
+ //For this we add to the lists the width/height of 1 page
+ updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( cell_range.right() ) + prinsheetWidthPts() ) );
+ updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( cell_range.bottom() ) + prinsheetHeightPts() ) );
+
+ // Find out how many pages need printing
+ // and which cells to print on which page.
+ TQValueList<TQRect> page_list; //contains the cols and rows of a page
+ TQValueList<KoRect> page_frame_list; //contains the coordinate range of a page
+ TQValueList<KoPoint> page_frame_list_offset; //contains the offset of the not repeated area
+
+ TQValueList<PrintNewPageEntry>::iterator itX;
+ TQValueList<PrintNewPageEntry>::iterator itY;
+ for( itX = m_lnewPageListX.begin(); itX != m_lnewPageListX.end(); ++itX )
+ {
+ for( itY = m_lnewPageListY.begin(); itY != m_lnewPageListY.end(); ++itY )
+ {
+ TQRect page_range( TQPoint( (*itX).startItem(), (*itY).startItem() ),
+ TQPoint( (*itX).endItem(), (*itY).endItem() ) );
+ kdDebug()<<" page_range :"<<page_range<<endl;
+ //Append page when there is something to print
+ if ( pageNeedsPrinting( page_range ) )
+ {
+ KoRect view = KoRect( KoPoint( m_pSheet->dblColumnPos( page_range.left() ),
+ m_pSheet->dblRowPos( page_range.top() ) ),
+ KoPoint( m_pSheet->dblColumnPos( page_range.right() ) +
+ m_pSheet->columnFormat( page_range.right() )->dblWidth(),
+ m_pSheet->dblRowPos( page_range.bottom() ) +
+ m_pSheet->rowFormat( page_range.bottom() )->dblHeight() ) );
+ page_list.append( page_range );
+ page_frame_list.append( view );
+ page_frame_list_offset.append( KoPoint( (*itX).offset(), (*itY).offset() ) );
+ }
+ }
+ }
+
+
+ kdDebug(36001) << "PRINTING " << page_list.count() << " pages" << endl;
+ m_uprintPages = page_list.count();
+
+
+ //Cache all object so they only need to be repainted once.
+ TQPtrListIterator<EmbeddedObject> itObject( m_pDoc->embeddedObjects() );
+ for ( ; itObject.current(); ++itObject )
+ {
+ EmbeddedObject *obj = itObject.current();
+ if ( obj->sheet() != m_pSheet ||
+ !( (( obj->getType() == OBJECT_KOFFICE_PART || obj->getType() == OBJECT_PICTURE ) && m_bPrintObjects) ||
+ ( obj->getType() == OBJECT_CHART && m_bPrintCharts ) ) )
+ continue;
+
+ TQRect zoomRect = m_pDoc->zoomRect( itObject.current()->geometry() );
+ TQPixmap *p = new TQPixmap( zoomRect.size() );
+ TQPainter painter(p);
+ painter.fillRect( p->rect(), TQColor("white") );
+ painter.translate( -zoomRect.x(), -zoomRect.y() ); //we cant to paint at (0,0)
+ bool const isSelected = itObject.current()->isSelected();
+ itObject.current()->setSelected( false );
+ itObject.current()->draw( &painter );
+ painter.end();
+ itObject.current()->setSelected( isSelected );
+
+ PrintObject *po = new PrintObject();
+ m_printObjects.append( po );
+ po->obj = itObject.current();
+ po->p = p;
+ }
+
+ if ( page_list.count() == 0 )
+ {
+ // nothing to print
+ painter.setPen( TQPen( TQt::black, 1 ) );
+ painter.drawPoint( 1, 1 );
+ }
+ else
+ {
+
+ int pageNo = 1;
+
+ //
+ // Print all pages in the list
+ //
+ TQValueList<TQRect>::Iterator it = page_list.begin();
+ TQValueList<KoRect>::Iterator fit = page_frame_list.begin();
+ TQValueList<KoPoint>::Iterator fito = page_frame_list_offset.begin();
+
+ for( ; it != page_list.end(); ++it, ++fit, ++fito, ++pageNo )
+ {
+ painter.setClipRect( 0, 0, m_pDoc->zoomItX( paperWidthPts() ),
+ m_pDoc->zoomItY( paperHeightPts() ) );
+ printHeaderFooter( painter, pageNo );
+
+ painter.translate( m_pDoc->zoomItX( leftBorderPts() ),
+ m_pDoc->zoomItY( topBorderPts() ) );
+
+ // Print the page
+ printPage( painter, *it, *fit, *fito );
+
+ painter.translate( - m_pDoc->zoomItX( leftBorderPts() ),
+ - m_pDoc->zoomItY( topBorderPts() ) );
+
+ if ( pageNo < (int)page_list.count() )
+ _printer->newPage();
+ }
+ }
+
+ if ( !m_bPrintGrid )
+ {
+ // Restore the grid pen
+ m_pDoc->setGridColor( gridPen.color() );
+ }
+ m_pSheet->setShowGrid( oldShowGrid );
+
+ TQValueList<PrintObject *>::iterator it;
+ for ( it = m_printObjects.begin(); it != m_printObjects.end(); ++it )
+ delete (*it)->p;
+ m_printObjects.clear();
+
+ return ( page_list.count() > 0 );
+}
+
+void SheetPrint::printPage( TQPainter &_painter, const TQRect& page_range,
+ const KoRect& view, const KoPoint _childOffset )
+{
+ kdDebug(36001) << "Rect x=" << page_range.left() << " y=" << page_range.top() << ", r="
+ << page_range.right() << " b=" << page_range.bottom() << " offsetx: "<< _childOffset.x()
+ << " offsety: " << _childOffset.y() <<" view-x: "<<view.x()<< endl;
+
+ //Don't paint on the page borders
+ TQRegion clipRegion( m_pDoc->zoomItX( leftBorderPts() ),
+ m_pDoc->zoomItY( topBorderPts() ),
+ m_pDoc->zoomItX( view.width() + _childOffset.x() ),
+ m_pDoc->zoomItY( view.height() + _childOffset.y() ) );
+ _painter.setClipRegion( clipRegion );
+
+ //
+ // Draw the cells.
+ //
+ //Check if we have to repeat some rows and columns (top left rect)
+ if ( ( _childOffset.x() != 0.0 ) && ( _childOffset.y() != 0.0 ) )
+ {
+ //TQRect(left,top,width,height) <<<< WIDTH AND HEIGHT!!!
+ TQRect _printRect( m_printRepeatColumns.first, m_printRepeatRows.first,
+ m_printRepeatColumns.second - m_printRepeatColumns.first + 1,
+ m_printRepeatRows.second - m_printRepeatRows.first + 1);
+ KoPoint _topLeft( 0.0, 0.0 );
+
+ printRect( _painter, _topLeft, _printRect, view, clipRegion );
+ }
+
+ //Check if we have to repeat some rows (left rect)
+ if ( _childOffset.y() != 0 )
+ {
+ TQRect _printRect( page_range.left(), m_printRepeatRows.first,
+ page_range.right() - page_range.left() + 1,
+ m_printRepeatRows.second - m_printRepeatRows.first + 1);
+ KoPoint _topLeft( _childOffset.x(), 0.0 );
+
+ printRect( _painter, _topLeft, _printRect, view, clipRegion );
+ }
+
+ //Check if we have to repeat some columns (top right rect)
+ if ( _childOffset.x() != 0 )
+ {
+ TQRect _printRect( m_printRepeatColumns.first, page_range.top(),
+ m_printRepeatColumns.second - m_printRepeatColumns.first + 1,
+ page_range.bottom() - page_range.top() + 1);
+ KoPoint _topLeft( 0.0, _childOffset.y() );
+
+ printRect( _painter, _topLeft, _printRect, view, clipRegion );
+ }
+
+
+ //Print the cells (right data rect)
+ KoPoint _topLeft( _childOffset.x(), _childOffset.y() );
+
+ printRect( _painter, _topLeft, page_range, view, clipRegion );
+}
+
+
+void SheetPrint::printRect( TQPainter& painter, const KoPoint& topLeft,
+ const TQRect& printRect, const KoRect& view,
+ TQRegion &clipRegion )
+{
+ //
+ // Draw the cells.
+ //
+ Cell *cell;
+ RowFormat *row_lay;
+ ColumnFormat *col_lay;
+
+ double xpos = 0;
+ double ypos = topLeft.y();
+
+ int regionBottom = printRect.bottom();
+ int regionRight = printRect.right();
+ int regionLeft = printRect.left();
+ int regionTop = printRect.top();
+
+ //Calculate the output rect
+ KoPoint bottomRight( topLeft );
+ for ( int x = regionLeft; x <= regionRight; ++x )
+ bottomRight.setX( bottomRight.x()
+ + m_pSheet->columnFormat( x )->dblWidth() );
+ for ( int y = regionTop; y <= regionBottom; ++y )
+ bottomRight.setY( bottomRight.y()
+ + m_pSheet->rowFormat( y )->dblHeight() );
+ KoRect rect( topLeft, bottomRight );
+
+ TQValueList<TQPoint> mergedCellsPainted;
+ for ( int y = regionTop; y <= regionBottom; ++y )
+ {
+ row_lay = m_pSheet->rowFormat( y );
+ xpos = topLeft.x();
+
+ for ( int x = regionLeft; x <= regionRight; ++x )
+ {
+ col_lay = m_pSheet->columnFormat( x );
+
+ cell = m_pSheet->cellAt( x, y );
+
+ bool paintBordersBottom = false;
+ bool paintBordersRight = false;
+ bool paintBordersLeft = false;
+ bool paintBordersTop = false;
+
+ TQPen rightPen = cell->effRightBorderPen( x, y );
+ TQPen leftPen = cell->effLeftBorderPen( x, y );
+ TQPen bottomPen = cell->effBottomBorderPen( x, y );
+ TQPen topPen = cell->effTopBorderPen( x, y );
+
+ // paint right border if rightmost cell or if the pen is more "worth" than the left border pen
+ // of the cell on the left or if the cell on the right is not painted. In the latter case get
+ // the pen that is of more "worth"
+ if ( x >= KS_colMax )
+ paintBordersRight = true;
+ else
+ if ( x == regionRight )
+ {
+ paintBordersRight = true;
+ if ( cell->effRightBorderValue( x, y ) < m_pSheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
+ rightPen = m_pSheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
+ }
+ else
+ {
+ paintBordersRight = true;
+ if ( cell->effRightBorderValue( x, y ) < m_pSheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
+ rightPen = m_pSheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
+ }
+
+ // similiar for other borders...
+ // bottom border:
+ if ( y >= KS_rowMax )
+ paintBordersBottom = true;
+ else
+ if ( y == regionBottom )
+ {
+ paintBordersBottom = true;
+ if ( cell->effBottomBorderValue( x, y ) < m_pSheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
+ bottomPen = m_pSheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
+ }
+ else
+ {
+ paintBordersBottom = true;
+ if ( cell->effBottomBorderValue( x, y ) < m_pSheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
+ bottomPen = m_pSheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
+ }
+
+ // left border:
+ if ( x == 1 )
+ paintBordersLeft = true;
+ else
+ if ( x == regionLeft )
+ {
+ paintBordersLeft = true;
+ if ( cell->effLeftBorderValue( x, y ) < m_pSheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
+ leftPen = m_pSheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
+ }
+ else
+ {
+ paintBordersLeft = true;
+ if ( cell->effLeftBorderValue( x, y ) < m_pSheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
+ leftPen = m_pSheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
+ }
+
+ // top border:
+ if ( y == 1 )
+ paintBordersTop = true;
+ else
+ if ( y == regionTop )
+ {
+ paintBordersTop = true;
+ if ( cell->effTopBorderValue( x, y ) < m_pSheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
+ topPen = m_pSheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
+ }
+ else
+ {
+ paintBordersTop = true;
+ if ( cell->effTopBorderValue( x, y ) < m_pSheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
+ topPen = m_pSheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
+ }
+
+ int paintBorder=Cell::Border_None;
+ if (paintBordersLeft) paintBorder |= Cell::Border_Left;
+ if (paintBordersRight) paintBorder |= Cell::Border_Right;
+ if (paintBordersTop) paintBorder |= Cell::Border_Top;
+ if (paintBordersBottom) paintBorder |= Cell::Border_Bottom;
+
+ TQPen highlightPen;
+
+ if ( m_pSheet->layoutDirection()==Sheet::RightToLeft )
+ cell->paintCell( rect, painter, NULL,
+ KoPoint( view.width() - xpos -
+ col_lay->dblWidth(), ypos ), TQPoint( x, y ),
+ paintBorder,
+ rightPen, bottomPen, leftPen, topPen,
+ mergedCellsPainted);
+ else
+ cell->paintCell( rect, painter, NULL,
+ KoPoint( xpos, ypos ), TQPoint( x, y ),
+ paintBorder,
+ rightPen, bottomPen, leftPen, topPen,
+ mergedCellsPainted);
+
+ xpos += col_lay->dblWidth();
+ }
+
+ ypos += row_lay->dblHeight();
+ }
+
+ //
+ // Draw the children
+ //
+ TQRect zoomedView = m_pDoc->zoomRect( view );
+ //TQPtrListIterator<KoDocumentChild> it( m_pDoc->children() );
+ //TQPtrListIterator<EmbeddedObject> itObject( m_pDoc->embeddedObjects() );
+
+ TQValueList<PrintObject *>::iterator itObject;
+ for ( itObject = m_printObjects.begin(); itObject != m_printObjects.end(); ++itObject ) {
+ EmbeddedObject *obj = (*itObject)->obj;
+// TQString tmp=TQString("Testing child %1/%2 %3/%4 against view %5/%6 %7/%8")
+// .arg(it.current()->contentRect().left())
+// .arg(it.current()->contentRect().top())
+// .arg(it.current()->contentRect().right())
+// .arg(it.current()->contentRect().bottom())
+// .arg(view.left()).arg(view.top()).arg(zoomedView.right()).arg(zoomedView.bottom());
+// kdDebug(36001)<<tmp<<" offset "<<_childOffset.x()<<"/"<<_childOffset.y()<<endl;
+
+ KoRect const bound = obj->geometry();
+ TQRect zoomedBound = m_pDoc->zoomRect( KoRect(bound.left(), bound.top(),
+ bound.width(),
+ bound.height() ) );
+#if 1
+// kdDebug(36001) << "printRect(): Bounding rect of view: " << view
+// << endl;
+// kdDebug(36001) << "printRect(): Bounding rect of zoomed view: "
+// << zoomedView << endl;
+// kdDebug(36001) << "printRect(): Bounding rect of child: " << bound
+// << endl;
+// kdDebug(36001) << "printRect(): Bounding rect of zoomed child: "
+// << zoomedBound << endl;
+#endif
+ if ( obj->sheet() == m_pSheet && zoomedBound.intersects( zoomedView ) )
+ {
+ painter.save();
+
+ painter.translate( -zoomedView.left() + m_pDoc->zoomItX( topLeft.x() ),
+ -zoomedView.top() + m_pDoc->zoomItY( topLeft.y() ) );
+
+ //obj->draw( &painter );
+ painter.drawPixmap( m_pDoc->zoomRect( obj->geometry() ).topLeft(), *(*itObject)->p ); //draw the cached object
+
+ //painter.fillRect(zoomedBound, TQBrush("red")); //for debug purpose
+ painter.restore();
+ }
+ }
+
+ //Don't let obscuring cells and children overpaint this area
+ clipRegion -= TQRegion ( m_pDoc->zoomItX( leftBorderPts() + topLeft.x() ),
+ m_pDoc->zoomItY( topBorderPts() + topLeft.y() ),
+ m_pDoc->zoomItX( xpos ),
+ m_pDoc->zoomItY( ypos ) );
+ painter.setClipRegion( clipRegion );
+}
+
+
+void SheetPrint::printHeaderFooter( TQPainter &painter, int pageNo )
+{
+ double w;
+ double headFootDistance = MM_TO_POINT( 10.0 /*mm*/ ) / m_dZoom;
+ TQFont font( "Times" );
+ font.setPointSizeFloat( 0.01 * m_pDoc->zoom() *
+ /* Font size of 10 */ 10.0 / m_dZoom );
+ painter.setFont( font );
+ TQFontMetrics fm = painter.fontMetrics();
+
+ // print head line left
+ w = fm.width( headLeft( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( m_pDoc->zoomItX( leftBorderPts() ),
+ m_pDoc->zoomItY( headFootDistance ),
+ headLeft( pageNo, m_pSheet->sheetName() ) );
+ // print head line middle
+ w = fm.width( headMid( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( (int) ( m_pDoc->zoomItX( leftBorderPts() ) +
+ ( m_pDoc->zoomItX( prinsheetWidthPts() ) -
+ w ) / 2.0 ),
+ m_pDoc->zoomItY( headFootDistance ),
+ headMid( pageNo, m_pSheet->sheetName() ) );
+ // print head line right
+ w = fm.width( headRight( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( m_pDoc->zoomItX( leftBorderPts() +
+ prinsheetWidthPts() ) - (int) w,
+ m_pDoc->zoomItY( headFootDistance ),
+ headRight( pageNo, m_pSheet->sheetName() ) );
+
+ // print foot line left
+ w = fm.width( footLeft( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( m_pDoc->zoomItX( leftBorderPts() ),
+ m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
+ footLeft( pageNo, m_pSheet->sheetName() ) );
+ // print foot line middle
+ w = fm.width( footMid( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( (int) ( m_pDoc->zoomItX( leftBorderPts() ) +
+ ( m_pDoc->zoomItX( prinsheetWidthPts() ) -
+ w ) / 2.0 ),
+ m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
+ footMid( pageNo, m_pSheet->sheetName() ) );
+ // print foot line right
+ w = fm.width( footRight( pageNo, m_pSheet->sheetName() ) ) / m_dZoom;
+ if ( w > 0 )
+ painter.drawText( m_pDoc->zoomItX( leftBorderPts() +
+ prinsheetWidthPts() ) -
+ (int) w,
+ m_pDoc->zoomItY( paperHeightPts() - headFootDistance ),
+ footRight( pageNo, m_pSheet->sheetName() ) );
+}
+
+
+bool SheetPrint::isOnNewPageX( int _column )
+{
+ if( _column > m_maxCheckedNewPageX )
+ updateNewPageX( _column );
+
+ //Are these the edges of the print range?
+ if ( _column == m_printRange.left() || _column == m_printRange.right() + 1 )
+ {
+ return true;
+ }
+
+ //beyond the print range it's always false
+ if ( _column < m_printRange.left() || _column > m_printRange.right() )
+ {
+ return false;
+ }
+
+ //Now check if we find the column already in the list
+ if ( m_lnewPageListX.findIndex( _column ) != -1 )
+ {
+ if( _column > m_maxCheckedNewPageX )
+ m_maxCheckedNewPageX = _column;
+ return true;
+ }
+ return false;
+}
+
+
+void SheetPrint::updateNewPageX( int _column )
+{
+ float offset = 0.0;
+
+ //Are these the edges of the print range?
+ if ( _column == m_printRange.left() || _column == m_printRange.right() + 1 )
+ {
+ if( _column > m_maxCheckedNewPageX )
+ m_maxCheckedNewPageX = _column;
+ return;
+ }
+
+ //We don't check beyond the print range
+ if ( _column < m_printRange.left() || _column > m_printRange.right() )
+ {
+ if( _column > m_maxCheckedNewPageX )
+ m_maxCheckedNewPageX = _column;
+ if ( _column > m_printRange.right() )
+ {
+ if ( m_lnewPageListX.last().endItem()==0 )
+ m_lnewPageListX.last().setEndItem( m_printRange.right() );
+ }
+ return;
+ }
+
+ //If we start, then add the left printrange
+ if ( m_lnewPageListX.empty() )
+ m_lnewPageListX.append( m_printRange.left() ); //Add the first entry
+
+ //If _column is greater than the last entry, we need to calculate the result
+ if ( _column > m_lnewPageListX.last().startItem() &&
+ _column > m_maxCheckedNewPageX ) //this columns hasn't been calculated before
+ {
+ int startCol = m_lnewPageListX.last().startItem();
+ int col = startCol;
+ double x = m_pSheet->columnFormat( col )->dblWidth();
+
+ //Add repeated column width, when necessary
+ if ( col > m_printRepeatColumns.first )
+ {
+ x += m_dPrintRepeatColumnsWidth;
+ offset = m_dPrintRepeatColumnsWidth;
+ }
+
+ while ( ( col <= _column ) && ( col < m_printRange.right() ) )
+ {
+ if ( x > prinsheetWidthPts() ) //end of page?
+ {
+ //We found a new page, so add it to the list
+ m_lnewPageListX.append( col );
+
+ //Now store into the previous entry the enditem and the width
+ TQValueList<PrintNewPageEntry>::iterator it;
+ it = findNewPageColumn( startCol );
+ (*it).setEndItem( col - 1 );
+ (*it).setSize( x - m_pSheet->columnFormat( col )->dblWidth() );
+ (*it).setOffset( offset );
+
+ //start a new page
+ startCol = col;
+ if ( col == _column )
+ {
+ if( _column > m_maxCheckedNewPageX )
+ m_maxCheckedNewPageX = _column;
+ return;
+ }
+ else
+ {
+ x = m_pSheet->columnFormat( col )->dblWidth();
+ if ( col >= m_printRepeatColumns.first )
+ {
+ x += m_dPrintRepeatColumnsWidth;
+ offset = m_dPrintRepeatColumnsWidth;
+ }
+ }
+ }
+
+ col++;
+ x += m_pSheet->columnFormat( col )->dblWidth();
+ }
+ }
+
+ if( _column > m_maxCheckedNewPageX )
+ m_maxCheckedNewPageX = _column;
+}
+
+
+bool SheetPrint::isOnNewPageY( int _row )
+{
+ if( _row > m_maxCheckedNewPageY )
+ updateNewPageY( _row );
+
+ //Are these the edges of the print range?
+ if ( _row == m_printRange.top() || _row == m_printRange.bottom() + 1 )
+ {
+ return true;
+ }
+
+ //beyond the print range it's always false
+ if ( _row < m_printRange.top() || _row > m_printRange.bottom() )
+ {
+ return false;
+ }
+
+ //Now check if we find the row already in the list
+ if ( m_lnewPageListY.findIndex( _row ) != -1 )
+ {
+ if( _row > m_maxCheckedNewPageY )
+ m_maxCheckedNewPageY = _row;
+ return true;
+ }
+
+ return false;
+}
+
+
+void SheetPrint::updateNewPageY( int _row )
+{
+ float offset = 0.0;
+
+ //Are these the edges of the print range?
+ if ( _row == m_printRange.top() || _row == m_printRange.bottom() + 1 )
+ {
+ if( _row > m_maxCheckedNewPageY )
+ m_maxCheckedNewPageY = _row;
+ return;
+ }
+
+ //beyond the print range it's always false
+ if ( _row < m_printRange.top() || _row > m_printRange.bottom() )
+ {
+ if( _row > m_maxCheckedNewPageY )
+ m_maxCheckedNewPageY = _row;
+ if ( _row > m_printRange.bottom() )
+ {
+ if ( m_lnewPageListY.last().endItem()==0 )
+ m_lnewPageListY.last().setEndItem( m_printRange.bottom() );
+ }
+ return;
+ }
+
+ //If we start, then add the top printrange
+ if ( m_lnewPageListY.empty() )
+ m_lnewPageListY.append( m_printRange.top() ); //Add the first entry
+
+ //If _column is greater than the last entry, we need to calculate the result
+ if ( _row > m_lnewPageListY.last().startItem() &&
+ _row > m_maxCheckedNewPageY ) //this columns hasn't been calculated before
+ {
+ int startRow = m_lnewPageListY.last().startItem();
+ int row = startRow;
+ double y = m_pSheet->rowFormat( row )->dblHeight();
+
+ //Add repeated row height, when necessary
+ if ( row > m_printRepeatRows.first )
+ {
+ y += m_dPrintRepeatRowsHeight;
+ offset = m_dPrintRepeatRowsHeight;
+ }
+
+ while ( ( row <= _row ) && ( row < m_printRange.bottom() ) )
+ {
+ if ( y > prinsheetHeightPts() )
+ {
+ //We found a new page, so add it to the list
+ m_lnewPageListY.append( row );
+
+ //Now store into the previous entry the enditem and the width
+ TQValueList<PrintNewPageEntry>::iterator it;
+ it = findNewPageRow( startRow );
+ (*it).setEndItem( row - 1 );
+ (*it).setSize( y - m_pSheet->rowFormat( row )->dblHeight() );
+ (*it).setOffset( offset );
+
+ //start a new page
+ startRow = row;
+ if ( row == _row )
+ {
+ if( _row > m_maxCheckedNewPageY )
+ m_maxCheckedNewPageY = _row;
+ return;
+ }
+ else
+ {
+ y = m_pSheet->rowFormat( row )->dblHeight();
+ if ( row >= m_printRepeatRows.first )
+ {
+ y += m_dPrintRepeatRowsHeight;
+ offset = m_dPrintRepeatRowsHeight;
+ }
+ }
+ }
+
+ row++;
+ y += m_pSheet->rowFormat( row )->dblHeight();
+ }
+ }
+
+ if( _row > m_maxCheckedNewPageY )
+ m_maxCheckedNewPageY = _row;
+}
+
+
+void SheetPrint::updateNewPageListX( int _col )
+{
+ //If the new range is after the first entry, we need to delete the whole list
+ if ( m_lnewPageListX.first().startItem() != m_printRange.left() ||
+ _col == 0 )
+ {
+ m_lnewPageListX.clear();
+ m_maxCheckedNewPageX = m_printRange.left();
+ m_lnewPageListX.append( m_printRange.left() );
+ return;
+ }
+
+ if ( _col < m_lnewPageListX.last().startItem() )
+ {
+ //Find the page entry for this column
+ TQValueList<PrintNewPageEntry>::iterator it;
+ it = m_lnewPageListX.find( _col );
+ while ( ( it == m_lnewPageListX.end() ) && _col > 0 )
+ {
+ _col--;
+ it = m_lnewPageListX.find( _col );
+ }
+
+ //Remove later pages
+ while ( it != m_lnewPageListX.end() )
+ it = m_lnewPageListX.remove( it );
+
+ //Add default page when list is now empty
+ if ( m_lnewPageListX.empty() )
+ m_lnewPageListX.append( m_printRange.left() );
+ }
+
+ m_maxCheckedNewPageX = _col;
+}
+
+void SheetPrint::updateNewPageListY( int _row )
+{
+ //If the new range is after the first entry, we need to delete the whole list
+ if ( m_lnewPageListY.first().startItem() != m_printRange.top() ||
+ _row == 0 )
+ {
+ m_lnewPageListY.clear();
+ m_maxCheckedNewPageY = m_printRange.top();
+ m_lnewPageListY.append( m_printRange.top() );
+ return;
+ }
+
+ if ( _row < m_lnewPageListY.last().startItem() )
+ {
+ //Find the page entry for this row
+ TQValueList<PrintNewPageEntry>::iterator it;
+ it = m_lnewPageListY.find( _row );
+ while ( ( it == m_lnewPageListY.end() ) && _row > 0 )
+ {
+ _row--;
+ it = m_lnewPageListY.find( _row );
+ }
+
+ //Remove later pages
+ while ( it != m_lnewPageListY.end() )
+ it = m_lnewPageListY.remove( it );
+
+ //Add default page when list is now empty
+ if ( m_lnewPageListY.empty() )
+ m_lnewPageListY.append( m_printRange.top() );
+ }
+
+ m_maxCheckedNewPageY = _row;
+}
+
+void SheetPrint::definePrintRange( Selection* selectionInfo )
+{
+ if ( !selectionInfo->isSingular() )
+ {
+ KCommand* command = new DefinePrintRangeCommand( m_pSheet );
+ m_pDoc->addCommand( command );
+ setPrintRange( selectionInfo->selection() );
+ }
+}
+
+void SheetPrint::resetPrintRange ()
+{
+ KCommand* command = new DefinePrintRangeCommand( m_pSheet );
+ m_pDoc->addCommand( command );
+ setPrintRange( TQRect( TQPoint( 1, 1 ), TQPoint( KS_colMax, KS_rowMax ) ) );
+}
+
+void SheetPrint::replaceHeadFootLineMacro ( TQString &_text, const TQString &_search, const TQString &_replace )
+{
+ if ( _search != _replace )
+ _text.replace ( TQString( "<" + _search + ">" ), "<" + _replace + ">" );
+}
+
+TQString SheetPrint::localizeHeadFootLine ( const TQString &_text )
+{
+ TQString tmp = _text;
+
+ /*
+ i18n:
+ Please use the same words (even upper/lower case) as in
+ KoPageLayoutDia.cpp function setupTab2(), without the brakets "<" and ">"
+ */
+ replaceHeadFootLineMacro ( tmp, "page", i18n("page") );
+ replaceHeadFootLineMacro ( tmp, "pages", i18n("pages") );
+ replaceHeadFootLineMacro ( tmp, "file", i18n("file") );
+ replaceHeadFootLineMacro ( tmp, "name", i18n("name") );
+ replaceHeadFootLineMacro ( tmp, "time", i18n("time") );
+ replaceHeadFootLineMacro ( tmp, "date", i18n("date") );
+ replaceHeadFootLineMacro ( tmp, "author", i18n("author") );
+ replaceHeadFootLineMacro ( tmp, "email", i18n("email") );
+ replaceHeadFootLineMacro ( tmp, "org", i18n("org") );
+ replaceHeadFootLineMacro ( tmp, "sheet", i18n("sheet") );
+
+ return tmp;
+}
+
+
+TQString SheetPrint::delocalizeHeadFootLine ( const TQString &_text )
+{
+ TQString tmp = _text;
+
+ /*
+ i18n:
+ Please use the same words (even upper/lower case) as in
+ KoPageLayoutDia.cpp function setupTab2(), without the brakets "<" and ">"
+ */
+ replaceHeadFootLineMacro ( tmp, i18n("page"), "page" );
+ replaceHeadFootLineMacro ( tmp, i18n("pages"), "pages" );
+ replaceHeadFootLineMacro ( tmp, i18n("file"), "file" );
+ replaceHeadFootLineMacro ( tmp, i18n("name"), "name" );
+ replaceHeadFootLineMacro ( tmp, i18n("time"), "time" );
+ replaceHeadFootLineMacro ( tmp, i18n("date"), "date" );
+ replaceHeadFootLineMacro ( tmp, i18n("author"), "author" );
+ replaceHeadFootLineMacro ( tmp, i18n("email"), "email" );
+ replaceHeadFootLineMacro ( tmp, i18n("org"), "org" );
+ replaceHeadFootLineMacro ( tmp, i18n("sheet"), "sheet" );
+
+ return tmp;
+}
+
+
+KoHeadFoot SheetPrint::headFootLine() const
+{
+ KoHeadFoot hf;
+ hf.headLeft = m_headLeft;
+ hf.headRight = m_headRight;
+ hf.headMid = m_headMid;
+ hf.footLeft = m_footLeft;
+ hf.footRight = m_footRight;
+ hf.footMid = m_footMid;
+
+ return hf;
+}
+
+
+void SheetPrint::setHeadFootLine( const TQString &_headl, const TQString &_headm, const TQString &_headr,
+ const TQString &_footl, const TQString &_footm, const TQString &_footr )
+{
+ if ( m_pSheet->isProtected() )
+ NO_MODIFICATION_POSSIBLE;
+
+ m_headLeft = _headl;
+ m_headRight = _headr;
+ m_headMid = _headm;
+ m_footLeft = _footl;
+ m_footRight = _footr;
+ m_footMid = _footm;
+
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPaperOrientation( KoOrientation _orient )
+{
+ if ( m_pSheet->isProtected() )
+ NO_MODIFICATION_POSSIBLE;
+
+ m_orientation = _orient;
+ calcPaperSize();
+ updatePrintRepeatColumnsWidth();
+ updatePrintRepeatRowsHeight();
+ updateNewPageListX( m_printRange.left() ); //Reset the list
+ updateNewPageListY( m_printRange.top() ); //Reset the list
+
+ if( m_pSheet->isShowPageBorders() )
+ emit sig_updateView( m_pSheet );
+}
+
+
+KoPageLayout SheetPrint::paperLayout() const
+{
+ KoPageLayout pl;
+ pl.format = m_paperFormat;
+ pl.orientation = m_orientation;
+ pl.ptWidth = m_paperWidth;
+ pl.ptHeight = m_paperHeight;
+ pl.ptLeft = m_leftBorder;
+ pl.ptRight = m_rightBorder;
+ pl.ptTop = m_topBorder;
+ pl.ptBottom = m_bottomBorder;
+ return pl;
+}
+
+
+void SheetPrint::setPaperLayout( float _leftBorder, float _topBorder,
+ float _rightBorder, float _bottomBorder,
+ KoFormat _paper,
+ KoOrientation _orientation )
+{
+ if ( m_pSheet->isProtected() )
+ NO_MODIFICATION_POSSIBLE;
+
+ m_leftBorder = _leftBorder;
+ m_rightBorder = _rightBorder;
+ m_topBorder = _topBorder;
+ m_bottomBorder = _bottomBorder;
+ m_paperFormat = _paper;
+
+ setPaperOrientation( _orientation ); //calcPaperSize() is done here already
+
+// TQPtrListIterator<KoView> it( views() );
+// for( ;it.current(); ++it )
+// {
+// View *v = static_cast<View *>( it.current() );
+ // We need to trigger the appropriate repaintings in the cells near the
+ // border of the page. The easiest way for this is to turn the borders
+ // off and on (or on and off if they were off).
+// bool bBorderWasShown = v->activeSheet()->isShowPageBorders();
+// v->activeSheet()->setShowPageBorders( !bBorderWasShown );
+// v->activeSheet()->setShowPageBorders( bBorderWasShown );
+// }
+
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPaperLayout( float _leftBorder, float _topBorder,
+ float _rightBorder, float _bottomBorder,
+ const TQString& _paper,
+ const TQString& _orientation )
+{
+ if ( m_pSheet->isProtected() )
+ NO_MODIFICATION_POSSIBLE;
+
+ KoFormat f = paperFormat();
+ KoOrientation newOrientation = orientation();
+
+ if ( _orientation == "Portrait" )
+ newOrientation = PG_PORTRAIT;
+ else if ( _orientation == "Landscape" )
+ newOrientation = PG_LANDSCAPE;
+
+
+ TQString paper( _paper );
+ if ( paper[0].isDigit() ) // Custom format
+ {
+ const int i = paper.find( 'x' );
+ if ( i < 0 )
+ {
+ // We have nothing useful, so assume ISO A4
+ f = PG_DIN_A4;
+ }
+ else
+ {
+ f = PG_CUSTOM;
+ m_paperWidth = paper.left(i).toFloat();
+ m_paperHeight = paper.mid(i+1).toFloat();
+ if ( m_paperWidth < 10.0 )
+ m_paperWidth = KoPageFormat::width( PG_DIN_A4, newOrientation );
+ if ( m_paperHeight < 10.0 )
+ m_paperHeight = KoPageFormat::height( PG_DIN_A4, newOrientation );
+ }
+ }
+ else
+ {
+ f = KoPageFormat::formatFromString( paper );
+ if ( f == PG_CUSTOM )
+ // We have no idea about height or width, therefore assume ISO A4
+ f = PG_DIN_A4;
+ }
+ setPaperLayout( _leftBorder, _topBorder, _rightBorder, _bottomBorder, f, newOrientation );
+}
+
+void SheetPrint::calcPaperSize()
+{
+ if ( m_paperFormat != PG_CUSTOM )
+ {
+ m_paperWidth = KoPageFormat::width( m_paperFormat, m_orientation );
+ m_paperHeight = KoPageFormat::height( m_paperFormat, m_orientation );
+ }
+}
+
+TQValueList<PrintNewPageEntry>::iterator SheetPrint::findNewPageColumn( int col )
+{
+ TQValueList<PrintNewPageEntry>::iterator it;
+ for( it = m_lnewPageListX.begin(); it != m_lnewPageListX.end(); ++it )
+ {
+ if( (*it).startItem() == col )
+ return it;
+ }
+ return it;
+// TQValueList<PrintNewPageEntry>::iterator it;
+// it = m_lnewPageListX.find( startCol );
+}
+
+TQValueList<PrintNewPageEntry>::iterator SheetPrint::findNewPageRow( int row )
+{
+ TQValueList<PrintNewPageEntry>::iterator it;
+ for( it = m_lnewPageListY.begin(); it != m_lnewPageListY.end(); ++it )
+ {
+ if( (*it).startItem() == row )
+ return it;
+ }
+ return it;
+}
+
+
+TQString SheetPrint::paperFormatString()const
+{
+ if ( m_paperFormat == PG_CUSTOM )
+ {
+ TQString tmp;
+ tmp.sprintf( "%fx%f", m_paperWidth, m_paperHeight );
+ return tmp;
+ }
+
+ return KoPageFormat::formatString( m_paperFormat );
+}
+
+const char* SheetPrint::orientationString() const
+{
+ switch( m_orientation )
+ {
+ case KPrinter::Portrait:
+ return "Portrait";
+ case KPrinter::Landscape:
+ return "Landscape";
+ }
+
+ kdWarning(36001)<<"SheetPrint: Unknown orientation, using now portrait"<<endl;
+ return 0;
+}
+
+TQString SheetPrint::completeHeading( const TQString &_data, int _page, const TQString &_sheet ) const
+{
+ TQString page( TQString::number( _page) );
+ TQString pages( TQString::number( m_uprintPages ) );
+
+ TQString pathFileName(m_pDoc->url().path());
+ if ( pathFileName.isNull() )
+ pathFileName="";
+
+ TQString fileName(m_pDoc->url().fileName());
+ if( fileName.isNull())
+ fileName="";
+
+ TQString t(TQTime::currentTime().toString());
+ TQString d(TQDate::currentDate().toString());
+ TQString ta;
+ if ( !_sheet.isEmpty() )
+ ta = _sheet;
+
+ KoDocumentInfo * info = m_pDoc->documentInfo();
+ KoDocumentInfoAuthor * authorPage = static_cast<KoDocumentInfoAuthor *>(info->page( "author" ));
+ TQString full_name;
+ TQString email_addr;
+ TQString organization;
+ TQString tmp;
+ if ( !authorPage )
+ kdWarning() << "Author information not found in Document Info !" << endl;
+ else
+ {
+ full_name = authorPage->fullName();
+ email_addr = authorPage->email();
+ organization = authorPage->company();
+ }
+
+ char hostname[80];
+ struct passwd *p;
+
+ p = getpwuid(getuid());
+ gethostname(hostname, sizeof(hostname));
+
+ if(full_name.isEmpty())
+ full_name=p->pw_gecos;
+
+ if( email_addr.isEmpty())
+ email_addr = TQString("%1@%2").arg(p->pw_name).arg(hostname);
+
+ tmp = _data;
+ int pos = 0;
+ while ( ( pos = tmp.find( "<page>", pos ) ) != -1 )
+ tmp.replace( pos, 6, page );
+ pos = 0;
+ while ( ( pos = tmp.find( "<pages>", pos ) ) != -1 )
+ tmp.replace( pos, 7, pages );
+ pos = 0;
+ while ( ( pos = tmp.find( "<file>", pos ) ) != -1 )
+ tmp.replace( pos, 6, pathFileName );
+ pos = 0;
+ while ( ( pos = tmp.find( "<name>", pos ) ) != -1 )
+ tmp.replace( pos, 6, fileName );
+ pos = 0;
+ while ( ( pos = tmp.find( "<time>", pos ) ) != -1 )
+ tmp.replace( pos, 6, t );
+ pos = 0;
+ while ( ( pos = tmp.find( "<date>", pos ) ) != -1 )
+ tmp.replace( pos, 6, d );
+ pos = 0;
+ while ( ( pos = tmp.find( "<author>", pos ) ) != -1 )
+ tmp.replace( pos, 8, full_name );
+ pos = 0;
+ while ( ( pos = tmp.find( "<email>", pos ) ) != -1 )
+ tmp.replace( pos, 7, email_addr );
+ pos = 0;
+ while ( ( pos = tmp.find( "<org>", pos ) ) != -1 )
+ tmp.replace( pos, 5, organization );
+ pos = 0;
+ while ( ( pos = tmp.find( "<sheet>", pos ) ) != -1 )
+ tmp.replace( pos, 7, ta );
+
+ return tmp;
+}
+
+void SheetPrint::setPrintRange( const TQRect &_printRange )
+{
+ if ( m_pSheet->isProtected() )
+ NO_MODIFICATION_POSSIBLE;
+
+
+ if ( m_printRange == _printRange )
+ return;
+
+ int oldLeft = m_printRange.left();
+ int oldTop = m_printRange.top();
+ m_printRange = _printRange;
+
+ //Refresh calculation of stored page breaks, the lower one of old and new
+ if ( oldLeft != _printRange.left() )
+ updateNewPageListX( TQMIN( oldLeft, _printRange.left() ) );
+ if ( oldTop != _printRange.top() )
+ updateNewPageListY( TQMIN( oldTop, _printRange.top() ) );
+
+ m_pDoc->setModified( true );
+
+ emit sig_updateView( m_pSheet );
+
+}
+
+void SheetPrint::setPageLimitX( int pages )
+{
+ //We do want an update in any case because the sheet content
+ //could have changed, thus we need to recalculate although
+ //it's the same setting!
+// if( m_iPageLimitX == pages )
+// return;
+
+ m_iPageLimitX = pages;
+
+ if( pages == 0 )
+ return;
+
+ calculateZoomForPageLimitX();
+}
+
+void SheetPrint::setPageLimitY( int pages )
+{
+ //We do want an update in any case because the sheet content
+ //could have changed, thus we need to recalculate although
+ //it's the same setting!
+// if( m_iPageLimitY == pages )
+// return;
+
+ m_iPageLimitY = pages;
+
+ if( pages == 0 )
+ return;
+
+ calculateZoomForPageLimitY();
+}
+
+void SheetPrint::calculateZoomForPageLimitX()
+{
+ kdDebug() << "Calculating zoom for X limit" << endl;
+ if( m_iPageLimitX == 0 )
+ return;
+
+ double origZoom = m_dZoom;
+
+ if( m_dZoom < 1.0 )
+ m_dZoom = 1.0;
+
+ TQRect printRange = cellsPrintRange();
+ updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
+ int currentPages = pagesX( printRange );
+
+ if (currentPages <= m_iPageLimitX)
+ return;
+
+ //calculating a factor for scaling the zoom down makes it lots faster
+ double factor = (double)m_iPageLimitX/(double)currentPages +
+ 1-(double)currentPages/((double)currentPages+1); //add possible error;
+ kdDebug() << "Calculated factor for scaling m_dZoom: " << factor << endl;
+ m_dZoom = m_dZoom*factor;
+
+ kdDebug() << "New exact zoom: " << m_dZoom << endl;
+
+ if (m_dZoom < 0.01)
+ m_dZoom = 0.01;
+ if (m_dZoom > 1.0)
+ m_dZoom = 1.0;
+
+ m_dZoom = (((int)(m_dZoom*100 + 0.5))/100.0);
+
+ kdDebug() << "New rounded zoom: " << m_dZoom << endl;
+
+ updatePrintRepeatColumnsWidth();
+ updateNewPageListX( 0 );
+ updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
+ currentPages = pagesX( printRange );
+
+ kdDebug() << "Number of pages with this zoom: " << currentPages << endl;
+
+ while( ( currentPages > m_iPageLimitX ) && ( m_dZoom > 0.01 ) )
+ {
+ m_dZoom -= 0.01;
+ updatePrintRepeatColumnsWidth();
+ updateNewPageListX( 0 );
+ updateNewPageX( m_pSheet->rightColumn( m_pSheet->dblColumnPos( printRange.right() ) + prinsheetWidthPts() ) );
+ currentPages = pagesX( printRange );
+ kdDebug() << "Looping -0.01; current zoom: " << m_dZoom << endl;
+ }
+
+ if ( m_dZoom < origZoom )
+ {
+ double newZoom = m_dZoom;
+ m_dZoom += 1.0; //set it to something different
+ setZoom( newZoom, false );
+ }
+ else
+ m_dZoom = origZoom;
+}
+
+void SheetPrint::calculateZoomForPageLimitY()
+{
+ kdDebug() << "Calculating zoom for Y limit" << endl;
+ if( m_iPageLimitY == 0 )
+ return;
+
+ double origZoom = m_dZoom;
+
+ if( m_dZoom < 1.0 )
+ m_dZoom = 1.0;
+
+ TQRect printRange = cellsPrintRange();
+ updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
+ int currentPages = pagesY( printRange );
+
+ if (currentPages <= m_iPageLimitY)
+ return;
+
+ double factor = (double)m_iPageLimitY/(double)currentPages +
+ 1-(double)currentPages/((double)currentPages+1); //add possible error
+ kdDebug() << "Calculated factor for scaling m_dZoom: " << factor << endl;
+ m_dZoom = m_dZoom*factor;
+
+ kdDebug() << "New exact zoom: " << m_dZoom << endl;
+
+ if (m_dZoom < 0.01)
+ m_dZoom = 0.01;
+ if (m_dZoom > 1.0)
+ m_dZoom = 1.0;
+
+ m_dZoom = (((int)(m_dZoom*100 + 0.5))/100.0);
+
+ kdDebug() << "New rounded zoom: " << m_dZoom << endl;
+
+ updatePrintRepeatRowsHeight();
+ updateNewPageListY( 0 );
+ updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
+ currentPages = pagesY( printRange );
+
+ kdDebug() << "Number of pages with this zoom: " << currentPages << endl;
+
+ while( ( currentPages > m_iPageLimitY ) && ( m_dZoom > 0.01 ) )
+ {
+ m_dZoom -= 0.01;
+ updatePrintRepeatRowsHeight();
+ updateNewPageListY( 0 );
+ updateNewPageY( m_pSheet->bottomRow( m_pSheet->dblRowPos( printRange.bottom() ) + prinsheetHeightPts() ) );
+ currentPages = pagesY( printRange );
+ kdDebug() << "Looping -0.01; current zoom: " << m_dZoom << endl;
+ }
+
+ if ( m_dZoom < origZoom )
+ {
+ double newZoom = m_dZoom;
+ m_dZoom += 1.0; //set it to something different
+ setZoom( newZoom, false );
+ }
+ else
+ m_dZoom = origZoom;
+}
+
+void SheetPrint::setPrintGrid( bool _printGrid )
+{
+ if ( m_bPrintGrid == _printGrid )
+ return;
+
+ m_bPrintGrid = _printGrid;
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintObjects( bool _printObjects )
+{
+ if ( m_bPrintObjects == _printObjects )
+ return;
+
+ m_bPrintObjects = _printObjects;
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintCharts( bool _printCharts )
+{
+ if ( m_bPrintCharts == _printCharts )
+ return;
+
+ m_bPrintCharts = _printCharts;
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintGraphics( bool _printGraphics )
+{
+ if ( m_bPrintGraphics == _printGraphics )
+ return;
+
+ m_bPrintGraphics = _printGraphics;
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintCommentIndicator( bool _printCommentIndicator )
+{
+ if ( m_bPrintCommentIndicator == _printCommentIndicator )
+ return;
+
+ m_bPrintCommentIndicator = _printCommentIndicator;
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintFormulaIndicator( bool _printFormulaIndicator )
+{
+ if( m_bPrintFormulaIndicator == _printFormulaIndicator )
+ return;
+
+ m_bPrintFormulaIndicator = _printFormulaIndicator;
+ m_pDoc->setModified( true );
+}
+void SheetPrint::updatePrintRepeatColumnsWidth()
+{
+ m_dPrintRepeatColumnsWidth = 0.0;
+ if( m_printRepeatColumns.first != 0 )
+ {
+ for( int i = m_printRepeatColumns.first; i <= m_printRepeatColumns.second; i++ )
+ {
+ m_dPrintRepeatColumnsWidth += m_pSheet->columnFormat( i )->dblWidth();
+ }
+ }
+}
+
+void SheetPrint::updatePrintRepeatRowsHeight()
+{
+ m_dPrintRepeatRowsHeight = 0.0;
+ if ( m_printRepeatRows.first != 0 )
+ {
+ for ( int i = m_printRepeatRows.first; i <= m_printRepeatRows.second; i++)
+ {
+ m_dPrintRepeatRowsHeight += m_pSheet->rowFormat( i )->dblHeight();
+ }
+ }
+}
+
+
+void SheetPrint::setPrintRepeatColumns( TQPair<int, int> _printRepeatColumns )
+{
+ //Bring arguments in order
+ if ( _printRepeatColumns.first > _printRepeatColumns.second )
+ {
+ int tmp = _printRepeatColumns.first;
+ _printRepeatColumns.first = _printRepeatColumns.second;
+ _printRepeatColumns.second = tmp;
+ }
+
+ //If old are equal to the new setting, nothing is to be done at all
+ if ( m_printRepeatColumns == _printRepeatColumns )
+ return;
+
+ int oldFirst = m_printRepeatColumns.first;
+ m_printRepeatColumns = _printRepeatColumns;
+
+ //Recalcualte the space needed for the repeated columns
+ updatePrintRepeatColumnsWidth();
+
+ //Refresh calculation of stored page breaks, the lower one of old and new
+ updateNewPageListX( TQMIN( oldFirst, _printRepeatColumns.first ) );
+
+ //Refresh view, if page borders are shown
+ if ( m_pSheet->isShowPageBorders() )
+ emit sig_updateView( m_pSheet );
+
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::setPrintRepeatRows( TQPair<int, int> _printRepeatRows )
+{
+ //Bring arguments in order
+ if ( _printRepeatRows.first > _printRepeatRows.second )
+ {
+ int tmp = _printRepeatRows.first;
+ _printRepeatRows.first = _printRepeatRows.second;
+ _printRepeatRows.second = tmp;
+ }
+
+ //If old are equal to the new setting, nothing is to be done at all
+ if ( m_printRepeatRows == _printRepeatRows )
+ return;
+
+ int oldFirst = m_printRepeatRows.first;
+ m_printRepeatRows = _printRepeatRows;
+
+ //Recalcualte the space needed for the repeated rows
+ updatePrintRepeatRowsHeight();
+
+ //Refresh calculation of stored page breaks, the lower one of old and new
+ updateNewPageListY( TQMIN( oldFirst, _printRepeatRows.first ) );
+
+ //Refresh view, if page borders are shown
+ if ( m_pSheet->isShowPageBorders() )
+ emit sig_updateView( m_pSheet );
+
+ m_pDoc->setModified( true );
+}
+
+void SheetPrint::insertColumn( int col, int nbCol )
+{
+ //update print range, when it has been defined
+ if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
+ {
+ int left = m_printRange.left();
+ int right = m_printRange.right();
+
+ for( int i = 0; i <= nbCol; i++ )
+ {
+ if ( left >= col ) left++;
+ if ( right >= col ) right++;
+ }
+ //Validity checks
+ if ( left > KS_colMax ) left = KS_colMax;
+ if ( right > KS_colMax ) right = KS_colMax;
+ setPrintRange( TQRect( TQPoint( left, m_printRange.top() ),
+ TQPoint( right, m_printRange.bottom() ) ) );
+ }
+}
+
+void SheetPrint::insertRow( int row, int nbRow )
+{
+ //update print range, when it has been defined
+ if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
+ {
+ int top = m_printRange.top();
+ int bottom = m_printRange.bottom();
+
+ for( int i = 0; i <= nbRow; i++ )
+ {
+ if ( top >= row ) top++;
+ if ( bottom >= row ) bottom++;
+ }
+ //Validity checks
+ if ( top > KS_rowMax ) top = KS_rowMax;
+ if ( bottom > KS_rowMax ) bottom = KS_rowMax;
+ setPrintRange( TQRect( TQPoint( m_printRange.left(), top ),
+ TQPoint( m_printRange.right(), bottom ) ) );
+ }
+}
+
+void SheetPrint::removeColumn( int col, int nbCol )
+{
+ //update print range, when it has been defined
+ if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
+ {
+ int left = m_printRange.left();
+ int right = m_printRange.right();
+
+ for( int i = 0; i <= nbCol; i++ )
+ {
+ if ( left > col ) left--;
+ if ( right >= col ) right--;
+ }
+ //Validity checks
+ if ( left < 1 ) left = 1;
+ if ( right < 1 ) right = 1;
+ setPrintRange( TQRect( TQPoint( left, m_printRange.top() ),
+ TQPoint( right, m_printRange.bottom() ) ) );
+ }
+
+ //update repeat columns, when it has been defined
+ if ( m_printRepeatColumns.first != 0 )
+ {
+ int left = m_printRepeatColumns.first;
+ int right = m_printRepeatColumns.second;
+
+ for( int i = 0; i <= nbCol; i++ )
+ {
+ if ( left > col ) left--;
+ if ( right >= col ) right--;
+ }
+ //Validity checks
+ if ( left < 1 ) left = 1;
+ if ( right < 1 ) right = 1;
+ setPrintRepeatColumns ( tqMakePair( left, right ) );
+ }
+}
+
+void SheetPrint::removeRow( int row, int nbRow )
+{
+ //update print range, when it has been defined
+ if ( m_printRange != TQRect( TQPoint(1, 1), TQPoint(KS_colMax, KS_rowMax) ) )
+ {
+ int top = m_printRange.top();
+ int bottom = m_printRange.bottom();
+
+ for( int i = 0; i <= nbRow; i++ )
+ {
+ if ( top > row ) top--;
+ if ( bottom >= row ) bottom--;
+ }
+ //Validity checks
+ if ( top < 1 ) top = 1;
+ if ( bottom < 1 ) bottom = 1;
+ setPrintRange( TQRect( TQPoint( m_printRange.left(), top ),
+ TQPoint( m_printRange.right(), bottom ) ) );
+ }
+
+ //update repeat rows, when it has been defined
+ if ( m_printRepeatRows.first != 0 )
+ {
+ int top = m_printRepeatRows.first;
+ int bottom = m_printRepeatRows.second;
+
+ for( int i = 0; i <= nbRow; i++ )
+ {
+ if ( top > row ) top--;
+ if ( bottom >= row ) bottom--;
+ }
+ //Validity checks
+ if ( top < 1 ) top = 1;
+ if ( bottom < 1 ) bottom = 1;
+ setPrintRepeatRows( tqMakePair( top, bottom ) );
+ }
+}
+
+void SheetPrint::setZoom( double _zoom, bool checkPageLimit )
+{
+ if( m_dZoom == _zoom )
+ {
+ return;
+ }
+
+ m_dZoom = _zoom;
+ updatePrintRepeatColumnsWidth();
+ updatePrintRepeatRowsHeight();
+ updateNewPageListX( 0 );
+ updateNewPageListY( 0 );
+ if( m_pSheet->isShowPageBorders() )
+ emit sig_updateView( m_pSheet );
+
+ if( checkPageLimit )
+ {
+ calculateZoomForPageLimitX();
+ calculateZoomForPageLimitY();
+ }
+
+ m_pDoc->setModified( true );
+}
+
+bool PrintNewPageEntry::operator==( PrintNewPageEntry const & entry ) const
+{
+ return m_iStartItem == entry.m_iStartItem;
+}
+
diff --git a/kspread/kspread_style.cc b/kspread/kspread_style.cpp
index bd58ac885..bd58ac885 100644
--- a/kspread/kspread_style.cc
+++ b/kspread/kspread_style.cpp
diff --git a/kspread/kspread_style_manager.cc b/kspread/kspread_style_manager.cpp
index 8bfb8acf9..8bfb8acf9 100644
--- a/kspread/kspread_style_manager.cc
+++ b/kspread/kspread_style_manager.cpp
diff --git a/kspread/kspread_toolbox.cc b/kspread/kspread_toolbox.cpp
index b868d9131..b868d9131 100644
--- a/kspread/kspread_toolbox.cc
+++ b/kspread/kspread_toolbox.cpp
diff --git a/kspread/kspread_undo.cc b/kspread/kspread_undo.cpp
index 28f592651..28f592651 100644
--- a/kspread/kspread_undo.cc
+++ b/kspread/kspread_undo.cpp
diff --git a/kspread/kspread_util.cc b/kspread/kspread_util.cc
deleted file mode 100644
index 3950c5b94..000000000
--- a/kspread/kspread_util.cc
+++ /dev/null
@@ -1,1218 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2006 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <ctype.h>
-
-#include <tqregexp.h>
-
-#include <kdebug.h>
-
-#include "formula.h"
-#include "kspread_doc.h"
-#include "kspread_locale.h"
-#include "kspread_map.h"
-#include "kspread_sheet.h"
-#include "kspread_style.h"
-#include "kspread_util.h"
-
-using namespace KSpread;
-
-//helper functions for the formatting
-bool KSpread::formatIsDate (FormatType fmt)
-{
- return ((fmt == ShortDate_format) || (fmt == TextDate_format) ||
- (((int) fmt >= 200) && ((int) fmt < 300)));
-}
-
-bool KSpread::formatIsTime (FormatType fmt)
-{
- return (((int) fmt >= 50) && ((int) fmt < 70));
-}
-
-bool KSpread::formatIsFraction (FormatType fmt)
-{
- return (((int) fmt >= 70) && ((int) fmt < 80));
-}
-
-
-//used in Point::init, Cell::encodeFormula and
-// dialogs/kspread_dlg_paperlayout.cc
-int KSpread::util_decodeColumnLabelText( const TQString &_col )
-{
- int col = 0;
- int offset='a'-'A';
- int counterColumn = 0;
- for ( uint i=0; i < _col.length(); i++ )
- {
- counterColumn = (int) pow(26.0 , static_cast<int>(_col.length() - i - 1));
- if( (int)(_col[i]) >= 'A' && (int)(_col[i]) <= 'Z' )
- col += counterColumn * ( _col[i].latin1() - 'A' + 1); // okay here (Werner)
- else if( (int)(_col[i]) >= 'a' && (int)(_col[i]) <= 'z' )
- col += counterColumn * ( _col[i].latin1() - 'A' - offset + 1 );
- else
- kdDebug(36001) << "util_decodeColumnLabelText: Wrong characters in label text for col:'" << _col << "'" << endl;
- }
- return col;
-}
-
-//used in dialogs/kspread_dlg_paperlayout.cc
-TQString KSpread::util_rangeColumnName( const TQRect &_area)
-{
- return TQString("%1:%2")
- .arg( Cell::columnName( _area.left()))
- .arg( Cell::columnName(_area.right()));
-}
-
-//used in dialogs/kspread_dlg_paperlayout.cc
-TQString KSpread::util_rangeRowName( const TQRect &_area)
-{
- return TQString("%1:%2")
- .arg( _area.top())
- .arg(_area.bottom());
-}
-
-TQString KSpread::util_rangeName(const TQRect &_area)
-{
- return Cell::name( _area.left(), _area.top() ) + ":" +
- Cell::name( _area.right(), _area.bottom() );
-}
-
-TQString KSpread::util_rangeName(Sheet * _sheet, const TQRect &_area)
-{
- return _sheet->sheetName() + "!" + util_rangeName(_area);
-}
-
-TQDomElement KSpread::util_createElement( const TQString & tagName, const TQFont & font, TQDomDocument & doc )
-{
- TQDomElement e( doc.createElement( tagName ) );
-
- e.setAttribute( "family", font.family() );
- e.setAttribute( "size", font.pointSize() );
- e.setAttribute( "weight", font.weight() );
- if ( font.bold() )
- e.setAttribute( "bold", "yes" );
- if ( font.italic() )
- e.setAttribute( "italic", "yes" );
- if ( font.underline() )
- e.setAttribute( "underline", "yes" );
- if ( font.strikeOut() )
- e.setAttribute( "strikeout", "yes" );
- //e.setAttribute( "charset", TDEGlobal::charsets()->name( font ) );
-
- return e;
-}
-
-TQDomElement KSpread::util_createElement( const TQString & tagname, const TQPen & pen, TQDomDocument & doc )
-{
- TQDomElement e( doc.createElement( tagname ) );
- e.setAttribute( "color", pen.color().name() );
- e.setAttribute( "style", (int)pen.style() );
- e.setAttribute( "width", (int)pen.width() );
- return e;
-}
-
-TQFont KSpread::util_toFont( TQDomElement & element )
-{
- TQFont f;
- f.setFamily( element.attribute( "family" ) );
-
- bool ok;
- f.setPointSize( element.attribute("size").toInt( &ok ) );
- if ( !ok )
- return TQFont();
-
- f.setWeight( element.attribute("weight").toInt( &ok ) );
- if ( !ok )
- return TQFont();
-
- if ( element.hasAttribute( "italic" ) && element.attribute("italic") == "yes" )
- f.setItalic( true );
-
- if ( element.hasAttribute( "bold" ) && element.attribute("bold") == "yes" )
- f.setBold( true );
-
- if ( element.hasAttribute( "underline" ) && element.attribute("underline") == "yes" )
- f.setUnderline( true );
-
- if ( element.hasAttribute( "strikeout" ) && element.attribute("strikeout") == "yes" )
- f.setStrikeOut( true );
-
- /* Uncomment when charset is added to kspread_dlg_layout
- + save a document-global charset
- if ( element.hasAttribute( "charset" ) )
- TDEGlobal::charsets()->setTQFont( f, element.attribute("charset") );
- else
- */
- // ######## Not needed anymore in 3.0?
- //TDEGlobal::charsets()->setTQFont( f, TDEGlobal::locale()->charset() );
-
- return f;
-}
-
-TQPen KSpread::util_toPen( TQDomElement & element )
-{
- bool ok;
- TQPen p;
-
- p.setStyle( (Qt::PenStyle)element.attribute("style").toInt( &ok ) );
- if ( !ok )
- return TQPen();
-
- p.setWidth( element.attribute("width").toInt( &ok ) );
- if ( !ok )
- return TQPen();
-
- p.setColor( TQColor( element.attribute("color") ) );
-
- return p;
-}
-
-Point::Point(const TQString & _str)
-{
- _sheet = 0;
- init(_str);
-}
-
-void Point::setPos(TQPoint pos)
-{
- _pos=pos;
-}
-TQPoint Point::pos() const
-{
- return _pos;
-}
-void Point::setSheet(Sheet* sheet)
-{
- _sheet=sheet;
-}
-KSpread::Sheet* Point::sheet() const
-{
- return _sheet;
-}
-void Point::setSheetName(TQString name)
-{
- _sheetName=name;
-}
-TQString Point::sheetName() const
-{
- return _sheetName;
-}
-void Point::setColumnFixed(bool colFixed)
-{
- _columnFixed=colFixed;
-}
-bool Point::columnFixed() const
-{
- return _columnFixed;
-}
-void Point::setRowFixed(bool rowFixed)
-{
- _rowFixed=rowFixed;
-}
-bool Point::rowFixed() const
-{
- return _rowFixed;
-}
-
-
-void Point::init(const TQString & _str)
-{
- _columnFixed=false;
- _rowFixed=false;
-
-// kdDebug(36001) <<"Point::init ("<<_str<<")"<<endl;
- _pos.setX(-1);
-
- uint len = _str.length();
- if ( !len )
- {
- kdDebug(36001) << "Point::init: len = 0" << endl;
- return;
- }
-
- TQString str( _str );
- int n = _str.find( '!' );
- if ( n != -1 )
- {
- _sheetName = _str.left( n );
- str = _str.right( len - n - 1 ); // remove the '!'
- len = str.length();
- }
-
- uint p = 0;
-
- // Fixed ?
- if ( str[0] == '$' )
- {
- _columnFixed = true;
- p++;
- }
- else
- _columnFixed = false;
-
- // Malformed ?
- if ( p == len )
- {
- kdDebug(36001) << "Point::init: no point after '$' (str: '" << str.mid( p ) << "'" << endl;
- return;
- }
- if ( str[p] < 'A' || str[p] > 'Z' )
- {
- if ( str[p] < 'a' || str[p] > 'z' )
- {
- kdDebug(36001) << "Point::init: wrong first character in point (str: '" << str.mid( p ) << "'" << endl;
- return;
- }
- }
- //default is error
- int x = -1;
- //search for the first character != text
- int result = str.find( TQRegExp("[^A-Za-z]+"), p );
-
- //get the colomn number for the character between actual position and the first non text charakter
- if ( result != -1 )
- x = util_decodeColumnLabelText( str.mid( p, result - p ) ); // x is defined now
- else // If there isn't any, then this is not a point -> return
- {
- kdDebug(36001) << "Point::init: no number in string (str: '" << str.mid( p, result ) << "'" << endl;
- return;
- }
- p = result;
-
- //limit is KS_colMax
- if ( x > KS_colMax )
- {
- kdDebug(36001) << "Point::init: column value too high (col: " << x << ")" << endl;
- return;
- }
-
- // Malformed ?
- if (p == len)
- {
- kdDebug(36001) << "Point::init: p==len after cols" << endl;
- return;
- }
-
- if (str[p] == '$')
- {
- _rowFixed = true;
- p++;
- // Malformed ?
- if ( p == len )
- {
- kdDebug(36001) << "Point::init: p==len after $ of row" << endl;
- return;
- }
- }
- else
- _rowFixed = false;
-
- uint p2 = p;
- while ( p < len )
- {
- if ( !isdigit( TQChar(str[p++]) ) )
- {
- kdDebug(36001) << "Point::init: no number" << endl;
- return;
- }
- }
-
- bool ok;
- int y = str.mid( p2, p-p2 ).toInt( &ok );
- if ( !ok )
- {
- kdDebug(36001) << "Point::init: Invalid number (str: '" << str.mid( p2, p-p2 ) << "'" << endl;
- return;
- }
- if ( y > KS_rowMax )
- {
- kdDebug(36001) << "Point::init: row value too high (row: " << y << ")" << endl;
- return;
- }
- if ( y <= 0 )
- {
- kdDebug(36001) << "Point::init: y <= 0" << endl;
- return;
- }
- _pos = TQPoint( x, y );
-}
-
-bool util_isPointValid( TQPoint point )
-{
- if ( point.x() >= 1
- && point.y() >= 1
- && point.x() <= KS_colMax
- && point.y() <= KS_rowMax
- )
- return true;
- else
- return false;
-}
-
-bool util_isRectValid( TQRect rect )
-{
- if ( util_isPointValid( rect.topLeft() )
- && util_isPointValid( rect.bottomRight() )
- )
- return true;
- else
- return false;
-}
-
-Point::Point( const TQString & str, Map * map,
- Sheet * sheet )
-{
-
- uint p = 0;
- int p2 = str.find( '!' );
- if ( p2 != -1 )
- {
- _sheetName = str.left( p2++ );
- while ( true )
- {
- _sheet = map->findSheet( _sheetName );
- if ( !sheet && _sheetName[0] == ' ' )
- {
- _sheetName = _sheetName.right( _sheetName.length() - 1 );
- continue;
- }
- break;
- }
- p = p2;
-
- //If the loop didn't return a sheet, better keep a string for isValid
- if ( _sheetName.isEmpty() )
- {
- kdDebug(36001) << "Point: tableName is unknown" << endl;
- _sheetName = "unknown";
- }
- }
- else
- {
- if ( sheet != 0 )
- {
- _sheet = sheet;
- _sheetName = sheet->sheetName();
- }
- else
- _sheet = 0;
- }
-
- init( str.mid( p ) );
-}
-
-Cell *Point::cell() const
-{
- return _sheet->cellAt(_pos);
-}
-
-bool Point::operator== (const Point &cell) const
-{
- //sheet info ignored
- return (_pos == cell.pos());
-}
-
-bool Point::operator< (const Point &cell) const
-{
- //sheet info ignored
- return (pos().y() < cell.pos().y()) ? true :
- ((pos().y() == cell.pos().y()) && (pos().x() < cell.pos().x()));
-}
-
-bool Range::operator ==(const Range& otherRange) const
-{
- if ( _range == otherRange._range
- && _leftFixed == otherRange._leftFixed
- && _rightFixed == otherRange._rightFixed
- && _bottomFixed == otherRange._bottomFixed
- && _topFixed == otherRange._topFixed
- && _sheet == otherRange._sheet )
- return true;
- else
- return false;
-}
-
-Range::Range()
-{
- _sheet = 0;
- _range.setLeft( -1 );
-
- _leftFixed=false;
- _rightFixed=false;
- _topFixed=false;
- _bottomFixed=false;
-}
-Range::Range(const TQString & _str)
-{
- _range.setLeft(-1);
- _sheet = 0;
-
- int p = _str.find(':');
- // if (p == -1)
- // return;
-
- Point ul;
- Point lr; ;
-
- if ( p != -1)
- {
- ul = Point(_str.left(p));
- lr = Point(_str.mid(p + 1));
- }
- else
- {
- ul = Point(_str);
- lr = ul;
- }
-
- _range = TQRect(ul.pos(), lr.pos());
- _sheetName = ul.sheetName();
-
- _leftFixed = ul.columnFixed();
- _rightFixed = lr.columnFixed();
- _topFixed = ul.rowFixed();
- _bottomFixed = lr.rowFixed();
-}
-
- Range::Range( const Range& r )
- {
- _sheet = r.sheet();
- _sheetName = r.sheetName();
- _range = r.range();
- _namedArea = r.namedArea();
-
- _leftFixed=r._leftFixed;
- _rightFixed=r._rightFixed;
- _topFixed=r._topFixed;
- _bottomFixed=r._bottomFixed;
- }
-
- Range::Range( const Point& ul, const Point& lr )
- {
- _range = TQRect( ul.pos(), lr.pos() );
- if ( ul.sheetName() != lr.sheetName() )
- {
- _range.setLeft( -1 );
- return;
- }
- _sheetName = ul.sheetName();
- _sheet = ul.sheet();
- _leftFixed = ul.columnFixed();
- _rightFixed = lr.columnFixed();
- _topFixed = ul.rowFixed();
- _bottomFixed = lr.rowFixed();
- }
-
-Range::Range(const TQString & str, Map * map,
- Sheet * sheet)
-{
- _range.setLeft(-1);
- _sheet = 0;
-
- //try to parse as named area
- bool gotNamed = false;
- TQString tmp = str.lower();
- TQValueList < Reference >::Iterator it;
- TQValueList < Reference > area = map->doc()->listArea();
- for (it = area.begin(); it != area.end(); ++it) {
- if ((*it).ref_name.lower() == tmp) {
- // success - such named area exists
- _range = (*it).rect;
- _sheet = map->findSheet((*it).sheet_name);
- gotNamed = true;
- _namedArea = tmp;
- break;
- }
- }
- if (gotNamed) {
- // we have a named area - no need to proceed further
- _leftFixed = false;
- _rightFixed = false;
- _topFixed = false;
- _bottomFixed = false;
- return;
- }
-
- _range.setLeft(-1);
- _sheet = 0;
-
- int p = 0;
- int p2 = str.find('!');
- if (p2 != -1)
- {
- _sheetName = str.left(p2++);
- while ( true )
- {
- _sheet = map->findSheet(_sheetName);
-
- if ( !_sheet && _sheetName[0] == ' ' )
- {
- _sheetName = _sheetName.right( _sheetName.length() - 1 );
- continue;
- }
- break;
- }
- p = p2;
- } else
- _sheet = sheet;
-
-
- int p3 = str.find(':', p);
- if (p3 == -1)
- return;
-
- Point ul(str.mid(p, p3 - p));
- Point lr(str.mid(p3 + 1));
- _range = TQRect(ul.pos(), lr.pos());
-
- _leftFixed = ul.columnFixed();
- _rightFixed = lr.columnFixed();
- _topFixed = ul.rowFixed();
- _bottomFixed = lr.rowFixed();
-}
-
-TQString Range::toString() const
-{
- TQString result;
-
- if (_sheet)
- {
- result=util_rangeName(_sheet,_range);
- }
- else
- {
- result=util_rangeName(_range);
- }
-
- //Insert $ characters to show fixed parts of range
-
- int pos=result.find("!")+1;
- Q_ASSERT(pos != -1);
-
- if (_leftFixed)
- {
- result.insert(pos,'$');
- pos++; //Takes account of extra character added in
- }
- if (_topFixed)
- {
- result.insert(pos+Cell::columnName(_range.left()).length(),'$');
- }
-
- pos=result.find(":")+1;
- Q_ASSERT(pos != -1);
-
- if (_rightFixed)
- {
- result.insert(pos,'$');
- pos++; //Takes account of extra character added in
- }
- if (_bottomFixed)
- {
- result.insert(pos+Cell::columnName(_range.right()).length(),'$');
- }
-
-
- return result;
-}
-
-void Range::getStartPoint(Point* pt)
-{
- if (!isValid()) return;
-
- pt->setRow(startRow());
- pt->setColumn(startCol());
- pt->setColumnFixed(_leftFixed);
- pt->setRowFixed(_topFixed);
- pt->setSheet(_sheet);
- pt->setSheetName(_sheetName);
-}
-
-void Range::getEndPoint(Point* pt)
-{
- if (!isValid()) return;
-
- pt->setRow(endRow());
- pt->setColumn(endCol());
- pt->setColumnFixed(_rightFixed);
- pt->setRowFixed(_bottomFixed);
- pt->setSheet(_sheet);
- pt->setSheetName(_sheetName);
-}
-
-bool Range::contains (const Point &cell) const
-{
- return _range.contains (cell.pos());
-}
-
-bool Range::intersects (const Range &r) const
-{
- return _range.intersects (r.range());
-}
-
-bool Range::isValid() const
-{
- return ( _range.left() >= 0 ) &&
- ( _range.right() >= 0 ) &&
- ( _sheet != 0 || _sheetName.isEmpty() ) &&
- ( _range.isValid() ) ;
-}
-
-TQRect Range::range() const
-{
- return _range;
-}
-
-void Range::setLeftFixed(bool fixed)
-{
- _leftFixed=fixed;
-}
-bool Range::leftFixed() const
-{
- return _leftFixed;
-}
-void Range::setRightFixed(bool fixed)
-{
- _rightFixed=fixed;
-}
-bool Range::rightFixed() const
-{
- return _rightFixed;
-}
-void Range::setTopFixed(bool fixed)
-{
- _topFixed=fixed;
-}
-bool Range::topFixed() const
-{
- return _topFixed;
-}
-void Range::setBottomFixed(bool fixed)
-{
- _bottomFixed=fixed;
-}
-bool Range::bottomFixed() const
-{
- return _bottomFixed;
-}
-void Range::setSheet(Sheet* sheet)
-{
- _sheet=sheet;
-}
-KSpread::Sheet* Range::sheet() const
-{
- return _sheet;
-}
-void Range::setSheetName(TQString sheetName)
-{
- _sheetName=sheetName;
-}
-TQString Range::sheetName() const
-{
- return _sheetName;
-}
-TQString Range::namedArea() const
-{
- return _namedArea;
-}
-
-
-bool KSpread::util_isAllSelected(const TQRect &selection)
-{
- return ( selection.top() == 1 && selection.bottom() == KS_rowMax
- && selection.left() == 1 && selection.right() == KS_colMax);
-}
-
-bool KSpread::util_isColumnSelected(const TQRect &selection)
-{
- return ( (selection.top() == 1) && (selection.bottom() == KS_rowMax) );
-}
-
-bool KSpread::util_isRowSelected(const TQRect &selection)
-{
- return ( (selection.left() == 1) && (selection.right() == KS_colMax) );
-}
-
-bool KSpread::util_isRowOrColumnSelected(const TQRect &selection)
-{
- return ( (selection.left() == 1) && (selection.right() == KS_colMax)
- || (selection.top() == 1) && (selection.bottom() == KS_rowMax) );
-}
-
-//used in View::slotRename
-bool KSpread::util_validateSheetName(const TQString &name)
-{
- if (name[0] == ' ')
- {
- return false;
- }
- for (unsigned int i = 0; i < name.length(); i++)
- {
- if ( !(name[i].isLetterOrNumber() ||
- name[i] == ' ' || name[i] == '.' ||
- name[i] == '_'))
- {
- return false;
- }
- }
- return true;
-}
-
-
-RangeIterator::RangeIterator(TQRect _range, Sheet* _sheet)
-{
- range = _range;
- sheet = _sheet;
- current = TQPoint(0,0);
-}
-
-RangeIterator::~RangeIterator()
-{
-}
-
-Cell* RangeIterator::first()
-{
- current.setY(range.top());
-
- /* OK, because even if this equals zero, the 'getNextCellRight' won't
- try to access it*/
- current.setX(range.left() - 1);
- return next();
-}
-
-Cell* RangeIterator::next()
-{
- if (current.x() == 0 && current.y() == 0)
- {
- return first();
- }
-
- Cell* cell = NULL;
- bool done = false;
-
- while (cell == NULL && !done)
- {
- cell = sheet->getNextCellRight(current.x(), current.y());
- if (cell != NULL && cell->column() > range.right())
- {
- cell = NULL;
- }
-
- if (cell == NULL)
- {
- current.setX(range.left() - 1);
- current.setY(current.y() + 1);
- done = (current.y() > range.bottom());
- }
- }
- return cell;
-}
-
-//not used anywhere
-int KSpread::util_penCompare( TQPen const & pen1, TQPen const & pen2 )
-{
- if ( pen1.style() == TQt::NoPen && pen2.style() == TQt::NoPen )
- return 0;
-
- if ( pen1.style() == TQt::NoPen )
- return -1;
-
- if ( pen2.style() == TQt::NoPen )
- return 1;
-
- if ( pen1.width() < pen2.width() )
- return -1;
-
- if ( pen1.width() > pen2.width() )
- return 1;
-
- if ( pen1.style() < pen2.style() )
- return -1;
-
- if ( pen1.style() > pen2.style() )
- return 1;
-
- if ( pen1.color().name() < pen2.color().name() )
- return -1;
-
- if ( pen1.color().name() > pen2.color().name() )
- return 1;
-
- return 0;
-}
-
-
-TQString KSpread::convertRefToBase( const TQString & sheet, const TQRect & rect )
-{
- TQPoint bottomRight( rect.bottomRight() );
-
- TQString s( "$" );
- s += sheet;
- s += ".$";
- s += Cell::columnName( bottomRight.x() );
- s += '$';
- s += TQString::number( bottomRight.y() );
-
- return s;
-}
-
-TQString KSpread::convertRefToRange( const TQString & sheet, const TQRect & rect )
-{
- TQPoint topLeft( rect.topLeft() );
- TQPoint bottomRight( rect.bottomRight() );
-
- if ( topLeft == bottomRight )
- return convertRefToBase( sheet, rect );
-
- TQString s( "$" );
- s += sheet;
- s += ".$";
- s += /*util_encodeColumnLabelText*/Cell::columnName( topLeft.x() );
- s += '$';
- s += TQString::number( topLeft.y() );
- s += ":.$";
- s += /*util_encodeColumnLabelText*/Cell::columnName( bottomRight.x() );
- s += '$';
- s += TQString::number( bottomRight.y() );
-
- return s;
-}
-
-//used in Cell::convertFormulaToOasisFormat
-void KSpread::insertBracket( TQString & s )
-{
- TQChar c;
- int i = (int) s.length() - 1;
-
- while ( i >= 0 )
- {
- c = s[i];
- if ( c == ' ' )
- s[i] = '_';
- if ( !(c.isLetterOrNumber() || c == ' ' || c == '.'
- || c == '_') )
- {
- s.insert( i + 1, '[' );
- return;
- }
- --i;
- }
-}
-
- // e.g.: Sheet4.A1:Sheet4.E28
- //used in Sheet::saveOasis
-TQString KSpread::convertRangeToRef( const TQString & sheetName, const TQRect & _area )
-{
- return sheetName + "." + Cell::name( _area.left(), _area.top() ) + ":" + sheetName + "."+ Cell::name( _area.right(), _area.bottom() );
-}
-
-TQString KSpread::convertOasisPenToString( const TQPen & pen )
-{
-// kdDebug()<<"convertOasisPenToString( const TQPen & pen ) :"<<pen<<endl;
- // NOTE Stefan: TQPen api docs:
- // For horizontal and vertical lines a line width of 0 is
- // the same as a line width of 1.
- // A line width of 0 will produce a 1 pixel wide line using
- // a fast algorithm for diagonals. A line width of 1 will
- // also produce a 1 pixel wide line, but uses a slower more
- // accurate algorithm for diagonals.
- TQString s = TQString( "%1pt " ).arg( (pen.width() == 0) ? 1 : pen.width() );
- switch( pen.style() )
- {
- case TQt::NoPen:
- return "none";
- case TQt::SolidLine:
- s+="solid";
- break;
- case TQt::DashLine:
- s+="dashed";
- break;
- case TQt::DotLine:
- s+="dotted";
- break;
- case TQt::DashDotLine:
- s+="dot-dash";
- break;
- case TQt::DashDotDotLine:
- s+="dot-dot-dash";
- break;
- default: break;
- }
- kdDebug()<<" convertOasisPenToString :"<<s<<endl;
- if ( pen.color().isValid() )
- {
- s+=' ';
- s+=Style::colorName(pen.color());
- }
- return s;
-}
-
-TQPen KSpread::convertOasisStringToPen( const TQString &border )
-{
- TQPen pen;
- //string like "0.088cm solid #800000"
- if (border.isEmpty() || border=="none" || border=="hidden") // in fact no border
- {
- pen.setStyle( Qt::NoPen );
- return pen;
- }
- //code from koborder, for the moment kspread doesn't use koborder
- // ## isn't it faster to use TQStringList::split than parse it 3 times?
- TQString _width = border.section(' ', 0, 0);
- TQCString _style = border.section(' ', 1, 1).latin1();
- TQString _color = border.section(' ', 2, 2);
-
- pen.setWidth( ( int )( KoUnit::parseValue( _width, 1.0 ) ) );
-
- if ( _style =="none" )
- pen.setStyle( Qt::NoPen );
- else if ( _style =="solid" )
- pen.setStyle( Qt::SolidLine );
- else if ( _style =="dashed" )
- pen.setStyle( Qt::DashLine );
- else if ( _style =="dotted" )
- pen.setStyle( Qt::DotLine );
- else if ( _style =="dot-dash" )
- pen.setStyle( Qt::DashDotLine );
- else if ( _style =="dot-dot-dash" )
- pen.setStyle( Qt::DashDotDotLine );
- else
- kdDebug()<<" style undefined : "<<_style<<endl;
-
- if ( _color.isEmpty() )
- pen.setColor( TQColor() );
- else
- pen.setColor( TQColor( _color ) );
-
- return pen;
-}
-
-//Return true when it's a reference to cell from sheet.
-bool KSpread::localReferenceAnchor( const TQString &_ref )
-{
- bool isLocalRef = (_ref.find("http://") != 0 &&
- _ref.find("mailto:") != 0 &&
- _ref.find("ftp://") != 0 &&
- _ref.find("file:") != 0 );
- return isLocalRef;
-}
-
-
-TQString KSpread::Oasis::decodeFormula(const TQString& expr, const TDELocale* locale)
-{
- // parsing state
- enum { Start, InNumber, InString, InIdentifier, InReference, InSheetName } state;
-
- // use locale settings
- TQString decimal = locale ? locale->decimalSymbol() : ".";
-
- // initialize variables
- state = Start;
- unsigned int i = 0;
- const TQString ex = expr;
- TQString result;
-
- if (ex[0] == '=')
- {
- result="=";
- ++i;
- }
-
- // main loop
- while( i < ex.length() )
- {
- TQChar ch = ex[i];
-
- switch( state )
- {
- case Start:
- {
- // check for number
- if( ch.isDigit() )
- {
- state = InNumber;
- }
-
- // a string?
- else if ( ch == '"' )
- {
- state = InString;
- result.append( ex[i++] );
- }
-
- // beginning with alphanumeric ?
- // could be identifier, cell, range, or function...
- else if( isIdentifier( ch ) )
- {
- state = InIdentifier;
- }
-
- // [ marks sheet name for 3-d cell, e.g ['Sales Q3'.A4]
- else if ( ch.unicode() == '[' )
- {
- ++i;
- state = InReference;
- // NOTE Stefan: As long as KSpread does not support fixed sheets eat the dollar sign.
- if ( ex[i] == '$' ) ++i;
- }
-
- // decimal dot ?
- else if ( ch == '.' )
- {
- if ( ex[i+1].isDigit() )
- state = InNumber;
- else
- state = InReference;
- }
-
- // look for operator match
- else
- {
- int op;
- TQString s;
-
- // check for two-chars operator, such as '<=', '>=', etc
- s.append( ch ).append( ex[i+1] );
- op = matchOperator( s );
-
- // check for one-char operator, such as '+', ';', etc
- if( op == Token::InvalidOp )
- {
- s = TQString( ch );
- op = matchOperator( s );
- }
-
- // any matched operator ?
- if ( op == Token::Equal )
- {
- result.append( "==" );
- }
- else
- {
- result.append( s );
- }
- if( op != Token::InvalidOp )
- {
- int len = s.length();
- i += len;
- }
- else
- {
- ++i;
- state = Start;
- }
- }
- break;
- }
- case InReference:
- {
- // consume as long as alpha, dollar sign, underscore, or digit, or colon
- if( isIdentifier( ch ) || ch.isDigit() || ch == ':' )
- result.append( ex[i] );
- else if ( ch == '.' && i > 0 && ex[i-1] != '[' && ex[i-1] != ':' )
- result.append( '!' );
- else if( ch == ']' )
- state = Start;
- else if ( ch == '\'' )
- {
- result.append( ex[i] );
- state = InSheetName;
- // NOTE Stefan: As long as KSpread does not support fixed sheets eat the dollar sign.
- if ( ex[i] == '$' ) ++i;
- }
- else if ( ch != '.' )
- {
- state = Start;
- break;
- }
- ++i;
- break;
- }
- case InSheetName:
- {
- if ( ch == '\'' )
- state = InReference;
- result.append( ex[i] );
- ++i;
- break;
- }
- case InNumber:
- {
- // consume as long as it's digit
- if( ch.isDigit() )
- result.append( ex[i++] );
- // convert '.' to decimal separator
- else if ( ch == '.' )
- {
- result.append( decimal );
- ++i;
- }
- // exponent ?
- else if( ch.upper() == 'E' )
- {
- result.append( 'E' );
- ++i;
- }
- // we're done with integer number
- else
- state = Start;
- break;
- }
- case InString:
- {
- // consume until "
- if( ch != '"' )
- {
- result.append( ex[i++] );
- }
- // we're done
- else
- {
- result.append( ch );
- ++i;
- state = Start;
- }
- break;
- }
- case InIdentifier:
- {
- // consume as long as alpha, dollar sign, underscore, or digit
- if( isIdentifier( ch ) || ch.isDigit() )
- result.append( ex[i++] );
- // we're done
- else
- state = Start;
- break;
- }
- default:
- break;
- }
- }
- return result;
-}
-
-/*TQString KSpread::Oasis::encodeFormula(const TQString& expr, const TDELocale* locale)
-{
- // TODO move Cell::convertFormulaToOasisFormat to this point
- //expr = "not here yet";
- //Q_UNUSED(locale);
- kdDebug() << k_funcinfo << " not implemented"
- tqFatal(0);
-}*/
diff --git a/kspread/kspread_util.cpp b/kspread/kspread_util.cpp
new file mode 100644
index 000000000..c7b28af12
--- /dev/null
+++ b/kspread/kspread_util.cpp
@@ -0,0 +1,1218 @@
+/* This file is part of the KDE project
+ Copyright (C) 2006 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <ctype.h>
+
+#include <tqregexp.h>
+
+#include <kdebug.h>
+
+#include "formula.h"
+#include "kspread_doc.h"
+#include "kspread_locale.h"
+#include "kspread_map.h"
+#include "kspread_sheet.h"
+#include "kspread_style.h"
+#include "kspread_util.h"
+
+using namespace KSpread;
+
+//helper functions for the formatting
+bool KSpread::formatIsDate (FormatType fmt)
+{
+ return ((fmt == ShortDate_format) || (fmt == TextDate_format) ||
+ (((int) fmt >= 200) && ((int) fmt < 300)));
+}
+
+bool KSpread::formatIsTime (FormatType fmt)
+{
+ return (((int) fmt >= 50) && ((int) fmt < 70));
+}
+
+bool KSpread::formatIsFraction (FormatType fmt)
+{
+ return (((int) fmt >= 70) && ((int) fmt < 80));
+}
+
+
+//used in Point::init, Cell::encodeFormula and
+// dialogs/kspread_dlg_paperlayout.cpp
+int KSpread::util_decodeColumnLabelText( const TQString &_col )
+{
+ int col = 0;
+ int offset='a'-'A';
+ int counterColumn = 0;
+ for ( uint i=0; i < _col.length(); i++ )
+ {
+ counterColumn = (int) pow(26.0 , static_cast<int>(_col.length() - i - 1));
+ if( (int)(_col[i]) >= 'A' && (int)(_col[i]) <= 'Z' )
+ col += counterColumn * ( _col[i].latin1() - 'A' + 1); // okay here (Werner)
+ else if( (int)(_col[i]) >= 'a' && (int)(_col[i]) <= 'z' )
+ col += counterColumn * ( _col[i].latin1() - 'A' - offset + 1 );
+ else
+ kdDebug(36001) << "util_decodeColumnLabelText: Wrong characters in label text for col:'" << _col << "'" << endl;
+ }
+ return col;
+}
+
+//used in dialogs/kspread_dlg_paperlayout.cpp
+TQString KSpread::util_rangeColumnName( const TQRect &_area)
+{
+ return TQString("%1:%2")
+ .arg( Cell::columnName( _area.left()))
+ .arg( Cell::columnName(_area.right()));
+}
+
+//used in dialogs/kspread_dlg_paperlayout.cpp
+TQString KSpread::util_rangeRowName( const TQRect &_area)
+{
+ return TQString("%1:%2")
+ .arg( _area.top())
+ .arg(_area.bottom());
+}
+
+TQString KSpread::util_rangeName(const TQRect &_area)
+{
+ return Cell::name( _area.left(), _area.top() ) + ":" +
+ Cell::name( _area.right(), _area.bottom() );
+}
+
+TQString KSpread::util_rangeName(Sheet * _sheet, const TQRect &_area)
+{
+ return _sheet->sheetName() + "!" + util_rangeName(_area);
+}
+
+TQDomElement KSpread::util_createElement( const TQString & tagName, const TQFont & font, TQDomDocument & doc )
+{
+ TQDomElement e( doc.createElement( tagName ) );
+
+ e.setAttribute( "family", font.family() );
+ e.setAttribute( "size", font.pointSize() );
+ e.setAttribute( "weight", font.weight() );
+ if ( font.bold() )
+ e.setAttribute( "bold", "yes" );
+ if ( font.italic() )
+ e.setAttribute( "italic", "yes" );
+ if ( font.underline() )
+ e.setAttribute( "underline", "yes" );
+ if ( font.strikeOut() )
+ e.setAttribute( "strikeout", "yes" );
+ //e.setAttribute( "charset", TDEGlobal::charsets()->name( font ) );
+
+ return e;
+}
+
+TQDomElement KSpread::util_createElement( const TQString & tagname, const TQPen & pen, TQDomDocument & doc )
+{
+ TQDomElement e( doc.createElement( tagname ) );
+ e.setAttribute( "color", pen.color().name() );
+ e.setAttribute( "style", (int)pen.style() );
+ e.setAttribute( "width", (int)pen.width() );
+ return e;
+}
+
+TQFont KSpread::util_toFont( TQDomElement & element )
+{
+ TQFont f;
+ f.setFamily( element.attribute( "family" ) );
+
+ bool ok;
+ f.setPointSize( element.attribute("size").toInt( &ok ) );
+ if ( !ok )
+ return TQFont();
+
+ f.setWeight( element.attribute("weight").toInt( &ok ) );
+ if ( !ok )
+ return TQFont();
+
+ if ( element.hasAttribute( "italic" ) && element.attribute("italic") == "yes" )
+ f.setItalic( true );
+
+ if ( element.hasAttribute( "bold" ) && element.attribute("bold") == "yes" )
+ f.setBold( true );
+
+ if ( element.hasAttribute( "underline" ) && element.attribute("underline") == "yes" )
+ f.setUnderline( true );
+
+ if ( element.hasAttribute( "strikeout" ) && element.attribute("strikeout") == "yes" )
+ f.setStrikeOut( true );
+
+ /* Uncomment when charset is added to kspread_dlg_layout
+ + save a document-global charset
+ if ( element.hasAttribute( "charset" ) )
+ TDEGlobal::charsets()->setTQFont( f, element.attribute("charset") );
+ else
+ */
+ // ######## Not needed anymore in 3.0?
+ //TDEGlobal::charsets()->setTQFont( f, TDEGlobal::locale()->charset() );
+
+ return f;
+}
+
+TQPen KSpread::util_toPen( TQDomElement & element )
+{
+ bool ok;
+ TQPen p;
+
+ p.setStyle( (Qt::PenStyle)element.attribute("style").toInt( &ok ) );
+ if ( !ok )
+ return TQPen();
+
+ p.setWidth( element.attribute("width").toInt( &ok ) );
+ if ( !ok )
+ return TQPen();
+
+ p.setColor( TQColor( element.attribute("color") ) );
+
+ return p;
+}
+
+Point::Point(const TQString & _str)
+{
+ _sheet = 0;
+ init(_str);
+}
+
+void Point::setPos(TQPoint pos)
+{
+ _pos=pos;
+}
+TQPoint Point::pos() const
+{
+ return _pos;
+}
+void Point::setSheet(Sheet* sheet)
+{
+ _sheet=sheet;
+}
+KSpread::Sheet* Point::sheet() const
+{
+ return _sheet;
+}
+void Point::setSheetName(TQString name)
+{
+ _sheetName=name;
+}
+TQString Point::sheetName() const
+{
+ return _sheetName;
+}
+void Point::setColumnFixed(bool colFixed)
+{
+ _columnFixed=colFixed;
+}
+bool Point::columnFixed() const
+{
+ return _columnFixed;
+}
+void Point::setRowFixed(bool rowFixed)
+{
+ _rowFixed=rowFixed;
+}
+bool Point::rowFixed() const
+{
+ return _rowFixed;
+}
+
+
+void Point::init(const TQString & _str)
+{
+ _columnFixed=false;
+ _rowFixed=false;
+
+// kdDebug(36001) <<"Point::init ("<<_str<<")"<<endl;
+ _pos.setX(-1);
+
+ uint len = _str.length();
+ if ( !len )
+ {
+ kdDebug(36001) << "Point::init: len = 0" << endl;
+ return;
+ }
+
+ TQString str( _str );
+ int n = _str.find( '!' );
+ if ( n != -1 )
+ {
+ _sheetName = _str.left( n );
+ str = _str.right( len - n - 1 ); // remove the '!'
+ len = str.length();
+ }
+
+ uint p = 0;
+
+ // Fixed ?
+ if ( str[0] == '$' )
+ {
+ _columnFixed = true;
+ p++;
+ }
+ else
+ _columnFixed = false;
+
+ // Malformed ?
+ if ( p == len )
+ {
+ kdDebug(36001) << "Point::init: no point after '$' (str: '" << str.mid( p ) << "'" << endl;
+ return;
+ }
+ if ( str[p] < 'A' || str[p] > 'Z' )
+ {
+ if ( str[p] < 'a' || str[p] > 'z' )
+ {
+ kdDebug(36001) << "Point::init: wrong first character in point (str: '" << str.mid( p ) << "'" << endl;
+ return;
+ }
+ }
+ //default is error
+ int x = -1;
+ //search for the first character != text
+ int result = str.find( TQRegExp("[^A-Za-z]+"), p );
+
+ //get the colomn number for the character between actual position and the first non text charakter
+ if ( result != -1 )
+ x = util_decodeColumnLabelText( str.mid( p, result - p ) ); // x is defined now
+ else // If there isn't any, then this is not a point -> return
+ {
+ kdDebug(36001) << "Point::init: no number in string (str: '" << str.mid( p, result ) << "'" << endl;
+ return;
+ }
+ p = result;
+
+ //limit is KS_colMax
+ if ( x > KS_colMax )
+ {
+ kdDebug(36001) << "Point::init: column value too high (col: " << x << ")" << endl;
+ return;
+ }
+
+ // Malformed ?
+ if (p == len)
+ {
+ kdDebug(36001) << "Point::init: p==len after cols" << endl;
+ return;
+ }
+
+ if (str[p] == '$')
+ {
+ _rowFixed = true;
+ p++;
+ // Malformed ?
+ if ( p == len )
+ {
+ kdDebug(36001) << "Point::init: p==len after $ of row" << endl;
+ return;
+ }
+ }
+ else
+ _rowFixed = false;
+
+ uint p2 = p;
+ while ( p < len )
+ {
+ if ( !isdigit( TQChar(str[p++]) ) )
+ {
+ kdDebug(36001) << "Point::init: no number" << endl;
+ return;
+ }
+ }
+
+ bool ok;
+ int y = str.mid( p2, p-p2 ).toInt( &ok );
+ if ( !ok )
+ {
+ kdDebug(36001) << "Point::init: Invalid number (str: '" << str.mid( p2, p-p2 ) << "'" << endl;
+ return;
+ }
+ if ( y > KS_rowMax )
+ {
+ kdDebug(36001) << "Point::init: row value too high (row: " << y << ")" << endl;
+ return;
+ }
+ if ( y <= 0 )
+ {
+ kdDebug(36001) << "Point::init: y <= 0" << endl;
+ return;
+ }
+ _pos = TQPoint( x, y );
+}
+
+bool util_isPointValid( TQPoint point )
+{
+ if ( point.x() >= 1
+ && point.y() >= 1
+ && point.x() <= KS_colMax
+ && point.y() <= KS_rowMax
+ )
+ return true;
+ else
+ return false;
+}
+
+bool util_isRectValid( TQRect rect )
+{
+ if ( util_isPointValid( rect.topLeft() )
+ && util_isPointValid( rect.bottomRight() )
+ )
+ return true;
+ else
+ return false;
+}
+
+Point::Point( const TQString & str, Map * map,
+ Sheet * sheet )
+{
+
+ uint p = 0;
+ int p2 = str.find( '!' );
+ if ( p2 != -1 )
+ {
+ _sheetName = str.left( p2++ );
+ while ( true )
+ {
+ _sheet = map->findSheet( _sheetName );
+ if ( !sheet && _sheetName[0] == ' ' )
+ {
+ _sheetName = _sheetName.right( _sheetName.length() - 1 );
+ continue;
+ }
+ break;
+ }
+ p = p2;
+
+ //If the loop didn't return a sheet, better keep a string for isValid
+ if ( _sheetName.isEmpty() )
+ {
+ kdDebug(36001) << "Point: tableName is unknown" << endl;
+ _sheetName = "unknown";
+ }
+ }
+ else
+ {
+ if ( sheet != 0 )
+ {
+ _sheet = sheet;
+ _sheetName = sheet->sheetName();
+ }
+ else
+ _sheet = 0;
+ }
+
+ init( str.mid( p ) );
+}
+
+Cell *Point::cell() const
+{
+ return _sheet->cellAt(_pos);
+}
+
+bool Point::operator== (const Point &cell) const
+{
+ //sheet info ignored
+ return (_pos == cell.pos());
+}
+
+bool Point::operator< (const Point &cell) const
+{
+ //sheet info ignored
+ return (pos().y() < cell.pos().y()) ? true :
+ ((pos().y() == cell.pos().y()) && (pos().x() < cell.pos().x()));
+}
+
+bool Range::operator ==(const Range& otherRange) const
+{
+ if ( _range == otherRange._range
+ && _leftFixed == otherRange._leftFixed
+ && _rightFixed == otherRange._rightFixed
+ && _bottomFixed == otherRange._bottomFixed
+ && _topFixed == otherRange._topFixed
+ && _sheet == otherRange._sheet )
+ return true;
+ else
+ return false;
+}
+
+Range::Range()
+{
+ _sheet = 0;
+ _range.setLeft( -1 );
+
+ _leftFixed=false;
+ _rightFixed=false;
+ _topFixed=false;
+ _bottomFixed=false;
+}
+Range::Range(const TQString & _str)
+{
+ _range.setLeft(-1);
+ _sheet = 0;
+
+ int p = _str.find(':');
+ // if (p == -1)
+ // return;
+
+ Point ul;
+ Point lr; ;
+
+ if ( p != -1)
+ {
+ ul = Point(_str.left(p));
+ lr = Point(_str.mid(p + 1));
+ }
+ else
+ {
+ ul = Point(_str);
+ lr = ul;
+ }
+
+ _range = TQRect(ul.pos(), lr.pos());
+ _sheetName = ul.sheetName();
+
+ _leftFixed = ul.columnFixed();
+ _rightFixed = lr.columnFixed();
+ _topFixed = ul.rowFixed();
+ _bottomFixed = lr.rowFixed();
+}
+
+ Range::Range( const Range& r )
+ {
+ _sheet = r.sheet();
+ _sheetName = r.sheetName();
+ _range = r.range();
+ _namedArea = r.namedArea();
+
+ _leftFixed=r._leftFixed;
+ _rightFixed=r._rightFixed;
+ _topFixed=r._topFixed;
+ _bottomFixed=r._bottomFixed;
+ }
+
+ Range::Range( const Point& ul, const Point& lr )
+ {
+ _range = TQRect( ul.pos(), lr.pos() );
+ if ( ul.sheetName() != lr.sheetName() )
+ {
+ _range.setLeft( -1 );
+ return;
+ }
+ _sheetName = ul.sheetName();
+ _sheet = ul.sheet();
+ _leftFixed = ul.columnFixed();
+ _rightFixed = lr.columnFixed();
+ _topFixed = ul.rowFixed();
+ _bottomFixed = lr.rowFixed();
+ }
+
+Range::Range(const TQString & str, Map * map,
+ Sheet * sheet)
+{
+ _range.setLeft(-1);
+ _sheet = 0;
+
+ //try to parse as named area
+ bool gotNamed = false;
+ TQString tmp = str.lower();
+ TQValueList < Reference >::Iterator it;
+ TQValueList < Reference > area = map->doc()->listArea();
+ for (it = area.begin(); it != area.end(); ++it) {
+ if ((*it).ref_name.lower() == tmp) {
+ // success - such named area exists
+ _range = (*it).rect;
+ _sheet = map->findSheet((*it).sheet_name);
+ gotNamed = true;
+ _namedArea = tmp;
+ break;
+ }
+ }
+ if (gotNamed) {
+ // we have a named area - no need to proceed further
+ _leftFixed = false;
+ _rightFixed = false;
+ _topFixed = false;
+ _bottomFixed = false;
+ return;
+ }
+
+ _range.setLeft(-1);
+ _sheet = 0;
+
+ int p = 0;
+ int p2 = str.find('!');
+ if (p2 != -1)
+ {
+ _sheetName = str.left(p2++);
+ while ( true )
+ {
+ _sheet = map->findSheet(_sheetName);
+
+ if ( !_sheet && _sheetName[0] == ' ' )
+ {
+ _sheetName = _sheetName.right( _sheetName.length() - 1 );
+ continue;
+ }
+ break;
+ }
+ p = p2;
+ } else
+ _sheet = sheet;
+
+
+ int p3 = str.find(':', p);
+ if (p3 == -1)
+ return;
+
+ Point ul(str.mid(p, p3 - p));
+ Point lr(str.mid(p3 + 1));
+ _range = TQRect(ul.pos(), lr.pos());
+
+ _leftFixed = ul.columnFixed();
+ _rightFixed = lr.columnFixed();
+ _topFixed = ul.rowFixed();
+ _bottomFixed = lr.rowFixed();
+}
+
+TQString Range::toString() const
+{
+ TQString result;
+
+ if (_sheet)
+ {
+ result=util_rangeName(_sheet,_range);
+ }
+ else
+ {
+ result=util_rangeName(_range);
+ }
+
+ //Insert $ characters to show fixed parts of range
+
+ int pos=result.find("!")+1;
+ Q_ASSERT(pos != -1);
+
+ if (_leftFixed)
+ {
+ result.insert(pos,'$');
+ pos++; //Takes account of extra character added in
+ }
+ if (_topFixed)
+ {
+ result.insert(pos+Cell::columnName(_range.left()).length(),'$');
+ }
+
+ pos=result.find(":")+1;
+ Q_ASSERT(pos != -1);
+
+ if (_rightFixed)
+ {
+ result.insert(pos,'$');
+ pos++; //Takes account of extra character added in
+ }
+ if (_bottomFixed)
+ {
+ result.insert(pos+Cell::columnName(_range.right()).length(),'$');
+ }
+
+
+ return result;
+}
+
+void Range::getStartPoint(Point* pt)
+{
+ if (!isValid()) return;
+
+ pt->setRow(startRow());
+ pt->setColumn(startCol());
+ pt->setColumnFixed(_leftFixed);
+ pt->setRowFixed(_topFixed);
+ pt->setSheet(_sheet);
+ pt->setSheetName(_sheetName);
+}
+
+void Range::getEndPoint(Point* pt)
+{
+ if (!isValid()) return;
+
+ pt->setRow(endRow());
+ pt->setColumn(endCol());
+ pt->setColumnFixed(_rightFixed);
+ pt->setRowFixed(_bottomFixed);
+ pt->setSheet(_sheet);
+ pt->setSheetName(_sheetName);
+}
+
+bool Range::contains (const Point &cell) const
+{
+ return _range.contains (cell.pos());
+}
+
+bool Range::intersects (const Range &r) const
+{
+ return _range.intersects (r.range());
+}
+
+bool Range::isValid() const
+{
+ return ( _range.left() >= 0 ) &&
+ ( _range.right() >= 0 ) &&
+ ( _sheet != 0 || _sheetName.isEmpty() ) &&
+ ( _range.isValid() ) ;
+}
+
+TQRect Range::range() const
+{
+ return _range;
+}
+
+void Range::setLeftFixed(bool fixed)
+{
+ _leftFixed=fixed;
+}
+bool Range::leftFixed() const
+{
+ return _leftFixed;
+}
+void Range::setRightFixed(bool fixed)
+{
+ _rightFixed=fixed;
+}
+bool Range::rightFixed() const
+{
+ return _rightFixed;
+}
+void Range::setTopFixed(bool fixed)
+{
+ _topFixed=fixed;
+}
+bool Range::topFixed() const
+{
+ return _topFixed;
+}
+void Range::setBottomFixed(bool fixed)
+{
+ _bottomFixed=fixed;
+}
+bool Range::bottomFixed() const
+{
+ return _bottomFixed;
+}
+void Range::setSheet(Sheet* sheet)
+{
+ _sheet=sheet;
+}
+KSpread::Sheet* Range::sheet() const
+{
+ return _sheet;
+}
+void Range::setSheetName(TQString sheetName)
+{
+ _sheetName=sheetName;
+}
+TQString Range::sheetName() const
+{
+ return _sheetName;
+}
+TQString Range::namedArea() const
+{
+ return _namedArea;
+}
+
+
+bool KSpread::util_isAllSelected(const TQRect &selection)
+{
+ return ( selection.top() == 1 && selection.bottom() == KS_rowMax
+ && selection.left() == 1 && selection.right() == KS_colMax);
+}
+
+bool KSpread::util_isColumnSelected(const TQRect &selection)
+{
+ return ( (selection.top() == 1) && (selection.bottom() == KS_rowMax) );
+}
+
+bool KSpread::util_isRowSelected(const TQRect &selection)
+{
+ return ( (selection.left() == 1) && (selection.right() == KS_colMax) );
+}
+
+bool KSpread::util_isRowOrColumnSelected(const TQRect &selection)
+{
+ return ( (selection.left() == 1) && (selection.right() == KS_colMax)
+ || (selection.top() == 1) && (selection.bottom() == KS_rowMax) );
+}
+
+//used in View::slotRename
+bool KSpread::util_validateSheetName(const TQString &name)
+{
+ if (name[0] == ' ')
+ {
+ return false;
+ }
+ for (unsigned int i = 0; i < name.length(); i++)
+ {
+ if ( !(name[i].isLetterOrNumber() ||
+ name[i] == ' ' || name[i] == '.' ||
+ name[i] == '_'))
+ {
+ return false;
+ }
+ }
+ return true;
+}
+
+
+RangeIterator::RangeIterator(TQRect _range, Sheet* _sheet)
+{
+ range = _range;
+ sheet = _sheet;
+ current = TQPoint(0,0);
+}
+
+RangeIterator::~RangeIterator()
+{
+}
+
+Cell* RangeIterator::first()
+{
+ current.setY(range.top());
+
+ /* OK, because even if this equals zero, the 'getNextCellRight' won't
+ try to access it*/
+ current.setX(range.left() - 1);
+ return next();
+}
+
+Cell* RangeIterator::next()
+{
+ if (current.x() == 0 && current.y() == 0)
+ {
+ return first();
+ }
+
+ Cell* cell = NULL;
+ bool done = false;
+
+ while (cell == NULL && !done)
+ {
+ cell = sheet->getNextCellRight(current.x(), current.y());
+ if (cell != NULL && cell->column() > range.right())
+ {
+ cell = NULL;
+ }
+
+ if (cell == NULL)
+ {
+ current.setX(range.left() - 1);
+ current.setY(current.y() + 1);
+ done = (current.y() > range.bottom());
+ }
+ }
+ return cell;
+}
+
+//not used anywhere
+int KSpread::util_penCompare( TQPen const & pen1, TQPen const & pen2 )
+{
+ if ( pen1.style() == TQt::NoPen && pen2.style() == TQt::NoPen )
+ return 0;
+
+ if ( pen1.style() == TQt::NoPen )
+ return -1;
+
+ if ( pen2.style() == TQt::NoPen )
+ return 1;
+
+ if ( pen1.width() < pen2.width() )
+ return -1;
+
+ if ( pen1.width() > pen2.width() )
+ return 1;
+
+ if ( pen1.style() < pen2.style() )
+ return -1;
+
+ if ( pen1.style() > pen2.style() )
+ return 1;
+
+ if ( pen1.color().name() < pen2.color().name() )
+ return -1;
+
+ if ( pen1.color().name() > pen2.color().name() )
+ return 1;
+
+ return 0;
+}
+
+
+TQString KSpread::convertRefToBase( const TQString & sheet, const TQRect & rect )
+{
+ TQPoint bottomRight( rect.bottomRight() );
+
+ TQString s( "$" );
+ s += sheet;
+ s += ".$";
+ s += Cell::columnName( bottomRight.x() );
+ s += '$';
+ s += TQString::number( bottomRight.y() );
+
+ return s;
+}
+
+TQString KSpread::convertRefToRange( const TQString & sheet, const TQRect & rect )
+{
+ TQPoint topLeft( rect.topLeft() );
+ TQPoint bottomRight( rect.bottomRight() );
+
+ if ( topLeft == bottomRight )
+ return convertRefToBase( sheet, rect );
+
+ TQString s( "$" );
+ s += sheet;
+ s += ".$";
+ s += /*util_encodeColumnLabelText*/Cell::columnName( topLeft.x() );
+ s += '$';
+ s += TQString::number( topLeft.y() );
+ s += ":.$";
+ s += /*util_encodeColumnLabelText*/Cell::columnName( bottomRight.x() );
+ s += '$';
+ s += TQString::number( bottomRight.y() );
+
+ return s;
+}
+
+//used in Cell::convertFormulaToOasisFormat
+void KSpread::insertBracket( TQString & s )
+{
+ TQChar c;
+ int i = (int) s.length() - 1;
+
+ while ( i >= 0 )
+ {
+ c = s[i];
+ if ( c == ' ' )
+ s[i] = '_';
+ if ( !(c.isLetterOrNumber() || c == ' ' || c == '.'
+ || c == '_') )
+ {
+ s.insert( i + 1, '[' );
+ return;
+ }
+ --i;
+ }
+}
+
+ // e.g.: Sheet4.A1:Sheet4.E28
+ //used in Sheet::saveOasis
+TQString KSpread::convertRangeToRef( const TQString & sheetName, const TQRect & _area )
+{
+ return sheetName + "." + Cell::name( _area.left(), _area.top() ) + ":" + sheetName + "."+ Cell::name( _area.right(), _area.bottom() );
+}
+
+TQString KSpread::convertOasisPenToString( const TQPen & pen )
+{
+// kdDebug()<<"convertOasisPenToString( const TQPen & pen ) :"<<pen<<endl;
+ // NOTE Stefan: TQPen api docs:
+ // For horizontal and vertical lines a line width of 0 is
+ // the same as a line width of 1.
+ // A line width of 0 will produce a 1 pixel wide line using
+ // a fast algorithm for diagonals. A line width of 1 will
+ // also produce a 1 pixel wide line, but uses a slower more
+ // accurate algorithm for diagonals.
+ TQString s = TQString( "%1pt " ).arg( (pen.width() == 0) ? 1 : pen.width() );
+ switch( pen.style() )
+ {
+ case TQt::NoPen:
+ return "none";
+ case TQt::SolidLine:
+ s+="solid";
+ break;
+ case TQt::DashLine:
+ s+="dashed";
+ break;
+ case TQt::DotLine:
+ s+="dotted";
+ break;
+ case TQt::DashDotLine:
+ s+="dot-dash";
+ break;
+ case TQt::DashDotDotLine:
+ s+="dot-dot-dash";
+ break;
+ default: break;
+ }
+ kdDebug()<<" convertOasisPenToString :"<<s<<endl;
+ if ( pen.color().isValid() )
+ {
+ s+=' ';
+ s+=Style::colorName(pen.color());
+ }
+ return s;
+}
+
+TQPen KSpread::convertOasisStringToPen( const TQString &border )
+{
+ TQPen pen;
+ //string like "0.088cm solid #800000"
+ if (border.isEmpty() || border=="none" || border=="hidden") // in fact no border
+ {
+ pen.setStyle( Qt::NoPen );
+ return pen;
+ }
+ //code from koborder, for the moment kspread doesn't use koborder
+ // ## isn't it faster to use TQStringList::split than parse it 3 times?
+ TQString _width = border.section(' ', 0, 0);
+ TQCString _style = border.section(' ', 1, 1).latin1();
+ TQString _color = border.section(' ', 2, 2);
+
+ pen.setWidth( ( int )( KoUnit::parseValue( _width, 1.0 ) ) );
+
+ if ( _style =="none" )
+ pen.setStyle( Qt::NoPen );
+ else if ( _style =="solid" )
+ pen.setStyle( Qt::SolidLine );
+ else if ( _style =="dashed" )
+ pen.setStyle( Qt::DashLine );
+ else if ( _style =="dotted" )
+ pen.setStyle( Qt::DotLine );
+ else if ( _style =="dot-dash" )
+ pen.setStyle( Qt::DashDotLine );
+ else if ( _style =="dot-dot-dash" )
+ pen.setStyle( Qt::DashDotDotLine );
+ else
+ kdDebug()<<" style undefined : "<<_style<<endl;
+
+ if ( _color.isEmpty() )
+ pen.setColor( TQColor() );
+ else
+ pen.setColor( TQColor( _color ) );
+
+ return pen;
+}
+
+//Return true when it's a reference to cell from sheet.
+bool KSpread::localReferenceAnchor( const TQString &_ref )
+{
+ bool isLocalRef = (_ref.find("http://") != 0 &&
+ _ref.find("mailto:") != 0 &&
+ _ref.find("ftp://") != 0 &&
+ _ref.find("file:") != 0 );
+ return isLocalRef;
+}
+
+
+TQString KSpread::Oasis::decodeFormula(const TQString& expr, const TDELocale* locale)
+{
+ // parsing state
+ enum { Start, InNumber, InString, InIdentifier, InReference, InSheetName } state;
+
+ // use locale settings
+ TQString decimal = locale ? locale->decimalSymbol() : ".";
+
+ // initialize variables
+ state = Start;
+ unsigned int i = 0;
+ const TQString ex = expr;
+ TQString result;
+
+ if (ex[0] == '=')
+ {
+ result="=";
+ ++i;
+ }
+
+ // main loop
+ while( i < ex.length() )
+ {
+ TQChar ch = ex[i];
+
+ switch( state )
+ {
+ case Start:
+ {
+ // check for number
+ if( ch.isDigit() )
+ {
+ state = InNumber;
+ }
+
+ // a string?
+ else if ( ch == '"' )
+ {
+ state = InString;
+ result.append( ex[i++] );
+ }
+
+ // beginning with alphanumeric ?
+ // could be identifier, cell, range, or function...
+ else if( isIdentifier( ch ) )
+ {
+ state = InIdentifier;
+ }
+
+ // [ marks sheet name for 3-d cell, e.g ['Sales Q3'.A4]
+ else if ( ch.unicode() == '[' )
+ {
+ ++i;
+ state = InReference;
+ // NOTE Stefan: As long as KSpread does not support fixed sheets eat the dollar sign.
+ if ( ex[i] == '$' ) ++i;
+ }
+
+ // decimal dot ?
+ else if ( ch == '.' )
+ {
+ if ( ex[i+1].isDigit() )
+ state = InNumber;
+ else
+ state = InReference;
+ }
+
+ // look for operator match
+ else
+ {
+ int op;
+ TQString s;
+
+ // check for two-chars operator, such as '<=', '>=', etc
+ s.append( ch ).append( ex[i+1] );
+ op = matchOperator( s );
+
+ // check for one-char operator, such as '+', ';', etc
+ if( op == Token::InvalidOp )
+ {
+ s = TQString( ch );
+ op = matchOperator( s );
+ }
+
+ // any matched operator ?
+ if ( op == Token::Equal )
+ {
+ result.append( "==" );
+ }
+ else
+ {
+ result.append( s );
+ }
+ if( op != Token::InvalidOp )
+ {
+ int len = s.length();
+ i += len;
+ }
+ else
+ {
+ ++i;
+ state = Start;
+ }
+ }
+ break;
+ }
+ case InReference:
+ {
+ // consume as long as alpha, dollar sign, underscore, or digit, or colon
+ if( isIdentifier( ch ) || ch.isDigit() || ch == ':' )
+ result.append( ex[i] );
+ else if ( ch == '.' && i > 0 && ex[i-1] != '[' && ex[i-1] != ':' )
+ result.append( '!' );
+ else if( ch == ']' )
+ state = Start;
+ else if ( ch == '\'' )
+ {
+ result.append( ex[i] );
+ state = InSheetName;
+ // NOTE Stefan: As long as KSpread does not support fixed sheets eat the dollar sign.
+ if ( ex[i] == '$' ) ++i;
+ }
+ else if ( ch != '.' )
+ {
+ state = Start;
+ break;
+ }
+ ++i;
+ break;
+ }
+ case InSheetName:
+ {
+ if ( ch == '\'' )
+ state = InReference;
+ result.append( ex[i] );
+ ++i;
+ break;
+ }
+ case InNumber:
+ {
+ // consume as long as it's digit
+ if( ch.isDigit() )
+ result.append( ex[i++] );
+ // convert '.' to decimal separator
+ else if ( ch == '.' )
+ {
+ result.append( decimal );
+ ++i;
+ }
+ // exponent ?
+ else if( ch.upper() == 'E' )
+ {
+ result.append( 'E' );
+ ++i;
+ }
+ // we're done with integer number
+ else
+ state = Start;
+ break;
+ }
+ case InString:
+ {
+ // consume until "
+ if( ch != '"' )
+ {
+ result.append( ex[i++] );
+ }
+ // we're done
+ else
+ {
+ result.append( ch );
+ ++i;
+ state = Start;
+ }
+ break;
+ }
+ case InIdentifier:
+ {
+ // consume as long as alpha, dollar sign, underscore, or digit
+ if( isIdentifier( ch ) || ch.isDigit() )
+ result.append( ex[i++] );
+ // we're done
+ else
+ state = Start;
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ return result;
+}
+
+/*TQString KSpread::Oasis::encodeFormula(const TQString& expr, const TDELocale* locale)
+{
+ // TODO move Cell::convertFormulaToOasisFormat to this point
+ //expr = "not here yet";
+ //Q_UNUSED(locale);
+ kdDebug() << k_funcinfo << " not implemented"
+ tqFatal(0);
+}*/
diff --git a/kspread/kspread_value.cc b/kspread/kspread_value.cpp
index 898abd11b..898abd11b 100644
--- a/kspread/kspread_value.cc
+++ b/kspread/kspread_value.cpp
diff --git a/kspread/kspread_view.cc b/kspread/kspread_view.cpp
index 519e4425a..519e4425a 100644
--- a/kspread/kspread_view.cc
+++ b/kspread/kspread_view.cpp
diff --git a/kspread/main.cc b/kspread/main.cpp
index dd5962781..dd5962781 100644
--- a/kspread/main.cc
+++ b/kspread/main.cpp
diff --git a/kspread/manipulator.cc b/kspread/manipulator.cpp
index b8b603c8f..b8b603c8f 100644
--- a/kspread/manipulator.cc
+++ b/kspread/manipulator.cpp
diff --git a/kspread/manipulator_data.cc b/kspread/manipulator_data.cpp
index af2317225..af2317225 100644
--- a/kspread/manipulator_data.cc
+++ b/kspread/manipulator_data.cpp
diff --git a/kspread/plugins/insertcalendar/Makefile.am b/kspread/plugins/insertcalendar/Makefile.am
index f8b72e81b..730df0bf0 100644
--- a/kspread/plugins/insertcalendar/Makefile.am
+++ b/kspread/plugins/insertcalendar/Makefile.am
@@ -2,9 +2,9 @@ INCLUDES = -I$(srcdir)/../../../kspread $(KOFFICE_INCLUDES) $(KOTEXT_INCLUDES)
kde_module_LTLIBRARIES = libkspreadinsertcalendar.la
-libkspreadinsertcalendar_la_SOURCES = kspread_plugininsertcalendar.cc \
+libkspreadinsertcalendar_la_SOURCES = kspread_plugininsertcalendar.cpp \
kspread_insertcalendardialogbase.ui \
- kspread_insertcalendardialog.cc
+ kspread_insertcalendardialog.cpp
libkspreadinsertcalendar_la_LDFLAGS = $(all_libraries) -avoid-version -module -no-undefined
libkspreadinsertcalendar_la_LIBADD = ../../libkspreadcommon.la
@@ -23,4 +23,4 @@ rcdir = $(kde_datadir)/kspread/kpartplugins
SUBDIRS =
messages: rc.cpp
- $(XGETTEXT) rc.cpp *.cc -o $(podir)/kspreadinsertcalendar.pot
+ $(XGETTEXT) rc.cpp *.cpp -o $(podir)/kspreadinsertcalendar.pot
diff --git a/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cpp
index 0311c9137..0311c9137 100644
--- a/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc
+++ b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cpp
diff --git a/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cpp
index e2f9d954c..e2f9d954c 100644
--- a/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc
+++ b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cpp
diff --git a/kspread/plugins/scripting/Makefile.am b/kspread/plugins/scripting/Makefile.am
index 545ee148b..a90e1554f 100644
--- a/kspread/plugins/scripting/Makefile.am
+++ b/kspread/plugins/scripting/Makefile.am
@@ -7,7 +7,7 @@ INCLUDES = -I$(top_builddir)/lib/kross/main \
$(KOFFICE_INCLUDES) \
$(all_includes)
-kspreadscripting_la_SOURCES = scripting.cc
+kspreadscripting_la_SOURCES = scripting.cpp
kde_module_LTLIBRARIES = kspreadscripting.la
noinst_HEADERS = scripting.h
diff --git a/kspread/plugins/scripting/scripting.cc b/kspread/plugins/scripting/scripting.cpp
index 040bd98d7..040bd98d7 100644
--- a/kspread/plugins/scripting/scripting.cc
+++ b/kspread/plugins/scripting/scripting.cpp
diff --git a/kspread/region.cc b/kspread/region.cpp
index 92c408ef0..92c408ef0 100644
--- a/kspread/region.cc
+++ b/kspread/region.cpp
diff --git a/kspread/selection.cc b/kspread/selection.cpp
index f05a6db50..f05a6db50 100644
--- a/kspread/selection.cc
+++ b/kspread/selection.cpp
diff --git a/kspread/tests/Makefile.am b/kspread/tests/Makefile.am
index 87c3bbdca..16de4ba7c 100644
--- a/kspread/tests/Makefile.am
+++ b/kspread/tests/Makefile.am
@@ -8,7 +8,7 @@ INCLUDES = \
check_PROGRAMS = formulatest
TESTS = formulatest
-formulatest_SOURCES = test_formula.cc
+formulatest_SOURCES = test_formula.cpp
formulatest_LDADD = ../libkspreadcommon.la
@@ -16,11 +16,11 @@ noinst_LTLIBRARIES = \
libtests.la
libtests_la_SOURCES = \
- tester.cc \
- testrunner.cc \
- value_tester.cc \
- formula_tester.cc \
- inspector.cc
+ tester.cpp \
+ testrunner.cpp \
+ value_tester.cpp \
+ formula_tester.cpp \
+ inspector.cpp
noinst_HEADERS = \
tester.h \
diff --git a/kspread/tests/formula_tester.cc b/kspread/tests/formula_tester.cpp
index 2c7381e17..2c7381e17 100644
--- a/kspread/tests/formula_tester.cc
+++ b/kspread/tests/formula_tester.cpp
diff --git a/kspread/tests/inspector.cc b/kspread/tests/inspector.cpp
index d44b7bf33..d44b7bf33 100644
--- a/kspread/tests/inspector.cc
+++ b/kspread/tests/inspector.cpp
diff --git a/kspread/tests/test_formula.cc b/kspread/tests/test_formula.cpp
index 433efab3e..433efab3e 100644
--- a/kspread/tests/test_formula.cc
+++ b/kspread/tests/test_formula.cpp
diff --git a/kspread/tests/tester.cc b/kspread/tests/tester.cpp
index 05df95d10..05df95d10 100644
--- a/kspread/tests/tester.cc
+++ b/kspread/tests/tester.cpp
diff --git a/kspread/tests/testrunner.cc b/kspread/tests/testrunner.cpp
index d16dc1661..d16dc1661 100644
--- a/kspread/tests/testrunner.cc
+++ b/kspread/tests/testrunner.cpp
diff --git a/kspread/tests/value_tester.cc b/kspread/tests/value_tester.cpp
index 84e9e5637..84e9e5637 100644
--- a/kspread/tests/value_tester.cc
+++ b/kspread/tests/value_tester.cpp
diff --git a/kspread/valuecalc.cc b/kspread/valuecalc.cpp
index 3a1182e54..3a1182e54 100644
--- a/kspread/valuecalc.cc
+++ b/kspread/valuecalc.cpp
diff --git a/kspread/valueconverter.cc b/kspread/valueconverter.cpp
index 21cb75310..21cb75310 100644
--- a/kspread/valueconverter.cc
+++ b/kspread/valueconverter.cpp
diff --git a/kspread/valueformatter.cc b/kspread/valueformatter.cpp
index 94b6b57c2..94b6b57c2 100644
--- a/kspread/valueformatter.cc
+++ b/kspread/valueformatter.cpp
diff --git a/kspread/valueparser.cc b/kspread/valueparser.cpp
index 08ebe628a..08ebe628a 100644
--- a/kspread/valueparser.cc
+++ b/kspread/valueparser.cpp
diff --git a/kword/DEBUG b/kword/DEBUG
index 8e7924833..58a5f9d3e 100644
--- a/kword/DEBUG
+++ b/kword/DEBUG
@@ -12,4 +12,4 @@ Ctrl-Shift-V : Verbose parag debug. Includes formatting of each character.
Ctrl-Shift-S : Styles debug. Prints all KoStyles.
Ctrl-Shift-M : Mark the debug output. Just prints the current date/time.
-(The code is in koffice/kword/kwcanvas.cc.)
+(The code is in koffice/kword/kwcanvas.cpp.)
diff --git a/kword/HACKING b/kword/HACKING
index b288e2e81..a9d30dabd 100644
--- a/kword/HACKING
+++ b/kword/HACKING
@@ -86,9 +86,9 @@ FILES:
*IFace.h/cc - the dcop interface
misc app stuff:
- main.cc - the main
+ main.cpp - the main
kwaboutdata.h - the appname, authors...
- - shared between main.cc and kwfactory.cc
+ - shared between main.cpp and kwfactory.cpp
kword.rc - xml-gui layout
kword.desktop - application .desktop file
@@ -127,7 +127,7 @@ FILES:
doc outline:
docstruct.h/cc - gui for overall document structure
styles:
- stylenames.cc - contains builtin style names,
+ stylenames.cpp - contains builtin style names,
for translation purposes
kwstylemanager.h/cc - KWStyleManager, extension to KoStyleManager
(the style editor is in libkotext)
@@ -195,9 +195,9 @@ FILES:
mailmerge:
mailmerge.h/cc
mailmerge_actions.h/cc
- kwordmailmergedatabaseiface.cc
+ kwordmailmergedatabaseiface.cpp
mailmerge_interface.h/cc - dcop
- mailmerge_interface_skel.cc - (ditto)
+ mailmerge_interface_skel.cpp - (ditto)
kwmailmerge.desktop - mailmerge .desktop file
expressions:
kweditpersonnalexpressiondia.h/cc
@@ -207,7 +207,7 @@ FILES:
misc weird files: ;-)
kwstyle.h - Forwarder to kostyle.h,
- they're the same thing now.
- dummy.cc - empty file to compile as a
+ dummy.cpp - empty file to compile as a
- "tdeinit loadable module"
MISC FILES:
diff --git a/kword/KWCommand.cpp b/kword/KWCommand.cpp
index fec98ab78..8356ede9d 100644
--- a/kword/KWCommand.cpp
+++ b/kword/KWCommand.cpp
@@ -1266,7 +1266,7 @@ void KWInsertColumnCommand::execute()
{
kdDebug(32001) << "KWInsertColumnCommand::execute" << endl;
KWDocument * doc = m_pTable->kWordDocument();
- // a insert column = KWTableFrameSet::m_sDefaultColWidth, see kwtableframeset.cc
+ // a insert column = KWTableFrameSet::m_sDefaultColWidth, see kwtableframeset.cpp
if (m_pTable->boundingRect().right() + KWTableFrameSet::m_sDefaultColWidth >= static_cast<int>(m_maxRight))
{ // must create space (resize the table)
m_oldWidth = m_pTable->boundingRect().width();
diff --git a/kword/KWFrameSet.cpp b/kword/KWFrameSet.cpp
index 515b0df0c..1195815a4 100644
--- a/kword/KWFrameSet.cpp
+++ b/kword/KWFrameSet.cpp
@@ -960,7 +960,7 @@ KWFrame* KWFrameSet::loadOasisFrame( const TQDomElement& tag, KoOasisContext& co
frame->setZOrder( tag.attributeNS( KoXmlNS::draw, "z-index", TQString() ).toInt() );
// Copy-frames.
// We currently ignore the value of the copy-of attribute. It probably needs to
- // be handled like chain-next-name (kwtextframeset.cc) but for all types of frameset.
+ // be handled like chain-next-name (kwtextframeset.cpp) but for all types of frameset.
frame->setCopy( tag.hasAttributeNS( KoXmlNS::draw, "copy-of" ) );
frame->loadCommonOasisProperties( context, this, "graphic" );
diff --git a/kword/defs.h b/kword/defs.h
index b4b606655..aeaf3aeb3 100644
--- a/kword/defs.h
+++ b/kword/defs.h
@@ -53,7 +53,7 @@ enum FrameSetType { FT_BASE = 0, FT_TEXT = 1, FT_PICTURE = 2, FT_PART = 3,
FT_TABLE = 10 };
// This has to remain here because of KWDocument::refreshDocStructure()
-// This one has better remain here, otherwise kwdoc.cc needs docstruct.h
+// This one has better remain here, otherwise kwdoc.cpp needs docstruct.h
enum TypeStructDocItem {Arrangement=1, Tables=2, Pictures=4, TextFrames=16, Embedded=32, FormulaFrames=64};
// This one has better remain here, otherwise kwtexframeset.h needs footnote.h
diff --git a/kword/mailmerge/KWClassicSerialDataSource.cpp b/kword/mailmerge/KWClassicSerialDataSource.cpp
index 73eee9942..2588b06e4 100644
--- a/kword/mailmerge/KWClassicSerialDataSource.cpp
+++ b/kword/mailmerge/KWClassicSerialDataSource.cpp
@@ -1,5 +1,5 @@
/* This file is part of the KDE project
- Original file (mailmerge.cc): Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
+ Original file (mailmerge.cpp): Copyright (C) 1998, 1999 Reginald Stadlbauer <reggie@kde.org>
Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>
This library is free software; you can redistribute it and/or
diff --git a/lib/Makefile.am b/lib/Makefile.am
index 6a0eab165..d4d0da435 100644
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -14,15 +14,15 @@ SUBDIRS = store kwmf kofficecore kofficeui kotext \
endif
messages:
-# $(MAKE) -C kformula -f Makefile.am symbolnames.cc
+# $(MAKE) -C kformula -f Makefile.am symbolnames.cpp
EXCLUDE="-path ./koproperty"; \
LIST=`find . \( \( $$EXCLUDE \) -prune -o -name \*.ui -o -name \*.rc \) -type f | grep -v -e '/\.'`; \
$(EXTRACTRC) $$LIST > rc.cpp; \
- LIST=`find . \( \( $$EXCLUDE \) -prune -o -name \*.cpp -o -name \*.cc \) -type f | grep -v -e '/\.'`; \
+ LIST=`find . \( \( $$EXCLUDE \) -prune -o -name \*.cpp \) -type f | grep -v -e '/\.'`; \
$(XGETTEXT) $$LIST -o $(podir)/koffice.pot
# $(EXTRACTRC) */*.rc */*.ui > rc.cpp
-# $(XGETTEXT) kotext/kohyphen/*.cpp */*.cc */*.cpp -o $(podir)/koffice.pot
-# rm -f kformula/symbolnames.cc
+# $(XGETTEXT) kotext/kohyphen/*.cpp */*.cpp -o $(podir)/koffice.pot
+# rm -f kformula/symbolnames.cpp
DOXYGEN_REFERENCES = dcop kprint tdeui tdeparts
include ../admin/Doxyfile.am
diff --git a/lib/kformula/Makefile.am b/lib/kformula/Makefile.am
index 4ad27bcc9..e666bf48f 100644
--- a/lib/kformula/Makefile.am
+++ b/lib/kformula/Makefile.am
@@ -7,20 +7,20 @@ SUBDIRS = pics fonts dtd
# We have to name it kformulalib, not just kformula, since that's the name of the tdeinit module for kformula.
lib_LTLIBRARIES = libkformulalib.la
-libkformulalib_la_SOURCES = basicelement.cc contextstyle.cc formulacursor.cc \
- formulaelement.cc indexelement.cc kformulacontainer.cc \
- sequenceelement.cc textelement.cc bracketelement.cc \
- matrixelement.cc fractionelement.cc rootelement.cc symbolelement.cc \
- kformulacommand.cc kformulamimesource.cc \
- MatrixDialog.cc sequenceparser.cc elementtype.cc kformuladocument.cc \
- symboltable.cc kformulainputfilter.cc kformulaview.cc \
- spaceelement.cc kformulaconfigpage.cc \
- symbolaction.cc fontstyle.cc creationstrategy.cc \
- oasiscreationstrategy.cc tokenstyleelement.cc tokenelement.cc \
- identifierelement.cc operatorelement.cc glyphelement.cc styleelement.cc \
- stringelement.cc paddedelement.cc errorelement.cc phantomelement.cc \
- actionelement.cc encloseelement.cc entities.cc operatordictionary.cc \
- numberelement.cc
+libkformulalib_la_SOURCES = basicelement.cpp contextstyle.cpp formulacursor.cpp \
+ formulaelement.cpp indexelement.cpp kformulacontainer.cpp \
+ sequenceelement.cpp textelement.cpp bracketelement.cpp \
+ matrixelement.cpp fractionelement.cpp rootelement.cpp symbolelement.cpp \
+ kformulacommand.cpp kformulamimesource.cpp \
+ MatrixDialog.cpp sequenceparser.cpp elementtype.cpp kformuladocument.cpp \
+ symboltable.cpp kformulainputfilter.cpp kformulaview.cpp \
+ spaceelement.cpp kformulaconfigpage.cpp \
+ symbolaction.cpp fontstyle.cpp creationstrategy.cpp \
+ oasiscreationstrategy.cpp tokenstyleelement.cpp tokenelement.cpp \
+ identifierelement.cpp operatorelement.cpp glyphelement.cpp styleelement.cpp \
+ stringelement.cpp paddedelement.cpp errorelement.cpp phantomelement.cpp \
+ actionelement.cpp encloseelement.cpp entities.cpp operatordictionary.cpp \
+ numberelement.cpp
#include_HEADERS = kformulacontainer.h kformuladocument.h kformulaview.h \
# kformuladefs.h kformulaconfigpage.h
@@ -32,8 +32,8 @@ libkformulalib_la_METASOURCES = AUTO
check_PROGRAMS = kformulatest
-kformulatest_SOURCES = main.cc kformulawidget.cc
+kformulatest_SOURCES = main.cpp kformulawidget.cpp
kformulatest_LDADD = libkformulalib.la
-#symbolnames.cc:
-# awk -F, '$$1 !~ "#" {if (split($$3,a," ")>0) print "i18n(\"" a[1] "\");"}' config/unicode.tbl > symbolnames.cc
+#symbolnames.cpp:
+# awk -F, '$$1 !~ "#" {if (split($$3,a," ")>0) print "i18n(\"" a[1] "\");"}' config/unicode.tbl > symbolnames.cpp
diff --git a/lib/kformula/MatrixDialog.cc b/lib/kformula/MatrixDialog.cpp
index feac37cea..feac37cea 100644
--- a/lib/kformula/MatrixDialog.cc
+++ b/lib/kformula/MatrixDialog.cpp
diff --git a/lib/kformula/actionelement.cc b/lib/kformula/actionelement.cpp
index e1dce9371..e1dce9371 100644
--- a/lib/kformula/actionelement.cc
+++ b/lib/kformula/actionelement.cpp
diff --git a/lib/kformula/basicelement.cc b/lib/kformula/basicelement.cpp
index 096814aad..096814aad 100644
--- a/lib/kformula/basicelement.cc
+++ b/lib/kformula/basicelement.cpp
diff --git a/lib/kformula/bracketelement.cc b/lib/kformula/bracketelement.cpp
index 45aa54697..45aa54697 100644
--- a/lib/kformula/bracketelement.cc
+++ b/lib/kformula/bracketelement.cpp
diff --git a/lib/kformula/contextstyle.cc b/lib/kformula/contextstyle.cpp
index a744e02dd..a744e02dd 100644
--- a/lib/kformula/contextstyle.cc
+++ b/lib/kformula/contextstyle.cpp
diff --git a/lib/kformula/creationstrategy.cc b/lib/kformula/creationstrategy.cpp
index 592c744b8..592c744b8 100644
--- a/lib/kformula/creationstrategy.cc
+++ b/lib/kformula/creationstrategy.cpp
diff --git a/lib/kformula/elementtype.cc b/lib/kformula/elementtype.cpp
index bd2c33738..bd2c33738 100644
--- a/lib/kformula/elementtype.cc
+++ b/lib/kformula/elementtype.cpp
diff --git a/lib/kformula/encloseelement.cc b/lib/kformula/encloseelement.cpp
index 846f6bb2d..846f6bb2d 100644
--- a/lib/kformula/encloseelement.cc
+++ b/lib/kformula/encloseelement.cpp
diff --git a/lib/kformula/entities.cc b/lib/kformula/entities.cpp
index c6696e1ff..c6696e1ff 100644
--- a/lib/kformula/entities.cc
+++ b/lib/kformula/entities.cpp
diff --git a/lib/kformula/errorelement.cc b/lib/kformula/errorelement.cpp
index cb1f6c545..cb1f6c545 100644
--- a/lib/kformula/errorelement.cc
+++ b/lib/kformula/errorelement.cpp
diff --git a/lib/kformula/fontstyle.cc b/lib/kformula/fontstyle.cc
deleted file mode 100644
index 32479b0f3..000000000
--- a/lib/kformula/fontstyle.cc
+++ /dev/null
@@ -1,891 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2003 Ulrich Kuettler <ulrich.kuettler@gmx.de>
- Copyright (C) 2006 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <tqpainter.h>
-#include <tqpen.h>
-#include <tqfontdatabase.h>
-#include <tqapplication.h>
-
-#include <kstaticdeleter.h>
-#include <tdelocale.h>
-#include <kstandarddirs.h>
-#include <tdeio/netaccess.h>
-#include <tdeio/job.h>
-#include <tdemessagebox.h>
-
-#include "fontstyle.h"
-
-
-KFORMULA_NAMESPACE_BEGIN
-
-#include "unicodetable.cc"
-
-bool FontStyle::m_installed = false;
-
-bool FontStyle::init( ContextStyle* style, bool install )
-{
- if (!m_installed && install)
- installFonts();
- m_symbolTable.init( style->getMathFont() );
-
- return true;
-}
-
-// Cache the family list from TQFontDatabase after fixing it up (no foundry, lowercase)
-class FontList {
-public:
- FontList() {
- TQFontDatabase db;
- const TQStringList lst = db.families();
- for ( TQStringList::const_iterator it = lst.begin(), end = lst.end() ; it != end ; ++it ) {
- const TQString name = *it;
- int i = name.find('[');
- TQString family = name;
- // Remove foundry
- if ( i > -1 ) {
- const int li = name.findRev(']');
- if (i < li) {
- if (name[i - 1] == ' ')
- i--;
- family = name.left(i);
- }
- }
- m_fontNames.append( family.lower() );
- }
- }
- bool hasFont( const TQString& fontName ) const {
- return m_fontNames.find( fontName ) != m_fontNames.end();
- }
- TQStringList m_fontNames;
-};
-static FontList* s_fontList = 0;
-static KStaticDeleter<FontList> s_fontList_sd;
-
-void FontStyle::testFont( TQStringList& missing, const TQString& fontName ) {
- if ( !s_fontList )
- s_fontList_sd.setObject( s_fontList, new FontList() );
- if ( !s_fontList->hasFont( fontName ) ) {
- kdWarning(39001) << "Font '" << fontName << "' not found" << endl;
- missing.append( fontName );
- }
-}
-
-
-TQStringList FontStyle::missingFonts( bool install )
-{
- if (!m_installed && install)
- installFonts();
-
- TQStringList missing = missingFontsInternal();
- return missing;
-}
-
-TQStringList FontStyle::missingFontsInternal()
-{
- TQStringList missing;
-
- testFont( missing, "cmex10" );
- testFont( missing, "arev sans");
-
- return missing;
-}
-
-void FontStyle::installFonts()
-{
- if (m_installed)
- return;
- TQStringList missing = missingFontsInternal();
- if (!missing.isEmpty())
- {
- TQStringList urlList;
- for (TQStringList::iterator it = missing.begin(); it != missing.end(); ++it)
- {
- if ( *it == "arev sans" ) {
- if (!TDEIO::NetAccess::exists("fonts:/Personal/Arev.ttf", true, NULL))
- urlList.append(locate("data", "kformula/fonts/Arev.ttf"));
- if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevIt.ttf", true, NULL))
- urlList.append(locate("data", "kformula/fonts/ArevIt.ttf"));
- if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevBd.ttf", true, NULL))
- urlList.append(locate("data", "kformula/fonts/ArevBd.ttf"));
- if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevBI.ttf", true, NULL))
- urlList.append(locate("data", "kformula/fonts/ArevBI.ttf"));
- }
- else {
- if (!TDEIO::NetAccess::exists("fonts:/Personal/" + *it + ".ttf", true, NULL))
- urlList.append(locate("data", "kformula/fonts/" + *it + ".ttf"));
- }
- }
- TDEIO::copy(urlList, "fonts:/Personal/", false);
- KMessageBox::information(tqApp->mainWidget(),
- i18n("Some fonts have been installed to assure that symbols in formulas are properly visualized. You must restart the application in order so that changes take effect"));
- }
- m_installed = true;
-}
-
-Artwork* FontStyle::createArtwork( SymbolType type ) const
-{
- return new Artwork( type );
-}
-
-// We claim that all chars come from the same font.
-// It's up to the font tables to ensure this.
-const TQChar leftRoundBracket[] = {
- 0x30, // uppercorner
- 0x40, // lowercorner
- 0x42 // line
-};
-const TQChar leftSquareBracket[] = {
- 0x32, // uppercorner
- 0x34, // lowercorner
- 0x36 // line
-};
-const TQChar leftCurlyBracket[] = {
- 0x38, // uppercorner
- 0x3A, // lowercorner
- 0x3E, // line
- 0x3C // middle
-};
-
-const TQChar leftLineBracket[] = {
- 0x36, // line
- 0x36, // line
- 0x36 // line
-};
-const TQChar rightLineBracket[] = {
- 0x37, // line
- 0x37, // line
- 0x37 // line
-};
-
-const TQChar rightRoundBracket[] = {
- 0x31, // uppercorner
- 0x41, // lowercorner
- 0x43 // line
-};
-const TQChar rightSquareBracket[] = {
- 0x33, // uppercorner
- 0x35, // lowercorner
- 0x37 // line
-};
-const TQChar rightCurlyBracket[] = {
- 0x39, // uppercorner
- 0x3B, // lowercorner
- 0x3E, // line
- 0x3D // middle
-};
-
-
-static const char cmex_LeftSquareBracket = 163;
-static const char cmex_RightSquareBracket = 164;
-static const char cmex_LeftCurlyBracket = 169;
-static const char cmex_RightCurlyBracket = 170;
-static const char cmex_LeftCornerBracket = 173;
-static const char cmex_RightCornerBracket = 174;
-static const char cmex_LeftRoundBracket = 161;
-static const char cmex_RightRoundBracket = 162;
-static const char cmex_SlashBracket = 177;
-static const char cmex_BackSlashBracket = 178;
-//static const char cmex_LeftLineBracket = 0x4b;
-//static const char cmex_RightLineBracket = 0x4b;
-
-// use the big symbols here
-static const char cmex_Int = 90;
-static const char cmex_Sum = 88;
-static const char cmex_Prod = 89;
-
-
-// cmex is a special font with symbols in four sizes.
-static short cmex_nextchar( short ch )
-{
- switch ( ch ) {
- case 161: return 179;
- case 162: return 180;
- case 163: return 104;
- case 164: return 105;
- case 169: return 110;
- case 170: return 111;
- case 165: return 106;
- case 166: return 107;
- case 167: return 108;
- case 168: return 109;
- case 173: return 68;
- case 174: return 69;
- case 177: return 46;
- case 178: return 47;
-
- case 179: return 181;
- case 180: return 182;
- case 104: return 183;
- case 105: return 184;
- case 110: return 189;
- case 111: return 190;
- case 106: return 185;
- case 107: return 186;
- case 108: return 187;
- case 109: return 188;
- case 68: return 191;
- case 69: return 192;
- case 46: return 193;
- case 47: return 194;
-
- case 181: return 195;
- case 182: return 33;
- case 183: return 34;
- case 184: return 35;
- case 189: return 40;
- case 190: return 41;
- case 185: return 36;
- case 186: return 37;
- case 187: return 38;
- case 188: return 39;
- case 191: return 42;
- case 192: return 43;
- case 193: return 44;
- case 194: return 45;
- }
- return 0;
-}
-
-bool Artwork::calcCMDelimiterSize( const ContextStyle& context,
- uchar c,
- luPt fontSize,
- luPt parentSize )
-{
- TQFont f( "cmex10" );
- f.setPointSizeFloat( context.layoutUnitPtToPt( fontSize ) );
- TQFontMetrics fm( f );
-
- for ( char i=1; c != 0; ++i ) {
- LuPixelRect bound = fm.boundingRect( c );
-
- luPt height = context.ptToLayoutUnitPt( bound.height() );
- if ( height >= parentSize ) {
- luPt width = context.ptToLayoutUnitPt( fm.width( c ) );
- luPt baseline = context.ptToLayoutUnitPt( -bound.top() );
-
- cmChar = c;
-
- setHeight( height );
- setWidth( width );
- setBaseline( baseline );
-
- return true;
- }
- c = cmex_nextchar( c );
- }
-
- // Build it up from pieces.
- return false;
-}
-
-
-void Artwork::calcLargest( const ContextStyle& context,
- uchar c, luPt fontSize )
-{
- TQFont f( "cmex10" );
- f.setPointSizeFloat( context.layoutUnitPtToPt( fontSize ) );
- TQFontMetrics fm( f );
-
- cmChar = c;
- for ( ;; ) {
- c = cmex_nextchar( c );
- if ( c == 0 ) {
- break;
- }
- cmChar = c;
- }
-
- LuPixelRect bound = fm.boundingRect( cmChar );
-
- luPt height = context.ptToLayoutUnitPt( bound.height() );
- luPt width = context.ptToLayoutUnitPt( fm.width( cmChar ) );
- luPt baseline = context.ptToLayoutUnitPt( -bound.top() );
-
- setHeight( height );
- setWidth( width );
- setBaseline( baseline );
-}
-
-
-void Artwork::drawCMDelimiter( TQPainter& painter, const ContextStyle& style,
- luPixel x, luPixel y,
- luPt height )
-{
- TQFont f( "cmex10" );
- f.setPointSizeFloat( style.layoutUnitToFontSize( height, false ) );
-
- painter.setFont( f );
- painter.drawText( style.layoutUnitToPixelX( x ),
- style.layoutUnitToPixelY( y + getBaseline() ),
- TQString( TQChar( cmChar ) ) );
-
- // Debug
-#if 0
- TQFontMetrics fm( f );
- LuPixelRect bound = fm.boundingRect( cmChar );
- painter.setBrush(TQt::NoBrush);
- painter.setPen(TQt::green);
- painter.drawRect( style.layoutUnitToPixelX( x ),
- style.layoutUnitToPixelY( y ),
- fm.width( cmChar ),
- bound.height() );
-#endif
-}
-
-
-Artwork::Artwork(SymbolType t)
- : baseline( -1 ), type(t)
-{
-}
-
-
-void Artwork::calcSizes( const ContextStyle& style,
- ContextStyle::TextStyle tstyle,
- double factor,
- luPt parentSize )
-{
- setBaseline( -1 );
- cmChar = -1;
- luPt mySize = style.getAdjustedSize( tstyle, factor );
- switch (getType()) {
- case LeftSquareBracket:
- if ( calcCMDelimiterSize( style, cmex_LeftSquareBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcRoundBracket( style, leftSquareBracket, parentSize, mySize );
- break;
- case RightSquareBracket:
- if ( calcCMDelimiterSize( style, cmex_RightSquareBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcRoundBracket( style, rightSquareBracket, parentSize, mySize );
- break;
- case LeftLineBracket:
- calcRoundBracket( style, leftLineBracket, parentSize, mySize );
- setWidth( getWidth()/2 );
- break;
- case RightLineBracket:
- calcRoundBracket( style, rightLineBracket, parentSize, mySize );
- setWidth( getWidth()/2 );
- break;
- case SlashBracket:
- if ( calcCMDelimiterSize( style, cmex_SlashBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcLargest( style, cmex_SlashBracket, mySize );
- break;
- case BackSlashBracket:
- if ( calcCMDelimiterSize( style, cmex_BackSlashBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcLargest( style, cmex_BackSlashBracket, mySize );
- break;
- case LeftCornerBracket:
- if ( calcCMDelimiterSize( style, cmex_LeftCornerBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcLargest( style, cmex_LeftCornerBracket, mySize );
- break;
- case RightCornerBracket:
- if ( calcCMDelimiterSize( style, cmex_RightCornerBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcLargest( style, cmex_RightCornerBracket, mySize );
- break;
- case LeftRoundBracket:
- if ( calcCMDelimiterSize( style, cmex_LeftRoundBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcRoundBracket( style, leftRoundBracket, parentSize, mySize );
- break;
- case RightRoundBracket:
- if ( calcCMDelimiterSize( style, cmex_RightRoundBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcRoundBracket( style, rightRoundBracket, parentSize, mySize );
- break;
- case EmptyBracket:
- setHeight(parentSize);
- //setWidth(style.getEmptyRectWidth());
- setWidth(0);
- break;
- case LeftCurlyBracket:
- if ( calcCMDelimiterSize( style, cmex_LeftCurlyBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcCurlyBracket( style, leftCurlyBracket, parentSize, mySize );
- break;
- case RightCurlyBracket:
- if ( calcCMDelimiterSize( style, cmex_RightCurlyBracket,
- mySize, parentSize ) ) {
- return;
- }
- calcCurlyBracket( style, rightCurlyBracket, parentSize, mySize );
- break;
- case Integral:
- calcCharSize( style, style.getBracketFont(), mySize, cmex_Int );
- break;
- case Sum:
- calcCharSize( style, style.getBracketFont(), mySize, cmex_Sum );
- break;
- case Product:
- calcCharSize( style, style.getBracketFont(), mySize, cmex_Prod );
- break;
- }
-}
-
-void Artwork::calcSizes( const ContextStyle& style,
- ContextStyle::TextStyle tstyle,
- double factor )
-{
- luPt mySize = style.getAdjustedSize( tstyle, factor );
- switch (type) {
- case LeftSquareBracket:
- calcCharSize(style, mySize, leftSquareBracketChar);
- break;
- case RightSquareBracket:
- calcCharSize(style, mySize, rightSquareBracketChar);
- break;
- case LeftLineBracket:
- case RightLineBracket:
- calcCharSize(style, mySize, verticalLineChar);
- break;
- case SlashBracket:
- calcCharSize(style, mySize, slashChar);
- break;
- case BackSlashBracket:
- calcCharSize(style, mySize, backSlashChar);
- break;
- case LeftCornerBracket:
- calcCharSize(style, mySize, leftAngleBracketChar);
- break;
- case RightCornerBracket:
- calcCharSize(style, mySize, rightAngleBracketChar);
- break;
- case LeftRoundBracket:
- calcCharSize(style, mySize, leftParenthesisChar);
- break;
- case RightRoundBracket:
- calcCharSize(style, mySize, rightParenthesisChar);
- break;
- case EmptyBracket:
- //calcCharSize(style, mySize, spaceChar);
- setHeight(0);
- //setWidth(style.getEmptyRectWidth());
- setWidth(0);
- break;
- case LeftCurlyBracket:
- calcCharSize(style, mySize, leftCurlyBracketChar);
- break;
- case RightCurlyBracket:
- calcCharSize(style, mySize, rightCurlyBracketChar);
- break;
- case Integral:
- case Sum:
- case Product:
- break;
- }
-}
-
-
-void Artwork::draw(TQPainter& painter, const LuPixelRect& /*r*/,
- const ContextStyle& context, ContextStyle::TextStyle tstyle,
- StyleAttributes& style, const LuPixelPoint& parentOrigin)
-{
- luPt mySize = context.getAdjustedSize( tstyle, style.sizeFactor() );
- luPixel myX = parentOrigin.x() + getX();
- luPixel myY = parentOrigin.y() + getY();
- /*
- if ( !LuPixelRect( myX, myY, getWidth(), getHeight() ).intersects( r ) )
- return;
- */
-
- painter.setPen(context.getDefaultColor());
-
- switch (type) {
- case LeftSquareBracket:
- drawCharacter(painter, context, myX, myY, mySize, leftSquareBracketChar);
- break;
- case RightSquareBracket:
- drawCharacter(painter, context, myX, myY, mySize, rightSquareBracketChar);
- break;
- case LeftCurlyBracket:
- drawCharacter(painter, context, myX, myY, mySize, leftCurlyBracketChar);
- break;
- case RightCurlyBracket:
- drawCharacter(painter, context, myX, myY, mySize, rightCurlyBracketChar);
- break;
- case LeftLineBracket:
- case RightLineBracket:
- drawCharacter(painter, context, myX, myY, mySize, verticalLineChar);
- break;
- case SlashBracket:
- drawCharacter(painter, context, myX, myY, mySize, slashChar);
- break;
- case BackSlashBracket:
- drawCharacter(painter, context, myX, myY, mySize, backSlashChar);
- break;
- case LeftCornerBracket:
- drawCharacter(painter, context, myX, myY, mySize, leftAngleBracketChar);
- break;
- case RightCornerBracket:
- drawCharacter(painter, context, myX, myY, mySize, rightAngleBracketChar);
- break;
- case LeftRoundBracket:
- drawCharacter(painter, context, myX, myY, mySize, leftParenthesisChar);
- break;
- case RightRoundBracket:
- drawCharacter(painter, context, myX, myY, mySize, rightParenthesisChar);
- break;
- case EmptyBracket:
- break;
- case Integral:
- case Sum:
- case Product:
- break;
- }
-}
-
-void Artwork::draw(TQPainter& painter, const LuPixelRect& ,
- const ContextStyle& context, ContextStyle::TextStyle tstyle,
- StyleAttributes& style, luPt , const LuPixelPoint& origin)
-{
- luPt mySize = context.getAdjustedSize( tstyle, style.sizeFactor() );
- luPixel myX = origin.x() + getX();
- luPixel myY = origin.y() + getY();
- /*
- if ( !LuPixelRect( myX, myY, getWidth(), getHeight() ).intersects( r ) )
- return;
- */
-
- painter.setPen(context.getDefaultColor());
-
- switch (getType()) {
- case LeftSquareBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigRoundBracket( painter, context, leftSquareBracket, myX, myY, mySize );
- }
- break;
- case RightSquareBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigRoundBracket( painter, context, rightSquareBracket, myX, myY, mySize );
- }
- break;
- case LeftCurlyBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigCurlyBracket( painter, context, leftCurlyBracket, myX, myY, mySize );
- }
- break;
- case RightCurlyBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigCurlyBracket( painter, context, rightCurlyBracket, myX, myY, mySize );
- }
- break;
- case LeftLineBracket: {
- luPixel halfWidth = getWidth()/2;
- drawBigRoundBracket( painter, context, leftLineBracket,
- myX-halfWidth, myY, mySize );
- }
- break;
- case RightLineBracket: {
- luPixel halfWidth = getWidth()/2;
- drawBigRoundBracket( painter, context, rightLineBracket,
- myX-halfWidth, myY, mySize );
- }
- break;
- case SlashBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- break;
- case BackSlashBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- break;
- case LeftCornerBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else drawCharacter(painter, context, myX, myY, mySize, leftAngleBracketChar);
- break;
- case RightCornerBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else drawCharacter(painter, context, myX, myY, mySize, rightAngleBracketChar);
- break;
- case LeftRoundBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigRoundBracket( painter, context, leftRoundBracket, myX, myY, mySize );
- }
- break;
- case RightRoundBracket:
- if ( cmChar != -1 ) {
- drawCMDelimiter( painter, context, myX, myY, mySize );
- }
- else {
- drawBigRoundBracket( painter, context, rightRoundBracket, myX, myY, mySize );
- }
- break;
- case EmptyBracket:
- break;
- case Integral:
- drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Int);
- break;
- case Sum:
- drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Sum);
- break;
- case Product:
- drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Prod);
- break;
- }
-
- // debug
-// painter.setBrush(TQt::NoBrush);
-// painter.setPen(TQt::green);
-// painter.drawRect( context.layoutUnitToPixelX( myX ),
-// context.layoutUnitToPixelY( myY ),
-// context.layoutUnitToPixelX( getWidth() ),
-// context.layoutUnitToPixelY( getHeight() ) );
-}
-
-void Artwork::calcCharSize( const ContextStyle& style, luPt height, TQChar ch )
-{
- calcCharSize( style, style.getMathFont(), height, ch );
-}
-
-
-void Artwork::drawCharacter( TQPainter& painter, const ContextStyle& style,
- luPixel x, luPixel y,
- luPt height, TQChar ch )
-{
- drawCharacter( painter, style, style.getMathFont(), x, y, height, ch );
-}
-
-
-void Artwork::calcCharSize( const ContextStyle& style, TQFont f,
- luPt height, TQChar c )
-{
- f.setPointSizeFloat( style.layoutUnitPtToPt( height ) );
- //f.setPointSize( height );
- TQFontMetrics fm(f);
- setWidth( style.ptToLayoutUnitPt( fm.width( c ) ) );
- LuPixelRect bound = fm.boundingRect( c );
- setHeight( style.ptToLayoutUnitPt( bound.height() ) );
- setBaseline( style.ptToLayoutUnitPt( -bound.top() ) );
-}
-
-
-void Artwork::drawCharacter( TQPainter& painter, const ContextStyle& style,
- TQFont f,
- luPixel x, luPixel y, luPt height, uchar c )
-{
- f.setPointSizeFloat( style.layoutUnitToFontSize( height, false ) );
-
- painter.setFont( f );
- painter.drawText( style.layoutUnitToPixelX( x ),
- style.layoutUnitToPixelY( y+getBaseline() ),
- TQString( TQChar( c ) ) );
-}
-
-
-void Artwork::calcRoundBracket( const ContextStyle& style, const TQChar chars[],
- luPt height, luPt charHeight )
-{
- uchar uppercorner = chars[0];
- uchar lowercorner = chars[1];
- //uchar line = style.symbolTable().character( chars[2] );
-
- TQFont f = style.getBracketFont();
- f.setPointSizeFloat( style.layoutUnitPtToPt( charHeight ) );
- TQFontMetrics fm( f );
- LuPtRect upperBound = fm.boundingRect( uppercorner );
- LuPtRect lowerBound = fm.boundingRect( lowercorner );
- //LuPtRect lineBound = fm.boundingRect( line );
-
- setWidth( style.ptToLayoutUnitPt( fm.width( TQChar( uppercorner ) ) ) );
- luPt edgeHeight = style.ptToLayoutUnitPt( upperBound.height()+lowerBound.height() );
- //luPt lineHeight = style.ptToLayoutUnitPt( lineBound.height() );
-
- //setHeight( edgeHeight + ( ( height-edgeHeight-1 ) / lineHeight + 1 ) * lineHeight );
- setHeight( TQMAX( edgeHeight, height ) );
-}
-
-void Artwork::drawBigRoundBracket( TQPainter& p, const ContextStyle& style, const TQChar chars[],
- luPixel x, luPixel y, luPt charHeight )
-{
- uchar uppercorner = chars[0];
- uchar lowercorner = chars[1];
- uchar line = chars[2];
-
- TQFont f = style.getBracketFont();
- f.setPointSizeFloat( style.layoutUnitToFontSize( charHeight, false ) );
- p.setFont(f);
-
- TQFontMetrics fm(f);
- TQRect upperBound = fm.boundingRect(uppercorner);
- TQRect lowerBound = fm.boundingRect(lowercorner);
- TQRect lineBound = fm.boundingRect(line);
-
- pixel ptX = style.layoutUnitToPixelX( x );
- pixel ptY = style.layoutUnitToPixelY( y );
- pixel height = style.layoutUnitToPixelY( getHeight() );
-
-// p.setPen( TQt::red );
-// //p.drawRect( ptX, ptY, upperBound.width(), upperBound.height() + lowerBound.height() );
-// p.drawRect( ptX, ptY, style.layoutUnitToPixelX( getWidth() ),
-// style.layoutUnitToPixelY( getHeight() ) );
-
-// p.setPen( TQt::black );
- p.drawText( ptX, ptY-upperBound.top(), TQString( TQChar( uppercorner ) ) );
- p.drawText( ptX, ptY+height-lowerBound.top()-lowerBound.height(),
- TQString( TQChar( lowercorner ) ) );
-
- // for printing
- //pt safety = lineBound.height() / 10.0;
- pixel safety = 0;
-
- pixel gap = height - upperBound.height() - lowerBound.height();
- pixel lineHeight = lineBound.height() - safety;
- int lineCount = tqRound( static_cast<double>( gap ) / lineHeight );
- pixel start = upperBound.height()-lineBound.top() - safety;
-
- for (int i = 0; i < lineCount; i++) {
- p.drawText( ptX, ptY+start+i*lineHeight, TQString(TQChar(line)));
- }
- pixel remaining = gap - lineCount*lineHeight;
- pixel dist = ( lineHeight - remaining ) / 2;
- p.drawText( ptX, ptY+height-upperBound.height()+dist-lineBound.height()-lineBound.top(),
- TQString( TQChar( line ) ) );
-}
-
-void Artwork::calcCurlyBracket( const ContextStyle& style, const TQChar chars[],
- luPt height, luPt charHeight )
-{
- uchar uppercorner = chars[0];
- uchar lowercorner = chars[1];
- //uchar line = style.symbolTable().character( chars[2] );
- uchar middle = chars[3];
-
- TQFont f = style.getBracketFont();
- f.setPointSizeFloat( style.layoutUnitPtToPt( charHeight ) );
- TQFontMetrics fm( f );
- LuPtRect upperBound = fm.boundingRect( uppercorner );
- LuPtRect lowerBound = fm.boundingRect( lowercorner );
- //LuPtRect lineBound = fm.boundingRect( line );
- LuPtRect middleBound = fm.boundingRect( middle );
-
- setWidth( style.ptToLayoutUnitPt( fm.width( TQChar( uppercorner ) ) ) );
- luPt edgeHeight = style.ptToLayoutUnitPt( upperBound.height()+
- lowerBound.height()+
- middleBound.height() );
- //luPt lineHeight = style.ptToLayoutUnitPt( lineBound.height() );
-
- //setHeight( edgeHeight + ( ( height-edgeHeight-1 ) / lineHeight + 1 ) * lineHeight );
- setHeight( TQMAX( edgeHeight, height ) );
-}
-
-void Artwork::drawBigCurlyBracket( TQPainter& p, const ContextStyle& style, const TQChar chars[],
- luPixel x, luPixel y, luPt charHeight )
-{
- //TQFont f = style.getSymbolFont();
- TQFont f = style.getBracketFont();
- f.setPointSizeFloat( style.layoutUnitToFontSize( charHeight, false ) );
- p.setFont(f);
-
- uchar uppercorner = chars[0];
- uchar lowercorner = chars[1];
- uchar line = chars[2];
- uchar middle = chars[3];
-
- TQFontMetrics fm(p.fontMetrics());
- TQRect upperBound = fm.boundingRect(uppercorner);
- TQRect lowerBound = fm.boundingRect(lowercorner);
- TQRect middleBound = fm.boundingRect(middle);
- TQRect lineBound = fm.boundingRect(line);
-
- pixel ptX = style.layoutUnitToPixelX( x );
- pixel ptY = style.layoutUnitToPixelY( y );
- pixel height = style.layoutUnitToPixelY( getHeight() );
-
- //p.setPen(TQt::gray);
- //p.drawRect(x, y, upperBound.width() + offset, height);
-
- p.drawText( ptX, ptY-upperBound.top(), TQString( TQChar( uppercorner ) ) );
- p.drawText( ptX, ptY+(height-middleBound.height())/2-middleBound.top(),
- TQString( TQChar( middle ) ) );
- p.drawText( ptX, ptY+height-lowerBound.top()-lowerBound.height(),
- TQString( TQChar( lowercorner ) ) );
-
- // for printing
- // If the world was perfect and the urw-symbol font correct
- // this could be 0.
- //lu safety = lineBound.height() / 10;
- pixel safety = 0;
-
- pixel lineHeight = lineBound.height() - safety;
- pixel gap = height/2 - upperBound.height() - middleBound.height() / 2;
-
- if (gap > 0) {
- TQString ch = TQString(TQChar(line));
- int lineCount = tqRound( gap / lineHeight ) + 1;
-
- pixel start = (height - middleBound.height()) / 2 + safety;
- for (int i = 0; i < lineCount; i++) {
- p.drawText( ptX, ptY-lineBound.top()+TQMAX( start-(i+1)*lineHeight,
- upperBound.width() ),
- ch );
- }
-
- start = (height + middleBound.height()) / 2 - safety;
- for (int i = 0; i < lineCount; i++) {
- p.drawText( ptX, ptY-lineBound.top()+TQMIN( start+i*lineHeight,
- height-upperBound.width()-lineBound.height() ),
- ch );
- }
- }
-}
-
-KFORMULA_NAMESPACE_END
diff --git a/lib/kformula/fontstyle.cpp b/lib/kformula/fontstyle.cpp
new file mode 100644
index 000000000..33f9e9f76
--- /dev/null
+++ b/lib/kformula/fontstyle.cpp
@@ -0,0 +1,891 @@
+/* This file is part of the KDE project
+ Copyright (C) 2003 Ulrich Kuettler <ulrich.kuettler@gmx.de>
+ Copyright (C) 2006 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <tqpainter.h>
+#include <tqpen.h>
+#include <tqfontdatabase.h>
+#include <tqapplication.h>
+
+#include <kstaticdeleter.h>
+#include <tdelocale.h>
+#include <kstandarddirs.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/job.h>
+#include <tdemessagebox.h>
+
+#include "fontstyle.h"
+
+
+KFORMULA_NAMESPACE_BEGIN
+
+#include "unicodetable.cpp"
+
+bool FontStyle::m_installed = false;
+
+bool FontStyle::init( ContextStyle* style, bool install )
+{
+ if (!m_installed && install)
+ installFonts();
+ m_symbolTable.init( style->getMathFont() );
+
+ return true;
+}
+
+// Cache the family list from TQFontDatabase after fixing it up (no foundry, lowercase)
+class FontList {
+public:
+ FontList() {
+ TQFontDatabase db;
+ const TQStringList lst = db.families();
+ for ( TQStringList::const_iterator it = lst.begin(), end = lst.end() ; it != end ; ++it ) {
+ const TQString name = *it;
+ int i = name.find('[');
+ TQString family = name;
+ // Remove foundry
+ if ( i > -1 ) {
+ const int li = name.findRev(']');
+ if (i < li) {
+ if (name[i - 1] == ' ')
+ i--;
+ family = name.left(i);
+ }
+ }
+ m_fontNames.append( family.lower() );
+ }
+ }
+ bool hasFont( const TQString& fontName ) const {
+ return m_fontNames.find( fontName ) != m_fontNames.end();
+ }
+ TQStringList m_fontNames;
+};
+static FontList* s_fontList = 0;
+static KStaticDeleter<FontList> s_fontList_sd;
+
+void FontStyle::testFont( TQStringList& missing, const TQString& fontName ) {
+ if ( !s_fontList )
+ s_fontList_sd.setObject( s_fontList, new FontList() );
+ if ( !s_fontList->hasFont( fontName ) ) {
+ kdWarning(39001) << "Font '" << fontName << "' not found" << endl;
+ missing.append( fontName );
+ }
+}
+
+
+TQStringList FontStyle::missingFonts( bool install )
+{
+ if (!m_installed && install)
+ installFonts();
+
+ TQStringList missing = missingFontsInternal();
+ return missing;
+}
+
+TQStringList FontStyle::missingFontsInternal()
+{
+ TQStringList missing;
+
+ testFont( missing, "cmex10" );
+ testFont( missing, "arev sans");
+
+ return missing;
+}
+
+void FontStyle::installFonts()
+{
+ if (m_installed)
+ return;
+ TQStringList missing = missingFontsInternal();
+ if (!missing.isEmpty())
+ {
+ TQStringList urlList;
+ for (TQStringList::iterator it = missing.begin(); it != missing.end(); ++it)
+ {
+ if ( *it == "arev sans" ) {
+ if (!TDEIO::NetAccess::exists("fonts:/Personal/Arev.ttf", true, NULL))
+ urlList.append(locate("data", "kformula/fonts/Arev.ttf"));
+ if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevIt.ttf", true, NULL))
+ urlList.append(locate("data", "kformula/fonts/ArevIt.ttf"));
+ if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevBd.ttf", true, NULL))
+ urlList.append(locate("data", "kformula/fonts/ArevBd.ttf"));
+ if (!TDEIO::NetAccess::exists("fonts:/Personal/ArevBI.ttf", true, NULL))
+ urlList.append(locate("data", "kformula/fonts/ArevBI.ttf"));
+ }
+ else {
+ if (!TDEIO::NetAccess::exists("fonts:/Personal/" + *it + ".ttf", true, NULL))
+ urlList.append(locate("data", "kformula/fonts/" + *it + ".ttf"));
+ }
+ }
+ TDEIO::copy(urlList, "fonts:/Personal/", false);
+ KMessageBox::information(tqApp->mainWidget(),
+ i18n("Some fonts have been installed to assure that symbols in formulas are properly visualized. You must restart the application in order so that changes take effect"));
+ }
+ m_installed = true;
+}
+
+Artwork* FontStyle::createArtwork( SymbolType type ) const
+{
+ return new Artwork( type );
+}
+
+// We claim that all chars come from the same font.
+// It's up to the font tables to ensure this.
+const TQChar leftRoundBracket[] = {
+ 0x30, // uppercorner
+ 0x40, // lowercorner
+ 0x42 // line
+};
+const TQChar leftSquareBracket[] = {
+ 0x32, // uppercorner
+ 0x34, // lowercorner
+ 0x36 // line
+};
+const TQChar leftCurlyBracket[] = {
+ 0x38, // uppercorner
+ 0x3A, // lowercorner
+ 0x3E, // line
+ 0x3C // middle
+};
+
+const TQChar leftLineBracket[] = {
+ 0x36, // line
+ 0x36, // line
+ 0x36 // line
+};
+const TQChar rightLineBracket[] = {
+ 0x37, // line
+ 0x37, // line
+ 0x37 // line
+};
+
+const TQChar rightRoundBracket[] = {
+ 0x31, // uppercorner
+ 0x41, // lowercorner
+ 0x43 // line
+};
+const TQChar rightSquareBracket[] = {
+ 0x33, // uppercorner
+ 0x35, // lowercorner
+ 0x37 // line
+};
+const TQChar rightCurlyBracket[] = {
+ 0x39, // uppercorner
+ 0x3B, // lowercorner
+ 0x3E, // line
+ 0x3D // middle
+};
+
+
+static const char cmex_LeftSquareBracket = 163;
+static const char cmex_RightSquareBracket = 164;
+static const char cmex_LeftCurlyBracket = 169;
+static const char cmex_RightCurlyBracket = 170;
+static const char cmex_LeftCornerBracket = 173;
+static const char cmex_RightCornerBracket = 174;
+static const char cmex_LeftRoundBracket = 161;
+static const char cmex_RightRoundBracket = 162;
+static const char cmex_SlashBracket = 177;
+static const char cmex_BackSlashBracket = 178;
+//static const char cmex_LeftLineBracket = 0x4b;
+//static const char cmex_RightLineBracket = 0x4b;
+
+// use the big symbols here
+static const char cmex_Int = 90;
+static const char cmex_Sum = 88;
+static const char cmex_Prod = 89;
+
+
+// cmex is a special font with symbols in four sizes.
+static short cmex_nextchar( short ch )
+{
+ switch ( ch ) {
+ case 161: return 179;
+ case 162: return 180;
+ case 163: return 104;
+ case 164: return 105;
+ case 169: return 110;
+ case 170: return 111;
+ case 165: return 106;
+ case 166: return 107;
+ case 167: return 108;
+ case 168: return 109;
+ case 173: return 68;
+ case 174: return 69;
+ case 177: return 46;
+ case 178: return 47;
+
+ case 179: return 181;
+ case 180: return 182;
+ case 104: return 183;
+ case 105: return 184;
+ case 110: return 189;
+ case 111: return 190;
+ case 106: return 185;
+ case 107: return 186;
+ case 108: return 187;
+ case 109: return 188;
+ case 68: return 191;
+ case 69: return 192;
+ case 46: return 193;
+ case 47: return 194;
+
+ case 181: return 195;
+ case 182: return 33;
+ case 183: return 34;
+ case 184: return 35;
+ case 189: return 40;
+ case 190: return 41;
+ case 185: return 36;
+ case 186: return 37;
+ case 187: return 38;
+ case 188: return 39;
+ case 191: return 42;
+ case 192: return 43;
+ case 193: return 44;
+ case 194: return 45;
+ }
+ return 0;
+}
+
+bool Artwork::calcCMDelimiterSize( const ContextStyle& context,
+ uchar c,
+ luPt fontSize,
+ luPt parentSize )
+{
+ TQFont f( "cmex10" );
+ f.setPointSizeFloat( context.layoutUnitPtToPt( fontSize ) );
+ TQFontMetrics fm( f );
+
+ for ( char i=1; c != 0; ++i ) {
+ LuPixelRect bound = fm.boundingRect( c );
+
+ luPt height = context.ptToLayoutUnitPt( bound.height() );
+ if ( height >= parentSize ) {
+ luPt width = context.ptToLayoutUnitPt( fm.width( c ) );
+ luPt baseline = context.ptToLayoutUnitPt( -bound.top() );
+
+ cmChar = c;
+
+ setHeight( height );
+ setWidth( width );
+ setBaseline( baseline );
+
+ return true;
+ }
+ c = cmex_nextchar( c );
+ }
+
+ // Build it up from pieces.
+ return false;
+}
+
+
+void Artwork::calcLargest( const ContextStyle& context,
+ uchar c, luPt fontSize )
+{
+ TQFont f( "cmex10" );
+ f.setPointSizeFloat( context.layoutUnitPtToPt( fontSize ) );
+ TQFontMetrics fm( f );
+
+ cmChar = c;
+ for ( ;; ) {
+ c = cmex_nextchar( c );
+ if ( c == 0 ) {
+ break;
+ }
+ cmChar = c;
+ }
+
+ LuPixelRect bound = fm.boundingRect( cmChar );
+
+ luPt height = context.ptToLayoutUnitPt( bound.height() );
+ luPt width = context.ptToLayoutUnitPt( fm.width( cmChar ) );
+ luPt baseline = context.ptToLayoutUnitPt( -bound.top() );
+
+ setHeight( height );
+ setWidth( width );
+ setBaseline( baseline );
+}
+
+
+void Artwork::drawCMDelimiter( TQPainter& painter, const ContextStyle& style,
+ luPixel x, luPixel y,
+ luPt height )
+{
+ TQFont f( "cmex10" );
+ f.setPointSizeFloat( style.layoutUnitToFontSize( height, false ) );
+
+ painter.setFont( f );
+ painter.drawText( style.layoutUnitToPixelX( x ),
+ style.layoutUnitToPixelY( y + getBaseline() ),
+ TQString( TQChar( cmChar ) ) );
+
+ // Debug
+#if 0
+ TQFontMetrics fm( f );
+ LuPixelRect bound = fm.boundingRect( cmChar );
+ painter.setBrush(TQt::NoBrush);
+ painter.setPen(TQt::green);
+ painter.drawRect( style.layoutUnitToPixelX( x ),
+ style.layoutUnitToPixelY( y ),
+ fm.width( cmChar ),
+ bound.height() );
+#endif
+}
+
+
+Artwork::Artwork(SymbolType t)
+ : baseline( -1 ), type(t)
+{
+}
+
+
+void Artwork::calcSizes( const ContextStyle& style,
+ ContextStyle::TextStyle tstyle,
+ double factor,
+ luPt parentSize )
+{
+ setBaseline( -1 );
+ cmChar = -1;
+ luPt mySize = style.getAdjustedSize( tstyle, factor );
+ switch (getType()) {
+ case LeftSquareBracket:
+ if ( calcCMDelimiterSize( style, cmex_LeftSquareBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcRoundBracket( style, leftSquareBracket, parentSize, mySize );
+ break;
+ case RightSquareBracket:
+ if ( calcCMDelimiterSize( style, cmex_RightSquareBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcRoundBracket( style, rightSquareBracket, parentSize, mySize );
+ break;
+ case LeftLineBracket:
+ calcRoundBracket( style, leftLineBracket, parentSize, mySize );
+ setWidth( getWidth()/2 );
+ break;
+ case RightLineBracket:
+ calcRoundBracket( style, rightLineBracket, parentSize, mySize );
+ setWidth( getWidth()/2 );
+ break;
+ case SlashBracket:
+ if ( calcCMDelimiterSize( style, cmex_SlashBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcLargest( style, cmex_SlashBracket, mySize );
+ break;
+ case BackSlashBracket:
+ if ( calcCMDelimiterSize( style, cmex_BackSlashBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcLargest( style, cmex_BackSlashBracket, mySize );
+ break;
+ case LeftCornerBracket:
+ if ( calcCMDelimiterSize( style, cmex_LeftCornerBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcLargest( style, cmex_LeftCornerBracket, mySize );
+ break;
+ case RightCornerBracket:
+ if ( calcCMDelimiterSize( style, cmex_RightCornerBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcLargest( style, cmex_RightCornerBracket, mySize );
+ break;
+ case LeftRoundBracket:
+ if ( calcCMDelimiterSize( style, cmex_LeftRoundBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcRoundBracket( style, leftRoundBracket, parentSize, mySize );
+ break;
+ case RightRoundBracket:
+ if ( calcCMDelimiterSize( style, cmex_RightRoundBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcRoundBracket( style, rightRoundBracket, parentSize, mySize );
+ break;
+ case EmptyBracket:
+ setHeight(parentSize);
+ //setWidth(style.getEmptyRectWidth());
+ setWidth(0);
+ break;
+ case LeftCurlyBracket:
+ if ( calcCMDelimiterSize( style, cmex_LeftCurlyBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcCurlyBracket( style, leftCurlyBracket, parentSize, mySize );
+ break;
+ case RightCurlyBracket:
+ if ( calcCMDelimiterSize( style, cmex_RightCurlyBracket,
+ mySize, parentSize ) ) {
+ return;
+ }
+ calcCurlyBracket( style, rightCurlyBracket, parentSize, mySize );
+ break;
+ case Integral:
+ calcCharSize( style, style.getBracketFont(), mySize, cmex_Int );
+ break;
+ case Sum:
+ calcCharSize( style, style.getBracketFont(), mySize, cmex_Sum );
+ break;
+ case Product:
+ calcCharSize( style, style.getBracketFont(), mySize, cmex_Prod );
+ break;
+ }
+}
+
+void Artwork::calcSizes( const ContextStyle& style,
+ ContextStyle::TextStyle tstyle,
+ double factor )
+{
+ luPt mySize = style.getAdjustedSize( tstyle, factor );
+ switch (type) {
+ case LeftSquareBracket:
+ calcCharSize(style, mySize, leftSquareBracketChar);
+ break;
+ case RightSquareBracket:
+ calcCharSize(style, mySize, rightSquareBracketChar);
+ break;
+ case LeftLineBracket:
+ case RightLineBracket:
+ calcCharSize(style, mySize, verticalLineChar);
+ break;
+ case SlashBracket:
+ calcCharSize(style, mySize, slashChar);
+ break;
+ case BackSlashBracket:
+ calcCharSize(style, mySize, backSlashChar);
+ break;
+ case LeftCornerBracket:
+ calcCharSize(style, mySize, leftAngleBracketChar);
+ break;
+ case RightCornerBracket:
+ calcCharSize(style, mySize, rightAngleBracketChar);
+ break;
+ case LeftRoundBracket:
+ calcCharSize(style, mySize, leftParenthesisChar);
+ break;
+ case RightRoundBracket:
+ calcCharSize(style, mySize, rightParenthesisChar);
+ break;
+ case EmptyBracket:
+ //calcCharSize(style, mySize, spaceChar);
+ setHeight(0);
+ //setWidth(style.getEmptyRectWidth());
+ setWidth(0);
+ break;
+ case LeftCurlyBracket:
+ calcCharSize(style, mySize, leftCurlyBracketChar);
+ break;
+ case RightCurlyBracket:
+ calcCharSize(style, mySize, rightCurlyBracketChar);
+ break;
+ case Integral:
+ case Sum:
+ case Product:
+ break;
+ }
+}
+
+
+void Artwork::draw(TQPainter& painter, const LuPixelRect& /*r*/,
+ const ContextStyle& context, ContextStyle::TextStyle tstyle,
+ StyleAttributes& style, const LuPixelPoint& parentOrigin)
+{
+ luPt mySize = context.getAdjustedSize( tstyle, style.sizeFactor() );
+ luPixel myX = parentOrigin.x() + getX();
+ luPixel myY = parentOrigin.y() + getY();
+ /*
+ if ( !LuPixelRect( myX, myY, getWidth(), getHeight() ).intersects( r ) )
+ return;
+ */
+
+ painter.setPen(context.getDefaultColor());
+
+ switch (type) {
+ case LeftSquareBracket:
+ drawCharacter(painter, context, myX, myY, mySize, leftSquareBracketChar);
+ break;
+ case RightSquareBracket:
+ drawCharacter(painter, context, myX, myY, mySize, rightSquareBracketChar);
+ break;
+ case LeftCurlyBracket:
+ drawCharacter(painter, context, myX, myY, mySize, leftCurlyBracketChar);
+ break;
+ case RightCurlyBracket:
+ drawCharacter(painter, context, myX, myY, mySize, rightCurlyBracketChar);
+ break;
+ case LeftLineBracket:
+ case RightLineBracket:
+ drawCharacter(painter, context, myX, myY, mySize, verticalLineChar);
+ break;
+ case SlashBracket:
+ drawCharacter(painter, context, myX, myY, mySize, slashChar);
+ break;
+ case BackSlashBracket:
+ drawCharacter(painter, context, myX, myY, mySize, backSlashChar);
+ break;
+ case LeftCornerBracket:
+ drawCharacter(painter, context, myX, myY, mySize, leftAngleBracketChar);
+ break;
+ case RightCornerBracket:
+ drawCharacter(painter, context, myX, myY, mySize, rightAngleBracketChar);
+ break;
+ case LeftRoundBracket:
+ drawCharacter(painter, context, myX, myY, mySize, leftParenthesisChar);
+ break;
+ case RightRoundBracket:
+ drawCharacter(painter, context, myX, myY, mySize, rightParenthesisChar);
+ break;
+ case EmptyBracket:
+ break;
+ case Integral:
+ case Sum:
+ case Product:
+ break;
+ }
+}
+
+void Artwork::draw(TQPainter& painter, const LuPixelRect& ,
+ const ContextStyle& context, ContextStyle::TextStyle tstyle,
+ StyleAttributes& style, luPt , const LuPixelPoint& origin)
+{
+ luPt mySize = context.getAdjustedSize( tstyle, style.sizeFactor() );
+ luPixel myX = origin.x() + getX();
+ luPixel myY = origin.y() + getY();
+ /*
+ if ( !LuPixelRect( myX, myY, getWidth(), getHeight() ).intersects( r ) )
+ return;
+ */
+
+ painter.setPen(context.getDefaultColor());
+
+ switch (getType()) {
+ case LeftSquareBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigRoundBracket( painter, context, leftSquareBracket, myX, myY, mySize );
+ }
+ break;
+ case RightSquareBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigRoundBracket( painter, context, rightSquareBracket, myX, myY, mySize );
+ }
+ break;
+ case LeftCurlyBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigCurlyBracket( painter, context, leftCurlyBracket, myX, myY, mySize );
+ }
+ break;
+ case RightCurlyBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigCurlyBracket( painter, context, rightCurlyBracket, myX, myY, mySize );
+ }
+ break;
+ case LeftLineBracket: {
+ luPixel halfWidth = getWidth()/2;
+ drawBigRoundBracket( painter, context, leftLineBracket,
+ myX-halfWidth, myY, mySize );
+ }
+ break;
+ case RightLineBracket: {
+ luPixel halfWidth = getWidth()/2;
+ drawBigRoundBracket( painter, context, rightLineBracket,
+ myX-halfWidth, myY, mySize );
+ }
+ break;
+ case SlashBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ break;
+ case BackSlashBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ break;
+ case LeftCornerBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else drawCharacter(painter, context, myX, myY, mySize, leftAngleBracketChar);
+ break;
+ case RightCornerBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else drawCharacter(painter, context, myX, myY, mySize, rightAngleBracketChar);
+ break;
+ case LeftRoundBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigRoundBracket( painter, context, leftRoundBracket, myX, myY, mySize );
+ }
+ break;
+ case RightRoundBracket:
+ if ( cmChar != -1 ) {
+ drawCMDelimiter( painter, context, myX, myY, mySize );
+ }
+ else {
+ drawBigRoundBracket( painter, context, rightRoundBracket, myX, myY, mySize );
+ }
+ break;
+ case EmptyBracket:
+ break;
+ case Integral:
+ drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Int);
+ break;
+ case Sum:
+ drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Sum);
+ break;
+ case Product:
+ drawCharacter(painter, context, TQFont( "cmex10" ), myX, myY, mySize, cmex_Prod);
+ break;
+ }
+
+ // debug
+// painter.setBrush(TQt::NoBrush);
+// painter.setPen(TQt::green);
+// painter.drawRect( context.layoutUnitToPixelX( myX ),
+// context.layoutUnitToPixelY( myY ),
+// context.layoutUnitToPixelX( getWidth() ),
+// context.layoutUnitToPixelY( getHeight() ) );
+}
+
+void Artwork::calcCharSize( const ContextStyle& style, luPt height, TQChar ch )
+{
+ calcCharSize( style, style.getMathFont(), height, ch );
+}
+
+
+void Artwork::drawCharacter( TQPainter& painter, const ContextStyle& style,
+ luPixel x, luPixel y,
+ luPt height, TQChar ch )
+{
+ drawCharacter( painter, style, style.getMathFont(), x, y, height, ch );
+}
+
+
+void Artwork::calcCharSize( const ContextStyle& style, TQFont f,
+ luPt height, TQChar c )
+{
+ f.setPointSizeFloat( style.layoutUnitPtToPt( height ) );
+ //f.setPointSize( height );
+ TQFontMetrics fm(f);
+ setWidth( style.ptToLayoutUnitPt( fm.width( c ) ) );
+ LuPixelRect bound = fm.boundingRect( c );
+ setHeight( style.ptToLayoutUnitPt( bound.height() ) );
+ setBaseline( style.ptToLayoutUnitPt( -bound.top() ) );
+}
+
+
+void Artwork::drawCharacter( TQPainter& painter, const ContextStyle& style,
+ TQFont f,
+ luPixel x, luPixel y, luPt height, uchar c )
+{
+ f.setPointSizeFloat( style.layoutUnitToFontSize( height, false ) );
+
+ painter.setFont( f );
+ painter.drawText( style.layoutUnitToPixelX( x ),
+ style.layoutUnitToPixelY( y+getBaseline() ),
+ TQString( TQChar( c ) ) );
+}
+
+
+void Artwork::calcRoundBracket( const ContextStyle& style, const TQChar chars[],
+ luPt height, luPt charHeight )
+{
+ uchar uppercorner = chars[0];
+ uchar lowercorner = chars[1];
+ //uchar line = style.symbolTable().character( chars[2] );
+
+ TQFont f = style.getBracketFont();
+ f.setPointSizeFloat( style.layoutUnitPtToPt( charHeight ) );
+ TQFontMetrics fm( f );
+ LuPtRect upperBound = fm.boundingRect( uppercorner );
+ LuPtRect lowerBound = fm.boundingRect( lowercorner );
+ //LuPtRect lineBound = fm.boundingRect( line );
+
+ setWidth( style.ptToLayoutUnitPt( fm.width( TQChar( uppercorner ) ) ) );
+ luPt edgeHeight = style.ptToLayoutUnitPt( upperBound.height()+lowerBound.height() );
+ //luPt lineHeight = style.ptToLayoutUnitPt( lineBound.height() );
+
+ //setHeight( edgeHeight + ( ( height-edgeHeight-1 ) / lineHeight + 1 ) * lineHeight );
+ setHeight( TQMAX( edgeHeight, height ) );
+}
+
+void Artwork::drawBigRoundBracket( TQPainter& p, const ContextStyle& style, const TQChar chars[],
+ luPixel x, luPixel y, luPt charHeight )
+{
+ uchar uppercorner = chars[0];
+ uchar lowercorner = chars[1];
+ uchar line = chars[2];
+
+ TQFont f = style.getBracketFont();
+ f.setPointSizeFloat( style.layoutUnitToFontSize( charHeight, false ) );
+ p.setFont(f);
+
+ TQFontMetrics fm(f);
+ TQRect upperBound = fm.boundingRect(uppercorner);
+ TQRect lowerBound = fm.boundingRect(lowercorner);
+ TQRect lineBound = fm.boundingRect(line);
+
+ pixel ptX = style.layoutUnitToPixelX( x );
+ pixel ptY = style.layoutUnitToPixelY( y );
+ pixel height = style.layoutUnitToPixelY( getHeight() );
+
+// p.setPen( TQt::red );
+// //p.drawRect( ptX, ptY, upperBound.width(), upperBound.height() + lowerBound.height() );
+// p.drawRect( ptX, ptY, style.layoutUnitToPixelX( getWidth() ),
+// style.layoutUnitToPixelY( getHeight() ) );
+
+// p.setPen( TQt::black );
+ p.drawText( ptX, ptY-upperBound.top(), TQString( TQChar( uppercorner ) ) );
+ p.drawText( ptX, ptY+height-lowerBound.top()-lowerBound.height(),
+ TQString( TQChar( lowercorner ) ) );
+
+ // for printing
+ //pt safety = lineBound.height() / 10.0;
+ pixel safety = 0;
+
+ pixel gap = height - upperBound.height() - lowerBound.height();
+ pixel lineHeight = lineBound.height() - safety;
+ int lineCount = tqRound( static_cast<double>( gap ) / lineHeight );
+ pixel start = upperBound.height()-lineBound.top() - safety;
+
+ for (int i = 0; i < lineCount; i++) {
+ p.drawText( ptX, ptY+start+i*lineHeight, TQString(TQChar(line)));
+ }
+ pixel remaining = gap - lineCount*lineHeight;
+ pixel dist = ( lineHeight - remaining ) / 2;
+ p.drawText( ptX, ptY+height-upperBound.height()+dist-lineBound.height()-lineBound.top(),
+ TQString( TQChar( line ) ) );
+}
+
+void Artwork::calcCurlyBracket( const ContextStyle& style, const TQChar chars[],
+ luPt height, luPt charHeight )
+{
+ uchar uppercorner = chars[0];
+ uchar lowercorner = chars[1];
+ //uchar line = style.symbolTable().character( chars[2] );
+ uchar middle = chars[3];
+
+ TQFont f = style.getBracketFont();
+ f.setPointSizeFloat( style.layoutUnitPtToPt( charHeight ) );
+ TQFontMetrics fm( f );
+ LuPtRect upperBound = fm.boundingRect( uppercorner );
+ LuPtRect lowerBound = fm.boundingRect( lowercorner );
+ //LuPtRect lineBound = fm.boundingRect( line );
+ LuPtRect middleBound = fm.boundingRect( middle );
+
+ setWidth( style.ptToLayoutUnitPt( fm.width( TQChar( uppercorner ) ) ) );
+ luPt edgeHeight = style.ptToLayoutUnitPt( upperBound.height()+
+ lowerBound.height()+
+ middleBound.height() );
+ //luPt lineHeight = style.ptToLayoutUnitPt( lineBound.height() );
+
+ //setHeight( edgeHeight + ( ( height-edgeHeight-1 ) / lineHeight + 1 ) * lineHeight );
+ setHeight( TQMAX( edgeHeight, height ) );
+}
+
+void Artwork::drawBigCurlyBracket( TQPainter& p, const ContextStyle& style, const TQChar chars[],
+ luPixel x, luPixel y, luPt charHeight )
+{
+ //TQFont f = style.getSymbolFont();
+ TQFont f = style.getBracketFont();
+ f.setPointSizeFloat( style.layoutUnitToFontSize( charHeight, false ) );
+ p.setFont(f);
+
+ uchar uppercorner = chars[0];
+ uchar lowercorner = chars[1];
+ uchar line = chars[2];
+ uchar middle = chars[3];
+
+ TQFontMetrics fm(p.fontMetrics());
+ TQRect upperBound = fm.boundingRect(uppercorner);
+ TQRect lowerBound = fm.boundingRect(lowercorner);
+ TQRect middleBound = fm.boundingRect(middle);
+ TQRect lineBound = fm.boundingRect(line);
+
+ pixel ptX = style.layoutUnitToPixelX( x );
+ pixel ptY = style.layoutUnitToPixelY( y );
+ pixel height = style.layoutUnitToPixelY( getHeight() );
+
+ //p.setPen(TQt::gray);
+ //p.drawRect(x, y, upperBound.width() + offset, height);
+
+ p.drawText( ptX, ptY-upperBound.top(), TQString( TQChar( uppercorner ) ) );
+ p.drawText( ptX, ptY+(height-middleBound.height())/2-middleBound.top(),
+ TQString( TQChar( middle ) ) );
+ p.drawText( ptX, ptY+height-lowerBound.top()-lowerBound.height(),
+ TQString( TQChar( lowercorner ) ) );
+
+ // for printing
+ // If the world was perfect and the urw-symbol font correct
+ // this could be 0.
+ //lu safety = lineBound.height() / 10;
+ pixel safety = 0;
+
+ pixel lineHeight = lineBound.height() - safety;
+ pixel gap = height/2 - upperBound.height() - middleBound.height() / 2;
+
+ if (gap > 0) {
+ TQString ch = TQString(TQChar(line));
+ int lineCount = tqRound( gap / lineHeight ) + 1;
+
+ pixel start = (height - middleBound.height()) / 2 + safety;
+ for (int i = 0; i < lineCount; i++) {
+ p.drawText( ptX, ptY-lineBound.top()+TQMAX( start-(i+1)*lineHeight,
+ upperBound.width() ),
+ ch );
+ }
+
+ start = (height + middleBound.height()) / 2 - safety;
+ for (int i = 0; i < lineCount; i++) {
+ p.drawText( ptX, ptY-lineBound.top()+TQMIN( start+i*lineHeight,
+ height-upperBound.width()-lineBound.height() ),
+ ch );
+ }
+ }
+}
+
+KFORMULA_NAMESPACE_END
diff --git a/lib/kformula/formulacursor.cc b/lib/kformula/formulacursor.cpp
index 53d02b1f8..53d02b1f8 100644
--- a/lib/kformula/formulacursor.cc
+++ b/lib/kformula/formulacursor.cpp
diff --git a/lib/kformula/formulaelement.cc b/lib/kformula/formulaelement.cpp
index 946e595d3..946e595d3 100644
--- a/lib/kformula/formulaelement.cc
+++ b/lib/kformula/formulaelement.cpp
diff --git a/lib/kformula/fractionelement.cc b/lib/kformula/fractionelement.cpp
index 9f1125e12..9f1125e12 100644
--- a/lib/kformula/fractionelement.cc
+++ b/lib/kformula/fractionelement.cpp
diff --git a/lib/kformula/glyphelement.cc b/lib/kformula/glyphelement.cpp
index 709609cf1..709609cf1 100644
--- a/lib/kformula/glyphelement.cc
+++ b/lib/kformula/glyphelement.cpp
diff --git a/lib/kformula/identifierelement.cc b/lib/kformula/identifierelement.cpp
index 63275e1c6..63275e1c6 100644
--- a/lib/kformula/identifierelement.cc
+++ b/lib/kformula/identifierelement.cpp
diff --git a/lib/kformula/indexelement.cc b/lib/kformula/indexelement.cpp
index 6f2f6d1d7..6f2f6d1d7 100644
--- a/lib/kformula/indexelement.cc
+++ b/lib/kformula/indexelement.cpp
diff --git a/lib/kformula/kformulacommand.cc b/lib/kformula/kformulacommand.cpp
index 4aa311610..4aa311610 100644
--- a/lib/kformula/kformulacommand.cc
+++ b/lib/kformula/kformulacommand.cpp
diff --git a/lib/kformula/kformulacompatibility.cc b/lib/kformula/kformulacompatibility.cpp
index f64bf9de4..f64bf9de4 100644
--- a/lib/kformula/kformulacompatibility.cc
+++ b/lib/kformula/kformulacompatibility.cpp
diff --git a/lib/kformula/kformulaconfigpage.cc b/lib/kformula/kformulaconfigpage.cpp
index ce95c40c8..ce95c40c8 100644
--- a/lib/kformula/kformulaconfigpage.cc
+++ b/lib/kformula/kformulaconfigpage.cpp
diff --git a/lib/kformula/kformulacontainer.cc b/lib/kformula/kformulacontainer.cpp
index a6123154d..a6123154d 100644
--- a/lib/kformula/kformulacontainer.cc
+++ b/lib/kformula/kformulacontainer.cpp
diff --git a/lib/kformula/kformuladocument.cc b/lib/kformula/kformuladocument.cpp
index c041232fb..c041232fb 100644
--- a/lib/kformula/kformuladocument.cc
+++ b/lib/kformula/kformuladocument.cpp
diff --git a/lib/kformula/kformulainputfilter.cc b/lib/kformula/kformulainputfilter.cpp
index a26752710..a26752710 100644
--- a/lib/kformula/kformulainputfilter.cc
+++ b/lib/kformula/kformulainputfilter.cpp
diff --git a/lib/kformula/kformulamathmlread.cc b/lib/kformula/kformulamathmlread.cpp
index ff941d6f3..ff941d6f3 100644
--- a/lib/kformula/kformulamathmlread.cc
+++ b/lib/kformula/kformulamathmlread.cpp
diff --git a/lib/kformula/kformulamimesource.cc b/lib/kformula/kformulamimesource.cpp
index 4c7df0c77..4c7df0c77 100644
--- a/lib/kformula/kformulamimesource.cc
+++ b/lib/kformula/kformulamimesource.cpp
diff --git a/lib/kformula/kformulaview.cc b/lib/kformula/kformulaview.cpp
index 1e50694da..1e50694da 100644
--- a/lib/kformula/kformulaview.cc
+++ b/lib/kformula/kformulaview.cpp
diff --git a/lib/kformula/kformulawidget.cc b/lib/kformula/kformulawidget.cpp
index 68f941d98..68f941d98 100644
--- a/lib/kformula/kformulawidget.cc
+++ b/lib/kformula/kformulawidget.cpp
diff --git a/lib/kformula/main.cc b/lib/kformula/main.cpp
index c92adfd74..c92adfd74 100644
--- a/lib/kformula/main.cc
+++ b/lib/kformula/main.cpp
diff --git a/lib/kformula/matrixelement.cc b/lib/kformula/matrixelement.cpp
index 6b8783802..6b8783802 100644
--- a/lib/kformula/matrixelement.cc
+++ b/lib/kformula/matrixelement.cpp
diff --git a/lib/kformula/numberelement.cc b/lib/kformula/numberelement.cpp
index 7705e3ab5..7705e3ab5 100644
--- a/lib/kformula/numberelement.cc
+++ b/lib/kformula/numberelement.cpp
diff --git a/lib/kformula/oasiscreationstrategy.cc b/lib/kformula/oasiscreationstrategy.cpp
index 7d7a65cc1..7d7a65cc1 100644
--- a/lib/kformula/oasiscreationstrategy.cc
+++ b/lib/kformula/oasiscreationstrategy.cpp
diff --git a/lib/kformula/operatordictionary.cc b/lib/kformula/operatordictionary.cpp
index 787a58b55..787a58b55 100644
--- a/lib/kformula/operatordictionary.cc
+++ b/lib/kformula/operatordictionary.cpp
diff --git a/lib/kformula/operatorelement.cc b/lib/kformula/operatorelement.cpp
index 882eed01e..882eed01e 100644
--- a/lib/kformula/operatorelement.cc
+++ b/lib/kformula/operatorelement.cpp
diff --git a/lib/kformula/paddedelement.cc b/lib/kformula/paddedelement.cpp
index e4f28ce71..e4f28ce71 100644
--- a/lib/kformula/paddedelement.cc
+++ b/lib/kformula/paddedelement.cpp
diff --git a/lib/kformula/phantomelement.cc b/lib/kformula/phantomelement.cpp
index 78b0a1cb1..78b0a1cb1 100644
--- a/lib/kformula/phantomelement.cc
+++ b/lib/kformula/phantomelement.cpp
diff --git a/lib/kformula/prototype/gensymbolfontmap.py b/lib/kformula/prototype/gensymbolfontmap.py
index a13738152..df06eeed8 100644
--- a/lib/kformula/prototype/gensymbolfontmap.py
+++ b/lib/kformula/prototype/gensymbolfontmap.py
@@ -62,12 +62,12 @@ def write_header(f):
'''
def main():
- f = open('../symbolfontmapping.cc', 'w')
+ f = open('../symbolfontmapping.cpp', 'w')
write_header(f)
writeFontTable("symbol", f)
f.close()
- f = open('../esstixfontmapping.cc', 'w')
+ f = open('../esstixfontmapping.cpp', 'w')
write_header(f)
fontnames = [ "esstixnine",
"esstixthirteen",
@@ -90,7 +90,7 @@ def main():
writeFontTable(fn, f)
f.close()
- f = open('../cmmapping.cc', 'w')
+ f = open('../cmmapping.cpp', 'w')
write_header(f)
fontnames = [ "cmbx10",
"cmex10",
@@ -107,7 +107,7 @@ def main():
writeFontTable(fn, f)
f.close()
- f = open('../unicodenames.cc', 'w')
+ f = open('../unicodenames.cpp', 'w')
write_header(f)
print >>f, 'struct UnicodeNameTable { short unicode; const char* name; };'
print >>f, 'static UnicodeNameTable nameTable[] = {'
diff --git a/lib/kformula/rootelement.cc b/lib/kformula/rootelement.cpp
index 5e511cbee..5e511cbee 100644
--- a/lib/kformula/rootelement.cc
+++ b/lib/kformula/rootelement.cpp
diff --git a/lib/kformula/scripts/bynames.py b/lib/kformula/scripts/bynames.py
index afb9ece55..6b8c1d7ae 100755
--- a/lib/kformula/scripts/bynames.py
+++ b/lib/kformula/scripts/bynames.py
@@ -144,7 +144,7 @@ if __name__ == '__main__':
write_header( fh )
write_h( fh )
fh.close()
- fcc = open( '../entities.cc', 'w' )
+ fcc = open( '../entities.cpp', 'w' )
write_header( fcc )
fr = open( sys.argv[1] )
write_cc( fr , fcc )
diff --git a/lib/kformula/scripts/oper-dict.py b/lib/kformula/scripts/oper-dict.py
index 49191ef62..e9e105508 100755
--- a/lib/kformula/scripts/oper-dict.py
+++ b/lib/kformula/scripts/oper-dict.py
@@ -247,7 +247,7 @@ if __name__ == '__main__':
write_header( fh )
write_h( fh )
fh.close()
- fcc = codecs.open( '../operatordictionary.cc', 'w', 'utf-8' )
+ fcc = codecs.open( '../operatordictionary.cpp', 'w', 'utf-8' )
write_header( fcc )
fr = open( sys.argv[1] )
write_cc( fr , fcc )
diff --git a/lib/kformula/sequenceelement.cc b/lib/kformula/sequenceelement.cpp
index 187bcd65b..187bcd65b 100644
--- a/lib/kformula/sequenceelement.cc
+++ b/lib/kformula/sequenceelement.cpp
diff --git a/lib/kformula/sequenceparser.cc b/lib/kformula/sequenceparser.cpp
index bbc2f0b10..bbc2f0b10 100644
--- a/lib/kformula/sequenceparser.cc
+++ b/lib/kformula/sequenceparser.cpp
diff --git a/lib/kformula/spaceelement.cc b/lib/kformula/spaceelement.cpp
index 7d3723602..7d3723602 100644
--- a/lib/kformula/spaceelement.cc
+++ b/lib/kformula/spaceelement.cpp
diff --git a/lib/kformula/stringelement.cc b/lib/kformula/stringelement.cpp
index e98510331..e98510331 100644
--- a/lib/kformula/stringelement.cc
+++ b/lib/kformula/stringelement.cpp
diff --git a/lib/kformula/styleelement.cc b/lib/kformula/styleelement.cpp
index de7604532..de7604532 100644
--- a/lib/kformula/styleelement.cc
+++ b/lib/kformula/styleelement.cpp
diff --git a/lib/kformula/symbolaction.cc b/lib/kformula/symbolaction.cpp
index 8fe3d8f8a..8fe3d8f8a 100644
--- a/lib/kformula/symbolaction.cc
+++ b/lib/kformula/symbolaction.cpp
diff --git a/lib/kformula/symbolelement.cc b/lib/kformula/symbolelement.cpp
index 31787b160..31787b160 100644
--- a/lib/kformula/symbolelement.cc
+++ b/lib/kformula/symbolelement.cpp
diff --git a/lib/kformula/symbolfontmapping.cc b/lib/kformula/symbolfontmapping.cpp
index 71fbfcb09..71fbfcb09 100644
--- a/lib/kformula/symbolfontmapping.cc
+++ b/lib/kformula/symbolfontmapping.cpp
diff --git a/lib/kformula/symboltable.cc b/lib/kformula/symboltable.cc
deleted file mode 100644
index aca50b3ab..000000000
--- a/lib/kformula/symboltable.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2001 Andrea Rizzi <rizzi@kde.org>
- Ulrich Kuettler <ulrich.kuettler@mailbox.tu-dresden.de>
- Copyright (C) 2006 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-
-#include <tqfile.h>
-#include <tqregexp.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqtextstream.h>
-#include <tqfontmetrics.h>
-
-#include <tdeconfig.h>
-#include <kdebug.h>
-#include <tdeglobal.h>
-#include <tdelocale.h>
-#include <kstandarddirs.h>
-
-#include "symboltable.h"
-#include "contextstyle.h"
-#include "unicodetable.cc"
-
-
-KFORMULA_NAMESPACE_BEGIN
-
-#include "symbolfontmapping.cc"
-
-SymbolFontHelper::SymbolFontHelper()
- : greek("abgdezhqiklmnxpvrstufjcywGDTQLXPSUFYVW")
-{
- for ( uint i = 0; symbolMap[ i ].unicode != 0; i++ ) {
- compatibility[ symbolMap[ i ].pos ] = symbolMap[ i ].unicode;
- }
-}
-
-TQChar SymbolFontHelper::unicodeFromSymbolFont( TQChar pos ) const
-{
- if ( compatibility.contains( pos ) ) {
- return compatibility[ pos.latin1() ];
- }
- return TQChar::null;
-}
-
-
-SymbolTable::SymbolTable()
-{
-}
-
-
-void SymbolTable::init( const TQFont& font )
-{
- backupFont = font;
- for ( int i=0; operatorTable[i].unicode != 0; ++i ) {
- names[TQChar( operatorTable[i].unicode )] = get_name( operatorTable[i] );
- entries[get_name( operatorTable[i] )] = TQChar( operatorTable[i].unicode );
- }
- for ( int i=0; arrowTable[i].unicode != 0; ++i ) {
- names[TQChar( arrowTable[i].unicode )] = get_name( arrowTable[i] );
- entries[get_name( arrowTable[i] )] = TQChar( arrowTable[i].unicode );
- }
- for ( int i=0; greekTable[i].unicode != 0; ++i ) {
- names[TQChar( greekTable[i].unicode )] = get_name( greekTable[i] );
- entries[get_name( greekTable[i] )] = TQChar( greekTable[i].unicode );
- }
-}
-
-bool SymbolTable::contains(TQString name) const
-{
- return entries.find( name ) != entries.end();
-}
-
-TQChar SymbolTable::unicode(TQString name) const
-{
- return entries[ name ];
-}
-
-
-TQString SymbolTable::name( TQChar symbol ) const
-{
- return names[symbol];
-}
-
-TQFont SymbolTable::font( TQChar symbol, const TQFont& f ) const {
- TQFontMetrics fm( f );
- if ( fm.inFont( symbol ) ) {
- return f;
- }
- return TQFont("Arev Sans");
-}
-
-CharClass SymbolTable::charClass( TQChar symbol ) const
-{
- return ORDINARY;
- // FIXME
-// return entry( symbol, style ).charClass();
-}
-
-
-TQChar SymbolTable::unicodeFromSymbolFont( TQChar pos ) const
-{
- return symbolFontHelper.unicodeFromSymbolFont( pos );
-}
-
-
-TQString SymbolTable::greekLetters() const
-{
- return symbolFontHelper.greekLetters();
-}
-
-
-TQStringList SymbolTable::allNames() const
-{
- TQStringList list;
-
- for ( int i=0; operatorTable[i].unicode != 0; ++i ) {
- list.append( get_name( operatorTable[i] ));
- }
- for ( int i=0; arrowTable[i].unicode != 0; ++i ) {
- list.append( get_name( arrowTable[i] ));
- }
- for ( int i=0; greekTable[i].unicode != 0; ++i ) {
- list.append( get_name( greekTable[i] ) );
- }
- return list;
-}
-
-
-TQString SymbolTable::get_name( struct UnicodeNameTable entry ) const
-{
- if ( !*entry.name ) {
- return "U" + TQString( "%1" ).arg( entry.unicode, 4, 16 ).upper();
- }
- return entry.name;
-}
-
-KFORMULA_NAMESPACE_END
diff --git a/lib/kformula/symboltable.cpp b/lib/kformula/symboltable.cpp
new file mode 100644
index 000000000..a25e1b157
--- /dev/null
+++ b/lib/kformula/symboltable.cpp
@@ -0,0 +1,152 @@
+/* This file is part of the KDE project
+ Copyright (C) 2001 Andrea Rizzi <rizzi@kde.org>
+ Ulrich Kuettler <ulrich.kuettler@mailbox.tu-dresden.de>
+ Copyright (C) 2006 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include <tqfile.h>
+#include <tqregexp.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqtextstream.h>
+#include <tqfontmetrics.h>
+
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <tdeglobal.h>
+#include <tdelocale.h>
+#include <kstandarddirs.h>
+
+#include "symboltable.h"
+#include "contextstyle.h"
+#include "unicodetable.cpp"
+
+
+KFORMULA_NAMESPACE_BEGIN
+
+#include "symbolfontmapping.cpp"
+
+SymbolFontHelper::SymbolFontHelper()
+ : greek("abgdezhqiklmnxpvrstufjcywGDTQLXPSUFYVW")
+{
+ for ( uint i = 0; symbolMap[ i ].unicode != 0; i++ ) {
+ compatibility[ symbolMap[ i ].pos ] = symbolMap[ i ].unicode;
+ }
+}
+
+TQChar SymbolFontHelper::unicodeFromSymbolFont( TQChar pos ) const
+{
+ if ( compatibility.contains( pos ) ) {
+ return compatibility[ pos.latin1() ];
+ }
+ return TQChar::null;
+}
+
+
+SymbolTable::SymbolTable()
+{
+}
+
+
+void SymbolTable::init( const TQFont& font )
+{
+ backupFont = font;
+ for ( int i=0; operatorTable[i].unicode != 0; ++i ) {
+ names[TQChar( operatorTable[i].unicode )] = get_name( operatorTable[i] );
+ entries[get_name( operatorTable[i] )] = TQChar( operatorTable[i].unicode );
+ }
+ for ( int i=0; arrowTable[i].unicode != 0; ++i ) {
+ names[TQChar( arrowTable[i].unicode )] = get_name( arrowTable[i] );
+ entries[get_name( arrowTable[i] )] = TQChar( arrowTable[i].unicode );
+ }
+ for ( int i=0; greekTable[i].unicode != 0; ++i ) {
+ names[TQChar( greekTable[i].unicode )] = get_name( greekTable[i] );
+ entries[get_name( greekTable[i] )] = TQChar( greekTable[i].unicode );
+ }
+}
+
+bool SymbolTable::contains(TQString name) const
+{
+ return entries.find( name ) != entries.end();
+}
+
+TQChar SymbolTable::unicode(TQString name) const
+{
+ return entries[ name ];
+}
+
+
+TQString SymbolTable::name( TQChar symbol ) const
+{
+ return names[symbol];
+}
+
+TQFont SymbolTable::font( TQChar symbol, const TQFont& f ) const {
+ TQFontMetrics fm( f );
+ if ( fm.inFont( symbol ) ) {
+ return f;
+ }
+ return TQFont("Arev Sans");
+}
+
+CharClass SymbolTable::charClass( TQChar symbol ) const
+{
+ return ORDINARY;
+ // FIXME
+// return entry( symbol, style ).charClass();
+}
+
+
+TQChar SymbolTable::unicodeFromSymbolFont( TQChar pos ) const
+{
+ return symbolFontHelper.unicodeFromSymbolFont( pos );
+}
+
+
+TQString SymbolTable::greekLetters() const
+{
+ return symbolFontHelper.greekLetters();
+}
+
+
+TQStringList SymbolTable::allNames() const
+{
+ TQStringList list;
+
+ for ( int i=0; operatorTable[i].unicode != 0; ++i ) {
+ list.append( get_name( operatorTable[i] ));
+ }
+ for ( int i=0; arrowTable[i].unicode != 0; ++i ) {
+ list.append( get_name( arrowTable[i] ));
+ }
+ for ( int i=0; greekTable[i].unicode != 0; ++i ) {
+ list.append( get_name( greekTable[i] ) );
+ }
+ return list;
+}
+
+
+TQString SymbolTable::get_name( struct UnicodeNameTable entry ) const
+{
+ if ( !*entry.name ) {
+ return "U" + TQString( "%1" ).arg( entry.unicode, 4, 16 ).upper();
+ }
+ return entry.name;
+}
+
+KFORMULA_NAMESPACE_END
diff --git a/lib/kformula/textelement.cc b/lib/kformula/textelement.cpp
index 7f146b49b..7f146b49b 100644
--- a/lib/kformula/textelement.cc
+++ b/lib/kformula/textelement.cpp
diff --git a/lib/kformula/tokenelement.cc b/lib/kformula/tokenelement.cpp
index 9970ac450..9970ac450 100644
--- a/lib/kformula/tokenelement.cc
+++ b/lib/kformula/tokenelement.cpp
diff --git a/lib/kformula/tokenstyleelement.cc b/lib/kformula/tokenstyleelement.cpp
index fcce16e7c..fcce16e7c 100644
--- a/lib/kformula/tokenstyleelement.cc
+++ b/lib/kformula/tokenstyleelement.cpp
diff --git a/lib/kformula/unicodetable.cc b/lib/kformula/unicodetable.cpp
index 23dc8636e..23dc8636e 100644
--- a/lib/kformula/unicodetable.cc
+++ b/lib/kformula/unicodetable.cpp
diff --git a/lib/kofficecore/KoApplicationIface.cc b/lib/kofficecore/KoApplicationIface.cpp
index e8995ad66..e8995ad66 100644
--- a/lib/kofficecore/KoApplicationIface.cc
+++ b/lib/kofficecore/KoApplicationIface.cpp
diff --git a/lib/kofficecore/KoDocument.cpp b/lib/kofficecore/KoDocument.cpp
index 67e70ecc8..b8dbea814 100644
--- a/lib/kofficecore/KoDocument.cpp
+++ b/lib/kofficecore/KoDocument.cpp
@@ -74,7 +74,7 @@
// some kind of relative path to KoDocumentChild
#define INTERNAL_PROTOCOL "intern"
#define INTERNAL_PREFIX "intern:/"
-// Warning, keep it sync in koStore.cc and koDocumentChild.cc
+// Warning, keep it sync in koStore.cpp and koDocumentChild.cpp
TQPtrList<KoDocument> *KoDocument::s_documentList=0L;
@@ -138,7 +138,7 @@ public:
bool m_confirmNonNativeSave [2]; // used to pop up a dialog when saving for the
// first time if the file is in a foreign format
// (Save/Save As, Export)
- int m_specialOutputFlag; // See KoFileDialog in koMainWindow.cc
+ int m_specialOutputFlag; // See KoFileDialog in koMainWindow.cpp
bool m_isImporting, m_isExporting; // File --> Import/Export vs File --> Open/Save
TQTimer m_autoSaveTimer;
diff --git a/lib/kofficecore/KoDocumentChild.cpp b/lib/kofficecore/KoDocumentChild.cpp
index 00d6038ba..90a992801 100644
--- a/lib/kofficecore/KoDocumentChild.cpp
+++ b/lib/kofficecore/KoDocumentChild.cpp
@@ -44,7 +44,7 @@
// so let's simply make it "tar" !
#define STORE_PROTOCOL "tar"
#define INTERNAL_PROTOCOL "intern"
-// Warning, keep it sync in koStore.cc and koDocument.cc
+// Warning, keep it sync in koStore.cpp and koDocument.cpp
/**********************************************************
*
diff --git a/lib/kofficecore/KoDocumentIface.cc b/lib/kofficecore/KoDocumentIface.cpp
index e0196fdf3..e0196fdf3 100644
--- a/lib/kofficecore/KoDocumentIface.cc
+++ b/lib/kofficecore/KoDocumentIface.cpp
diff --git a/lib/kofficecore/KoMainWindowIface.cc b/lib/kofficecore/KoMainWindowIface.cc
deleted file mode 100644
index 146831880..000000000
--- a/lib/kofficecore/KoMainWindowIface.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2001 David Faure <faure@kde.org>
-
- $Id: KoMainWindowIface.cc 508787 2006-02-12 18:28:12Z ingwa $
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-#include "KoMainWindowIface.h"
-
-#include "KoMainWindow.h"
-
-#include <tdeapplication.h>
-#include <dcopclient.h>
-#include <kdcopactionproxy.h>
-
-KoMainWindowIface::KoMainWindowIface( KoMainWindow *mainwindow )
- : DCOPObject( TQT_TQOBJECT(mainwindow) )
-{
- m_pMainWindow = mainwindow;
- m_actionProxy = new KDCOPActionProxy( mainwindow->actionCollection(), this );
-}
-
-KoMainWindowIface::~KoMainWindowIface()
-{
- delete m_actionProxy;
-}
-
-DCOPRef KoMainWindowIface::action( const TQCString &name )
-{
- return DCOPRef( kapp->dcopClient()->appId(), m_actionProxy->actionObjectId( name ) );
-}
-
-QCStringList KoMainWindowIface::actions()
-{
- QCStringList res;
- TQValueList<TDEAction *> lst = m_actionProxy->actions();
- TQValueList<TDEAction *>::ConstIterator it = lst.begin();
- TQValueList<TDEAction *>::ConstIterator end = lst.end();
- for (; it != end; ++it )
- res.append( (*it)->name() );
-
- return res;
-}
-
-TQMap<TQCString,DCOPRef> KoMainWindowIface::actionMap()
-{
- return m_actionProxy->actionMap();
-}
-
-ASYNC KoMainWindowIface::print(bool quick) {
- m_pMainWindow->print(quick);
-}
diff --git a/lib/kofficecore/KoMainWindowIface.cpp b/lib/kofficecore/KoMainWindowIface.cpp
new file mode 100644
index 000000000..51d782b14
--- /dev/null
+++ b/lib/kofficecore/KoMainWindowIface.cpp
@@ -0,0 +1,65 @@
+/* This file is part of the KDE project
+ Copyright (c) 2001 David Faure <faure@kde.org>
+
+ $Id: KoMainWindowIface.cpp 508787 2006-02-12 18:28:12Z ingwa $
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+#include "KoMainWindowIface.h"
+
+#include "KoMainWindow.h"
+
+#include <tdeapplication.h>
+#include <dcopclient.h>
+#include <kdcopactionproxy.h>
+
+KoMainWindowIface::KoMainWindowIface( KoMainWindow *mainwindow )
+ : DCOPObject( TQT_TQOBJECT(mainwindow) )
+{
+ m_pMainWindow = mainwindow;
+ m_actionProxy = new KDCOPActionProxy( mainwindow->actionCollection(), this );
+}
+
+KoMainWindowIface::~KoMainWindowIface()
+{
+ delete m_actionProxy;
+}
+
+DCOPRef KoMainWindowIface::action( const TQCString &name )
+{
+ return DCOPRef( kapp->dcopClient()->appId(), m_actionProxy->actionObjectId( name ) );
+}
+
+QCStringList KoMainWindowIface::actions()
+{
+ QCStringList res;
+ TQValueList<TDEAction *> lst = m_actionProxy->actions();
+ TQValueList<TDEAction *>::ConstIterator it = lst.begin();
+ TQValueList<TDEAction *>::ConstIterator end = lst.end();
+ for (; it != end; ++it )
+ res.append( (*it)->name() );
+
+ return res;
+}
+
+TQMap<TQCString,DCOPRef> KoMainWindowIface::actionMap()
+{
+ return m_actionProxy->actionMap();
+}
+
+ASYNC KoMainWindowIface::print(bool quick) {
+ m_pMainWindow->print(quick);
+}
diff --git a/lib/kofficecore/KoViewIface.cc b/lib/kofficecore/KoViewIface.cc
deleted file mode 100644
index ae5449b9f..000000000
--- a/lib/kofficecore/KoViewIface.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
-
- $Id: KoViewIface.cc 508787 2006-02-12 18:28:12Z ingwa $
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
-*/
-#include "KoViewIface.h"
-
-#include "KoView.h"
-
-#include <tdeapplication.h>
-#include <dcopclient.h>
-#include <kdcopactionproxy.h>
-#include <tdeaction.h>
-
-//static
-TQCString KoViewIface::newIfaceName()
-{
- static int s_viewIFNumber = 0;
- TQCString name; name.setNum( s_viewIFNumber++ ); name.prepend("View-");
- return name;
-}
-
-KoViewIface::KoViewIface( KoView *view )
- : DCOPObject( newIfaceName() )
-{
- m_actionProxy = new KDCOPActionProxy( view->actionCollection(), this );
-}
-
-KoViewIface::KoViewIface( const char *name, KoView *view )
- : DCOPObject( name )
-{
- m_pView = view;
- m_actionProxy = new KDCOPActionProxy( view->actionCollection(), this );
-}
-
-KoViewIface::~KoViewIface()
-{
- delete m_actionProxy;
-}
-
-DCOPRef KoViewIface::action( const TQCString &name )
-{
- return DCOPRef( kapp->dcopClient()->appId(), m_actionProxy->actionObjectId( name ) );
-}
-
-QCStringList KoViewIface::actions()
-{
- QCStringList res;
- TQValueList<TDEAction *> lst = m_actionProxy->actions();
- TQValueList<TDEAction *>::ConstIterator it = lst.begin();
- TQValueList<TDEAction *>::ConstIterator end = lst.end();
- for (; it != end; ++it )
- res.append( (*it)->name() );
-
- return res;
-}
-
-TQMap<TQCString,DCOPRef> KoViewIface::actionMap()
-{
- return m_actionProxy->actionMap();
-}
diff --git a/lib/kofficecore/KoViewIface.cpp b/lib/kofficecore/KoViewIface.cpp
new file mode 100644
index 000000000..18c5dae57
--- /dev/null
+++ b/lib/kofficecore/KoViewIface.cpp
@@ -0,0 +1,76 @@
+/* This file is part of the KDE project
+ Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
+
+ $Id: KoViewIface.cpp 508787 2006-02-12 18:28:12Z ingwa $
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+#include "KoViewIface.h"
+
+#include "KoView.h"
+
+#include <tdeapplication.h>
+#include <dcopclient.h>
+#include <kdcopactionproxy.h>
+#include <tdeaction.h>
+
+//static
+TQCString KoViewIface::newIfaceName()
+{
+ static int s_viewIFNumber = 0;
+ TQCString name; name.setNum( s_viewIFNumber++ ); name.prepend("View-");
+ return name;
+}
+
+KoViewIface::KoViewIface( KoView *view )
+ : DCOPObject( newIfaceName() )
+{
+ m_actionProxy = new KDCOPActionProxy( view->actionCollection(), this );
+}
+
+KoViewIface::KoViewIface( const char *name, KoView *view )
+ : DCOPObject( name )
+{
+ m_pView = view;
+ m_actionProxy = new KDCOPActionProxy( view->actionCollection(), this );
+}
+
+KoViewIface::~KoViewIface()
+{
+ delete m_actionProxy;
+}
+
+DCOPRef KoViewIface::action( const TQCString &name )
+{
+ return DCOPRef( kapp->dcopClient()->appId(), m_actionProxy->actionObjectId( name ) );
+}
+
+QCStringList KoViewIface::actions()
+{
+ QCStringList res;
+ TQValueList<TDEAction *> lst = m_actionProxy->actions();
+ TQValueList<TDEAction *>::ConstIterator it = lst.begin();
+ TQValueList<TDEAction *>::ConstIterator end = lst.end();
+ for (; it != end; ++it )
+ res.append( (*it)->name() );
+
+ return res;
+}
+
+TQMap<TQCString,DCOPRef> KoViewIface::actionMap()
+{
+ return m_actionProxy->actionMap();
+}
diff --git a/lib/kofficecore/Makefile.am b/lib/kofficecore/Makefile.am
index 0a2d9de22..3e83bfffd 100644
--- a/lib/kofficecore/Makefile.am
+++ b/lib/kofficecore/Makefile.am
@@ -24,9 +24,9 @@ libkofficecore_la_SOURCES = KoDocument.cpp \
KoDocumentInfoDlg.cpp KoFactory.cpp KoChild.cpp \
koDocumentInfoAboutWidget.ui koDocumentInfoAuthorWidget.ui \
koDocumentInfoUserMetadataWidget.ui \
- KoApplicationIface.cc KoApplicationIface.skel \
- KoDocumentIface.cc KoDocumentIface.skel KoViewIface.cc KoViewIface.skel \
- KoMainWindowIface.cc KoMainWindowIface.skel kofficeversion.cc KoOasisStyles.cpp \
+ KoApplicationIface.cpp KoApplicationIface.skel \
+ KoDocumentIface.cpp KoDocumentIface.skel KoViewIface.cpp KoViewIface.skel \
+ KoMainWindowIface.cpp KoMainWindowIface.skel kofficeversion.cpp KoOasisStyles.cpp \
KoStyleStack.cpp KoGenStyles.cpp KoOasisSettings.cpp KoPageLayout.cpp \
KoFileDialog.cpp KoXmlNS.cpp KoDom.cpp Koversiondialog.cpp KoOasisStore.cpp \
kkbdaccessextensions.cpp koDetailsPaneBase.ui koOpenPaneBase.ui KoOpenPane.cpp \
diff --git a/lib/kofficecore/kofficeversion.cc b/lib/kofficecore/kofficeversion.cpp
index 262664fce..262664fce 100644
--- a/lib/kofficecore/kofficeversion.cc
+++ b/lib/kofficecore/kofficeversion.cpp
diff --git a/lib/kofficeui/KoImageResource.cpp b/lib/kofficeui/KoImageResource.cpp
index 9f92ef3d5..9572b0602 100644
--- a/lib/kofficeui/KoImageResource.cpp
+++ b/lib/kofficeui/KoImageResource.cpp
@@ -1,5 +1,5 @@
/*
- * koImageResource.cc - part of KOffice
+ * koImageResource.cpp - part of KOffice
*
* Copyright (c) 2005 Thomas Zander <zander@kde.org>
*
diff --git a/lib/kopainter/Makefile.am b/lib/kopainter/Makefile.am
index 8143db4d0..310b5f8c7 100644
--- a/lib/kopainter/Makefile.am
+++ b/lib/kopainter/Makefile.am
@@ -1,18 +1,18 @@
INCLUDES= $(KOFFICECORE_INCLUDES) $(KOFFICEUI_INCLUDES) $(all_includes)
lib_LTLIBRARIES = libkopainter.la
-libkopainter_la_SOURCES = svgpathparser.cc \
- koColor.cc \
- koFrameButton.cc \
- koColorSlider.cc \
- koColorChooser.cc \
- koIconChooser.cc \
- kogradientmanager.cc \
- ko_color_wheel.cc \
- ko_gray_widget.cc \
- ko_hsv_widget.cc \
- ko_rgb_widget.cc \
- ko_cmyk_widget.cc
+libkopainter_la_SOURCES = svgpathparser.cpp \
+ koColor.cpp \
+ koFrameButton.cpp \
+ koColorSlider.cpp \
+ koColorChooser.cpp \
+ koIconChooser.cpp \
+ kogradientmanager.cpp \
+ ko_color_wheel.cpp \
+ ko_gray_widget.cpp \
+ ko_hsv_widget.cpp \
+ ko_rgb_widget.cpp \
+ ko_cmyk_widget.cpp
libkopainter_la_LDFLAGS = $(all_libraries) -version-info 2:0:0 -no-undefined
diff --git a/lib/kopainter/koColor.cc b/lib/kopainter/koColor.cpp
index 813aee8dc..813aee8dc 100644
--- a/lib/kopainter/koColor.cc
+++ b/lib/kopainter/koColor.cpp
diff --git a/lib/kopainter/koColorChooser.cc b/lib/kopainter/koColorChooser.cpp
index 02439a8cb..02439a8cb 100644
--- a/lib/kopainter/koColorChooser.cc
+++ b/lib/kopainter/koColorChooser.cpp
diff --git a/lib/kopainter/koColorSlider.cc b/lib/kopainter/koColorSlider.cpp
index 6e7c0239e..6e7c0239e 100644
--- a/lib/kopainter/koColorSlider.cc
+++ b/lib/kopainter/koColorSlider.cpp
diff --git a/lib/kopainter/koFrameButton.cc b/lib/kopainter/koFrameButton.cpp
index d5f2dada0..d5f2dada0 100644
--- a/lib/kopainter/koFrameButton.cc
+++ b/lib/kopainter/koFrameButton.cpp
diff --git a/lib/kopainter/koIconChooser.cc b/lib/kopainter/koIconChooser.cpp
index e8647ffb3..e8647ffb3 100644
--- a/lib/kopainter/koIconChooser.cc
+++ b/lib/kopainter/koIconChooser.cpp
diff --git a/lib/kopainter/ko_cmyk_widget.cc b/lib/kopainter/ko_cmyk_widget.cpp
index af2136f97..af2136f97 100644
--- a/lib/kopainter/ko_cmyk_widget.cc
+++ b/lib/kopainter/ko_cmyk_widget.cpp
diff --git a/lib/kopainter/ko_color_wheel.cc b/lib/kopainter/ko_color_wheel.cpp
index f309125ca..f309125ca 100644
--- a/lib/kopainter/ko_color_wheel.cc
+++ b/lib/kopainter/ko_color_wheel.cpp
diff --git a/lib/kopainter/ko_gray_widget.cc b/lib/kopainter/ko_gray_widget.cpp
index af09dfa08..af09dfa08 100644
--- a/lib/kopainter/ko_gray_widget.cc
+++ b/lib/kopainter/ko_gray_widget.cpp
diff --git a/lib/kopainter/ko_hsv_widget.cc b/lib/kopainter/ko_hsv_widget.cpp
index 8d77bedc9..8d77bedc9 100644
--- a/lib/kopainter/ko_hsv_widget.cc
+++ b/lib/kopainter/ko_hsv_widget.cpp
diff --git a/lib/kopainter/ko_rgb_widget.cc b/lib/kopainter/ko_rgb_widget.cpp
index 7680d50ac..7680d50ac 100644
--- a/lib/kopainter/ko_rgb_widget.cc
+++ b/lib/kopainter/ko_rgb_widget.cpp
diff --git a/lib/kopainter/kogradientmanager.cc b/lib/kopainter/kogradientmanager.cpp
index c95a5671c..c95a5671c 100644
--- a/lib/kopainter/kogradientmanager.cc
+++ b/lib/kopainter/kogradientmanager.cpp
diff --git a/lib/kopainter/svgpathparser.cc b/lib/kopainter/svgpathparser.cpp
index 5698cd47e..5698cd47e 100644
--- a/lib/kopainter/svgpathparser.cc
+++ b/lib/kopainter/svgpathparser.cpp
diff --git a/lib/kopalette/Makefile.am b/lib/kopalette/Makefile.am
index ad9a29e02..e19b6a638 100644
--- a/lib/kopalette/Makefile.am
+++ b/lib/kopalette/Makefile.am
@@ -6,10 +6,10 @@ INCLUDES = -I$(srcdir) \
lib_LTLIBRARIES = libkopalette.la
libkopalette_la_SOURCES = \
- kopalette.cc \
- kopalettemanager.cc \
- kotoolboxpalette.cc \
- kotabpalette.cc
+ kopalette.cpp \
+ kopalettemanager.cpp \
+ kotoolboxpalette.cpp \
+ kotabpalette.cpp
libkopalette_la_LDFLAGS = -version-info 1:0:0 -no-undefined $(all_libraries)
libkopalette_la_LIBADD = $(LIB_KOFFICECORE)
diff --git a/lib/kopalette/kopalette.cc b/lib/kopalette/kopalette.cpp
index cd3922055..cd3922055 100644
--- a/lib/kopalette/kopalette.cc
+++ b/lib/kopalette/kopalette.cpp
diff --git a/lib/kopalette/kopalettemanager.cc b/lib/kopalette/kopalettemanager.cpp
index 26f309925..26f309925 100644
--- a/lib/kopalette/kopalettemanager.cc
+++ b/lib/kopalette/kopalettemanager.cpp
diff --git a/lib/kopalette/kotabpalette.cc b/lib/kopalette/kotabpalette.cpp
index 0e7988429..0e7988429 100644
--- a/lib/kopalette/kotabpalette.cc
+++ b/lib/kopalette/kotabpalette.cpp
diff --git a/lib/kopalette/kotoolboxpalette.cc b/lib/kopalette/kotoolboxpalette.cpp
index e4c2bd630..e4c2bd630 100644
--- a/lib/kopalette/kotoolboxpalette.cc
+++ b/lib/kopalette/kotoolboxpalette.cpp
diff --git a/lib/kotext/KoRichText.cpp b/lib/kotext/KoRichText.cpp
index cc0fe4a9a..5d3e99d11 100644
--- a/lib/kotext/KoRichText.cpp
+++ b/lib/kotext/KoRichText.cpp
@@ -1199,7 +1199,7 @@ void KoTextString::clear()
KoTextStringChar &ch = data[ i ];
if ( ch.isCustom() ) {
// Can't do that here, no access to the doc. See ~KoTextParag instead.
- // However clear() is also called by operator=, many times in kotextobject.cc...
+ // However clear() is also called by operator=, many times in kotextobject.cpp...
// Hopefully not with customitems in there...
//if ( doc )
// doc->unregisterCustomItem( ch->customItem(), this );
diff --git a/lib/kotext/KoTextFormatter.cpp b/lib/kotext/KoTextFormatter.cpp
index 39817a201..60e6528f5 100644
--- a/lib/kotext/KoTextFormatter.cpp
+++ b/lib/kotext/KoTextFormatter.cpp
@@ -39,7 +39,7 @@
// Hyphenation
//#define DEBUG_HYPHENATION
-/////// keep in sync with kotextformat.cc !
+/////// keep in sync with kotextformat.cpp !
//#define REF_IS_LU
KoTextFormatter::KoTextFormatter()
diff --git a/lib/kotext/KoTextParag.h b/lib/kotext/KoTextParag.h
index 86fc40116..c89582c5e 100644
--- a/lib/kotext/KoTextParag.h
+++ b/lib/kotext/KoTextParag.h
@@ -132,7 +132,7 @@ public:
uint alignment() const;
virtual void paint( TQPainter &painter, const TQColorGroup &cg, KoTextCursor *cursor, bool drawSelections,
- int clipx, int clipy, int clipw, int cliph ); // kotextparag.cc
+ int clipx, int clipy, int clipw, int cliph ); // kotextparag.cpp
int topMargin() const;
diff --git a/lib/kotext/KoTextViewIface.cc b/lib/kotext/KoTextViewIface.cpp
index dec0e0320..dec0e0320 100644
--- a/lib/kotext/KoTextViewIface.cc
+++ b/lib/kotext/KoTextViewIface.cpp
diff --git a/lib/kotext/Makefile.am b/lib/kotext/Makefile.am
index ab2214555..c186cd8ce 100644
--- a/lib/kotext/Makefile.am
+++ b/lib/kotext/Makefile.am
@@ -15,7 +15,7 @@ libkotext_la_SOURCES = KoComplexText.cpp KoRichText.cpp \
TDEFontDialog_local.cpp kofonttabbase.ui KoFontTab.cpp kohighlightingtabbase.ui KoHighlightingTab.cpp \
kodecorationtabbase.ui KoDecorationTab.cpp kolayouttabbase.ui KoLayoutTab.cpp kolanguagetabbase.ui KoLanguageTab.cpp \
KoFontDiaPreview.cpp KoCompletionDia.cpp KoCompletionBase.ui \
- KoTextViewIface.skel KoTextViewIface.cc KoFontDia.cpp KoBgSpellCheck.cpp \
+ KoTextViewIface.skel KoTextViewIface.cpp KoFontDia.cpp KoBgSpellCheck.cpp \
KoCommentDia.cpp KoSpell.cpp KoCreateStyleDia.cpp KoTextCustomItem.cpp \
KoImportStyleDia.cpp KoTextIterator.cpp KoOasisContext.cpp KoListStyleStack.cpp \
KoUserStyle.cpp KoUserStyleCollection.cpp KoParagStyle.cpp KoParagDecorationTab.ui \
diff --git a/lib/kotext/tests/kotextformattertest.cpp b/lib/kotext/tests/kotextformattertest.cpp
index 74014c2d5..69d5b1592 100644
--- a/lib/kotext/tests/kotextformattertest.cpp
+++ b/lib/kotext/tests/kotextformattertest.cpp
@@ -130,7 +130,7 @@ void KoTextFormatterTest::noWidthEverTest()
KoTextParag* parag = doc->firstParag();
parag->append( "abcdefghi" );
parag->format();
- // The resulting paragraph is NOT marked as formatted. See kotextformatter.cc -r1.79
+ // The resulting paragraph is NOT marked as formatted. See kotextformatter.cpp -r1.79
assert( !parag->isValid() );
doc->clear(false);
doc->setFlow( new KoTextFlow ); // default
diff --git a/lib/kross/python/cxx/Config.hxx b/lib/kross/python/cxx/Config.h
index 7959c4039..7959c4039 100644
--- a/lib/kross/python/cxx/Config.hxx
+++ b/lib/kross/python/cxx/Config.h
diff --git a/lib/kross/python/cxx/Exception.h b/lib/kross/python/cxx/Exception.h
new file mode 100644
index 000000000..94cfcff4a
--- /dev/null
+++ b/lib/kross/python/cxx/Exception.h
@@ -0,0 +1,212 @@
+//---------------------------------------------------------------------------//
+// Copyright 1998 The Regents of the University of California.
+// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
+//---------------------------------------------------------------------------//
+
+#ifndef __CXX_Exception_h
+#define __CXX_Exception_h
+
+#include "Python.h"
+#include "Config.h"
+#include "IndirectPythonInterface.h"
+
+#include <string>
+#include <iostream>
+
+// This mimics the Python structure, in order to minimize confusion
+namespace Py
+ {
+ class ExtensionExceptionType;
+
+ class Exception
+ {
+ public:
+ Exception( ExtensionExceptionType &exception, const std::string& reason );
+
+ explicit Exception ()
+ {}
+
+ Exception (const std::string& reason)
+ {
+ PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str());
+ }
+
+ Exception (PyObject* exception, const std::string& reason)
+ {
+ PyErr_SetString (exception, reason.c_str());
+ }
+
+
+ void clear() // clear the error
+ // technically but not philosophically const
+ {
+ PyErr_Clear();
+ }
+ };
+
+
+ // Abstract
+ class StandardError: public Exception
+ {
+ protected:
+ explicit StandardError()
+ {}
+ };
+
+ class LookupError: public StandardError
+ {
+ protected:
+ explicit LookupError()
+ {}
+ };
+
+ class ArithmeticError: public StandardError
+ {
+ protected:
+ explicit ArithmeticError()
+ {}
+ };
+
+ class EnvironmentError: public StandardError
+ {
+ protected:
+ explicit EnvironmentError()
+ {}
+ };
+
+ // Concrete
+
+ class TypeError: public StandardError
+ {
+ public:
+ TypeError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_TypeError(),reason.c_str());
+ }
+ };
+
+ class IndexError: public LookupError
+ {
+ public:
+ IndexError (const std::string& reason)
+ : LookupError()
+ {
+ PyErr_SetString (Py::_Exc_IndexError(), reason.c_str());
+ }
+ };
+
+ class AttributeError: public StandardError
+ {
+ public:
+ AttributeError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_AttributeError(), reason.c_str());
+ }
+ };
+
+ class NameError: public StandardError
+ {
+ public:
+ NameError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_NameError(), reason.c_str());
+ }
+ };
+
+ class RuntimeError: public StandardError
+ {
+ public:
+ RuntimeError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str());
+ }
+ };
+
+ class SystemError: public StandardError
+ {
+ public:
+ SystemError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_SystemError(),reason.c_str());
+ }
+ };
+
+ class KeyError: public LookupError
+ {
+ public:
+ KeyError (const std::string& reason)
+ : LookupError()
+ {
+ PyErr_SetString (Py::_Exc_KeyError(),reason.c_str());
+ }
+ };
+
+
+ class ValueError: public StandardError
+ {
+ public:
+ ValueError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_ValueError(), reason.c_str());
+ }
+ };
+
+ class OverflowError: public ArithmeticError
+ {
+ public:
+ OverflowError (const std::string& reason)
+ : ArithmeticError()
+ {
+ PyErr_SetString (Py::_Exc_OverflowError(), reason.c_str());
+ }
+ };
+
+ class ZeroDivisionError: public ArithmeticError
+ {
+ public:
+ ZeroDivisionError (const std::string& reason)
+ : ArithmeticError()
+ {
+ PyErr_SetString (Py::_Exc_ZeroDivisionError(), reason.c_str());
+ }
+ };
+
+ class FloatingPointError: public ArithmeticError
+ {
+ public:
+ FloatingPointError (const std::string& reason)
+ : ArithmeticError()
+ {
+ PyErr_SetString (Py::_Exc_FloatingPointError(), reason.c_str());
+ }
+ };
+
+ class MemoryError: public StandardError
+ {
+ public:
+ MemoryError (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_MemoryError(), reason.c_str());
+ }
+ };
+
+ class SystemExit: public StandardError
+ {
+ public:
+ SystemExit (const std::string& reason)
+ : StandardError()
+ {
+ PyErr_SetString (Py::_Exc_SystemExit(),reason.c_str());
+ }
+ };
+
+ }// Py
+
+#endif
diff --git a/lib/kross/python/cxx/Exception.hxx b/lib/kross/python/cxx/Exception.hxx
deleted file mode 100644
index 044d4198e..000000000
--- a/lib/kross/python/cxx/Exception.hxx
+++ /dev/null
@@ -1,212 +0,0 @@
-//---------------------------------------------------------------------------//
-// Copyright 1998 The Regents of the University of California.
-// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
-//---------------------------------------------------------------------------//
-
-#ifndef __CXX_Exception_h
-#define __CXX_Exception_h
-
-#include "Python.h"
-#include "Config.hxx"
-#include "IndirectPythonInterface.hxx"
-
-#include <string>
-#include <iostream>
-
-// This mimics the Python structure, in order to minimize confusion
-namespace Py
- {
- class ExtensionExceptionType;
-
- class Exception
- {
- public:
- Exception( ExtensionExceptionType &exception, const std::string& reason );
-
- explicit Exception ()
- {}
-
- Exception (const std::string& reason)
- {
- PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str());
- }
-
- Exception (PyObject* exception, const std::string& reason)
- {
- PyErr_SetString (exception, reason.c_str());
- }
-
-
- void clear() // clear the error
- // technically but not philosophically const
- {
- PyErr_Clear();
- }
- };
-
-
- // Abstract
- class StandardError: public Exception
- {
- protected:
- explicit StandardError()
- {}
- };
-
- class LookupError: public StandardError
- {
- protected:
- explicit LookupError()
- {}
- };
-
- class ArithmeticError: public StandardError
- {
- protected:
- explicit ArithmeticError()
- {}
- };
-
- class EnvironmentError: public StandardError
- {
- protected:
- explicit EnvironmentError()
- {}
- };
-
- // Concrete
-
- class TypeError: public StandardError
- {
- public:
- TypeError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_TypeError(),reason.c_str());
- }
- };
-
- class IndexError: public LookupError
- {
- public:
- IndexError (const std::string& reason)
- : LookupError()
- {
- PyErr_SetString (Py::_Exc_IndexError(), reason.c_str());
- }
- };
-
- class AttributeError: public StandardError
- {
- public:
- AttributeError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_AttributeError(), reason.c_str());
- }
- };
-
- class NameError: public StandardError
- {
- public:
- NameError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_NameError(), reason.c_str());
- }
- };
-
- class RuntimeError: public StandardError
- {
- public:
- RuntimeError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_RuntimeError(), reason.c_str());
- }
- };
-
- class SystemError: public StandardError
- {
- public:
- SystemError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_SystemError(),reason.c_str());
- }
- };
-
- class KeyError: public LookupError
- {
- public:
- KeyError (const std::string& reason)
- : LookupError()
- {
- PyErr_SetString (Py::_Exc_KeyError(),reason.c_str());
- }
- };
-
-
- class ValueError: public StandardError
- {
- public:
- ValueError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_ValueError(), reason.c_str());
- }
- };
-
- class OverflowError: public ArithmeticError
- {
- public:
- OverflowError (const std::string& reason)
- : ArithmeticError()
- {
- PyErr_SetString (Py::_Exc_OverflowError(), reason.c_str());
- }
- };
-
- class ZeroDivisionError: public ArithmeticError
- {
- public:
- ZeroDivisionError (const std::string& reason)
- : ArithmeticError()
- {
- PyErr_SetString (Py::_Exc_ZeroDivisionError(), reason.c_str());
- }
- };
-
- class FloatingPointError: public ArithmeticError
- {
- public:
- FloatingPointError (const std::string& reason)
- : ArithmeticError()
- {
- PyErr_SetString (Py::_Exc_FloatingPointError(), reason.c_str());
- }
- };
-
- class MemoryError: public StandardError
- {
- public:
- MemoryError (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_MemoryError(), reason.c_str());
- }
- };
-
- class SystemExit: public StandardError
- {
- public:
- SystemExit (const std::string& reason)
- : StandardError()
- {
- PyErr_SetString (Py::_Exc_SystemExit(),reason.c_str());
- }
- };
-
- }// Py
-
-#endif
diff --git a/lib/kross/python/cxx/Extensions.h b/lib/kross/python/cxx/Extensions.h
new file mode 100644
index 000000000..48eb4e091
--- /dev/null
+++ b/lib/kross/python/cxx/Extensions.h
@@ -0,0 +1,756 @@
+//---------------------------------------------------------------------------//
+// Copyright 1998 The Regents of the University of California.
+// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
+//---------------------------------------------------------------------------//
+
+#ifndef __CXX_Extensions__h
+#define __CXX_Extensions__h
+
+
+#ifdef _MSC_VER
+// disable warning C4786: symbol greater than 255 character,
+// okay to ignore
+#pragma warning(disable: 4786)
+#endif
+
+
+#include "Config.h"
+#include "Objects.h"
+
+extern "C"
+ {
+ extern PyObject py_object_initializer;
+ }
+
+#include <vector>
+#include <map>
+
+namespace Py
+ {
+ class ExtensionModuleBase;
+
+ // Make an Exception Type for use in raising custom exceptions
+ class ExtensionExceptionType : public Object
+ {
+ public:
+ ExtensionExceptionType();
+ virtual ~ExtensionExceptionType();
+
+ // call init to create the type
+ void init( ExtensionModuleBase &module, const std::string& name );
+ };
+
+
+ class MethodTable
+ {
+ public:
+ MethodTable();
+ virtual ~MethodTable();
+
+ void add(const char* method_name, PyCFunction f, const char* doc="", int flag=1);
+ PyMethodDef* table();
+
+ protected:
+ std::vector<PyMethodDef> t; // accumulator of PyMethodDef's
+ PyMethodDef *mt; // Actual method table produced when full
+
+ static PyMethodDef method (const char* method_name, PyCFunction f, int flags = 1, const char* doc="");
+
+ private:
+ //
+ // prevent the compiler generating these unwanted functions
+ //
+ MethodTable(const MethodTable& m); //unimplemented
+ void operator=(const MethodTable& m); //unimplemented
+
+ }; // end class MethodTable
+
+ extern "C"
+ {
+ typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args );
+ typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict );
+ }
+
+ template<class T>
+ class MethodDefExt : public PyMethodDef
+ {
+ public:
+ typedef Object (T::*method_varargs_function_t)( const Tuple &args );
+ typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
+
+ MethodDefExt
+ (
+ const char *_name,
+ method_varargs_function_t _function,
+ method_varargs_call_handler_t _handler,
+ const char *_doc
+ )
+ {
+ ext_meth_def.ml_name = const_cast<char *>(_name);
+ ext_meth_def.ml_meth = _handler;
+ ext_meth_def.ml_flags = METH_VARARGS;
+ ext_meth_def.ml_doc = const_cast<char *>(_doc);
+
+ ext_varargs_function = _function;
+ ext_keyword_function = NULL;
+ }
+
+ MethodDefExt
+ (
+ const char *_name,
+ method_keyword_function_t _function,
+ method_keyword_call_handler_t _handler,
+ const char *_doc
+ )
+ {
+ ext_meth_def.ml_name = const_cast<char *>(_name);
+ ext_meth_def.ml_meth = method_varargs_call_handler_t( _handler );
+ ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS;
+ ext_meth_def.ml_doc = const_cast<char *>(_doc);
+
+ ext_varargs_function = NULL;
+ ext_keyword_function = _function;
+ }
+
+ ~MethodDefExt()
+ {}
+
+ PyMethodDef ext_meth_def;
+ method_varargs_function_t ext_varargs_function;
+ method_keyword_function_t ext_keyword_function;
+ };
+
+ class ExtensionModuleBase
+ {
+ public:
+ ExtensionModuleBase( const char *name );
+ virtual ~ExtensionModuleBase();
+
+ Module module(void) const; // only valid after initialize() has been called
+ Dict moduleDictionary(void) const; // only valid after initialize() has been called
+
+ virtual Object invoke_method_keyword( const std::string &_name, const Tuple &_args, const Dict &_keywords ) = 0;
+ virtual Object invoke_method_varargs( const std::string &_name, const Tuple &_args ) = 0;
+
+ const std::string &name() const;
+ const std::string &fullName() const;
+
+ protected:
+ // Initialize the module
+ void initialize( const char *module_doc );
+
+ const std::string module_name;
+ const std::string full_module_name;
+ MethodTable method_table;
+
+ private:
+
+ //
+ // prevent the compiler generating these unwanted functions
+ //
+ ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented
+ void operator=( const ExtensionModuleBase & ); //unimplemented
+
+ };
+
+ extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords );
+ extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args );
+ extern "C" void do_not_dealloc( void * );
+
+
+ template<typename T>
+ class ExtensionModule : public ExtensionModuleBase
+ {
+ public:
+ ExtensionModule( const char *name )
+ : ExtensionModuleBase( name )
+ {}
+ virtual ~ExtensionModule()
+ {}
+
+ protected:
+ typedef Object (T::*method_varargs_function_t)( const Tuple &args );
+ typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
+ typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
+
+ static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
+ {
+ method_map_t &mm = methods();
+
+ MethodDefExt<T> *method_definition = new MethodDefExt<T>
+ (
+ name,
+ function,
+ method_varargs_call_handler,
+ doc
+ );
+
+ mm[std::string( name )] = method_definition;
+ }
+
+ static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
+ {
+ method_map_t &mm = methods();
+
+ MethodDefExt<T> *method_definition = new MethodDefExt<T>
+ (
+ name,
+ function,
+ method_keyword_call_handler,
+ doc
+ );
+
+ mm[std::string( name )] = method_definition;
+ }
+
+ void initialize( const char *module_doc="" )
+ {
+ ExtensionModuleBase::initialize( module_doc );
+ Dict dict( moduleDictionary() );
+
+ //
+ // put each of the methods into the modules dictionary
+ // so that we get called back at the function in T.
+ //
+ method_map_t &mm = methods();
+ typename method_map_t::iterator i;
+
+ for( i=mm.begin(); i != mm.end(); ++i )
+ {
+ MethodDefExt<T> *method_definition = (*i).second;
+
+ static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc );
+
+ Tuple args( 2 );
+ args[0] = Object( self );
+ args[1] = String( (*i).first );
+
+ PyObject *func = PyCFunction_New
+ (
+ &method_definition->ext_meth_def,
+ new_reference_to( args )
+ );
+
+ dict[ (*i).first ] = Object( func );
+ }
+ }
+
+ protected: // Tom Malcolmson reports that derived classes need access to these
+
+ static method_map_t &methods(void)
+ {
+ static method_map_t *map_of_methods = NULL;
+ if( map_of_methods == NULL )
+ map_of_methods = new method_map_t;
+
+ return *map_of_methods;
+ }
+
+
+ // this invoke function must be called from within a try catch block
+ virtual Object invoke_method_keyword( const std::string &name, const Tuple &args, const Dict &keywords )
+ {
+ method_map_t &mm = methods();
+ MethodDefExt<T> *meth_def = mm[ name ];
+ if( meth_def == NULL )
+ {
+ std::string error_msg( "CXX - cannot invoke keyword method named " );
+ error_msg += name;
+ throw RuntimeError( error_msg );
+ }
+
+ // cast up to the derived class
+ T *self = static_cast<T *>(this);
+
+ return (self->*meth_def->ext_keyword_function)( args, keywords );
+ }
+
+ // this invoke function must be called from within a try catch block
+ virtual Object invoke_method_varargs( const std::string &name, const Tuple &args )
+ {
+ method_map_t &mm = methods();
+ MethodDefExt<T> *meth_def = mm[ name ];
+ if( meth_def == NULL )
+ {
+ std::string error_msg( "CXX - cannot invoke varargs method named " );
+ error_msg += name;
+ throw RuntimeError( error_msg );
+ }
+
+ // cast up to the derived class
+ T *self = static_cast<T *>(this);
+
+ return (self->*meth_def->ext_varargs_function)( args );
+ }
+
+ private:
+ //
+ // prevent the compiler generating these unwanted functions
+ //
+ ExtensionModule( const ExtensionModule<T> & ); //unimplemented
+ void operator=( const ExtensionModule<T> & ); //unimplemented
+ };
+
+
+ class PythonType
+ {
+ public:
+ // if you define one sequence method you must define
+ // all of them except the assigns
+
+ PythonType (size_t base_size, int itemsize, const char *default_name );
+ virtual ~PythonType ();
+
+ const char *getName () const;
+ const char *getDoc () const;
+
+ PyTypeObject* type_object () const;
+ void name (const char* nam);
+ void doc (const char* d);
+ void dealloc(void (*f)(PyObject*));
+
+ void supportPrint(void);
+ void supportGetattr(void);
+ void supportSetattr(void);
+ void supportGetattro(void);
+ void supportSetattro(void);
+ void supportCompare(void);
+ void supportRepr(void);
+ void supportStr(void);
+ void supportHash(void);
+ void supportCall(void);
+
+ void supportSequenceType(void);
+ void supportMappingType(void);
+ void supportNumberType(void);
+ void supportBufferType(void);
+
+ protected:
+ PyTypeObject *table;
+ PySequenceMethods *sequence_table;
+ PyMappingMethods *mapping_table;
+ PyNumberMethods *number_table;
+ PyBufferProcs *buffer_table;
+
+ void init_sequence();
+ void init_mapping();
+ void init_number();
+ void init_buffer();
+
+ private:
+ //
+ // prevent the compiler generating these unwanted functions
+ //
+ PythonType (const PythonType& tb); // unimplemented
+ void operator=(const PythonType& t); // unimplemented
+
+ }; // end of PythonType
+
+
+
+ // Class PythonExtension is what you inherit from to create
+ // a new Python extension type. You give your class itself
+ // as the template paramter.
+
+ // There are two ways that extension objects can get destroyed.
+ // 1. Their reference count goes to zero
+ // 2. Someone does an explicit delete on a pointer.
+ // In (1) the problem is to get the destructor called
+ // We register a special deallocator in the Python type object
+ // (see behaviors()) to do this.
+ // In (2) there is no problem, the dtor gets called.
+
+ // PythonExtension does not use the usual Python heap allocator,
+ // instead using new/delete. We do the setting of the type object
+ // and reference count, usually done by PyObject_New, in the
+ // base class ctor.
+
+ // This special deallocator does a delete on the pointer.
+
+
+ class PythonExtensionBase : public PyObject
+ {
+ public:
+ PythonExtensionBase();
+ virtual ~PythonExtensionBase();
+
+ public:
+ virtual int print( FILE *, int );
+ virtual Object getattr( const char * ) = 0;
+ virtual int setattr( const char *, const Object & );
+ virtual Object getattro( const Object & );
+ virtual int setattro( const Object &, const Object & );
+ virtual int compare( const Object & );
+ virtual Object repr();
+ virtual Object str();
+ virtual long hash();
+ virtual Object call( const Object &, const Object & );
+
+ // Sequence methods
+ virtual int sequence_length();
+ virtual Object sequence_concat( const Object & );
+ virtual Object sequence_repeat( int );
+ virtual Object sequence_item( int );
+ virtual Object sequence_slice( int, int );
+ virtual int sequence_ass_item( int, const Object & );
+ virtual int sequence_ass_slice( int, int, const Object & );
+
+ // Mapping
+ virtual int mapping_length();
+ virtual Object mapping_subscript( const Object & );
+ virtual int mapping_ass_subscript( const Object &, const Object & );
+
+ // Number
+ virtual int number_nonzero();
+ virtual Object number_negative();
+ virtual Object number_positive();
+ virtual Object number_absolute();
+ virtual Object number_invert();
+ virtual Object number_int();
+ virtual Object number_float();
+ virtual Object number_long();
+ virtual Object number_oct();
+ virtual Object number_hex();
+ virtual Object number_add( const Object & );
+ virtual Object number_subtract( const Object & );
+ virtual Object number_multiply( const Object & );
+ virtual Object number_divide( const Object & );
+ virtual Object number_remainder( const Object & );
+ virtual Object number_divmod( const Object & );
+ virtual Object number_lshift( const Object & );
+ virtual Object number_rshift( const Object & );
+ virtual Object number_and( const Object & );
+ virtual Object number_xor( const Object & );
+ virtual Object number_or( const Object & );
+ virtual Object number_power( const Object &, const Object & );
+
+ // Buffer
+ virtual int buffer_getreadbuffer( int, void** );
+ virtual int buffer_getwritebuffer( int, void** );
+ virtual int buffer_getsegcount( int* );
+
+ private:
+ void missing_method( void );
+ static PyObject *method_call_handler( PyObject *self, PyObject *args );
+ };
+
+ template<typename T>
+ class PythonExtension: public PythonExtensionBase
+ {
+ public:
+ static PyTypeObject* type_object()
+ {
+ return behaviors().type_object();
+ }
+
+ static int check( PyObject *p )
+ {
+ // is p like me?
+ return p->ob_type == type_object();
+ }
+
+ static int check( const Object& ob )
+ {
+ return check( ob.ptr());
+ }
+
+
+ //
+ // every object needs getattr implemented
+ // to support methods
+ //
+ virtual Object getattr( const char *name )
+ {
+ return getattr_methods( name );
+ }
+
+ protected:
+ explicit PythonExtension()
+ : PythonExtensionBase()
+ {
+ #ifdef PyObject_INIT
+ (void)PyObject_INIT( this, type_object() );
+ #else
+ ob_refcnt = 1;
+ ob_type = type_object();
+ #endif
+
+ // every object must support getattr
+ behaviors().supportGetattr();
+ }
+
+ virtual ~PythonExtension()
+ {}
+
+ static PythonType &behaviors()
+ {
+ static PythonType* p;
+ if( p == NULL )
+ {
+#if defined( _CPPRTTI )
+ const char *default_name = (typeid ( T )).name();
+#else
+ const char *default_name = "unknown";
+#endif
+ p = new PythonType( sizeof( T ), 0, default_name );
+ p->dealloc( extension_object_deallocator );
+ }
+
+ return *p;
+ }
+
+
+ typedef Object (T::*method_varargs_function_t)( const Tuple &args );
+ typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
+ typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
+
+ // support the default attributes, __name__, __doc__ and methods
+ virtual Object getattr_default( const char *_name )
+ {
+ std::string name( _name );
+
+ if( name == "__name__" && type_object()->tp_name != NULL )
+ {
+ return Py::String( type_object()->tp_name );
+ }
+ else if( name == "__doc__" && type_object()->tp_doc != NULL )
+ {
+ return Py::String( type_object()->tp_doc );
+ }
+
+// trying to fake out being a class for help()
+// else if( name == "__bases__" )
+// {
+// return Py::Tuple(0);
+// }
+// else if( name == "__module__" )
+// {
+// return Py::Nothing();
+// }
+// else if( name == "__dict__" )
+// {
+// return Py::Dict();
+// }
+ else
+ {
+ return getattr_methods( _name );
+ }
+ }
+
+ // turn a name into function object
+ virtual Object getattr_methods( const char *_name )
+ {
+ std::string name( _name );
+
+ method_map_t &mm = methods();
+
+ if( name == "__methods__" )
+ {
+ List methods;
+
+ for( typename method_map_t::iterator i = mm.begin(); i != mm.end(); ++i )
+ methods.append( String( (*i).first ) );
+
+ return methods;
+ }
+
+ // see if name exists
+ if( mm.find( name ) == mm.end() )
+ throw AttributeError( "method '" + name + "' does not exist." );
+
+ Tuple self( 2 );
+
+ self[0] = Object( this );
+ self[1] = String( name );
+
+ MethodDefExt<T> *method_definition = mm[ name ];
+
+ PyObject *func = PyCFunction_New( &method_definition->ext_meth_def, self.ptr() );
+
+ return Object(func, true);
+ }
+
+ static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
+ {
+ method_map_t &mm = methods();
+
+ MethodDefExt<T> *method_definition = new MethodDefExt<T>
+ (
+ name,
+ function,
+ method_varargs_call_handler,
+ doc
+ );
+
+ mm[std::string( name )] = method_definition;
+ }
+
+ static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
+ {
+ method_map_t &mm = methods();
+
+ MethodDefExt<T> *method_definition = new MethodDefExt<T>
+ (
+ name,
+ function,
+ method_keyword_call_handler,
+ doc
+ );
+
+ mm[std::string( name )] = method_definition;
+ }
+
+ private:
+ static method_map_t &methods(void)
+ {
+ static method_map_t *map_of_methods = NULL;
+ if( map_of_methods == NULL )
+ map_of_methods = new method_map_t;
+
+ return *map_of_methods;
+ }
+
+ static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
+ {
+ try
+ {
+ Tuple self_and_name_tuple( _self_and_name_tuple );
+
+ PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
+ T *self = static_cast<T *>( self_in_cobject );
+
+ String name( self_and_name_tuple[1] );
+
+ method_map_t &mm = methods();
+ MethodDefExt<T> *meth_def = mm[ name ];
+ if( meth_def == NULL )
+ return 0;
+
+ Tuple args( _args );
+
+ // _keywords may be NULL so be careful about the way the dict is created
+ Dict keywords;
+ if( _keywords != NULL )
+ keywords = Dict( _keywords );
+
+ Object result( (self->*meth_def->ext_keyword_function)( args, keywords ) );
+
+ return new_reference_to( result.ptr() );
+ }
+ catch( Exception & )
+ {
+ return 0;
+ }
+ }
+
+ static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
+ {
+ try
+ {
+ Tuple self_and_name_tuple( _self_and_name_tuple );
+
+ PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
+ T *self = static_cast<T *>( self_in_cobject );
+
+ String name( self_and_name_tuple[1] );
+
+ method_map_t &mm = methods();
+ MethodDefExt<T> *meth_def = mm[ name ];
+ if( meth_def == NULL )
+ return 0;
+
+ Tuple args( _args );
+
+ Object result;
+
+ // TMM: 7Jun'01 - Adding try & catch in case of STL debug-mode exceptions.
+ #ifdef _STLP_DEBUG
+ try
+ {
+ result = (self->*meth_def->ext_varargs_function)( args );
+ }
+ catch (std::__stl_debug_exception)
+ {
+ // throw cxx::RuntimeError( sErrMsg );
+ throw cxx::RuntimeError( "Error message not set yet." );
+ }
+ #else
+ result = (self->*meth_def->ext_varargs_function)( args );
+ #endif // _STLP_DEBUG
+
+ return new_reference_to( result.ptr() );
+ }
+ catch( Exception & )
+ {
+ return 0;
+ }
+ }
+
+ static void extension_object_deallocator ( PyObject* t )
+ {
+ delete (T *)( t );
+ }
+
+ //
+ // prevent the compiler generating these unwanted functions
+ //
+ explicit PythonExtension( const PythonExtension<T>& other );
+ void operator=( const PythonExtension<T>& rhs );
+ };
+
+ //
+ // ExtensionObject<T> is an Object that will accept only T's.
+ //
+ template<typename T>
+ class ExtensionObject: public Object
+ {
+ public:
+
+ explicit ExtensionObject ( PyObject *pyob )
+ : Object( pyob )
+ {
+ validate();
+ }
+
+ ExtensionObject( const ExtensionObject<T>& other )
+ : Object( *other )
+ {
+ validate();
+ }
+
+ ExtensionObject( const Object& other )
+ : Object( *other )
+ {
+ validate();
+ }
+
+ ExtensionObject& operator= ( const Object& rhs )
+ {
+ return (*this = *rhs );
+ }
+
+ ExtensionObject& operator= ( PyObject* rhsp )
+ {
+ if( ptr() == rhsp )
+ return *this;
+ set( rhsp );
+ return *this;
+ }
+
+ virtual bool accepts ( PyObject *pyob ) const
+ {
+ return ( pyob && T::check( pyob ));
+ }
+
+ //
+ // Obtain a pointer to the PythonExtension object
+ //
+ T *extensionObject(void)
+ {
+ return static_cast<T *>( ptr() );
+ }
+ };
+
+ } // Namespace Py
+// End of CXX_Extensions.h
+#endif
diff --git a/lib/kross/python/cxx/Extensions.hxx b/lib/kross/python/cxx/Extensions.hxx
deleted file mode 100644
index 5c7c2bcf3..000000000
--- a/lib/kross/python/cxx/Extensions.hxx
+++ /dev/null
@@ -1,756 +0,0 @@
-//---------------------------------------------------------------------------//
-// Copyright 1998 The Regents of the University of California.
-// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
-//---------------------------------------------------------------------------//
-
-#ifndef __CXX_Extensions__h
-#define __CXX_Extensions__h
-
-
-#ifdef _MSC_VER
-// disable warning C4786: symbol greater than 255 character,
-// okay to ignore
-#pragma warning(disable: 4786)
-#endif
-
-
-#include "Config.hxx"
-#include "Objects.hxx"
-
-extern "C"
- {
- extern PyObject py_object_initializer;
- }
-
-#include <vector>
-#include <map>
-
-namespace Py
- {
- class ExtensionModuleBase;
-
- // Make an Exception Type for use in raising custom exceptions
- class ExtensionExceptionType : public Object
- {
- public:
- ExtensionExceptionType();
- virtual ~ExtensionExceptionType();
-
- // call init to create the type
- void init( ExtensionModuleBase &module, const std::string& name );
- };
-
-
- class MethodTable
- {
- public:
- MethodTable();
- virtual ~MethodTable();
-
- void add(const char* method_name, PyCFunction f, const char* doc="", int flag=1);
- PyMethodDef* table();
-
- protected:
- std::vector<PyMethodDef> t; // accumulator of PyMethodDef's
- PyMethodDef *mt; // Actual method table produced when full
-
- static PyMethodDef method (const char* method_name, PyCFunction f, int flags = 1, const char* doc="");
-
- private:
- //
- // prevent the compiler generating these unwanted functions
- //
- MethodTable(const MethodTable& m); //unimplemented
- void operator=(const MethodTable& m); //unimplemented
-
- }; // end class MethodTable
-
- extern "C"
- {
- typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args );
- typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict );
- }
-
- template<class T>
- class MethodDefExt : public PyMethodDef
- {
- public:
- typedef Object (T::*method_varargs_function_t)( const Tuple &args );
- typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
-
- MethodDefExt
- (
- const char *_name,
- method_varargs_function_t _function,
- method_varargs_call_handler_t _handler,
- const char *_doc
- )
- {
- ext_meth_def.ml_name = const_cast<char *>(_name);
- ext_meth_def.ml_meth = _handler;
- ext_meth_def.ml_flags = METH_VARARGS;
- ext_meth_def.ml_doc = const_cast<char *>(_doc);
-
- ext_varargs_function = _function;
- ext_keyword_function = NULL;
- }
-
- MethodDefExt
- (
- const char *_name,
- method_keyword_function_t _function,
- method_keyword_call_handler_t _handler,
- const char *_doc
- )
- {
- ext_meth_def.ml_name = const_cast<char *>(_name);
- ext_meth_def.ml_meth = method_varargs_call_handler_t( _handler );
- ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS;
- ext_meth_def.ml_doc = const_cast<char *>(_doc);
-
- ext_varargs_function = NULL;
- ext_keyword_function = _function;
- }
-
- ~MethodDefExt()
- {}
-
- PyMethodDef ext_meth_def;
- method_varargs_function_t ext_varargs_function;
- method_keyword_function_t ext_keyword_function;
- };
-
- class ExtensionModuleBase
- {
- public:
- ExtensionModuleBase( const char *name );
- virtual ~ExtensionModuleBase();
-
- Module module(void) const; // only valid after initialize() has been called
- Dict moduleDictionary(void) const; // only valid after initialize() has been called
-
- virtual Object invoke_method_keyword( const std::string &_name, const Tuple &_args, const Dict &_keywords ) = 0;
- virtual Object invoke_method_varargs( const std::string &_name, const Tuple &_args ) = 0;
-
- const std::string &name() const;
- const std::string &fullName() const;
-
- protected:
- // Initialize the module
- void initialize( const char *module_doc );
-
- const std::string module_name;
- const std::string full_module_name;
- MethodTable method_table;
-
- private:
-
- //
- // prevent the compiler generating these unwanted functions
- //
- ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented
- void operator=( const ExtensionModuleBase & ); //unimplemented
-
- };
-
- extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords );
- extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args );
- extern "C" void do_not_dealloc( void * );
-
-
- template<typename T>
- class ExtensionModule : public ExtensionModuleBase
- {
- public:
- ExtensionModule( const char *name )
- : ExtensionModuleBase( name )
- {}
- virtual ~ExtensionModule()
- {}
-
- protected:
- typedef Object (T::*method_varargs_function_t)( const Tuple &args );
- typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
- typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
-
- static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
- {
- method_map_t &mm = methods();
-
- MethodDefExt<T> *method_definition = new MethodDefExt<T>
- (
- name,
- function,
- method_varargs_call_handler,
- doc
- );
-
- mm[std::string( name )] = method_definition;
- }
-
- static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
- {
- method_map_t &mm = methods();
-
- MethodDefExt<T> *method_definition = new MethodDefExt<T>
- (
- name,
- function,
- method_keyword_call_handler,
- doc
- );
-
- mm[std::string( name )] = method_definition;
- }
-
- void initialize( const char *module_doc="" )
- {
- ExtensionModuleBase::initialize( module_doc );
- Dict dict( moduleDictionary() );
-
- //
- // put each of the methods into the modules dictionary
- // so that we get called back at the function in T.
- //
- method_map_t &mm = methods();
- typename method_map_t::iterator i;
-
- for( i=mm.begin(); i != mm.end(); ++i )
- {
- MethodDefExt<T> *method_definition = (*i).second;
-
- static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc );
-
- Tuple args( 2 );
- args[0] = Object( self );
- args[1] = String( (*i).first );
-
- PyObject *func = PyCFunction_New
- (
- &method_definition->ext_meth_def,
- new_reference_to( args )
- );
-
- dict[ (*i).first ] = Object( func );
- }
- }
-
- protected: // Tom Malcolmson reports that derived classes need access to these
-
- static method_map_t &methods(void)
- {
- static method_map_t *map_of_methods = NULL;
- if( map_of_methods == NULL )
- map_of_methods = new method_map_t;
-
- return *map_of_methods;
- }
-
-
- // this invoke function must be called from within a try catch block
- virtual Object invoke_method_keyword( const std::string &name, const Tuple &args, const Dict &keywords )
- {
- method_map_t &mm = methods();
- MethodDefExt<T> *meth_def = mm[ name ];
- if( meth_def == NULL )
- {
- std::string error_msg( "CXX - cannot invoke keyword method named " );
- error_msg += name;
- throw RuntimeError( error_msg );
- }
-
- // cast up to the derived class
- T *self = static_cast<T *>(this);
-
- return (self->*meth_def->ext_keyword_function)( args, keywords );
- }
-
- // this invoke function must be called from within a try catch block
- virtual Object invoke_method_varargs( const std::string &name, const Tuple &args )
- {
- method_map_t &mm = methods();
- MethodDefExt<T> *meth_def = mm[ name ];
- if( meth_def == NULL )
- {
- std::string error_msg( "CXX - cannot invoke varargs method named " );
- error_msg += name;
- throw RuntimeError( error_msg );
- }
-
- // cast up to the derived class
- T *self = static_cast<T *>(this);
-
- return (self->*meth_def->ext_varargs_function)( args );
- }
-
- private:
- //
- // prevent the compiler generating these unwanted functions
- //
- ExtensionModule( const ExtensionModule<T> & ); //unimplemented
- void operator=( const ExtensionModule<T> & ); //unimplemented
- };
-
-
- class PythonType
- {
- public:
- // if you define one sequence method you must define
- // all of them except the assigns
-
- PythonType (size_t base_size, int itemsize, const char *default_name );
- virtual ~PythonType ();
-
- const char *getName () const;
- const char *getDoc () const;
-
- PyTypeObject* type_object () const;
- void name (const char* nam);
- void doc (const char* d);
- void dealloc(void (*f)(PyObject*));
-
- void supportPrint(void);
- void supportGetattr(void);
- void supportSetattr(void);
- void supportGetattro(void);
- void supportSetattro(void);
- void supportCompare(void);
- void supportRepr(void);
- void supportStr(void);
- void supportHash(void);
- void supportCall(void);
-
- void supportSequenceType(void);
- void supportMappingType(void);
- void supportNumberType(void);
- void supportBufferType(void);
-
- protected:
- PyTypeObject *table;
- PySequenceMethods *sequence_table;
- PyMappingMethods *mapping_table;
- PyNumberMethods *number_table;
- PyBufferProcs *buffer_table;
-
- void init_sequence();
- void init_mapping();
- void init_number();
- void init_buffer();
-
- private:
- //
- // prevent the compiler generating these unwanted functions
- //
- PythonType (const PythonType& tb); // unimplemented
- void operator=(const PythonType& t); // unimplemented
-
- }; // end of PythonType
-
-
-
- // Class PythonExtension is what you inherit from to create
- // a new Python extension type. You give your class itself
- // as the template paramter.
-
- // There are two ways that extension objects can get destroyed.
- // 1. Their reference count goes to zero
- // 2. Someone does an explicit delete on a pointer.
- // In (1) the problem is to get the destructor called
- // We register a special deallocator in the Python type object
- // (see behaviors()) to do this.
- // In (2) there is no problem, the dtor gets called.
-
- // PythonExtension does not use the usual Python heap allocator,
- // instead using new/delete. We do the setting of the type object
- // and reference count, usually done by PyObject_New, in the
- // base class ctor.
-
- // This special deallocator does a delete on the pointer.
-
-
- class PythonExtensionBase : public PyObject
- {
- public:
- PythonExtensionBase();
- virtual ~PythonExtensionBase();
-
- public:
- virtual int print( FILE *, int );
- virtual Object getattr( const char * ) = 0;
- virtual int setattr( const char *, const Object & );
- virtual Object getattro( const Object & );
- virtual int setattro( const Object &, const Object & );
- virtual int compare( const Object & );
- virtual Object repr();
- virtual Object str();
- virtual long hash();
- virtual Object call( const Object &, const Object & );
-
- // Sequence methods
- virtual int sequence_length();
- virtual Object sequence_concat( const Object & );
- virtual Object sequence_repeat( int );
- virtual Object sequence_item( int );
- virtual Object sequence_slice( int, int );
- virtual int sequence_ass_item( int, const Object & );
- virtual int sequence_ass_slice( int, int, const Object & );
-
- // Mapping
- virtual int mapping_length();
- virtual Object mapping_subscript( const Object & );
- virtual int mapping_ass_subscript( const Object &, const Object & );
-
- // Number
- virtual int number_nonzero();
- virtual Object number_negative();
- virtual Object number_positive();
- virtual Object number_absolute();
- virtual Object number_invert();
- virtual Object number_int();
- virtual Object number_float();
- virtual Object number_long();
- virtual Object number_oct();
- virtual Object number_hex();
- virtual Object number_add( const Object & );
- virtual Object number_subtract( const Object & );
- virtual Object number_multiply( const Object & );
- virtual Object number_divide( const Object & );
- virtual Object number_remainder( const Object & );
- virtual Object number_divmod( const Object & );
- virtual Object number_lshift( const Object & );
- virtual Object number_rshift( const Object & );
- virtual Object number_and( const Object & );
- virtual Object number_xor( const Object & );
- virtual Object number_or( const Object & );
- virtual Object number_power( const Object &, const Object & );
-
- // Buffer
- virtual int buffer_getreadbuffer( int, void** );
- virtual int buffer_getwritebuffer( int, void** );
- virtual int buffer_getsegcount( int* );
-
- private:
- void missing_method( void );
- static PyObject *method_call_handler( PyObject *self, PyObject *args );
- };
-
- template<typename T>
- class PythonExtension: public PythonExtensionBase
- {
- public:
- static PyTypeObject* type_object()
- {
- return behaviors().type_object();
- }
-
- static int check( PyObject *p )
- {
- // is p like me?
- return p->ob_type == type_object();
- }
-
- static int check( const Object& ob )
- {
- return check( ob.ptr());
- }
-
-
- //
- // every object needs getattr implemented
- // to support methods
- //
- virtual Object getattr( const char *name )
- {
- return getattr_methods( name );
- }
-
- protected:
- explicit PythonExtension()
- : PythonExtensionBase()
- {
- #ifdef PyObject_INIT
- (void)PyObject_INIT( this, type_object() );
- #else
- ob_refcnt = 1;
- ob_type = type_object();
- #endif
-
- // every object must support getattr
- behaviors().supportGetattr();
- }
-
- virtual ~PythonExtension()
- {}
-
- static PythonType &behaviors()
- {
- static PythonType* p;
- if( p == NULL )
- {
-#if defined( _CPPRTTI )
- const char *default_name = (typeid ( T )).name();
-#else
- const char *default_name = "unknown";
-#endif
- p = new PythonType( sizeof( T ), 0, default_name );
- p->dealloc( extension_object_deallocator );
- }
-
- return *p;
- }
-
-
- typedef Object (T::*method_varargs_function_t)( const Tuple &args );
- typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
- typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
-
- // support the default attributes, __name__, __doc__ and methods
- virtual Object getattr_default( const char *_name )
- {
- std::string name( _name );
-
- if( name == "__name__" && type_object()->tp_name != NULL )
- {
- return Py::String( type_object()->tp_name );
- }
- else if( name == "__doc__" && type_object()->tp_doc != NULL )
- {
- return Py::String( type_object()->tp_doc );
- }
-
-// trying to fake out being a class for help()
-// else if( name == "__bases__" )
-// {
-// return Py::Tuple(0);
-// }
-// else if( name == "__module__" )
-// {
-// return Py::Nothing();
-// }
-// else if( name == "__dict__" )
-// {
-// return Py::Dict();
-// }
- else
- {
- return getattr_methods( _name );
- }
- }
-
- // turn a name into function object
- virtual Object getattr_methods( const char *_name )
- {
- std::string name( _name );
-
- method_map_t &mm = methods();
-
- if( name == "__methods__" )
- {
- List methods;
-
- for( typename method_map_t::iterator i = mm.begin(); i != mm.end(); ++i )
- methods.append( String( (*i).first ) );
-
- return methods;
- }
-
- // see if name exists
- if( mm.find( name ) == mm.end() )
- throw AttributeError( "method '" + name + "' does not exist." );
-
- Tuple self( 2 );
-
- self[0] = Object( this );
- self[1] = String( name );
-
- MethodDefExt<T> *method_definition = mm[ name ];
-
- PyObject *func = PyCFunction_New( &method_definition->ext_meth_def, self.ptr() );
-
- return Object(func, true);
- }
-
- static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
- {
- method_map_t &mm = methods();
-
- MethodDefExt<T> *method_definition = new MethodDefExt<T>
- (
- name,
- function,
- method_varargs_call_handler,
- doc
- );
-
- mm[std::string( name )] = method_definition;
- }
-
- static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
- {
- method_map_t &mm = methods();
-
- MethodDefExt<T> *method_definition = new MethodDefExt<T>
- (
- name,
- function,
- method_keyword_call_handler,
- doc
- );
-
- mm[std::string( name )] = method_definition;
- }
-
- private:
- static method_map_t &methods(void)
- {
- static method_map_t *map_of_methods = NULL;
- if( map_of_methods == NULL )
- map_of_methods = new method_map_t;
-
- return *map_of_methods;
- }
-
- static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
- {
- try
- {
- Tuple self_and_name_tuple( _self_and_name_tuple );
-
- PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
- T *self = static_cast<T *>( self_in_cobject );
-
- String name( self_and_name_tuple[1] );
-
- method_map_t &mm = methods();
- MethodDefExt<T> *meth_def = mm[ name ];
- if( meth_def == NULL )
- return 0;
-
- Tuple args( _args );
-
- // _keywords may be NULL so be careful about the way the dict is created
- Dict keywords;
- if( _keywords != NULL )
- keywords = Dict( _keywords );
-
- Object result( (self->*meth_def->ext_keyword_function)( args, keywords ) );
-
- return new_reference_to( result.ptr() );
- }
- catch( Exception & )
- {
- return 0;
- }
- }
-
- static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
- {
- try
- {
- Tuple self_and_name_tuple( _self_and_name_tuple );
-
- PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
- T *self = static_cast<T *>( self_in_cobject );
-
- String name( self_and_name_tuple[1] );
-
- method_map_t &mm = methods();
- MethodDefExt<T> *meth_def = mm[ name ];
- if( meth_def == NULL )
- return 0;
-
- Tuple args( _args );
-
- Object result;
-
- // TMM: 7Jun'01 - Adding try & catch in case of STL debug-mode exceptions.
- #ifdef _STLP_DEBUG
- try
- {
- result = (self->*meth_def->ext_varargs_function)( args );
- }
- catch (std::__stl_debug_exception)
- {
- // throw cxx::RuntimeError( sErrMsg );
- throw cxx::RuntimeError( "Error message not set yet." );
- }
- #else
- result = (self->*meth_def->ext_varargs_function)( args );
- #endif // _STLP_DEBUG
-
- return new_reference_to( result.ptr() );
- }
- catch( Exception & )
- {
- return 0;
- }
- }
-
- static void extension_object_deallocator ( PyObject* t )
- {
- delete (T *)( t );
- }
-
- //
- // prevent the compiler generating these unwanted functions
- //
- explicit PythonExtension( const PythonExtension<T>& other );
- void operator=( const PythonExtension<T>& rhs );
- };
-
- //
- // ExtensionObject<T> is an Object that will accept only T's.
- //
- template<typename T>
- class ExtensionObject: public Object
- {
- public:
-
- explicit ExtensionObject ( PyObject *pyob )
- : Object( pyob )
- {
- validate();
- }
-
- ExtensionObject( const ExtensionObject<T>& other )
- : Object( *other )
- {
- validate();
- }
-
- ExtensionObject( const Object& other )
- : Object( *other )
- {
- validate();
- }
-
- ExtensionObject& operator= ( const Object& rhs )
- {
- return (*this = *rhs );
- }
-
- ExtensionObject& operator= ( PyObject* rhsp )
- {
- if( ptr() == rhsp )
- return *this;
- set( rhsp );
- return *this;
- }
-
- virtual bool accepts ( PyObject *pyob ) const
- {
- return ( pyob && T::check( pyob ));
- }
-
- //
- // Obtain a pointer to the PythonExtension object
- //
- T *extensionObject(void)
- {
- return static_cast<T *>( ptr() );
- }
- };
-
- } // Namespace Py
-// End of CXX_Extensions.h
-#endif
diff --git a/lib/kross/python/cxx/IndirectPythonInterface.cpp b/lib/kross/python/cxx/IndirectPythonInterface.cpp
new file mode 100644
index 000000000..6f3be354e
--- /dev/null
+++ b/lib/kross/python/cxx/IndirectPythonInterface.cpp
@@ -0,0 +1,550 @@
+//
+// IndirectPythonInterface.cpp
+//
+#undef _XOPEN_SOURCE
+#include "IndirectPythonInterface.h"
+
+namespace Py
+{
+bool _Buffer_Check( PyObject *op ) { return (op)->ob_type == _Buffer_Type(); }
+bool _CFunction_Check( PyObject *op ) { return (op)->ob_type == _CFunction_Type(); }
+bool _Class_Check( PyObject *op ) { return (op)->ob_type == _Class_Type(); }
+bool _CObject_Check( PyObject *op ) { return (op)->ob_type == _CObject_Type(); }
+bool _Complex_Check( PyObject *op ) { return (op)->ob_type == _Complex_Type(); }
+bool _Dict_Check( PyObject *op ) { return (op)->ob_type == _Dict_Type(); }
+bool _File_Check( PyObject *op ) { return (op)->ob_type == _File_Type(); }
+bool _Float_Check( PyObject *op ) { return (op)->ob_type == _Float_Type(); }
+bool _Function_Check( PyObject *op ) { return (op)->ob_type == _Function_Type(); }
+bool _Instance_Check( PyObject *op ) { return (op)->ob_type == _Instance_Type(); }
+bool _Int_Check( PyObject *op ) { return (op)->ob_type == _Int_Type(); }
+bool _List_Check( PyObject *o ) { return o->ob_type == _List_Type(); }
+bool _Long_Check( PyObject *op ) { return (op)->ob_type == _Long_Type(); }
+bool _Method_Check( PyObject *op ) { return (op)->ob_type == _Method_Type(); }
+bool _Module_Check( PyObject *op ) { return (op)->ob_type == _Module_Type(); }
+bool _Range_Check( PyObject *op ) { return (op)->ob_type == _Range_Type(); }
+bool _Slice_Check( PyObject *op ) { return (op)->ob_type == _Slice_Type(); }
+bool _String_Check( PyObject *o ) { return o->ob_type == _String_Type(); }
+bool _TraceBack_Check( PyObject *v ) { return (v)->ob_type == _TraceBack_Type(); }
+bool _Tuple_Check( PyObject *op ) { return (op)->ob_type == _Tuple_Type(); }
+bool _Type_Check( PyObject *op ) { return (op)->ob_type == _Type_Type(); }
+
+#if PY_MAJOR_VERSION >= 2
+bool _Unicode_Check( PyObject *op ) { return (op)->ob_type == _Unicode_Type(); }
+#endif
+
+
+
+#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)
+
+#if defined(MS_WINDOWS)
+#include <windows.h>
+
+
+static HMODULE python_dll;
+
+static PyObject *ptr__Exc_ArithmeticError = NULL;
+static PyObject *ptr__Exc_AssertionError = NULL;
+static PyObject *ptr__Exc_AttributeError = NULL;
+static PyObject *ptr__Exc_EnvironmentError = NULL;
+static PyObject *ptr__Exc_EOFError = NULL;
+static PyObject *ptr__Exc_Exception = NULL;
+static PyObject *ptr__Exc_FloatingPointError = NULL;
+static PyObject *ptr__Exc_ImportError = NULL;
+static PyObject *ptr__Exc_IndexError = NULL;
+static PyObject *ptr__Exc_IOError = NULL;
+static PyObject *ptr__Exc_KeyboardInterrupt = NULL;
+static PyObject *ptr__Exc_KeyError = NULL;
+static PyObject *ptr__Exc_LookupError = NULL;
+static PyObject *ptr__Exc_MemoryError = NULL;
+static PyObject *ptr__Exc_MemoryErrorInst = NULL;
+static PyObject *ptr__Exc_NameError = NULL;
+static PyObject *ptr__Exc_NotImplementedError = NULL;
+static PyObject *ptr__Exc_OSError = NULL;
+static PyObject *ptr__Exc_OverflowError = NULL;
+static PyObject *ptr__Exc_RuntimeError = NULL;
+static PyObject *ptr__Exc_StandardError = NULL;
+static PyObject *ptr__Exc_SyntaxError = NULL;
+static PyObject *ptr__Exc_SystemError = NULL;
+static PyObject *ptr__Exc_SystemExit = NULL;
+static PyObject *ptr__Exc_TypeError = NULL;
+static PyObject *ptr__Exc_ValueError = NULL;
+static PyObject *ptr__Exc_ZeroDivisionError = NULL;
+
+#ifdef MS_WINDOWS
+static PyObject *ptr__Exc_WindowsError = NULL;
+#endif
+
+#if PY_MAJOR_VERSION >= 2
+static PyObject *ptr__Exc_IndentationError = NULL;
+static PyObject *ptr__Exc_TabError = NULL;
+static PyObject *ptr__Exc_UnboundLocalError = NULL;
+static PyObject *ptr__Exc_UnicodeError = NULL;
+#endif
+
+static PyObject *ptr__PyNone = NULL;
+
+static PyTypeObject *ptr__Buffer_Type = NULL;
+static PyTypeObject *ptr__CFunction_Type = NULL;
+static PyTypeObject *ptr__Class_Type = NULL;
+static PyTypeObject *ptr__CObject_Type = NULL;
+static PyTypeObject *ptr__Complex_Type = NULL;
+static PyTypeObject *ptr__Dict_Type = NULL;
+static PyTypeObject *ptr__File_Type = NULL;
+static PyTypeObject *ptr__Float_Type = NULL;
+static PyTypeObject *ptr__Function_Type = NULL;
+static PyTypeObject *ptr__Instance_Type = NULL;
+static PyTypeObject *ptr__Int_Type = NULL;
+static PyTypeObject *ptr__List_Type = NULL;
+static PyTypeObject *ptr__Long_Type = NULL;
+static PyTypeObject *ptr__Method_Type = NULL;
+static PyTypeObject *ptr__Module_Type = NULL;
+static PyTypeObject *ptr__Range_Type = NULL;
+static PyTypeObject *ptr__Slice_Type = NULL;
+static PyTypeObject *ptr__String_Type = NULL;
+static PyTypeObject *ptr__TraceBack_Type = NULL;
+static PyTypeObject *ptr__Tuple_Type = NULL;
+static PyTypeObject *ptr__Type_Type = NULL;
+
+#if PY_MAJOR_VERSION >= 2
+static PyTypeObject *ptr__Unicode_Type = NULL;
+#endif
+
+static int *ptr_Py_DebugFlag = NULL;
+static int *ptr_Py_InteractiveFlag = NULL;
+static int *ptr_Py_OptimizeFlag = NULL;
+static int *ptr_Py_NoSiteFlag = NULL;
+static int *ptr_Py_TabcheckFlag = NULL;
+static int *ptr_Py_VerboseFlag = NULL;
+
+#if PY_MAJOR_VERSION >= 2
+static int *ptr_Py_UnicodeFlag = NULL;
+#endif
+
+static char **ptr__Py_PackageContext = NULL;
+
+#ifdef Py_REF_DEBUG
+int *ptr_Py_RefTotal;
+#endif
+
+
+//--------------------------------------------------------------------------------
+class GetAddressException
+ {
+public:
+ GetAddressException( const char *_name )
+ : name( _name )
+ {}
+ virtual ~GetAddressException() {}
+ const char *name;
+ };
+
+
+//--------------------------------------------------------------------------------
+static PyObject *GetPyObjectPointer_As_PyObjectPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return *(PyObject **)addr;
+ }
+
+static PyObject *GetPyObject_As_PyObjectPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return (PyObject *)addr;
+ }
+
+static PyTypeObject *GetPyTypeObjectPointer_As_PyTypeObjectPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return *(PyTypeObject **)addr;
+ }
+
+static PyTypeObject *GetPyTypeObject_As_PyTypeObjectPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return (PyTypeObject *)addr;
+ }
+
+static int *GetInt_as_IntPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return (int *)addr;
+ }
+
+static char **GetCharPointer_as_CharPointerPointer( const char *name )
+ {
+ FARPROC addr = GetProcAddress( python_dll, name );
+ if( addr == NULL )
+ throw GetAddressException( name );
+
+ return (char **)addr;
+ }
+
+
+#ifdef _DEBUG
+static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d_D.DLL";
+#else
+static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d.DLL";
+#endif
+
+//--------------------------------------------------------------------------------
+bool InitialisePythonIndirectInterface()
+ {
+ char python_dll_name[sizeof(python_dll_name_format)];
+
+ sprintf( python_dll_name, python_dll_name_format, PY_MAJOR_VERSION, PY_MINOR_VERSION );
+
+ python_dll = LoadLibrary( python_dll_name );
+ if( python_dll == NULL )
+ return false;
+
+ try
+ {
+#ifdef Py_REF_DEBUG
+ ptr_Py_RefTotal = GetInt_as_IntPointer( "_Py_RefTotal" );
+#endif
+ ptr_Py_DebugFlag = GetInt_as_IntPointer( "Py_DebugFlag" );
+ ptr_Py_InteractiveFlag = GetInt_as_IntPointer( "Py_InteractiveFlag" );
+ ptr_Py_OptimizeFlag = GetInt_as_IntPointer( "Py_OptimizeFlag" );
+ ptr_Py_NoSiteFlag = GetInt_as_IntPointer( "Py_NoSiteFlag" );
+ ptr_Py_TabcheckFlag = GetInt_as_IntPointer( "Py_TabcheckFlag" );
+ ptr_Py_VerboseFlag = GetInt_as_IntPointer( "Py_VerboseFlag" );
+#if PY_MAJOR_VERSION >= 2
+ ptr_Py_UnicodeFlag = GetInt_as_IntPointer( "Py_UnicodeFlag" );
+#endif
+ ptr__Py_PackageContext = GetCharPointer_as_CharPointerPointer( "_Py_PackageContext" );
+
+ ptr__Exc_ArithmeticError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ArithmeticError" );
+ ptr__Exc_AssertionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AssertionError" );
+ ptr__Exc_AttributeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AttributeError" );
+ ptr__Exc_EnvironmentError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EnvironmentError" );
+ ptr__Exc_EOFError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EOFError" );
+ ptr__Exc_Exception = GetPyObjectPointer_As_PyObjectPointer( "PyExc_Exception" );
+ ptr__Exc_FloatingPointError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_FloatingPointError" );
+ ptr__Exc_ImportError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ImportError" );
+ ptr__Exc_IndexError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndexError" );
+ ptr__Exc_IOError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IOError" );
+ ptr__Exc_KeyboardInterrupt = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyboardInterrupt" );
+ ptr__Exc_KeyError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyError" );
+ ptr__Exc_LookupError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_LookupError" );
+ ptr__Exc_MemoryError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryError" );
+ ptr__Exc_MemoryErrorInst = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryErrorInst" );
+ ptr__Exc_NameError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NameError" );
+ ptr__Exc_NotImplementedError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NotImplementedError" );
+ ptr__Exc_OSError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OSError" );
+ ptr__Exc_OverflowError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OverflowError" );
+ ptr__Exc_RuntimeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_RuntimeError" );
+ ptr__Exc_StandardError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_StandardError" );
+ ptr__Exc_SyntaxError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SyntaxError" );
+ ptr__Exc_SystemError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemError" );
+ ptr__Exc_SystemExit = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemExit" );
+ ptr__Exc_TypeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TypeError" );
+ ptr__Exc_ValueError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ValueError" );
+#ifdef MS_WINDOWS
+ ptr__Exc_WindowsError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_WindowsError" );
+#endif
+ ptr__Exc_ZeroDivisionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ZeroDivisionError" );
+
+#if PY_MAJOR_VERSION >= 2
+ ptr__Exc_IndentationError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndentationError" );
+ ptr__Exc_TabError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TabError" );
+ ptr__Exc_UnboundLocalError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnboundLocalError" );
+ ptr__Exc_UnicodeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnicodeError" );
+#endif
+ ptr__PyNone = GetPyObject_As_PyObjectPointer( "_Py_NoneStruct" );
+
+ ptr__Buffer_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBuffer_Type" );
+ ptr__CFunction_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCFunction_Type" );
+ ptr__Class_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyClass_Type" );
+ ptr__CObject_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCObject_Type" );
+ ptr__Complex_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyComplex_Type" );
+ ptr__Dict_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyDict_Type" );
+ ptr__File_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFile_Type" );
+ ptr__Float_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFloat_Type" );
+ ptr__Function_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFunction_Type" );
+ ptr__Instance_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInstance_Type" );
+ ptr__Int_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInt_Type" );
+ ptr__List_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyList_Type" );
+ ptr__Long_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyLong_Type" );
+ ptr__Method_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyMethod_Type" );
+ ptr__Module_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyModule_Type" );
+ ptr__Range_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyRange_Type" );
+ ptr__Slice_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PySlice_Type" );
+ ptr__String_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyString_Type" );
+ ptr__TraceBack_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTraceBack_Type" );
+ ptr__Tuple_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTuple_Type" );
+ ptr__Type_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyType_Type" );
+
+#if PY_MAJOR_VERSION >= 2
+ ptr__Unicode_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyUnicode_Type" );
+#endif
+ }
+ catch( GetAddressException &e )
+ {
+ OutputDebugString( python_dll_name );
+ OutputDebugString( " does not contain symbol ");
+ OutputDebugString( e.name );
+ OutputDebugString( "\n" );
+
+ return false;
+ }
+
+ return true;
+ }
+
+//
+// Wrap variables as function calls
+//
+PyObject * _Exc_ArithmeticError() { return ptr__Exc_ArithmeticError; }
+PyObject * _Exc_AssertionError() { return ptr__Exc_AssertionError; }
+PyObject * _Exc_AttributeError() { return ptr__Exc_AttributeError; }
+PyObject * _Exc_EnvironmentError() { return ptr__Exc_EnvironmentError; }
+PyObject * _Exc_EOFError() { return ptr__Exc_EOFError; }
+PyObject * _Exc_Exception() { return ptr__Exc_Exception; }
+PyObject * _Exc_FloatingPointError() { return ptr__Exc_FloatingPointError; }
+PyObject * _Exc_ImportError() { return ptr__Exc_ImportError; }
+PyObject * _Exc_IndexError() { return ptr__Exc_IndexError; }
+PyObject * _Exc_IOError() { return ptr__Exc_IOError; }
+PyObject * _Exc_KeyboardInterrupt() { return ptr__Exc_KeyboardInterrupt; }
+PyObject * _Exc_KeyError() { return ptr__Exc_KeyError; }
+PyObject * _Exc_LookupError() { return ptr__Exc_LookupError; }
+PyObject * _Exc_MemoryError() { return ptr__Exc_MemoryError; }
+PyObject * _Exc_MemoryErrorInst() { return ptr__Exc_MemoryErrorInst; }
+PyObject * _Exc_NameError() { return ptr__Exc_NameError; }
+PyObject * _Exc_NotImplementedError() { return ptr__Exc_NotImplementedError; }
+PyObject * _Exc_OSError() { return ptr__Exc_OSError; }
+PyObject * _Exc_OverflowError() { return ptr__Exc_OverflowError; }
+PyObject * _Exc_RuntimeError() { return ptr__Exc_RuntimeError; }
+PyObject * _Exc_StandardError() { return ptr__Exc_StandardError; }
+PyObject * _Exc_SyntaxError() { return ptr__Exc_SyntaxError; }
+PyObject * _Exc_SystemError() { return ptr__Exc_SystemError; }
+PyObject * _Exc_SystemExit() { return ptr__Exc_SystemExit; }
+PyObject * _Exc_TypeError() { return ptr__Exc_TypeError; }
+PyObject * _Exc_ValueError() { return ptr__Exc_ValueError; }
+#ifdef MS_WINDOWS
+PyObject * _Exc_WindowsError() { return ptr__Exc_WindowsError; }
+#endif
+PyObject * _Exc_ZeroDivisionError() { return ptr__Exc_ZeroDivisionError; }
+
+#if PY_MAJOR_VERSION >= 2
+PyObject * _Exc_IndentationError() { return ptr__Exc_IndentationError; }
+PyObject * _Exc_TabError() { return ptr__Exc_TabError; }
+PyObject * _Exc_UnboundLocalError() { return ptr__Exc_UnboundLocalError; }
+PyObject * _Exc_UnicodeError() { return ptr__Exc_UnicodeError; }
+#endif
+
+//
+// wrap items in Object.h
+//
+PyObject * _None() { return ptr__PyNone; }
+
+
+PyTypeObject * _Buffer_Type() { return ptr__Buffer_Type; }
+PyTypeObject * _CFunction_Type() { return ptr__CFunction_Type; }
+PyTypeObject * _Class_Type() { return ptr__Class_Type; }
+PyTypeObject * _CObject_Type() { return ptr__CObject_Type; }
+PyTypeObject * _Complex_Type() { return ptr__Complex_Type; }
+PyTypeObject * _Dict_Type() { return ptr__Dict_Type; }
+PyTypeObject * _File_Type() { return ptr__File_Type; }
+PyTypeObject * _Float_Type() { return ptr__Float_Type; }
+PyTypeObject * _Function_Type() { return ptr__Function_Type; }
+PyTypeObject * _Instance_Type() { return ptr__Instance_Type; }
+PyTypeObject * _Int_Type() { return ptr__Int_Type; }
+PyTypeObject * _List_Type() { return ptr__List_Type; }
+PyTypeObject * _Long_Type() { return ptr__Long_Type; }
+PyTypeObject * _Method_Type() { return ptr__Method_Type; }
+PyTypeObject * _Module_Type() { return ptr__Module_Type; }
+PyTypeObject * _Range_Type() { return ptr__Range_Type; }
+PyTypeObject * _Slice_Type() { return ptr__Slice_Type; }
+PyTypeObject * _String_Type() { return ptr__String_Type; }
+PyTypeObject * _TraceBack_Type() { return ptr__TraceBack_Type; }
+PyTypeObject * _Tuple_Type() { return ptr__Tuple_Type; }
+PyTypeObject * _Type_Type() { return ptr__Type_Type; }
+
+#if PY_MAJOR_VERSION >= 2
+PyTypeObject * _Unicode_Type() { return ptr__Unicode_Type; }
+#endif
+
+char *__Py_PackageContext() { return *ptr__Py_PackageContext; }
+
+
+//
+// wrap the Python Flag variables
+//
+int &_Py_DebugFlag() { return *ptr_Py_DebugFlag; }
+int &_Py_InteractiveFlag() { return *ptr_Py_InteractiveFlag; }
+int &_Py_OptimizeFlag() { return *ptr_Py_OptimizeFlag; }
+int &_Py_NoSiteFlag() { return *ptr_Py_NoSiteFlag; }
+int &_Py_TabcheckFlag() { return *ptr_Py_TabcheckFlag; }
+int &_Py_VerboseFlag() { return *ptr_Py_VerboseFlag; }
+#if PY_MAJOR_VERSION >= 2
+int &_Py_UnicodeFlag() { return *ptr_Py_UnicodeFlag; }
+#endif
+
+void _XINCREF( PyObject *op )
+ {
+ // This function must match the contents of Py_XINCREF(op)
+ if( op == NULL )
+ return;
+
+#ifdef Py_REF_DEBUG
+ (*ptr_Py_RefTotal)++;
+#endif
+ (op)->ob_refcnt++;
+
+ }
+
+void _XDECREF( PyObject *op )
+ {
+ // This function must match the contents of Py_XDECREF(op);
+ if( op == NULL )
+ return;
+
+#ifdef Py_REF_DEBUG
+ (*ptr_Py_RefTotal)--;
+#endif
+
+ if (--(op)->ob_refcnt == 0)
+ _Py_Dealloc((PyObject *)(op));
+ }
+
+
+#else
+#error "Can only delay load under Win32"
+#endif
+
+#else
+
+//
+// Duplicated these declarations from rangeobject.h which is missing the
+// extern "C". This has been reported as a bug upto and include 2.1
+//
+extern "C" DL_IMPORT(PyTypeObject) PyRange_Type;
+extern "C" DL_IMPORT(PyObject *) PyRange_New(long, long, long, int);
+
+
+//================================================================================
+//
+// Map onto Macros
+//
+//================================================================================
+
+//
+// Wrap variables as function calls
+//
+
+PyObject * _Exc_ArithmeticError() { return ::PyExc_ArithmeticError; }
+PyObject * _Exc_AssertionError() { return ::PyExc_AssertionError; }
+PyObject * _Exc_AttributeError() { return ::PyExc_AttributeError; }
+PyObject * _Exc_EnvironmentError() { return ::PyExc_EnvironmentError; }
+PyObject * _Exc_EOFError() { return ::PyExc_EOFError; }
+PyObject * _Exc_Exception() { return ::PyExc_Exception; }
+PyObject * _Exc_FloatingPointError() { return ::PyExc_FloatingPointError; }
+PyObject * _Exc_ImportError() { return ::PyExc_ImportError; }
+PyObject * _Exc_IndexError() { return ::PyExc_IndexError; }
+PyObject * _Exc_IOError() { return ::PyExc_IOError; }
+PyObject * _Exc_KeyboardInterrupt() { return ::PyExc_KeyboardInterrupt; }
+PyObject * _Exc_KeyError() { return ::PyExc_KeyError; }
+PyObject * _Exc_LookupError() { return ::PyExc_LookupError; }
+PyObject * _Exc_MemoryError() { return ::PyExc_MemoryError; }
+PyObject * _Exc_MemoryErrorInst() { return ::PyExc_MemoryErrorInst; }
+PyObject * _Exc_NameError() { return ::PyExc_NameError; }
+PyObject * _Exc_NotImplementedError() { return ::PyExc_NotImplementedError; }
+PyObject * _Exc_OSError() { return ::PyExc_OSError; }
+PyObject * _Exc_OverflowError() { return ::PyExc_OverflowError; }
+PyObject * _Exc_RuntimeError() { return ::PyExc_RuntimeError; }
+PyObject * _Exc_StandardError() { return ::PyExc_StandardError; }
+PyObject * _Exc_SyntaxError() { return ::PyExc_SyntaxError; }
+PyObject * _Exc_SystemError() { return ::PyExc_SystemError; }
+PyObject * _Exc_SystemExit() { return ::PyExc_SystemExit; }
+PyObject * _Exc_TypeError() { return ::PyExc_TypeError; }
+PyObject * _Exc_ValueError() { return ::PyExc_ValueError; }
+PyObject * _Exc_ZeroDivisionError() { return ::PyExc_ZeroDivisionError; }
+
+#ifdef MS_WINDOWS
+PyObject * _Exc_WindowsError() { return ::PyExc_WindowsError; }
+#endif
+
+
+#if PY_MAJOR_VERSION >= 2
+PyObject * _Exc_IndentationError() { return ::PyExc_IndentationError; }
+PyObject * _Exc_TabError() { return ::PyExc_TabError; }
+PyObject * _Exc_UnboundLocalError() { return ::PyExc_UnboundLocalError; }
+PyObject * _Exc_UnicodeError() { return ::PyExc_UnicodeError; }
+#endif
+
+
+//
+// wrap items in Object.h
+//
+PyObject * _None() { return &::_Py_NoneStruct; }
+
+PyTypeObject * _Buffer_Type() { return &PyBuffer_Type; }
+PyTypeObject * _CFunction_Type() { return &PyCFunction_Type; }
+PyTypeObject * _Class_Type() { return &PyClass_Type; }
+PyTypeObject * _CObject_Type() { return &PyCObject_Type; }
+PyTypeObject * _Complex_Type() { return &PyComplex_Type; }
+PyTypeObject * _Dict_Type() { return &PyDict_Type; }
+PyTypeObject * _File_Type() { return &PyFile_Type; }
+PyTypeObject * _Float_Type() { return &PyFloat_Type; }
+PyTypeObject * _Function_Type() { return &PyFunction_Type; }
+PyTypeObject * _Instance_Type() { return &PyInstance_Type; }
+PyTypeObject * _Int_Type() { return &PyInt_Type; }
+PyTypeObject * _List_Type() { return &PyList_Type; }
+PyTypeObject * _Long_Type() { return &PyLong_Type; }
+PyTypeObject * _Method_Type() { return &PyMethod_Type; }
+PyTypeObject * _Module_Type() { return &PyModule_Type; }
+PyTypeObject * _Range_Type() { return &PyRange_Type; }
+PyTypeObject * _Slice_Type() { return &PySlice_Type; }
+PyTypeObject * _String_Type() { return &PyString_Type; }
+PyTypeObject * _TraceBack_Type() { return &PyTraceBack_Type; }
+PyTypeObject * _Tuple_Type() { return &PyTuple_Type; }
+PyTypeObject * _Type_Type() { return &PyType_Type; }
+
+#if PY_MAJOR_VERSION >= 2
+PyTypeObject * _Unicode_Type() { return &PyUnicode_Type; }
+#endif
+
+//
+// wrap flags
+//
+int &_Py_DebugFlag() { return Py_DebugFlag; }
+int &_Py_InteractiveFlag() { return Py_InteractiveFlag; }
+int &_Py_OptimizeFlag() { return Py_OptimizeFlag; }
+int &_Py_NoSiteFlag() { return Py_NoSiteFlag; }
+int &_Py_TabcheckFlag() { return Py_TabcheckFlag; }
+int &_Py_VerboseFlag() { return Py_VerboseFlag; }
+#if PY_MAJOR_VERSION >= 2
+int &_Py_UnicodeFlag() { return Py_UnicodeFlag; }
+#endif
+char *__Py_PackageContext() { return _Py_PackageContext; }
+
+//
+// Needed to keep the abstactions for delayload interface
+//
+void _XINCREF( PyObject *op )
+ {
+ Py_XINCREF(op);
+ }
+
+void _XDECREF( PyObject *op )
+ {
+ Py_XDECREF(op);
+ }
+
+#endif
+}
diff --git a/lib/kross/python/cxx/IndirectPythonInterface.cxx b/lib/kross/python/cxx/IndirectPythonInterface.cxx
deleted file mode 100644
index caaa09134..000000000
--- a/lib/kross/python/cxx/IndirectPythonInterface.cxx
+++ /dev/null
@@ -1,550 +0,0 @@
-//
-// IndirectPythonInterface.cxx
-//
-#undef _XOPEN_SOURCE
-#include "IndirectPythonInterface.hxx"
-
-namespace Py
-{
-bool _Buffer_Check( PyObject *op ) { return (op)->ob_type == _Buffer_Type(); }
-bool _CFunction_Check( PyObject *op ) { return (op)->ob_type == _CFunction_Type(); }
-bool _Class_Check( PyObject *op ) { return (op)->ob_type == _Class_Type(); }
-bool _CObject_Check( PyObject *op ) { return (op)->ob_type == _CObject_Type(); }
-bool _Complex_Check( PyObject *op ) { return (op)->ob_type == _Complex_Type(); }
-bool _Dict_Check( PyObject *op ) { return (op)->ob_type == _Dict_Type(); }
-bool _File_Check( PyObject *op ) { return (op)->ob_type == _File_Type(); }
-bool _Float_Check( PyObject *op ) { return (op)->ob_type == _Float_Type(); }
-bool _Function_Check( PyObject *op ) { return (op)->ob_type == _Function_Type(); }
-bool _Instance_Check( PyObject *op ) { return (op)->ob_type == _Instance_Type(); }
-bool _Int_Check( PyObject *op ) { return (op)->ob_type == _Int_Type(); }
-bool _List_Check( PyObject *o ) { return o->ob_type == _List_Type(); }
-bool _Long_Check( PyObject *op ) { return (op)->ob_type == _Long_Type(); }
-bool _Method_Check( PyObject *op ) { return (op)->ob_type == _Method_Type(); }
-bool _Module_Check( PyObject *op ) { return (op)->ob_type == _Module_Type(); }
-bool _Range_Check( PyObject *op ) { return (op)->ob_type == _Range_Type(); }
-bool _Slice_Check( PyObject *op ) { return (op)->ob_type == _Slice_Type(); }
-bool _String_Check( PyObject *o ) { return o->ob_type == _String_Type(); }
-bool _TraceBack_Check( PyObject *v ) { return (v)->ob_type == _TraceBack_Type(); }
-bool _Tuple_Check( PyObject *op ) { return (op)->ob_type == _Tuple_Type(); }
-bool _Type_Check( PyObject *op ) { return (op)->ob_type == _Type_Type(); }
-
-#if PY_MAJOR_VERSION >= 2
-bool _Unicode_Check( PyObject *op ) { return (op)->ob_type == _Unicode_Type(); }
-#endif
-
-
-
-#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)
-
-#if defined(MS_WINDOWS)
-#include <windows.h>
-
-
-static HMODULE python_dll;
-
-static PyObject *ptr__Exc_ArithmeticError = NULL;
-static PyObject *ptr__Exc_AssertionError = NULL;
-static PyObject *ptr__Exc_AttributeError = NULL;
-static PyObject *ptr__Exc_EnvironmentError = NULL;
-static PyObject *ptr__Exc_EOFError = NULL;
-static PyObject *ptr__Exc_Exception = NULL;
-static PyObject *ptr__Exc_FloatingPointError = NULL;
-static PyObject *ptr__Exc_ImportError = NULL;
-static PyObject *ptr__Exc_IndexError = NULL;
-static PyObject *ptr__Exc_IOError = NULL;
-static PyObject *ptr__Exc_KeyboardInterrupt = NULL;
-static PyObject *ptr__Exc_KeyError = NULL;
-static PyObject *ptr__Exc_LookupError = NULL;
-static PyObject *ptr__Exc_MemoryError = NULL;
-static PyObject *ptr__Exc_MemoryErrorInst = NULL;
-static PyObject *ptr__Exc_NameError = NULL;
-static PyObject *ptr__Exc_NotImplementedError = NULL;
-static PyObject *ptr__Exc_OSError = NULL;
-static PyObject *ptr__Exc_OverflowError = NULL;
-static PyObject *ptr__Exc_RuntimeError = NULL;
-static PyObject *ptr__Exc_StandardError = NULL;
-static PyObject *ptr__Exc_SyntaxError = NULL;
-static PyObject *ptr__Exc_SystemError = NULL;
-static PyObject *ptr__Exc_SystemExit = NULL;
-static PyObject *ptr__Exc_TypeError = NULL;
-static PyObject *ptr__Exc_ValueError = NULL;
-static PyObject *ptr__Exc_ZeroDivisionError = NULL;
-
-#ifdef MS_WINDOWS
-static PyObject *ptr__Exc_WindowsError = NULL;
-#endif
-
-#if PY_MAJOR_VERSION >= 2
-static PyObject *ptr__Exc_IndentationError = NULL;
-static PyObject *ptr__Exc_TabError = NULL;
-static PyObject *ptr__Exc_UnboundLocalError = NULL;
-static PyObject *ptr__Exc_UnicodeError = NULL;
-#endif
-
-static PyObject *ptr__PyNone = NULL;
-
-static PyTypeObject *ptr__Buffer_Type = NULL;
-static PyTypeObject *ptr__CFunction_Type = NULL;
-static PyTypeObject *ptr__Class_Type = NULL;
-static PyTypeObject *ptr__CObject_Type = NULL;
-static PyTypeObject *ptr__Complex_Type = NULL;
-static PyTypeObject *ptr__Dict_Type = NULL;
-static PyTypeObject *ptr__File_Type = NULL;
-static PyTypeObject *ptr__Float_Type = NULL;
-static PyTypeObject *ptr__Function_Type = NULL;
-static PyTypeObject *ptr__Instance_Type = NULL;
-static PyTypeObject *ptr__Int_Type = NULL;
-static PyTypeObject *ptr__List_Type = NULL;
-static PyTypeObject *ptr__Long_Type = NULL;
-static PyTypeObject *ptr__Method_Type = NULL;
-static PyTypeObject *ptr__Module_Type = NULL;
-static PyTypeObject *ptr__Range_Type = NULL;
-static PyTypeObject *ptr__Slice_Type = NULL;
-static PyTypeObject *ptr__String_Type = NULL;
-static PyTypeObject *ptr__TraceBack_Type = NULL;
-static PyTypeObject *ptr__Tuple_Type = NULL;
-static PyTypeObject *ptr__Type_Type = NULL;
-
-#if PY_MAJOR_VERSION >= 2
-static PyTypeObject *ptr__Unicode_Type = NULL;
-#endif
-
-static int *ptr_Py_DebugFlag = NULL;
-static int *ptr_Py_InteractiveFlag = NULL;
-static int *ptr_Py_OptimizeFlag = NULL;
-static int *ptr_Py_NoSiteFlag = NULL;
-static int *ptr_Py_TabcheckFlag = NULL;
-static int *ptr_Py_VerboseFlag = NULL;
-
-#if PY_MAJOR_VERSION >= 2
-static int *ptr_Py_UnicodeFlag = NULL;
-#endif
-
-static char **ptr__Py_PackageContext = NULL;
-
-#ifdef Py_REF_DEBUG
-int *ptr_Py_RefTotal;
-#endif
-
-
-//--------------------------------------------------------------------------------
-class GetAddressException
- {
-public:
- GetAddressException( const char *_name )
- : name( _name )
- {}
- virtual ~GetAddressException() {}
- const char *name;
- };
-
-
-//--------------------------------------------------------------------------------
-static PyObject *GetPyObjectPointer_As_PyObjectPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return *(PyObject **)addr;
- }
-
-static PyObject *GetPyObject_As_PyObjectPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return (PyObject *)addr;
- }
-
-static PyTypeObject *GetPyTypeObjectPointer_As_PyTypeObjectPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return *(PyTypeObject **)addr;
- }
-
-static PyTypeObject *GetPyTypeObject_As_PyTypeObjectPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return (PyTypeObject *)addr;
- }
-
-static int *GetInt_as_IntPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return (int *)addr;
- }
-
-static char **GetCharPointer_as_CharPointerPointer( const char *name )
- {
- FARPROC addr = GetProcAddress( python_dll, name );
- if( addr == NULL )
- throw GetAddressException( name );
-
- return (char **)addr;
- }
-
-
-#ifdef _DEBUG
-static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d_D.DLL";
-#else
-static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d.DLL";
-#endif
-
-//--------------------------------------------------------------------------------
-bool InitialisePythonIndirectInterface()
- {
- char python_dll_name[sizeof(python_dll_name_format)];
-
- sprintf( python_dll_name, python_dll_name_format, PY_MAJOR_VERSION, PY_MINOR_VERSION );
-
- python_dll = LoadLibrary( python_dll_name );
- if( python_dll == NULL )
- return false;
-
- try
- {
-#ifdef Py_REF_DEBUG
- ptr_Py_RefTotal = GetInt_as_IntPointer( "_Py_RefTotal" );
-#endif
- ptr_Py_DebugFlag = GetInt_as_IntPointer( "Py_DebugFlag" );
- ptr_Py_InteractiveFlag = GetInt_as_IntPointer( "Py_InteractiveFlag" );
- ptr_Py_OptimizeFlag = GetInt_as_IntPointer( "Py_OptimizeFlag" );
- ptr_Py_NoSiteFlag = GetInt_as_IntPointer( "Py_NoSiteFlag" );
- ptr_Py_TabcheckFlag = GetInt_as_IntPointer( "Py_TabcheckFlag" );
- ptr_Py_VerboseFlag = GetInt_as_IntPointer( "Py_VerboseFlag" );
-#if PY_MAJOR_VERSION >= 2
- ptr_Py_UnicodeFlag = GetInt_as_IntPointer( "Py_UnicodeFlag" );
-#endif
- ptr__Py_PackageContext = GetCharPointer_as_CharPointerPointer( "_Py_PackageContext" );
-
- ptr__Exc_ArithmeticError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ArithmeticError" );
- ptr__Exc_AssertionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AssertionError" );
- ptr__Exc_AttributeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AttributeError" );
- ptr__Exc_EnvironmentError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EnvironmentError" );
- ptr__Exc_EOFError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EOFError" );
- ptr__Exc_Exception = GetPyObjectPointer_As_PyObjectPointer( "PyExc_Exception" );
- ptr__Exc_FloatingPointError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_FloatingPointError" );
- ptr__Exc_ImportError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ImportError" );
- ptr__Exc_IndexError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndexError" );
- ptr__Exc_IOError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IOError" );
- ptr__Exc_KeyboardInterrupt = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyboardInterrupt" );
- ptr__Exc_KeyError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyError" );
- ptr__Exc_LookupError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_LookupError" );
- ptr__Exc_MemoryError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryError" );
- ptr__Exc_MemoryErrorInst = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryErrorInst" );
- ptr__Exc_NameError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NameError" );
- ptr__Exc_NotImplementedError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NotImplementedError" );
- ptr__Exc_OSError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OSError" );
- ptr__Exc_OverflowError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OverflowError" );
- ptr__Exc_RuntimeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_RuntimeError" );
- ptr__Exc_StandardError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_StandardError" );
- ptr__Exc_SyntaxError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SyntaxError" );
- ptr__Exc_SystemError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemError" );
- ptr__Exc_SystemExit = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemExit" );
- ptr__Exc_TypeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TypeError" );
- ptr__Exc_ValueError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ValueError" );
-#ifdef MS_WINDOWS
- ptr__Exc_WindowsError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_WindowsError" );
-#endif
- ptr__Exc_ZeroDivisionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ZeroDivisionError" );
-
-#if PY_MAJOR_VERSION >= 2
- ptr__Exc_IndentationError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndentationError" );
- ptr__Exc_TabError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TabError" );
- ptr__Exc_UnboundLocalError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnboundLocalError" );
- ptr__Exc_UnicodeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnicodeError" );
-#endif
- ptr__PyNone = GetPyObject_As_PyObjectPointer( "_Py_NoneStruct" );
-
- ptr__Buffer_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBuffer_Type" );
- ptr__CFunction_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCFunction_Type" );
- ptr__Class_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyClass_Type" );
- ptr__CObject_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCObject_Type" );
- ptr__Complex_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyComplex_Type" );
- ptr__Dict_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyDict_Type" );
- ptr__File_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFile_Type" );
- ptr__Float_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFloat_Type" );
- ptr__Function_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFunction_Type" );
- ptr__Instance_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInstance_Type" );
- ptr__Int_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInt_Type" );
- ptr__List_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyList_Type" );
- ptr__Long_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyLong_Type" );
- ptr__Method_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyMethod_Type" );
- ptr__Module_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyModule_Type" );
- ptr__Range_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyRange_Type" );
- ptr__Slice_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PySlice_Type" );
- ptr__String_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyString_Type" );
- ptr__TraceBack_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTraceBack_Type" );
- ptr__Tuple_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTuple_Type" );
- ptr__Type_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyType_Type" );
-
-#if PY_MAJOR_VERSION >= 2
- ptr__Unicode_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyUnicode_Type" );
-#endif
- }
- catch( GetAddressException &e )
- {
- OutputDebugString( python_dll_name );
- OutputDebugString( " does not contain symbol ");
- OutputDebugString( e.name );
- OutputDebugString( "\n" );
-
- return false;
- }
-
- return true;
- }
-
-//
-// Wrap variables as function calls
-//
-PyObject * _Exc_ArithmeticError() { return ptr__Exc_ArithmeticError; }
-PyObject * _Exc_AssertionError() { return ptr__Exc_AssertionError; }
-PyObject * _Exc_AttributeError() { return ptr__Exc_AttributeError; }
-PyObject * _Exc_EnvironmentError() { return ptr__Exc_EnvironmentError; }
-PyObject * _Exc_EOFError() { return ptr__Exc_EOFError; }
-PyObject * _Exc_Exception() { return ptr__Exc_Exception; }
-PyObject * _Exc_FloatingPointError() { return ptr__Exc_FloatingPointError; }
-PyObject * _Exc_ImportError() { return ptr__Exc_ImportError; }
-PyObject * _Exc_IndexError() { return ptr__Exc_IndexError; }
-PyObject * _Exc_IOError() { return ptr__Exc_IOError; }
-PyObject * _Exc_KeyboardInterrupt() { return ptr__Exc_KeyboardInterrupt; }
-PyObject * _Exc_KeyError() { return ptr__Exc_KeyError; }
-PyObject * _Exc_LookupError() { return ptr__Exc_LookupError; }
-PyObject * _Exc_MemoryError() { return ptr__Exc_MemoryError; }
-PyObject * _Exc_MemoryErrorInst() { return ptr__Exc_MemoryErrorInst; }
-PyObject * _Exc_NameError() { return ptr__Exc_NameError; }
-PyObject * _Exc_NotImplementedError() { return ptr__Exc_NotImplementedError; }
-PyObject * _Exc_OSError() { return ptr__Exc_OSError; }
-PyObject * _Exc_OverflowError() { return ptr__Exc_OverflowError; }
-PyObject * _Exc_RuntimeError() { return ptr__Exc_RuntimeError; }
-PyObject * _Exc_StandardError() { return ptr__Exc_StandardError; }
-PyObject * _Exc_SyntaxError() { return ptr__Exc_SyntaxError; }
-PyObject * _Exc_SystemError() { return ptr__Exc_SystemError; }
-PyObject * _Exc_SystemExit() { return ptr__Exc_SystemExit; }
-PyObject * _Exc_TypeError() { return ptr__Exc_TypeError; }
-PyObject * _Exc_ValueError() { return ptr__Exc_ValueError; }
-#ifdef MS_WINDOWS
-PyObject * _Exc_WindowsError() { return ptr__Exc_WindowsError; }
-#endif
-PyObject * _Exc_ZeroDivisionError() { return ptr__Exc_ZeroDivisionError; }
-
-#if PY_MAJOR_VERSION >= 2
-PyObject * _Exc_IndentationError() { return ptr__Exc_IndentationError; }
-PyObject * _Exc_TabError() { return ptr__Exc_TabError; }
-PyObject * _Exc_UnboundLocalError() { return ptr__Exc_UnboundLocalError; }
-PyObject * _Exc_UnicodeError() { return ptr__Exc_UnicodeError; }
-#endif
-
-//
-// wrap items in Object.h
-//
-PyObject * _None() { return ptr__PyNone; }
-
-
-PyTypeObject * _Buffer_Type() { return ptr__Buffer_Type; }
-PyTypeObject * _CFunction_Type() { return ptr__CFunction_Type; }
-PyTypeObject * _Class_Type() { return ptr__Class_Type; }
-PyTypeObject * _CObject_Type() { return ptr__CObject_Type; }
-PyTypeObject * _Complex_Type() { return ptr__Complex_Type; }
-PyTypeObject * _Dict_Type() { return ptr__Dict_Type; }
-PyTypeObject * _File_Type() { return ptr__File_Type; }
-PyTypeObject * _Float_Type() { return ptr__Float_Type; }
-PyTypeObject * _Function_Type() { return ptr__Function_Type; }
-PyTypeObject * _Instance_Type() { return ptr__Instance_Type; }
-PyTypeObject * _Int_Type() { return ptr__Int_Type; }
-PyTypeObject * _List_Type() { return ptr__List_Type; }
-PyTypeObject * _Long_Type() { return ptr__Long_Type; }
-PyTypeObject * _Method_Type() { return ptr__Method_Type; }
-PyTypeObject * _Module_Type() { return ptr__Module_Type; }
-PyTypeObject * _Range_Type() { return ptr__Range_Type; }
-PyTypeObject * _Slice_Type() { return ptr__Slice_Type; }
-PyTypeObject * _String_Type() { return ptr__String_Type; }
-PyTypeObject * _TraceBack_Type() { return ptr__TraceBack_Type; }
-PyTypeObject * _Tuple_Type() { return ptr__Tuple_Type; }
-PyTypeObject * _Type_Type() { return ptr__Type_Type; }
-
-#if PY_MAJOR_VERSION >= 2
-PyTypeObject * _Unicode_Type() { return ptr__Unicode_Type; }
-#endif
-
-char *__Py_PackageContext() { return *ptr__Py_PackageContext; }
-
-
-//
-// wrap the Python Flag variables
-//
-int &_Py_DebugFlag() { return *ptr_Py_DebugFlag; }
-int &_Py_InteractiveFlag() { return *ptr_Py_InteractiveFlag; }
-int &_Py_OptimizeFlag() { return *ptr_Py_OptimizeFlag; }
-int &_Py_NoSiteFlag() { return *ptr_Py_NoSiteFlag; }
-int &_Py_TabcheckFlag() { return *ptr_Py_TabcheckFlag; }
-int &_Py_VerboseFlag() { return *ptr_Py_VerboseFlag; }
-#if PY_MAJOR_VERSION >= 2
-int &_Py_UnicodeFlag() { return *ptr_Py_UnicodeFlag; }
-#endif
-
-void _XINCREF( PyObject *op )
- {
- // This function must match the contents of Py_XINCREF(op)
- if( op == NULL )
- return;
-
-#ifdef Py_REF_DEBUG
- (*ptr_Py_RefTotal)++;
-#endif
- (op)->ob_refcnt++;
-
- }
-
-void _XDECREF( PyObject *op )
- {
- // This function must match the contents of Py_XDECREF(op);
- if( op == NULL )
- return;
-
-#ifdef Py_REF_DEBUG
- (*ptr_Py_RefTotal)--;
-#endif
-
- if (--(op)->ob_refcnt == 0)
- _Py_Dealloc((PyObject *)(op));
- }
-
-
-#else
-#error "Can only delay load under Win32"
-#endif
-
-#else
-
-//
-// Duplicated these declarations from rangeobject.h which is missing the
-// extern "C". This has been reported as a bug upto and include 2.1
-//
-extern "C" DL_IMPORT(PyTypeObject) PyRange_Type;
-extern "C" DL_IMPORT(PyObject *) PyRange_New(long, long, long, int);
-
-
-//================================================================================
-//
-// Map onto Macros
-//
-//================================================================================
-
-//
-// Wrap variables as function calls
-//
-
-PyObject * _Exc_ArithmeticError() { return ::PyExc_ArithmeticError; }
-PyObject * _Exc_AssertionError() { return ::PyExc_AssertionError; }
-PyObject * _Exc_AttributeError() { return ::PyExc_AttributeError; }
-PyObject * _Exc_EnvironmentError() { return ::PyExc_EnvironmentError; }
-PyObject * _Exc_EOFError() { return ::PyExc_EOFError; }
-PyObject * _Exc_Exception() { return ::PyExc_Exception; }
-PyObject * _Exc_FloatingPointError() { return ::PyExc_FloatingPointError; }
-PyObject * _Exc_ImportError() { return ::PyExc_ImportError; }
-PyObject * _Exc_IndexError() { return ::PyExc_IndexError; }
-PyObject * _Exc_IOError() { return ::PyExc_IOError; }
-PyObject * _Exc_KeyboardInterrupt() { return ::PyExc_KeyboardInterrupt; }
-PyObject * _Exc_KeyError() { return ::PyExc_KeyError; }
-PyObject * _Exc_LookupError() { return ::PyExc_LookupError; }
-PyObject * _Exc_MemoryError() { return ::PyExc_MemoryError; }
-PyObject * _Exc_MemoryErrorInst() { return ::PyExc_MemoryErrorInst; }
-PyObject * _Exc_NameError() { return ::PyExc_NameError; }
-PyObject * _Exc_NotImplementedError() { return ::PyExc_NotImplementedError; }
-PyObject * _Exc_OSError() { return ::PyExc_OSError; }
-PyObject * _Exc_OverflowError() { return ::PyExc_OverflowError; }
-PyObject * _Exc_RuntimeError() { return ::PyExc_RuntimeError; }
-PyObject * _Exc_StandardError() { return ::PyExc_StandardError; }
-PyObject * _Exc_SyntaxError() { return ::PyExc_SyntaxError; }
-PyObject * _Exc_SystemError() { return ::PyExc_SystemError; }
-PyObject * _Exc_SystemExit() { return ::PyExc_SystemExit; }
-PyObject * _Exc_TypeError() { return ::PyExc_TypeError; }
-PyObject * _Exc_ValueError() { return ::PyExc_ValueError; }
-PyObject * _Exc_ZeroDivisionError() { return ::PyExc_ZeroDivisionError; }
-
-#ifdef MS_WINDOWS
-PyObject * _Exc_WindowsError() { return ::PyExc_WindowsError; }
-#endif
-
-
-#if PY_MAJOR_VERSION >= 2
-PyObject * _Exc_IndentationError() { return ::PyExc_IndentationError; }
-PyObject * _Exc_TabError() { return ::PyExc_TabError; }
-PyObject * _Exc_UnboundLocalError() { return ::PyExc_UnboundLocalError; }
-PyObject * _Exc_UnicodeError() { return ::PyExc_UnicodeError; }
-#endif
-
-
-//
-// wrap items in Object.h
-//
-PyObject * _None() { return &::_Py_NoneStruct; }
-
-PyTypeObject * _Buffer_Type() { return &PyBuffer_Type; }
-PyTypeObject * _CFunction_Type() { return &PyCFunction_Type; }
-PyTypeObject * _Class_Type() { return &PyClass_Type; }
-PyTypeObject * _CObject_Type() { return &PyCObject_Type; }
-PyTypeObject * _Complex_Type() { return &PyComplex_Type; }
-PyTypeObject * _Dict_Type() { return &PyDict_Type; }
-PyTypeObject * _File_Type() { return &PyFile_Type; }
-PyTypeObject * _Float_Type() { return &PyFloat_Type; }
-PyTypeObject * _Function_Type() { return &PyFunction_Type; }
-PyTypeObject * _Instance_Type() { return &PyInstance_Type; }
-PyTypeObject * _Int_Type() { return &PyInt_Type; }
-PyTypeObject * _List_Type() { return &PyList_Type; }
-PyTypeObject * _Long_Type() { return &PyLong_Type; }
-PyTypeObject * _Method_Type() { return &PyMethod_Type; }
-PyTypeObject * _Module_Type() { return &PyModule_Type; }
-PyTypeObject * _Range_Type() { return &PyRange_Type; }
-PyTypeObject * _Slice_Type() { return &PySlice_Type; }
-PyTypeObject * _String_Type() { return &PyString_Type; }
-PyTypeObject * _TraceBack_Type() { return &PyTraceBack_Type; }
-PyTypeObject * _Tuple_Type() { return &PyTuple_Type; }
-PyTypeObject * _Type_Type() { return &PyType_Type; }
-
-#if PY_MAJOR_VERSION >= 2
-PyTypeObject * _Unicode_Type() { return &PyUnicode_Type; }
-#endif
-
-//
-// wrap flags
-//
-int &_Py_DebugFlag() { return Py_DebugFlag; }
-int &_Py_InteractiveFlag() { return Py_InteractiveFlag; }
-int &_Py_OptimizeFlag() { return Py_OptimizeFlag; }
-int &_Py_NoSiteFlag() { return Py_NoSiteFlag; }
-int &_Py_TabcheckFlag() { return Py_TabcheckFlag; }
-int &_Py_VerboseFlag() { return Py_VerboseFlag; }
-#if PY_MAJOR_VERSION >= 2
-int &_Py_UnicodeFlag() { return Py_UnicodeFlag; }
-#endif
-char *__Py_PackageContext() { return _Py_PackageContext; }
-
-//
-// Needed to keep the abstactions for delayload interface
-//
-void _XINCREF( PyObject *op )
- {
- Py_XINCREF(op);
- }
-
-void _XDECREF( PyObject *op )
- {
- Py_XDECREF(op);
- }
-
-#endif
-}
diff --git a/lib/kross/python/cxx/IndirectPythonInterface.h b/lib/kross/python/cxx/IndirectPythonInterface.h
new file mode 100644
index 000000000..8cc0bcec7
--- /dev/null
+++ b/lib/kross/python/cxx/IndirectPythonInterface.h
@@ -0,0 +1,156 @@
+#ifndef __CXX_INDIRECT_PYTHON_INTERFACE__H__
+#define __CXX_INDIRECT_PYTHON_INTERFACE__H__
+
+#include <Python.h>
+
+namespace Py
+{
+bool InitialisePythonIndirectInterface();
+
+//
+// Wrap Exception variables as function calls
+//
+PyObject * _Exc_Exception();
+PyObject * _Exc_StandardError();
+PyObject * _Exc_ArithmeticError();
+PyObject * _Exc_LookupError();
+
+PyObject * _Exc_AssertionError();
+PyObject * _Exc_AttributeError();
+PyObject * _Exc_EOFError();
+PyObject * _Exc_FloatingPointError();
+PyObject * _Exc_EnvironmentError();
+PyObject * _Exc_IOError();
+PyObject * _Exc_OSError();
+PyObject * _Exc_ImportError();
+PyObject * _Exc_IndexError();
+PyObject * _Exc_KeyError();
+PyObject * _Exc_KeyboardInterrupt();
+PyObject * _Exc_MemoryError();
+PyObject * _Exc_NameError();
+PyObject * _Exc_OverflowError();
+PyObject * _Exc_RuntimeError();
+PyObject * _Exc_NotImplementedError();
+PyObject * _Exc_SyntaxError();
+PyObject * _Exc_SystemError();
+PyObject * _Exc_SystemExit();
+PyObject * _Exc_TypeError();
+PyObject * _Exc_ValueError();
+PyObject * _Exc_ZeroDivisionError();
+#ifdef MS_WINDOWS
+PyObject * _Exc_WindowsError();
+#endif
+
+PyObject * _Exc_MemoryErrorInst();
+
+#if PY_MAJOR_VERSION >= 2
+PyObject * _Exc_IndentationError();
+PyObject * _Exc_TabError();
+PyObject * _Exc_UnboundLocalError();
+PyObject * _Exc_UnicodeError();
+#endif
+
+//
+// Wrap Object variables as function calls
+//
+PyObject * _None();
+
+
+//
+// Wrap Type variables as function calls
+//
+PyTypeObject * _List_Type();
+bool _List_Check( PyObject *o );
+
+PyTypeObject * _Buffer_Type();
+bool _Buffer_Check( PyObject *op );
+
+PyTypeObject * _Class_Type();
+bool _Class_Check( PyObject *op );
+
+PyTypeObject * _Instance_Type();
+bool _Instance_Check( PyObject *op );
+
+PyTypeObject * _Method_Type();
+bool _Method_Check( PyObject *op );
+
+PyTypeObject * _CObject_Type();
+bool _CObject_Check( PyObject *op );
+
+PyTypeObject * _Complex_Type();
+bool _Complex_Check( PyObject *op );
+
+PyTypeObject * _Dict_Type();
+bool _Dict_Check( PyObject *op );
+
+PyTypeObject * _File_Type();
+bool _File_Check( PyObject *op );
+
+PyTypeObject * _Float_Type();
+bool _Float_Check( PyObject *op );
+
+PyTypeObject * _Frame_Type();
+bool _Frame_Check( PyObject *op );
+
+PyTypeObject * _Function_Type();
+bool _Function_Check( PyObject *op );
+
+PyTypeObject * _Int_Type();
+bool _Int_Check( PyObject *op );
+
+PyTypeObject * _List_Type();
+bool _List_Check( PyObject *op );
+
+PyTypeObject * _Long_Type();
+bool _Long_Check( PyObject *op );
+
+PyTypeObject * _CFunction_Type();
+bool _CFunction_Check( PyObject *op );
+
+PyTypeObject * _Module_Type();
+bool _Module_Check( PyObject *op );
+
+PyTypeObject * _Type_Type();
+bool _Type_Check( PyObject *op );
+
+PyTypeObject * _Range_Type();
+bool _Range_Check( PyObject *op );
+
+PyTypeObject * _Slice_Type();
+bool _Slice_Check( PyObject *op );
+
+PyTypeObject * _String_Type();
+bool _String_Check( PyObject *op );
+
+PyTypeObject * _Unicode_Type();
+bool _Unicode_Check( PyObject *op );
+
+PyTypeObject * _TraceBack_Type();
+bool _TraceBack_Check( PyObject *v );
+
+PyTypeObject * _Tuple_Type();
+bool _Tuple_Check( PyObject *op );
+
+#if PY_MAJOR_VERSION >= 2
+PyTypeObject * _Unicode_Type();
+bool _Unicode_Check( PyObject *op );
+#endif
+
+int &_Py_DebugFlag();
+int &_Py_InteractiveFlag();
+int &_Py_OptimizeFlag();
+int &_Py_NoSiteFlag();
+int &_Py_TabcheckFlag();
+int &_Py_VerboseFlag();
+
+#if PY_MAJOR_VERSION >= 2
+int &_Py_UnicodeFlag();
+#endif
+
+void _XINCREF( PyObject *op );
+void _XDECREF( PyObject *op );
+
+char *__Py_PackageContext();
+}
+
+#endif // __CXX_INDIRECT_PYTHON_INTERFACE__H__
diff --git a/lib/kross/python/cxx/IndirectPythonInterface.hxx b/lib/kross/python/cxx/IndirectPythonInterface.hxx
deleted file mode 100644
index 8f2d275dd..000000000
--- a/lib/kross/python/cxx/IndirectPythonInterface.hxx
+++ /dev/null
@@ -1,156 +0,0 @@
-#ifndef __CXX_INDIRECT_PYTHON_INTERFACE__HXX__
-#define __CXX_INDIRECT_PYTHON_INTERFACE__HXX__
-
-#include <Python.h>
-
-namespace Py
-{
-bool InitialisePythonIndirectInterface();
-
-//
-// Wrap Exception variables as function calls
-//
-PyObject * _Exc_Exception();
-PyObject * _Exc_StandardError();
-PyObject * _Exc_ArithmeticError();
-PyObject * _Exc_LookupError();
-
-PyObject * _Exc_AssertionError();
-PyObject * _Exc_AttributeError();
-PyObject * _Exc_EOFError();
-PyObject * _Exc_FloatingPointError();
-PyObject * _Exc_EnvironmentError();
-PyObject * _Exc_IOError();
-PyObject * _Exc_OSError();
-PyObject * _Exc_ImportError();
-PyObject * _Exc_IndexError();
-PyObject * _Exc_KeyError();
-PyObject * _Exc_KeyboardInterrupt();
-PyObject * _Exc_MemoryError();
-PyObject * _Exc_NameError();
-PyObject * _Exc_OverflowError();
-PyObject * _Exc_RuntimeError();
-PyObject * _Exc_NotImplementedError();
-PyObject * _Exc_SyntaxError();
-PyObject * _Exc_SystemError();
-PyObject * _Exc_SystemExit();
-PyObject * _Exc_TypeError();
-PyObject * _Exc_ValueError();
-PyObject * _Exc_ZeroDivisionError();
-#ifdef MS_WINDOWS
-PyObject * _Exc_WindowsError();
-#endif
-
-PyObject * _Exc_MemoryErrorInst();
-
-#if PY_MAJOR_VERSION >= 2
-PyObject * _Exc_IndentationError();
-PyObject * _Exc_TabError();
-PyObject * _Exc_UnboundLocalError();
-PyObject * _Exc_UnicodeError();
-#endif
-
-//
-// Wrap Object variables as function calls
-//
-PyObject * _None();
-
-
-//
-// Wrap Type variables as function calls
-//
-PyTypeObject * _List_Type();
-bool _List_Check( PyObject *o );
-
-PyTypeObject * _Buffer_Type();
-bool _Buffer_Check( PyObject *op );
-
-PyTypeObject * _Class_Type();
-bool _Class_Check( PyObject *op );
-
-PyTypeObject * _Instance_Type();
-bool _Instance_Check( PyObject *op );
-
-PyTypeObject * _Method_Type();
-bool _Method_Check( PyObject *op );
-
-PyTypeObject * _CObject_Type();
-bool _CObject_Check( PyObject *op );
-
-PyTypeObject * _Complex_Type();
-bool _Complex_Check( PyObject *op );
-
-PyTypeObject * _Dict_Type();
-bool _Dict_Check( PyObject *op );
-
-PyTypeObject * _File_Type();
-bool _File_Check( PyObject *op );
-
-PyTypeObject * _Float_Type();
-bool _Float_Check( PyObject *op );
-
-PyTypeObject * _Frame_Type();
-bool _Frame_Check( PyObject *op );
-
-PyTypeObject * _Function_Type();
-bool _Function_Check( PyObject *op );
-
-PyTypeObject * _Int_Type();
-bool _Int_Check( PyObject *op );
-
-PyTypeObject * _List_Type();
-bool _List_Check( PyObject *op );
-
-PyTypeObject * _Long_Type();
-bool _Long_Check( PyObject *op );
-
-PyTypeObject * _CFunction_Type();
-bool _CFunction_Check( PyObject *op );
-
-PyTypeObject * _Module_Type();
-bool _Module_Check( PyObject *op );
-
-PyTypeObject * _Type_Type();
-bool _Type_Check( PyObject *op );
-
-PyTypeObject * _Range_Type();
-bool _Range_Check( PyObject *op );
-
-PyTypeObject * _Slice_Type();
-bool _Slice_Check( PyObject *op );
-
-PyTypeObject * _String_Type();
-bool _String_Check( PyObject *op );
-
-PyTypeObject * _Unicode_Type();
-bool _Unicode_Check( PyObject *op );
-
-PyTypeObject * _TraceBack_Type();
-bool _TraceBack_Check( PyObject *v );
-
-PyTypeObject * _Tuple_Type();
-bool _Tuple_Check( PyObject *op );
-
-#if PY_MAJOR_VERSION >= 2
-PyTypeObject * _Unicode_Type();
-bool _Unicode_Check( PyObject *op );
-#endif
-
-int &_Py_DebugFlag();
-int &_Py_InteractiveFlag();
-int &_Py_OptimizeFlag();
-int &_Py_NoSiteFlag();
-int &_Py_TabcheckFlag();
-int &_Py_VerboseFlag();
-
-#if PY_MAJOR_VERSION >= 2
-int &_Py_UnicodeFlag();
-#endif
-
-void _XINCREF( PyObject *op );
-void _XDECREF( PyObject *op );
-
-char *__Py_PackageContext();
-}
-
-#endif // __CXX_INDIRECT_PYTHON_INTERFACE__HXX__
diff --git a/lib/kross/python/cxx/Makefile.am b/lib/kross/python/cxx/Makefile.am
index 4e1377c00..702027dab 100644
--- a/lib/kross/python/cxx/Makefile.am
+++ b/lib/kross/python/cxx/Makefile.am
@@ -5,10 +5,10 @@ CXXFLAGS += $(USE_EXCEPTIONS)
noinst_LTLIBRARIES = libkrosspythoncxx.la
libkrosspythoncxx_la_SOURCES = \
- cxxsupport.cxx \
- cxx_extensions.cxx \
+ cxxsupport.cpp \
+ cxx_extensions.cpp \
cxxextensions.c \
- IndirectPythonInterface.cxx
+ IndirectPythonInterface.cpp
libkrosspythoncxx_la_LDFLAGS = $(LIBPYTHON) $(all_libraries) -Wnounresolved
diff --git a/lib/kross/python/cxx/Objects.h b/lib/kross/python/cxx/Objects.h
new file mode 100644
index 000000000..b6ab958bb
--- /dev/null
+++ b/lib/kross/python/cxx/Objects.h
@@ -0,0 +1,2804 @@
+//---------------------------------------------------------------------------//
+// Copyright 1998 The Regents of the University of California.
+// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
+//---------------------------------------------------------------------------//
+
+#ifndef __CXX_Objects__h
+#define __CXX_Objects__h
+
+// Prevent warnings
+#if defined(_XOPEN_SOURCE)
+#undef _XOPEN_SOURCE
+#endif
+
+#include "Python.h"
+#include "Config.h"
+#include "Exception.h"
+
+
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <iterator>
+#include <utility>
+#include <typeinfo>
+
+namespace Py
+ {
+ typedef int sequence_index_type; // type of an index into a sequence
+
+ // Forward declarations
+ class Object;
+ class Type;
+ template<typename T> class SeqBase;
+ class String;
+ class List;
+ template<typename T> class MapBase;
+
+ // new_reference_to also overloaded below on Object
+ inline PyObject* new_reference_to(PyObject* p)
+ {
+ Py::_XINCREF(p);
+ return p;
+ }
+
+ // returning Null() from an extension method triggers a
+ // Python exception
+ inline PyObject* Null()
+ {
+ return (static_cast<PyObject*>(0));
+ }
+
+ //===========================================================================//
+ // class Object
+ // The purpose of this class is to serve as the most general kind of
+ // Python object, for the purpose of writing C++ extensions in Python
+ // Objects hold a PyObject* which they own. This pointer is always a
+ // valid pointer to a Python object. In children we must maintain this behavior.
+ //
+ // Instructions on how to make your own class MyType descended from Object:
+ // (0) Pick a base class, either Object or perhaps SeqBase<T> or MapBase<T>.
+ // This example assumes Object.
+
+ // (1) Write a routine int MyType_Check (PyObject *) modeled after PyInt_Check,
+ // PyFloat_Check, etc.
+
+ // (2) Add method accepts:
+ // virtual bool accepts (PyObject *pyob) const {
+ // return pyob && MyType_Check (pyob);
+ // }
+
+ // (3) Include the following constructor and copy constructor
+ //
+ /*
+ explicit MyType (PyObject *pyob): Object(pyob) {
+ validate();
+ }
+
+ MyType(const Object& other): Object(other.ptr()) {
+ validate();
+ }
+ */
+
+ // Alernate version for the constructor to allow for construction from owned pointers:
+ /*
+ explicit MyType (PyObject *pyob): Object(pyob) {
+ validate();
+ }
+ */
+
+ // You may wish to add other constructors; see the classes below for examples.
+ // Each constructor must use "set" to set the pointer
+ // and end by validating the pointer you have created.
+
+ // (4) Each class needs at least these two assignment operators:
+ /*
+ MyType& operator= (const Object& rhs) {
+ return (*this = *rhs);
+ }
+
+ Mytype& operator= (PyObject* rhsp) {
+ if(ptr() == rhsp) return *this;
+ set(rhsp);
+ return *this;
+ }
+ */
+ // Note on accepts: constructors call the base class
+ // version of a virtual when calling the base class constructor,
+ // so the test has to be done explicitly in a descendent.
+
+ // If you are inheriting from PythonExtension<T> to define an object
+ // note that it contains PythonExtension<T>::check
+ // which you can use in accepts when writing a wrapper class.
+ // See Demo/range.h and Demo/range.cpp for an example.
+
+ class Object
+ {
+ private:
+ // the pointer to the Python object
+ // Only Object sets this directly.
+ // The default constructor for Object sets it to Py_None and
+ // child classes must use "set" to set it
+ //
+ PyObject* p;
+
+ protected:
+
+ void set (PyObject* pyob, bool owned = false)
+ {
+ release();
+ p = pyob;
+ if (!owned)
+ {
+ Py::_XINCREF (p);
+ }
+ validate();
+ }
+
+ void release ()
+ {
+ Py::_XDECREF (p);
+ p = 0;
+ }
+
+ void validate()
+ {
+ // release pointer if not the right type
+ if (! accepts (p))
+ {
+ release ();
+ if(PyErr_Occurred())
+ { // Error message already set
+ throw Exception();
+ }
+ // Better error message if RTTI available
+#if defined( _CPPRTTI )
+ std::string s("Error creating object of type ");
+ s += (typeid (*this)).name();
+ throw TypeError (s);
+#else
+ throw TypeError ("CXX: type error.");
+#endif
+ }
+ }
+
+ public:
+ // Constructor acquires new ownership of pointer unless explicitly told not to.
+ explicit Object (PyObject* pyob=Py::_None(), bool owned = false): p (pyob)
+ {
+ if(!owned)
+ {
+ Py::_XINCREF (p);
+ }
+ validate();
+ }
+
+ // Copy constructor acquires new ownership of pointer
+ Object (const Object& ob): p(ob.p)
+ {
+ Py::_XINCREF (p);
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+ Object& operator= (const Object& rhs)
+ {
+ set(rhs.p);
+ return *this;
+ }
+
+ Object& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+
+ // Destructor
+ virtual ~Object ()
+ {
+ release ();
+ }
+
+ // Loaning the pointer to others, retain ownership
+ PyObject* operator* () const
+ {
+ return p;
+ }
+
+ // Explicit reference_counting changes
+ void increment_reference_count()
+ {
+ Py::_XINCREF(p);
+ }
+
+ void decrement_reference_count()
+ {
+ // not allowed to commit suicide, however
+ if(reference_count() == 1)
+ throw RuntimeError("Object::decrement_reference_count error.");
+ Py::_XDECREF(p);
+ }
+ // Would like to call this pointer() but messes up STL in SeqBase<T>
+ PyObject* ptr () const
+ {
+ return p;
+ }
+
+ //
+ // Queries
+ //
+
+ // Can pyob be used in this object's constructor?
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return (pyob != 0);
+ }
+
+ int reference_count () const
+ { // the reference count
+ return p ? p->ob_refcnt : 0;
+ }
+
+ Type type () const; // the type object associated with this one
+
+ String str () const; // the str() representation
+
+ std::string as_string() const;
+
+ String repr () const; // the repr () representation
+
+ List dir () const; // the dir() list
+
+ bool hasAttr (const std::string& s) const
+ {
+ return PyObject_HasAttrString (p, const_cast<char*>(s.c_str())) ? true: false;
+ }
+
+ Object getAttr (const std::string& s) const
+ {
+ return Object (PyObject_GetAttrString (p, const_cast<char*>(s.c_str())), true);
+ }
+
+ Object getItem (const Object& key) const
+ {
+ return Object (PyObject_GetItem(p, *key), true);
+ }
+
+ long hashValue () const
+ {
+ return PyObject_Hash (p);
+ }
+
+ //
+ // int print (FILE* fp, int flags=Py_Print_RAW)
+ // {
+ // return PyObject_Print (p, fp, flags);
+ // }
+ //
+ bool is(PyObject *pother) const
+ { // identity test
+ return p == pother;
+ }
+
+ bool is(const Object& other) const
+ { // identity test
+ return p == other.p;
+ }
+
+ bool isCallable () const
+ {
+ return PyCallable_Check (p) != 0;
+ }
+
+ bool isInstance () const
+ {
+ return PyInstance_Check (p) != 0;
+ }
+
+ bool isDict () const
+ {
+ return Py::_Dict_Check (p);
+ }
+
+ bool isList () const
+ {
+ return Py::_List_Check (p);
+ }
+
+ bool isMapping () const
+ {
+ return PyMapping_Check (p) != 0;
+ }
+
+ bool isNumeric () const
+ {
+ return PyNumber_Check (p) != 0;
+ }
+
+ bool isSequence () const
+ {
+ return PySequence_Check (p) != 0;
+ }
+
+ bool isTrue () const
+ {
+ return PyObject_IsTrue (p) != 0;
+ }
+
+ bool isType (const Type& t) const;
+
+ bool isTuple() const
+ {
+ return Py::_Tuple_Check(p);
+ }
+
+ bool isString() const
+ {
+ return Py::_String_Check(p) || Py::_Unicode_Check(p);
+ }
+
+ bool isUnicode() const
+ {
+ return Py::_Unicode_Check(p);
+ }
+
+ // Commands
+ void setAttr (const std::string& s, const Object& value)
+ {
+ if(PyObject_SetAttrString (p, const_cast<char*>(s.c_str()), *value) == -1)
+ throw AttributeError ("getAttr failed.");
+ }
+
+ void delAttr (const std::string& s)
+ {
+ if(PyObject_DelAttrString (p, const_cast<char*>(s.c_str())) == -1)
+ throw AttributeError ("delAttr failed.");
+ }
+
+ // PyObject_SetItem is too weird to be using from C++
+ // so it is intentionally omitted.
+
+ void delItem (const Object& /*key*/)
+ {
+ //if(PyObject_DelItem(p, *key) == -1)
+ // failed to link on Windows?
+ throw KeyError("delItem failed.");
+ }
+ // Equality and comparison use PyObject_Compare
+
+ bool operator==(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k == 0;
+ }
+
+ bool operator!=(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k != 0;
+
+ }
+
+ bool operator>=(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k >= 0;
+ }
+
+ bool operator<=(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k <= 0;
+ }
+
+ bool operator<(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k < 0;
+ }
+
+ bool operator>(const Object& o2) const
+ {
+ int k = PyObject_Compare (p, *o2);
+ if (PyErr_Occurred()) throw Exception();
+ return k > 0;
+ }
+ };
+ // End of class Object
+ inline PyObject* new_reference_to(const Object& g)
+ {
+ PyObject* p = g.ptr();
+ Py::_XINCREF(p);
+ return p;
+ }
+
+ // Nothing() is what an extension method returns if
+ // there is no other return value.
+ inline Object Nothing()
+ {
+ return Object(Py::_None());
+ }
+
+ // Python special None value
+ inline Object None()
+ {
+ return Object(Py::_None());
+ }
+
+ // TMM: 31May'01 - Added the #ifndef so I can exlude iostreams.
+#ifndef CXX_NO_IOSTREAMS
+ std::ostream& operator<< (std::ostream& os, const Object& ob);
+#endif
+
+ // Class Type
+ class Type: public Object
+ {
+ public:
+ explicit Type (PyObject* pyob, bool owned = false): Object(pyob, owned)
+ {
+ validate();
+ }
+
+ Type (const Object& ob): Object(*ob)
+ {
+ validate();
+ }
+
+ Type(const Type& t): Object(t)
+ {
+ validate();
+ }
+
+ Type& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Type& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Type_Check (pyob);
+ }
+ };
+
+
+ //
+ // Convert an owned Python pointer into a CXX Object
+ //
+ inline Object asObject (PyObject *p)
+ {
+ return Object(p, true);
+ }
+
+
+
+
+ // ===============================================
+ // class Int
+ class Int: public Object
+ {
+ public:
+ // Constructor
+ explicit Int (PyObject *pyob, bool owned = false): Object (pyob, owned)
+ {
+ validate();
+ }
+
+ Int (const Int& ob): Object(*ob)
+ {
+ validate();
+ }
+
+ // create from long
+ explicit Int (long v = 0L): Object(PyInt_FromLong(v), true)
+ {
+ validate();
+ }
+
+ // create from int
+ explicit Int (int v)
+ {
+ long w = v;
+ set(PyInt_FromLong(w), true);
+ validate();
+ }
+
+ Int (const Object& ob)
+ {
+ set(PyNumber_Int(*ob), true);
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+
+ Int& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Int& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (PyNumber_Int(rhsp), true);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Int_Check (pyob);
+ }
+ // convert to long
+ operator long() const
+ {
+ return PyInt_AsLong (ptr());
+ }
+ // assign from an int
+ Int& operator= (int v)
+ {
+ set (PyInt_FromLong (long(v)), true);
+ return *this;
+ }
+ // assign from long
+ Int& operator= (long v)
+ {
+ set (PyInt_FromLong (v), true);
+ return *this;
+ }
+ };
+
+ // ===============================================
+ // class Long
+ class Long: public Object
+ {
+ public:
+ // Constructor
+ explicit Long (PyObject *pyob, bool owned = false): Object (pyob, owned)
+ {
+ validate();
+ }
+
+ Long (const Long& ob): Object(ob.ptr())
+ {
+ validate();
+ }
+
+ // create from long
+ explicit Long (long v = 0L)
+ : Object(PyLong_FromLong(v), true)
+ {
+ validate();
+ }
+ // create from int
+ explicit Long (int v)
+ : Object(PyLong_FromLong(static_cast<long>(v)), true)
+ {
+ validate();
+ }
+
+ // create from unsigned long
+ explicit Long (unsigned long v)
+ : Object(PyLong_FromUnsignedLong(v), true)
+ {
+ validate();
+ }
+
+ // try to create from any object
+ Long (const Object& ob)
+ : Object(PyNumber_Long(*ob), true)
+ {
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+
+ Long& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Long& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (PyNumber_Long(rhsp), true);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Long_Check (pyob);
+ }
+ // convert to long
+ operator long() const
+ {
+ return PyLong_AsLong (ptr());
+ }
+ operator double() const
+ {
+ return PyLong_AsDouble (ptr());
+ }
+ operator unsigned long() const
+ {
+ return PyLong_AsUnsignedLong (ptr());
+ }
+ // assign from an int
+ Long& operator= (int v)
+ {
+ set(PyLong_FromLong (long(v)), true);
+ return *this;
+ }
+ // assign from long
+ Long& operator= (long v)
+ {
+ set(PyLong_FromLong (v), true);
+ return *this;
+ }
+ // assign from unsigned long
+ Long& operator= (unsigned long v)
+ {
+ set(PyLong_FromUnsignedLong (v), true);
+ return *this;
+ }
+ };
+
+ // ===============================================
+ // class Float
+ //
+ class Float: public Object
+ {
+ public:
+ // Constructor
+ explicit Float (PyObject *pyob, bool owned = false): Object(pyob, owned)
+ {
+ validate();
+ }
+
+ Float (const Float& f): Object(f)
+ {
+ validate();
+ }
+
+ // make from double
+ explicit Float (double v=0.0)
+ : Object(PyFloat_FromDouble (v), true)
+ {
+ validate();
+ }
+
+ // try to make from any object
+ Float (const Object& ob)
+ : Object(PyNumber_Float(*ob), true)
+ {
+ validate();
+ }
+
+ Float& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Float& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (PyNumber_Float(rhsp), true);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Float_Check (pyob);
+ }
+ // convert to double
+ operator double () const
+ {
+ return PyFloat_AsDouble (ptr());
+ }
+ // assign from a double
+ Float& operator= (double v)
+ {
+ set(PyFloat_FromDouble (v), true);
+ return *this;
+ }
+ // assign from an int
+ Float& operator= (int v)
+ {
+ set(PyFloat_FromDouble (double(v)), true);
+ return *this;
+ }
+ // assign from long
+ Float& operator= (long v)
+ {
+ set(PyFloat_FromDouble (double(v)), true);
+ return *this;
+ }
+ // assign from an Int
+ Float& operator= (const Int& iob)
+ {
+ set(PyFloat_FromDouble (double(long(iob))), true);
+ return *this;
+ }
+ };
+
+ // ===============================================
+ // class Complex
+ class Complex: public Object
+ {
+ public:
+ // Constructor
+ explicit Complex (PyObject *pyob, bool owned = false): Object(pyob, owned)
+ {
+ validate();
+ }
+
+ Complex (const Complex& f): Object(f)
+ {
+ validate();
+ }
+
+ // make from double
+ explicit Complex (double v=0.0, double w=0.0)
+ :Object(PyComplex_FromDoubles (v, w), true)
+ {
+ validate();
+ }
+
+ Complex& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Complex& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Complex_Check (pyob);
+ }
+ // convert to Py_complex
+ operator Py_complex () const
+ {
+ return PyComplex_AsCComplex (ptr());
+ }
+ // assign from a Py_complex
+ Complex& operator= (const Py_complex& v)
+ {
+ set(PyComplex_FromCComplex (v), true);
+ return *this;
+ }
+ // assign from a double
+ Complex& operator= (double v)
+ {
+ set(PyComplex_FromDoubles (v, 0.0), true);
+ return *this;
+ }
+ // assign from an int
+ Complex& operator= (int v)
+ {
+ set(PyComplex_FromDoubles (double(v), 0.0), true);
+ return *this;
+ }
+ // assign from long
+ Complex& operator= (long v)
+ {
+ set(PyComplex_FromDoubles (double(v), 0.0), true);
+ return *this;
+ }
+ // assign from an Int
+ Complex& operator= (const Int& iob)
+ {
+ set(PyComplex_FromDoubles (double(long(iob)), 0.0), true);
+ return *this;
+ }
+
+ double real() const
+ {
+ return PyComplex_RealAsDouble(ptr());
+ }
+
+ double imag() const
+ {
+ return PyComplex_ImagAsDouble(ptr());
+ }
+ };
+ // Sequences
+ // Sequences are here represented as sequences of items of type T.
+ // The base class SeqBase<T> represents that.
+ // In basic Python T is always "Object".
+
+ // seqref<T> is what you get if you get elements from a non-const SeqBase<T>.
+ // Note: seqref<T> could probably be a nested class in SeqBase<T> but that might stress
+ // some compilers needlessly. Simlarly for mapref later.
+
+ // While this class is not intended for enduser use, it needs some public
+ // constructors for the benefit of the STL.
+
+ // See Scott Meyer's More Essential C++ for a description of proxies.
+ // This application is even more complicated. We are doing an unusual thing
+ // in having a double proxy. If we want the STL to work
+ // properly we have to compromise by storing the rvalue inside. The
+ // entire Object API is repeated so that things like s[i].isList() will
+ // work properly.
+
+ // Still, once in a while a weird compiler message may occur using expressions like x[i]
+ // Changing them to Object(x[i]) helps the compiler to understand that the
+ // conversion of a seqref to an Object is wanted.
+
+ template<typename T>
+ class seqref
+ {
+ protected:
+ SeqBase<T>& s; // the sequence
+ int offset; // item number
+ T the_item; // lvalue
+ public:
+
+ seqref (SeqBase<T>& seq, sequence_index_type j)
+ : s(seq), offset(j), the_item (s.getItem(j))
+ {}
+
+ seqref (const seqref<T>& range)
+ : s(range.s), offset(range.offset), the_item(range.the_item)
+ {}
+
+ // TMM: added this seqref ctor for use with STL algorithms
+ seqref (Object& obj)
+ : s(dynamic_cast< SeqBase<T>&>(obj))
+ , offset( NULL )
+ , the_item(s.getItem(offset))
+ {}
+ ~seqref()
+ {}
+
+ operator T() const
+ { // rvalue
+ return the_item;
+ }
+
+ seqref<T>& operator=(const seqref<T>& rhs)
+ { //used as lvalue
+ the_item = rhs.the_item;
+ s.setItem(offset, the_item);
+ return *this;
+ }
+
+ seqref<T>& operator=(const T& ob)
+ { // used as lvalue
+ the_item = ob;
+ s.setItem(offset, ob);
+ return *this;
+ }
+
+ // forward everything else to the item
+ PyObject* ptr () const
+ {
+ return the_item.ptr();
+ }
+
+ int reference_count () const
+ { // the reference count
+ return the_item.reference_count();
+ }
+
+ Type type () const
+ {
+ return the_item.type();
+ }
+
+ String str () const;
+
+ String repr () const;
+
+ bool hasAttr (const std::string& attr_name) const
+ {
+ return the_item.hasAttr(attr_name);
+ }
+
+ Object getAttr (const std::string& attr_name) const
+ {
+ return the_item.getAttr(attr_name);
+ }
+
+ Object getItem (const Object& key) const
+ {
+ return the_item.getItem(key);
+ }
+
+ long hashValue () const
+ {
+ return the_item.hashValue();
+ }
+
+ bool isCallable () const
+ {
+ return the_item.isCallable();
+ }
+
+ bool isInstance () const
+ {
+ return the_item.isInstance();
+ }
+
+ bool isDict () const
+ {
+ return the_item.isDict();
+ }
+
+ bool isList () const
+ {
+ return the_item.isList();
+ }
+
+ bool isMapping () const
+ {
+ return the_item.isMapping();
+ }
+
+ bool isNumeric () const
+ {
+ return the_item.isNumeric();
+ }
+
+ bool isSequence () const
+ {
+ return the_item.isSequence();
+ }
+
+ bool isTrue () const
+ {
+ return the_item.isTrue();
+ }
+
+ bool isType (const Type& t) const
+ {
+ return the_item.isType (t);
+ }
+
+ bool isTuple() const
+ {
+ return the_item.isTuple();
+ }
+
+ bool isString() const
+ {
+ return the_item.isString();
+ }
+ // Commands
+ void setAttr (const std::string& attr_name, const Object& value)
+ {
+ the_item.setAttr(attr_name, value);
+ }
+
+ void delAttr (const std::string& attr_name)
+ {
+ the_item.delAttr(attr_name);
+ }
+
+ void delItem (const Object& key)
+ {
+ the_item.delItem(key);
+ }
+
+ bool operator==(const Object& o2) const
+ {
+ return the_item == o2;
+ }
+
+ bool operator!=(const Object& o2) const
+ {
+ return the_item != o2;
+ }
+
+ bool operator>=(const Object& o2) const
+ {
+ return the_item >= o2;
+ }
+
+ bool operator<=(const Object& o2) const
+ {
+ return the_item <= o2;
+ }
+
+ bool operator<(const Object& o2) const
+ {
+ return the_item < o2;
+ }
+
+ bool operator>(const Object& o2) const
+ {
+ return the_item > o2;
+ }
+ }; // end of seqref
+
+
+ // class SeqBase<T>
+ // ...the base class for all sequence types
+
+ template<typename T>
+ class SeqBase: public Object
+ {
+ public:
+ // STL definitions
+ typedef size_t size_type;
+ typedef seqref<T> reference;
+ typedef T const_reference;
+ typedef seqref<T>* pointer;
+ typedef int difference_type;
+ typedef T value_type; // TMM: 26Jun'01
+
+ virtual size_type max_size() const
+ {
+ return std::string::npos; // ?
+ }
+
+ virtual size_type capacity() const
+ {
+ return size();
+ }
+
+ virtual void swap(SeqBase<T>& c)
+ {
+ SeqBase<T> temp = c;
+ c = ptr();
+ set(temp.ptr());
+ }
+
+ virtual size_type size () const
+ {
+ return PySequence_Length (ptr());
+ }
+
+ explicit SeqBase<T> ()
+ :Object(PyTuple_New(0), true)
+ {
+ validate();
+ }
+
+ explicit SeqBase<T> (PyObject* pyob, bool owned=false)
+ : Object(pyob, owned)
+ {
+ validate();
+ }
+
+ SeqBase<T> (const Object& ob): Object(ob)
+ {
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+
+ SeqBase<T>& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ SeqBase<T>& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && PySequence_Check (pyob);
+ }
+
+ size_type length () const
+ {
+ return PySequence_Length (ptr());
+ }
+
+ // Element access
+ const T operator[](sequence_index_type index) const
+ {
+ return getItem(index);
+ }
+
+ seqref<T> operator[](sequence_index_type index)
+ {
+ return seqref<T>(*this, index);
+ }
+
+ virtual T getItem (sequence_index_type i) const
+ {
+ return T(asObject(PySequence_GetItem (ptr(), i)));
+ }
+
+ virtual void setItem (sequence_index_type i, const T& ob)
+ {
+ if (PySequence_SetItem (ptr(), i, *ob) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ SeqBase<T> repeat (int count) const
+ {
+ return SeqBase<T> (PySequence_Repeat (ptr(), count), true);
+ }
+
+ SeqBase<T> concat (const SeqBase<T>& other) const
+ {
+ return SeqBase<T> (PySequence_Concat(ptr(), *other), true);
+ }
+
+ // more STL compatability
+ const T front () const
+ {
+ return getItem(0);
+ }
+
+ seqref<T> front()
+ {
+ return seqref<T>(this, 0);
+ }
+
+ const T back () const
+ {
+ return getItem(size()-1);
+ }
+
+ seqref<T> back()
+ {
+ return seqref<T>(this, size()-1);
+ }
+
+ void verify_length(size_type required_size) const
+ {
+ if (size() != required_size)
+ throw IndexError ("Unexpected SeqBase<T> length.");
+ }
+
+ void verify_length(size_type min_size, size_type max_size) const
+ {
+ size_type n = size();
+ if (n < min_size || n > max_size)
+ throw IndexError ("Unexpected SeqBase<T> length.");
+ }
+
+ class iterator
+ : public random_access_iterator_parent(seqref<T>)
+ {
+ protected:
+ friend class SeqBase<T>;
+ SeqBase<T>* seq;
+ int count;
+
+ public:
+ ~iterator ()
+ {}
+
+ iterator ()
+ : seq( 0 )
+ , count( 0 )
+ {}
+
+ iterator (SeqBase<T>* s, int where)
+ : seq( s )
+ , count( where )
+ {}
+
+ iterator (const iterator& other)
+ : seq( other.seq )
+ , count( other.count )
+ {}
+
+ bool eql (const iterator& other) const
+ {
+ return (*seq == *other.seq) && (count == other.count);
+ }
+
+ bool neq (const iterator& other) const
+ {
+ return (*seq != *other.seq) || (count != other.count);
+ }
+
+ bool lss (const iterator& other) const
+ {
+ return (count < other.count);
+ }
+
+ bool gtr (const iterator& other) const
+ {
+ return (count > other.count);
+ }
+
+ bool leq (const iterator& other) const
+ {
+ return (count <= other.count);
+ }
+
+ bool geq (const iterator& other) const
+ {
+ return (count >= other.count);
+ }
+
+ seqref<T> operator*()
+ {
+ return seqref<T>(*seq, count);
+ }
+
+ seqref<T> operator[] (sequence_index_type i)
+ {
+ return seqref<T>(*seq, count + i);
+ }
+
+ iterator& operator=(const iterator& other)
+ {
+ if (this == &other) return *this;
+ seq = other.seq;
+ count = other.count;
+ return *this;
+ }
+
+ iterator operator+(int n) const
+ {
+ return iterator(seq, count + n);
+ }
+
+ iterator operator-(int n) const
+ {
+ return iterator(seq, count - n);
+ }
+
+ iterator& operator+=(int n)
+ {
+ count = count + n;
+ return *this;
+ }
+
+ iterator& operator-=(int n)
+ {
+ count = count - n;
+ return *this;
+ }
+
+ int operator-(const iterator& other) const
+ {
+ if (*seq != *other.seq)
+ throw RuntimeError ("SeqBase<T>::iterator comparison error");
+ return count - other.count;
+ }
+
+ // prefix ++
+ iterator& operator++ ()
+ { count++; return *this;}
+ // postfix ++
+ iterator operator++ (int)
+ { return iterator(seq, count++);}
+ // prefix --
+ iterator& operator-- ()
+ { count--; return *this;}
+ // postfix --
+ iterator operator-- (int)
+ { return iterator(seq, count--);}
+
+ std::string diagnose() const
+ {
+ std::ostringstream oss;
+ oss << "iterator diagnosis " << seq << ", " << count << std::ends;
+ return std::string(oss.str());
+ }
+ }; // end of class SeqBase<T>::iterator
+
+ iterator begin ()
+ {
+ return iterator(this, 0);
+ }
+
+ iterator end ()
+ {
+ return iterator(this, length());
+ }
+
+ class const_iterator
+ : public random_access_iterator_parent(const Object)
+ {
+ protected:
+ friend class SeqBase<T>;
+ const SeqBase<T>* seq;
+ sequence_index_type count;
+
+ public:
+ ~const_iterator ()
+ {}
+
+ const_iterator ()
+ : seq( 0 )
+ , count( 0 )
+ {}
+
+ const_iterator (const SeqBase<T>* s, int where)
+ : seq( s )
+ , count( where )
+ {}
+
+ const_iterator(const const_iterator& other)
+ : seq( other.seq )
+ , count( other.count )
+ {}
+
+ const T operator*() const
+ {
+ return seq->getItem(count);
+ }
+
+ const T operator[] (sequence_index_type i) const
+ {
+ return seq->getItem(count + i);
+ }
+
+ const_iterator& operator=(const const_iterator& other)
+ {
+ if (this == &other) return *this;
+ seq = other.seq;
+ count = other.count;
+ return *this;
+ }
+
+ const_iterator operator+(int n) const
+ {
+ return const_iterator(seq, count + n);
+ }
+
+ bool eql (const const_iterator& other) const
+ {
+ return (*seq == *other.seq) && (count == other.count);
+ }
+
+ bool neq (const const_iterator& other) const
+ {
+ return (*seq != *other.seq) || (count != other.count);
+ }
+
+ bool lss (const const_iterator& other) const
+ {
+ return (count < other.count);
+ }
+
+ bool gtr (const const_iterator& other) const
+ {
+ return (count > other.count);
+ }
+
+ bool leq (const const_iterator& other) const
+ {
+ return (count <= other.count);
+ }
+
+ bool geq (const const_iterator& other) const
+ {
+ return (count >= other.count);
+ }
+
+ const_iterator operator-(int n)
+ {
+ return const_iterator(seq, count - n);
+ }
+
+ const_iterator& operator+=(int n)
+ {
+ count = count + n;
+ return *this;
+ }
+
+ const_iterator& operator-=(int n)
+ {
+ count = count - n;
+ return *this;
+ }
+
+ int operator-(const const_iterator& other) const
+ {
+ if (*seq != *other.seq)
+ throw RuntimeError ("SeqBase<T>::const_iterator::- error");
+ return count - other.count;
+ }
+ // prefix ++
+ const_iterator& operator++ ()
+ { count++; return *this;}
+ // postfix ++
+ const_iterator operator++ (int)
+ { return const_iterator(seq, count++);}
+ // prefix --
+ const_iterator& operator-- ()
+ { count--; return *this;}
+ // postfix --
+ const_iterator operator-- (int)
+ { return const_iterator(seq, count--);}
+ }; // end of class SeqBase<T>::const_iterator
+
+ const_iterator begin () const
+ {
+ return const_iterator(this, 0);
+ }
+
+ const_iterator end () const
+ {
+ return const_iterator(this, length());
+ }
+ };
+
+ // Here's an important typedef you might miss if reading too fast...
+ typedef SeqBase<Object> Sequence;
+
+ template <typename T> bool operator==(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+ template <typename T> bool operator!=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+ template <typename T> bool operator< (const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+ template <typename T> bool operator> (const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+ template <typename T> bool operator<=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+ template <typename T> bool operator>=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
+
+ template <typename T> bool operator==(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+ template <typename T> bool operator!=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+ template <typename T> bool operator< (const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+ template <typename T> bool operator> (const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+ template <typename T> bool operator<=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+ template <typename T> bool operator>=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
+
+
+ extern bool operator==(const Sequence::iterator& left, const Sequence::iterator& right);
+ extern bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right);
+ extern bool operator< (const Sequence::iterator& left, const Sequence::iterator& right);
+ extern bool operator> (const Sequence::iterator& left, const Sequence::iterator& right);
+ extern bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right);
+ extern bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right);
+
+ extern bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+ extern bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+ extern bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+ extern bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+ extern bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+ extern bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
+
+ // ==================================================
+ // class Char
+ // Python strings return strings as individual elements.
+ // I'll try having a class Char which is a String of length 1
+ //
+ typedef std::basic_string<Py_UNICODE> unicodestring;
+ extern Py_UNICODE unicode_null_string[1];
+
+ class Char: public Object
+ {
+ public:
+ explicit Char (PyObject *pyob, bool owned = false): Object(pyob, owned)
+ {
+ validate();
+ }
+
+ Char (const Object& ob): Object(ob)
+ {
+ validate();
+ }
+
+ Char (const std::string& v = "")
+ :Object(PyString_FromStringAndSize (const_cast<char*>(v.c_str()),1), true)
+ {
+ validate();
+ }
+
+ Char (char v)
+ : Object(PyString_FromStringAndSize (&v, 1), true)
+ {
+ validate();
+ }
+
+ Char (Py_UNICODE v)
+ : Object(PyUnicode_FromUnicode (&v, 1), true)
+ {
+ validate();
+ }
+ // Assignment acquires new ownership of pointer
+ Char& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Char& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob)) && PySequence_Length (pyob) == 1;
+ }
+
+ // Assignment from C string
+ Char& operator= (const std::string& v)
+ {
+ set(PyString_FromStringAndSize (const_cast<char*>(v.c_str()),1), true);
+ return *this;
+ }
+
+ Char& operator= (char v)
+ {
+ set(PyString_FromStringAndSize (&v, 1), true);
+ return *this;
+ }
+
+ Char& operator= (const unicodestring& v)
+ {
+ set(PyUnicode_FromUnicode (const_cast<Py_UNICODE*>(v.data()),1), true);
+ return *this;
+ }
+
+ Char& operator= (Py_UNICODE v)
+ {
+ set(PyUnicode_FromUnicode (&v, 1), true);
+ return *this;
+ }
+
+ // Conversion
+ operator String() const;
+
+ operator std::string () const
+ {
+ return std::string(PyString_AsString (ptr()));
+ }
+ };
+
+ class String: public SeqBase<Char>
+ {
+ public:
+ virtual size_type capacity() const
+ {
+ return max_size();
+ }
+
+ explicit String (PyObject *pyob, bool owned = false): SeqBase<Char>(pyob, owned)
+ {
+ validate();
+ }
+
+ String (const Object& ob): SeqBase<Char>(ob)
+ {
+ validate();
+ }
+
+ String()
+ : SeqBase<Char>( PyString_FromStringAndSize( "", 0 ), true )
+ {
+ validate();
+ }
+
+ String( const std::string& v )
+ : SeqBase<Char>( PyString_FromStringAndSize( const_cast<char*>(v.data()),
+ static_cast<int>( v.length() ) ), true )
+ {
+ validate();
+ }
+
+ String( const char *s, const char *encoding, const char *error="strict" )
+ : SeqBase<Char>( PyUnicode_Decode( s, strlen( s ), encoding, error ), true )
+ {
+ validate();
+ }
+
+ String( const char *s, int len, const char *encoding, const char *error="strict" )
+ : SeqBase<Char>( PyUnicode_Decode( s, len, encoding, error ), true )
+ {
+ validate();
+ }
+
+ String( const std::string &s, const char *encoding, const char *error="strict" )
+ : SeqBase<Char>( PyUnicode_Decode( s.c_str(), s.length(), encoding, error ), true )
+ {
+ validate();
+ }
+
+ String( const std::string& v, std::string::size_type vsize )
+ : SeqBase<Char>(PyString_FromStringAndSize( const_cast<char*>(v.data()),
+ static_cast<int>( vsize ) ), true)
+ {
+ validate();
+ }
+
+ String( const char *v, int vsize )
+ : SeqBase<Char>(PyString_FromStringAndSize( const_cast<char*>(v), vsize ), true )
+ {
+ validate();
+ }
+
+ String( const char* v )
+ : SeqBase<Char>( PyString_FromString( v ), true )
+ {
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+ String& operator= ( const Object& rhs )
+ {
+ return *this = *rhs;
+ }
+
+ String& operator= (PyObject* rhsp)
+ {
+ if( ptr() == rhsp )
+ return *this;
+ set (rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob));
+ }
+
+ // Assignment from C string
+ String& operator= (const std::string& v)
+ {
+ set( PyString_FromStringAndSize( const_cast<char*>( v.data() ),
+ static_cast<int>( v.length() ) ), true );
+ return *this;
+ }
+ String& operator= (const unicodestring& v)
+ {
+ set( PyUnicode_FromUnicode( const_cast<Py_UNICODE*>( v.data() ),
+ static_cast<int>( v.length() ) ), true );
+ return *this;
+ }
+
+
+ // Encode
+ String encode( const char *encoding, const char *error="strict" )
+ {
+ if( isUnicode() )
+ {
+ return String( PyUnicode_AsEncodedString( ptr(), encoding, error ) );
+ }
+ else
+ {
+ return String( PyString_AsEncodedObject( ptr(), encoding, error ) );
+ }
+ }
+
+ String decode( const char *encoding, const char *error="strict" )
+ {
+ return Object( PyString_AsDecodedObject( ptr(), encoding, error ) );
+ }
+
+ // Queries
+ virtual size_type size () const
+ {
+ if( isUnicode() )
+ {
+ return static_cast<size_type>( PyUnicode_GET_SIZE (ptr()) );
+ }
+ else
+ {
+ return static_cast<size_type>( PyString_Size (ptr()) );
+ }
+ }
+
+ operator std::string () const
+ {
+ return as_std_string();
+ }
+
+ std::string as_std_string() const
+ {
+ if( isUnicode() )
+ {
+ throw TypeError("cannot return std::string from Unicode object");
+ }
+ else
+ {
+ return std::string( PyString_AsString( ptr() ), static_cast<size_type>( PyString_Size( ptr() ) ) );
+ }
+ }
+
+ unicodestring as_unicodestring() const
+ {
+ if( isUnicode() )
+ {
+ return unicodestring( PyUnicode_AS_UNICODE( ptr() ),
+ static_cast<size_type>( PyUnicode_GET_SIZE( ptr() ) ) );
+ }
+ else
+ {
+ throw TypeError("can only return unicodestring from Unicode object");
+ }
+ }
+ };
+
+ // ==================================================
+ // class Tuple
+ class Tuple: public Sequence
+ {
+ public:
+ virtual void setItem (sequence_index_type offset, const Object&ob)
+ {
+ // note PyTuple_SetItem is a thief...
+ if(PyTuple_SetItem (ptr(), offset, new_reference_to(ob)) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ // Constructor
+ explicit Tuple (PyObject *pyob, bool owned = false): Sequence (pyob, owned)
+ {
+ validate();
+ }
+
+ Tuple (const Object& ob): Sequence(ob)
+ {
+ validate();
+ }
+
+ // New tuple of a given size
+ explicit Tuple (int size = 0)
+ {
+ set(PyTuple_New (size), true);
+ validate ();
+ for (sequence_index_type i=0; i < size; i++)
+ {
+ if(PyTuple_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1)
+ {
+ throw Exception();
+ }
+ }
+ }
+ // Tuple from any sequence
+ explicit Tuple (const Sequence& s)
+ {
+ sequence_index_type limit( sequence_index_type( s.length() ) );
+
+ set(PyTuple_New (limit), true);
+ validate();
+
+ for(sequence_index_type i=0; i < limit; i++)
+ {
+ if(PyTuple_SetItem (ptr(), i, new_reference_to(s[i])) == -1)
+ {
+ throw Exception();
+ }
+ }
+ }
+ // Assignment acquires new ownership of pointer
+
+ Tuple& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Tuple& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Tuple_Check (pyob);
+ }
+
+ Tuple getSlice (int i, int j) const
+ {
+ return Tuple (PySequence_GetSlice (ptr(), i, j), true);
+ }
+
+ };
+
+ // ==================================================
+ // class List
+
+ class List: public Sequence
+ {
+ public:
+ // Constructor
+ explicit List (PyObject *pyob, bool owned = false): Sequence(pyob, owned)
+ {
+ validate();
+ }
+ List (const Object& ob): Sequence(ob)
+ {
+ validate();
+ }
+ // Creation at a fixed size
+ List (int size = 0)
+ {
+ set(PyList_New (size), true);
+ validate();
+ for (sequence_index_type i=0; i < size; i++)
+ {
+ if(PyList_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1)
+ {
+ throw Exception();
+ }
+ }
+ }
+
+ // List from a sequence
+ List (const Sequence& s): Sequence()
+ {
+ int n = s.length();
+ set(PyList_New (n), true);
+ validate();
+ for (sequence_index_type i=0; i < n; i++)
+ {
+ if(PyList_SetItem (ptr(), i, new_reference_to(s[i])) == -1)
+ {
+ throw Exception();
+ }
+ }
+ }
+
+ virtual size_type capacity() const
+ {
+ return max_size();
+ }
+ // Assignment acquires new ownership of pointer
+
+ List& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ List& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_List_Check (pyob);
+ }
+
+ List getSlice (int i, int j) const
+ {
+ return List (PyList_GetSlice (ptr(), i, j), true);
+ }
+
+ void setSlice (int i, int j, const Object& v)
+ {
+ if(PyList_SetSlice (ptr(), i, j, *v) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void append (const Object& ob)
+ {
+ if(PyList_Append (ptr(), *ob) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void insert (int i, const Object& ob)
+ {
+ if(PyList_Insert (ptr(), i, *ob) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void sort ()
+ {
+ if(PyList_Sort(ptr()) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void reverse ()
+ {
+ if(PyList_Reverse(ptr()) == -1)
+ {
+ throw Exception();
+ }
+ }
+ };
+
+
+ // Mappings
+ // ==================================================
+ template<typename T>
+ class mapref
+ {
+ protected:
+ MapBase<T>& s; // the map
+ Object key; // item key
+ T the_item;
+
+ public:
+ mapref<T> (MapBase<T>& map, const std::string& k)
+ : s(map), the_item()
+ {
+ key = String(k);
+ if(map.hasKey(key)) the_item = map.getItem(key);
+ };
+
+ mapref<T> (MapBase<T>& map, const Object& k)
+ : s(map), key(k), the_item()
+ {
+ if(map.hasKey(key)) the_item = map.getItem(key);
+ };
+
+ ~mapref()
+ {}
+
+ // MapBase<T> stuff
+ // lvalue
+ mapref<T>& operator=(const mapref<T>& other)
+ {
+ if(this == &other) return *this;
+ the_item = other.the_item;
+ s.setItem(key, other.the_item);
+ return *this;
+ };
+
+ mapref<T>& operator= (const T& ob)
+ {
+ the_item = ob;
+ s.setItem (key, ob);
+ return *this;
+ }
+
+ // rvalue
+ operator T() const
+ {
+ return the_item;
+ }
+
+ // forward everything else to the_item
+ PyObject* ptr () const
+ {
+ return the_item.ptr();
+ }
+
+ int reference_count () const
+ { // the mapref count
+ return the_item.reference_count();
+ }
+
+ Type type () const
+ {
+ return the_item.type();
+ }
+
+ String str () const
+ {
+ return the_item.str();
+ }
+
+ String repr () const
+ {
+ return the_item.repr();
+ }
+
+ bool hasAttr (const std::string& attr_name) const
+ {
+ return the_item.hasAttr(attr_name);
+ }
+
+ Object getAttr (const std::string& attr_name) const
+ {
+ return the_item.getAttr(attr_name);
+ }
+
+ Object getItem (const Object& k) const
+ {
+ return the_item.getItem(k);
+ }
+
+ long hashValue () const
+ {
+ return the_item.hashValue();
+ }
+
+ bool isCallable () const
+ {
+ return the_item.isCallable();
+ }
+
+ bool isList () const
+ {
+ return the_item.isList();
+ }
+
+ bool isMapping () const
+ {
+ return the_item.isMapping();
+ }
+
+ bool isNumeric () const
+ {
+ return the_item.isNumeric();
+ }
+
+ bool isSequence () const
+ {
+ return the_item.isSequence();
+ }
+
+ bool isTrue () const
+ {
+ return the_item.isTrue();
+ }
+
+ bool isType (const Type& t) const
+ {
+ return the_item.isType (t);
+ }
+
+ bool isTuple() const
+ {
+ return the_item.isTuple();
+ }
+
+ bool isString() const
+ {
+ return the_item.isString();
+ }
+
+ // Commands
+ void setAttr (const std::string& attr_name, const Object& value)
+ {
+ the_item.setAttr(attr_name, value);
+ }
+
+ void delAttr (const std::string& attr_name)
+ {
+ the_item.delAttr(attr_name);
+ }
+
+ void delItem (const Object& k)
+ {
+ the_item.delItem(k);
+ }
+ }; // end of mapref
+
+ // TMM: now for mapref<T>
+ template< class T >
+ bool operator==(const mapref<T>& left, const mapref<T>& right)
+ {
+ return true; // NOT completed.
+ }
+
+ template< class T >
+ bool operator!=(const mapref<T>& left, const mapref<T>& right)
+ {
+ return true; // not completed.
+ }
+
+ template<typename T>
+ class MapBase: public Object
+ {
+ protected:
+ explicit MapBase<T>()
+ {}
+ public:
+ // reference: proxy class for implementing []
+ // TMM: 26Jun'01 - the types
+ // If you assume that Python mapping is a hash_map...
+ // hash_map::value_type is not assignable, but
+ // (*it).second = data must be a valid expression
+ typedef size_t size_type;
+ typedef Object key_type;
+ typedef mapref<T> data_type;
+ typedef std::pair< const T, T > value_type;
+ typedef std::pair< const T, mapref<T> > reference;
+ typedef const std::pair< const T, const T > const_reference;
+ typedef std::pair< const T, mapref<T> > pointer;
+
+ // Constructor
+ explicit MapBase<T> (PyObject *pyob, bool owned = false): Object(pyob, owned)
+ {
+ validate();
+ }
+
+ // TMM: 02Jul'01 - changed MapBase<T> to Object in next line
+ MapBase<T> (const Object& ob): Object(ob)
+ {
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+ MapBase<T>& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ MapBase<T>& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && PyMapping_Check(pyob);
+ }
+
+ // Clear -- PyMapping Clear is missing
+ //
+
+ void clear ()
+ {
+ List k = keys();
+ for(List::iterator i = k.begin(); i != k.end(); i++)
+ {
+ delItem(*i);
+ }
+ }
+
+ virtual size_type size() const
+ {
+ return PyMapping_Length (ptr());
+ }
+
+ // Element Access
+ T operator[](const std::string& key) const
+ {
+ return getItem(key);
+ }
+
+ T operator[](const Object& key) const
+ {
+ return getItem(key);
+ }
+
+ mapref<T> operator[](const std::string& key)
+ {
+ return mapref<T>(*this, key);
+ }
+
+ mapref<T> operator[](const Object& key)
+ {
+ return mapref<T>(*this, key);
+ }
+
+ int length () const
+ {
+ return PyMapping_Length (ptr());
+ }
+
+ bool hasKey (const std::string& s) const
+ {
+ return PyMapping_HasKeyString (ptr(),const_cast<char*>(s.c_str())) != 0;
+ }
+
+ bool hasKey (const Object& s) const
+ {
+ return PyMapping_HasKey (ptr(), s.ptr()) != 0;
+ }
+
+ T getItem (const std::string& s) const
+ {
+ return T(
+ asObject(PyMapping_GetItemString (ptr(),const_cast<char*>(s.c_str())))
+ );
+ }
+
+ T getItem (const Object& s) const
+ {
+ return T(
+ asObject(PyObject_GetItem (ptr(), s.ptr()))
+ );
+ }
+
+ virtual void setItem (const char *s, const Object& ob)
+ {
+ if (PyMapping_SetItemString (ptr(), const_cast<char*>(s), *ob) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ virtual void setItem (const std::string& s, const Object& ob)
+ {
+ if (PyMapping_SetItemString (ptr(), const_cast<char*>(s.c_str()), *ob) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ virtual void setItem (const Object& s, const Object& ob)
+ {
+ if (PyObject_SetItem (ptr(), s.ptr(), ob.ptr()) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void delItem (const std::string& s)
+ {
+ if (PyMapping_DelItemString (ptr(), const_cast<char*>(s.c_str())) == -1)
+ {
+ throw Exception();
+ }
+ }
+
+ void delItem (const Object& s)
+ {
+ if (PyMapping_DelItem (ptr(), *s) == -1)
+ {
+ throw Exception();
+ }
+ }
+ // Queries
+ List keys () const
+ {
+ return List(PyMapping_Keys(ptr()), true);
+ }
+
+ List values () const
+ { // each returned item is a (key, value) pair
+ return List(PyMapping_Values(ptr()), true);
+ }
+
+ List items () const
+ {
+ return List(PyMapping_Items(ptr()), true);
+ }
+
+ // iterators for MapBase<T>
+ // Added by TMM: 2Jul'01 - NOT COMPLETED
+ // There is still a bug. I decided to stop, before fixing the bug, because
+ // this can't be halfway efficient until Python gets built-in iterators.
+ // My current soln is to iterate over the map by getting a copy of its keys
+ // and iterating over that. Not a good solution.
+
+ // The iterator holds a MapBase<T>* rather than a MapBase<T> because that's
+ // how the sequence iterator is implemented and it works. But it does seem
+ // odd to me - we are iterating over the map object, not the reference.
+
+#if 0 // here is the test code with which I found the (still existing) bug
+ typedef cxx::Dict d_t;
+ d_t d;
+ cxx::String s1("blah");
+ cxx::String s2("gorf");
+ d[ "one" ] = s1;
+ d[ "two" ] = s1;
+ d[ "three" ] = s2;
+ d[ "four" ] = s2;
+
+ d_t::iterator it;
+ it = d.begin(); // this (using the assignment operator) is causing
+ // a problem; if I just use the copy ctor it works fine.
+ for( ; it != d.end(); ++it )
+ {
+ d_t::value_type vt( *it );
+ cxx::String rs = vt.second.repr();
+ std::string ls = rs.operator std::string();
+ fprintf( stderr, "%s\n", ls );
+ }
+#endif // 0
+
+ class iterator
+ {
+ // : public forward_iterator_parent( std::pair<const T,T> ) {
+ protected:
+ typedef std::forward_iterator_tag iterator_category;
+ typedef std::pair< const T, T > value_type;
+ typedef int difference_type;
+ typedef std::pair< const T, mapref<T> > pointer;
+ typedef std::pair< const T, mapref<T> > reference;
+
+ friend class MapBase<T>;
+ //
+ MapBase<T>* map;
+ List keys; // for iterating over the map
+ List::iterator pos; // index into the keys
+
+ public:
+ ~iterator ()
+ {}
+
+ iterator ()
+ : map( 0 )
+ , keys()
+ , pos()
+ {}
+
+ iterator (MapBase<T>* m, bool end = false )
+ : map( m )
+ , keys( m->keys() )
+ , pos( end ? keys.end() : keys.begin() )
+ {}
+
+ iterator (const iterator& other)
+ : map( other.map )
+ , keys( other.keys )
+ , pos( other.pos )
+ {}
+
+ reference operator*()
+ {
+ Object key = *pos;
+ return std::make_pair(key, mapref<T>(*map,key));
+ }
+
+ iterator& operator=(const iterator& other)
+ {
+ if (this == &other)
+ return *this;
+ map = other.map;
+ keys = other.keys;
+ pos = other.pos;
+ return *this;
+ }
+
+ bool eql(const iterator& right) const
+ {
+ return *map == *right.map && pos == right.pos;
+ }
+ bool neq( const iterator& right ) const
+ {
+ return *map != *right.map || pos != right.pos;
+ }
+
+ // pointer operator->() {
+ // return ;
+ // }
+
+ // prefix ++
+ iterator& operator++ ()
+ { pos++; return *this;}
+ // postfix ++
+ iterator operator++ (int)
+ { return iterator(map, keys, pos++);}
+ // prefix --
+ iterator& operator-- ()
+ { pos--; return *this;}
+ // postfix --
+ iterator operator-- (int)
+ { return iterator(map, keys, pos--);}
+
+ std::string diagnose() const
+ {
+ std::ostringstream oss;
+ oss << "iterator diagnosis " << map << ", " << pos << std::ends;
+ return std::string(oss.str());
+ }
+ }; // end of class MapBase<T>::iterator
+
+ iterator begin ()
+ {
+ return iterator(this);
+ }
+
+ iterator end ()
+ {
+ return iterator(this, true);
+ }
+
+ class const_iterator
+ {
+ protected:
+ typedef std::forward_iterator_tag iterator_category;
+ typedef const std::pair< const T, T > value_type;
+ typedef int difference_type;
+ typedef const std::pair< const T, T > pointer;
+ typedef const std::pair< const T, T > reference;
+
+ friend class MapBase<T>;
+ const MapBase<T>* map;
+ List keys; // for iterating over the map
+ List::iterator pos; // index into the keys
+
+ public:
+ ~const_iterator ()
+ {}
+
+ const_iterator ()
+ : map( 0 )
+ , keys()
+ , pos()
+ {}
+
+ const_iterator (const MapBase<T>* m, List k, List::iterator p )
+ : map( m )
+ , keys( k )
+ , pos( p )
+ {}
+
+ const_iterator(const const_iterator& other)
+ : map( other.map )
+ , keys( other.keys )
+ , pos( other.pos )
+ {}
+
+ bool eql(const const_iterator& right) const
+ {
+ return *map == *right.map && pos == right.pos;
+ }
+ bool neq( const const_iterator& right ) const
+ {
+ return *map != *right.map || pos != right.pos;
+ }
+
+
+ // const_reference operator*() {
+ // Object key = *pos;
+ // return std::make_pair( key, map->[key] );
+ // GCC < 3 barfes on this line at the '['.
+ // }
+
+ const_iterator& operator=(const const_iterator& other)
+ {
+ if (this == &other) return *this;
+ map = other.map;
+ keys = other.keys;
+ pos = other.pos;
+ return *this;
+ }
+
+ // prefix ++
+ const_iterator& operator++ ()
+ { pos++; return *this;}
+ // postfix ++
+ const_iterator operator++ (int)
+ { return const_iterator(map, keys, pos++);}
+ // prefix --
+ const_iterator& operator-- ()
+ { pos--; return *this;}
+ // postfix --
+ const_iterator operator-- (int)
+ { return const_iterator(map, keys, pos--);}
+ }; // end of class MapBase<T>::const_iterator
+
+ const_iterator begin () const
+ {
+ return const_iterator(this, 0);
+ }
+
+ const_iterator end () const
+ {
+ return const_iterator(this, length());
+ }
+
+ }; // end of MapBase<T>
+
+ typedef MapBase<Object> Mapping;
+
+ template <typename T> bool operator==(const typename MapBase<T>::iterator& left, const typename MapBase<T>::iterator& right);
+ template <typename T> bool operator!=(const typename MapBase<T>::iterator& left, const typename MapBase<T>::iterator& right);
+ template <typename T> bool operator==(const typename MapBase<T>::const_iterator& left, const typename MapBase<T>::const_iterator& right);
+ template <typename T> bool operator!=(const typename MapBase<T>::const_iterator& left, const typename MapBase<T>::const_iterator& right);
+
+ extern bool operator==(const Mapping::iterator& left, const Mapping::iterator& right);
+ extern bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right);
+ extern bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right);
+ extern bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right);
+
+
+ // ==================================================
+ // class Dict
+ class Dict: public Mapping
+ {
+ public:
+ // Constructor
+ explicit Dict (PyObject *pyob, bool owned=false): Mapping (pyob, owned)
+ {
+ validate();
+ }
+ Dict (const Dict& ob): Mapping(ob)
+ {
+ validate();
+ }
+ // Creation
+ Dict ()
+ {
+ set(PyDict_New (), true);
+ validate();
+ }
+ // Assignment acquires new ownership of pointer
+
+ Dict& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Dict& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set(rhsp);
+ return *this;
+ }
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && Py::_Dict_Check (pyob);
+ }
+ };
+
+ class Callable: public Object
+ {
+ protected:
+ explicit Callable (): Object()
+ {}
+ public:
+ // Constructor
+ explicit Callable (PyObject *pyob, bool owned = false): Object (pyob, owned)
+ {
+ validate();
+ }
+
+ Callable (const Object& ob): Object(ob)
+ {
+ validate();
+ }
+
+ // Assignment acquires new ownership of pointer
+
+ Callable& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Callable& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set (rhsp);
+ return *this;
+ }
+
+ // Membership
+ virtual bool accepts (PyObject *pyob) const
+ {
+ return pyob && PyCallable_Check (pyob);
+ }
+
+ // Call
+ Object apply(const Tuple& args) const
+ {
+ return asObject(PyObject_CallObject(ptr(), args.ptr()));
+ }
+
+ // Call with keywords
+ Object apply(const Tuple& args, const Dict& kw) const
+ {
+ return asObject( PyEval_CallObjectWithKeywords( ptr(), args.ptr(), kw.ptr() ) );
+ }
+
+ Object apply(PyObject* pargs = 0) const
+ {
+ return apply (Tuple(pargs));
+ }
+ };
+
+ class Module: public Object
+ {
+ public:
+ explicit Module (PyObject* pyob, bool owned = false): Object (pyob, owned)
+ {
+ validate();
+ }
+
+ // Construct from module name
+ explicit Module (const std::string&s): Object()
+ {
+ PyObject *m = PyImport_AddModule( const_cast<char *>(s.c_str()) );
+ set( m, false );
+ validate ();
+ }
+
+ // Copy constructor acquires new ownership of pointer
+ Module (const Module& ob): Object(*ob)
+ {
+ validate();
+ }
+
+ Module& operator= (const Object& rhs)
+ {
+ return (*this = *rhs);
+ }
+
+ Module& operator= (PyObject* rhsp)
+ {
+ if(ptr() == rhsp) return *this;
+ set(rhsp);
+ return *this;
+ }
+
+ Dict getDict()
+ {
+ return Dict(PyModule_GetDict(ptr()));
+ // Caution -- PyModule_GetDict returns borrowed reference!
+ }
+ };
+
+ // Numeric interface
+ inline Object operator+ (const Object& a)
+ {
+ return asObject(PyNumber_Positive(*a));
+ }
+ inline Object operator- (const Object& a)
+ {
+ return asObject(PyNumber_Negative(*a));
+ }
+
+ inline Object abs(const Object& a)
+ {
+ return asObject(PyNumber_Absolute(*a));
+ }
+
+ inline std::pair<Object,Object> coerce(const Object& a, const Object& b)
+ {
+ PyObject *p1, *p2;
+ p1 = *a;
+ p2 = *b;
+ if(PyNumber_Coerce(&p1,&p2) == -1)
+ {
+ throw Exception();
+ }
+ return std::pair<Object,Object>(asObject(p1), asObject(p2));
+ }
+
+ inline Object operator+ (const Object& a, const Object& b)
+ {
+ return asObject(PyNumber_Add(*a, *b));
+ }
+ inline Object operator+ (const Object& a, int j)
+ {
+ return asObject(PyNumber_Add(*a, *Int(j)));
+ }
+ inline Object operator+ (const Object& a, double v)
+ {
+ return asObject(PyNumber_Add(*a, *Float(v)));
+ }
+ inline Object operator+ (int j, const Object& b)
+ {
+ return asObject(PyNumber_Add(*Int(j), *b));
+ }
+ inline Object operator+ (double v, const Object& b)
+ {
+ return asObject(PyNumber_Add(*Float(v), *b));
+ }
+
+ inline Object operator- (const Object& a, const Object& b)
+ {
+ return asObject(PyNumber_Subtract(*a, *b));
+ }
+ inline Object operator- (const Object& a, int j)
+ {
+ return asObject(PyNumber_Subtract(*a, *Int(j)));
+ }
+ inline Object operator- (const Object& a, double v)
+ {
+ return asObject(PyNumber_Subtract(*a, *Float(v)));
+ }
+ inline Object operator- (int j, const Object& b)
+ {
+ return asObject(PyNumber_Subtract(*Int(j), *b));
+ }
+ inline Object operator- (double v, const Object& b)
+ {
+ return asObject(PyNumber_Subtract(*Float(v), *b));
+ }
+
+ inline Object operator* (const Object& a, const Object& b)
+ {
+ return asObject(PyNumber_Multiply(*a, *b));
+ }
+ inline Object operator* (const Object& a, int j)
+ {
+ return asObject(PyNumber_Multiply(*a, *Int(j)));
+ }
+ inline Object operator* (const Object& a, double v)
+ {
+ return asObject(PyNumber_Multiply(*a, *Float(v)));
+ }
+ inline Object operator* (int j, const Object& b)
+ {
+ return asObject(PyNumber_Multiply(*Int(j), *b));
+ }
+ inline Object operator* (double v, const Object& b)
+ {
+ return asObject(PyNumber_Multiply(*Float(v), *b));
+ }
+
+ inline Object operator/ (const Object& a, const Object& b)
+ {
+ return asObject(PyNumber_Divide(*a, *b));
+ }
+ inline Object operator/ (const Object& a, int j)
+ {
+ return asObject(PyNumber_Divide(*a, *Int(j)));
+ }
+ inline Object operator/ (const Object& a, double v)
+ {
+ return asObject(PyNumber_Divide(*a, *Float(v)));
+ }
+ inline Object operator/ (int j, const Object& b)
+ {
+ return asObject(PyNumber_Divide(*Int(j), *b));
+ }
+ inline Object operator/ (double v, const Object& b)
+ {
+ return asObject(PyNumber_Divide(*Float(v), *b));
+ }
+
+ inline Object operator% (const Object& a, const Object& b)
+ {
+ return asObject(PyNumber_Remainder(*a, *b));
+ }
+ inline Object operator% (const Object& a, int j)
+ {
+ return asObject(PyNumber_Remainder(*a, *Int(j)));
+ }
+ inline Object operator% (const Object& a, double v)
+ {
+ return asObject(PyNumber_Remainder(*a, *Float(v)));
+ }
+ inline Object operator% (int j, const Object& b)
+ {
+ return asObject(PyNumber_Remainder(*Int(j), *b));
+ }
+ inline Object operator% (double v, const Object& b)
+ {
+ return asObject(PyNumber_Remainder(*Float(v), *b));
+ }
+
+ inline Object type(const Exception&) // return the type of the error
+ {
+ PyObject *ptype, *pvalue, *ptrace;
+ PyErr_Fetch(&ptype, &pvalue, &ptrace);
+ Object result(ptype);
+ PyErr_Restore(ptype, pvalue, ptrace);
+ return result;
+ }
+
+ inline Object value(const Exception&) // return the value of the error
+ {
+ PyObject *ptype, *pvalue, *ptrace;
+ PyErr_Fetch(&ptype, &pvalue, &ptrace);
+ Object result;
+ if(pvalue) result = pvalue;
+ PyErr_Restore(ptype, pvalue, ptrace);
+ return result;
+ }
+
+ inline Object trace(const Exception&) // return the traceback of the error
+ {
+ PyObject *ptype, *pvalue, *ptrace;
+ PyErr_Fetch(&ptype, &pvalue, &ptrace);
+ Object result;
+ if(ptrace) result = ptrace;
+ PyErr_Restore(ptype, pvalue, ptrace);
+ return result;
+ }
+
+
+
+template<typename T>
+String seqref<T>::str () const
+ {
+ return the_item.str();
+ }
+
+template<typename T>
+String seqref<T>::repr () const
+ {
+ return the_item.repr();
+ }
+
+
+ } // namespace Py
+#endif // __CXX_Objects__h
diff --git a/lib/kross/python/cxx/Objects.hxx b/lib/kross/python/cxx/Objects.hxx
deleted file mode 100644
index 97e52fc0e..000000000
--- a/lib/kross/python/cxx/Objects.hxx
+++ /dev/null
@@ -1,2804 +0,0 @@
-//---------------------------------------------------------------------------//
-// Copyright 1998 The Regents of the University of California.
-// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
-//---------------------------------------------------------------------------//
-
-#ifndef __CXX_Objects__h
-#define __CXX_Objects__h
-
-// Prevent warnings
-#if defined(_XOPEN_SOURCE)
-#undef _XOPEN_SOURCE
-#endif
-
-#include "Python.h"
-#include "Config.hxx"
-#include "Exception.hxx"
-
-
-#include <iostream>
-#include <sstream>
-#include <string>
-#include <iterator>
-#include <utility>
-#include <typeinfo>
-
-namespace Py
- {
- typedef int sequence_index_type; // type of an index into a sequence
-
- // Forward declarations
- class Object;
- class Type;
- template<typename T> class SeqBase;
- class String;
- class List;
- template<typename T> class MapBase;
-
- // new_reference_to also overloaded below on Object
- inline PyObject* new_reference_to(PyObject* p)
- {
- Py::_XINCREF(p);
- return p;
- }
-
- // returning Null() from an extension method triggers a
- // Python exception
- inline PyObject* Null()
- {
- return (static_cast<PyObject*>(0));
- }
-
- //===========================================================================//
- // class Object
- // The purpose of this class is to serve as the most general kind of
- // Python object, for the purpose of writing C++ extensions in Python
- // Objects hold a PyObject* which they own. This pointer is always a
- // valid pointer to a Python object. In children we must maintain this behavior.
- //
- // Instructions on how to make your own class MyType descended from Object:
- // (0) Pick a base class, either Object or perhaps SeqBase<T> or MapBase<T>.
- // This example assumes Object.
-
- // (1) Write a routine int MyType_Check (PyObject *) modeled after PyInt_Check,
- // PyFloat_Check, etc.
-
- // (2) Add method accepts:
- // virtual bool accepts (PyObject *pyob) const {
- // return pyob && MyType_Check (pyob);
- // }
-
- // (3) Include the following constructor and copy constructor
- //
- /*
- explicit MyType (PyObject *pyob): Object(pyob) {
- validate();
- }
-
- MyType(const Object& other): Object(other.ptr()) {
- validate();
- }
- */
-
- // Alernate version for the constructor to allow for construction from owned pointers:
- /*
- explicit MyType (PyObject *pyob): Object(pyob) {
- validate();
- }
- */
-
- // You may wish to add other constructors; see the classes below for examples.
- // Each constructor must use "set" to set the pointer
- // and end by validating the pointer you have created.
-
- // (4) Each class needs at least these two assignment operators:
- /*
- MyType& operator= (const Object& rhs) {
- return (*this = *rhs);
- }
-
- Mytype& operator= (PyObject* rhsp) {
- if(ptr() == rhsp) return *this;
- set(rhsp);
- return *this;
- }
- */
- // Note on accepts: constructors call the base class
- // version of a virtual when calling the base class constructor,
- // so the test has to be done explicitly in a descendent.
-
- // If you are inheriting from PythonExtension<T> to define an object
- // note that it contains PythonExtension<T>::check
- // which you can use in accepts when writing a wrapper class.
- // See Demo/range.h and Demo/range.cxx for an example.
-
- class Object
- {
- private:
- // the pointer to the Python object
- // Only Object sets this directly.
- // The default constructor for Object sets it to Py_None and
- // child classes must use "set" to set it
- //
- PyObject* p;
-
- protected:
-
- void set (PyObject* pyob, bool owned = false)
- {
- release();
- p = pyob;
- if (!owned)
- {
- Py::_XINCREF (p);
- }
- validate();
- }
-
- void release ()
- {
- Py::_XDECREF (p);
- p = 0;
- }
-
- void validate()
- {
- // release pointer if not the right type
- if (! accepts (p))
- {
- release ();
- if(PyErr_Occurred())
- { // Error message already set
- throw Exception();
- }
- // Better error message if RTTI available
-#if defined( _CPPRTTI )
- std::string s("Error creating object of type ");
- s += (typeid (*this)).name();
- throw TypeError (s);
-#else
- throw TypeError ("CXX: type error.");
-#endif
- }
- }
-
- public:
- // Constructor acquires new ownership of pointer unless explicitly told not to.
- explicit Object (PyObject* pyob=Py::_None(), bool owned = false): p (pyob)
- {
- if(!owned)
- {
- Py::_XINCREF (p);
- }
- validate();
- }
-
- // Copy constructor acquires new ownership of pointer
- Object (const Object& ob): p(ob.p)
- {
- Py::_XINCREF (p);
- validate();
- }
-
- // Assignment acquires new ownership of pointer
- Object& operator= (const Object& rhs)
- {
- set(rhs.p);
- return *this;
- }
-
- Object& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
-
- // Destructor
- virtual ~Object ()
- {
- release ();
- }
-
- // Loaning the pointer to others, retain ownership
- PyObject* operator* () const
- {
- return p;
- }
-
- // Explicit reference_counting changes
- void increment_reference_count()
- {
- Py::_XINCREF(p);
- }
-
- void decrement_reference_count()
- {
- // not allowed to commit suicide, however
- if(reference_count() == 1)
- throw RuntimeError("Object::decrement_reference_count error.");
- Py::_XDECREF(p);
- }
- // Would like to call this pointer() but messes up STL in SeqBase<T>
- PyObject* ptr () const
- {
- return p;
- }
-
- //
- // Queries
- //
-
- // Can pyob be used in this object's constructor?
- virtual bool accepts (PyObject *pyob) const
- {
- return (pyob != 0);
- }
-
- int reference_count () const
- { // the reference count
- return p ? p->ob_refcnt : 0;
- }
-
- Type type () const; // the type object associated with this one
-
- String str () const; // the str() representation
-
- std::string as_string() const;
-
- String repr () const; // the repr () representation
-
- List dir () const; // the dir() list
-
- bool hasAttr (const std::string& s) const
- {
- return PyObject_HasAttrString (p, const_cast<char*>(s.c_str())) ? true: false;
- }
-
- Object getAttr (const std::string& s) const
- {
- return Object (PyObject_GetAttrString (p, const_cast<char*>(s.c_str())), true);
- }
-
- Object getItem (const Object& key) const
- {
- return Object (PyObject_GetItem(p, *key), true);
- }
-
- long hashValue () const
- {
- return PyObject_Hash (p);
- }
-
- //
- // int print (FILE* fp, int flags=Py_Print_RAW)
- // {
- // return PyObject_Print (p, fp, flags);
- // }
- //
- bool is(PyObject *pother) const
- { // identity test
- return p == pother;
- }
-
- bool is(const Object& other) const
- { // identity test
- return p == other.p;
- }
-
- bool isCallable () const
- {
- return PyCallable_Check (p) != 0;
- }
-
- bool isInstance () const
- {
- return PyInstance_Check (p) != 0;
- }
-
- bool isDict () const
- {
- return Py::_Dict_Check (p);
- }
-
- bool isList () const
- {
- return Py::_List_Check (p);
- }
-
- bool isMapping () const
- {
- return PyMapping_Check (p) != 0;
- }
-
- bool isNumeric () const
- {
- return PyNumber_Check (p) != 0;
- }
-
- bool isSequence () const
- {
- return PySequence_Check (p) != 0;
- }
-
- bool isTrue () const
- {
- return PyObject_IsTrue (p) != 0;
- }
-
- bool isType (const Type& t) const;
-
- bool isTuple() const
- {
- return Py::_Tuple_Check(p);
- }
-
- bool isString() const
- {
- return Py::_String_Check(p) || Py::_Unicode_Check(p);
- }
-
- bool isUnicode() const
- {
- return Py::_Unicode_Check(p);
- }
-
- // Commands
- void setAttr (const std::string& s, const Object& value)
- {
- if(PyObject_SetAttrString (p, const_cast<char*>(s.c_str()), *value) == -1)
- throw AttributeError ("getAttr failed.");
- }
-
- void delAttr (const std::string& s)
- {
- if(PyObject_DelAttrString (p, const_cast<char*>(s.c_str())) == -1)
- throw AttributeError ("delAttr failed.");
- }
-
- // PyObject_SetItem is too weird to be using from C++
- // so it is intentionally omitted.
-
- void delItem (const Object& /*key*/)
- {
- //if(PyObject_DelItem(p, *key) == -1)
- // failed to link on Windows?
- throw KeyError("delItem failed.");
- }
- // Equality and comparison use PyObject_Compare
-
- bool operator==(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k == 0;
- }
-
- bool operator!=(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k != 0;
-
- }
-
- bool operator>=(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k >= 0;
- }
-
- bool operator<=(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k <= 0;
- }
-
- bool operator<(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k < 0;
- }
-
- bool operator>(const Object& o2) const
- {
- int k = PyObject_Compare (p, *o2);
- if (PyErr_Occurred()) throw Exception();
- return k > 0;
- }
- };
- // End of class Object
- inline PyObject* new_reference_to(const Object& g)
- {
- PyObject* p = g.ptr();
- Py::_XINCREF(p);
- return p;
- }
-
- // Nothing() is what an extension method returns if
- // there is no other return value.
- inline Object Nothing()
- {
- return Object(Py::_None());
- }
-
- // Python special None value
- inline Object None()
- {
- return Object(Py::_None());
- }
-
- // TMM: 31May'01 - Added the #ifndef so I can exlude iostreams.
-#ifndef CXX_NO_IOSTREAMS
- std::ostream& operator<< (std::ostream& os, const Object& ob);
-#endif
-
- // Class Type
- class Type: public Object
- {
- public:
- explicit Type (PyObject* pyob, bool owned = false): Object(pyob, owned)
- {
- validate();
- }
-
- Type (const Object& ob): Object(*ob)
- {
- validate();
- }
-
- Type(const Type& t): Object(t)
- {
- validate();
- }
-
- Type& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Type& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Type_Check (pyob);
- }
- };
-
-
- //
- // Convert an owned Python pointer into a CXX Object
- //
- inline Object asObject (PyObject *p)
- {
- return Object(p, true);
- }
-
-
-
-
- // ===============================================
- // class Int
- class Int: public Object
- {
- public:
- // Constructor
- explicit Int (PyObject *pyob, bool owned = false): Object (pyob, owned)
- {
- validate();
- }
-
- Int (const Int& ob): Object(*ob)
- {
- validate();
- }
-
- // create from long
- explicit Int (long v = 0L): Object(PyInt_FromLong(v), true)
- {
- validate();
- }
-
- // create from int
- explicit Int (int v)
- {
- long w = v;
- set(PyInt_FromLong(w), true);
- validate();
- }
-
- Int (const Object& ob)
- {
- set(PyNumber_Int(*ob), true);
- validate();
- }
-
- // Assignment acquires new ownership of pointer
-
- Int& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Int& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (PyNumber_Int(rhsp), true);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Int_Check (pyob);
- }
- // convert to long
- operator long() const
- {
- return PyInt_AsLong (ptr());
- }
- // assign from an int
- Int& operator= (int v)
- {
- set (PyInt_FromLong (long(v)), true);
- return *this;
- }
- // assign from long
- Int& operator= (long v)
- {
- set (PyInt_FromLong (v), true);
- return *this;
- }
- };
-
- // ===============================================
- // class Long
- class Long: public Object
- {
- public:
- // Constructor
- explicit Long (PyObject *pyob, bool owned = false): Object (pyob, owned)
- {
- validate();
- }
-
- Long (const Long& ob): Object(ob.ptr())
- {
- validate();
- }
-
- // create from long
- explicit Long (long v = 0L)
- : Object(PyLong_FromLong(v), true)
- {
- validate();
- }
- // create from int
- explicit Long (int v)
- : Object(PyLong_FromLong(static_cast<long>(v)), true)
- {
- validate();
- }
-
- // create from unsigned long
- explicit Long (unsigned long v)
- : Object(PyLong_FromUnsignedLong(v), true)
- {
- validate();
- }
-
- // try to create from any object
- Long (const Object& ob)
- : Object(PyNumber_Long(*ob), true)
- {
- validate();
- }
-
- // Assignment acquires new ownership of pointer
-
- Long& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Long& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (PyNumber_Long(rhsp), true);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Long_Check (pyob);
- }
- // convert to long
- operator long() const
- {
- return PyLong_AsLong (ptr());
- }
- operator double() const
- {
- return PyLong_AsDouble (ptr());
- }
- operator unsigned long() const
- {
- return PyLong_AsUnsignedLong (ptr());
- }
- // assign from an int
- Long& operator= (int v)
- {
- set(PyLong_FromLong (long(v)), true);
- return *this;
- }
- // assign from long
- Long& operator= (long v)
- {
- set(PyLong_FromLong (v), true);
- return *this;
- }
- // assign from unsigned long
- Long& operator= (unsigned long v)
- {
- set(PyLong_FromUnsignedLong (v), true);
- return *this;
- }
- };
-
- // ===============================================
- // class Float
- //
- class Float: public Object
- {
- public:
- // Constructor
- explicit Float (PyObject *pyob, bool owned = false): Object(pyob, owned)
- {
- validate();
- }
-
- Float (const Float& f): Object(f)
- {
- validate();
- }
-
- // make from double
- explicit Float (double v=0.0)
- : Object(PyFloat_FromDouble (v), true)
- {
- validate();
- }
-
- // try to make from any object
- Float (const Object& ob)
- : Object(PyNumber_Float(*ob), true)
- {
- validate();
- }
-
- Float& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Float& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (PyNumber_Float(rhsp), true);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Float_Check (pyob);
- }
- // convert to double
- operator double () const
- {
- return PyFloat_AsDouble (ptr());
- }
- // assign from a double
- Float& operator= (double v)
- {
- set(PyFloat_FromDouble (v), true);
- return *this;
- }
- // assign from an int
- Float& operator= (int v)
- {
- set(PyFloat_FromDouble (double(v)), true);
- return *this;
- }
- // assign from long
- Float& operator= (long v)
- {
- set(PyFloat_FromDouble (double(v)), true);
- return *this;
- }
- // assign from an Int
- Float& operator= (const Int& iob)
- {
- set(PyFloat_FromDouble (double(long(iob))), true);
- return *this;
- }
- };
-
- // ===============================================
- // class Complex
- class Complex: public Object
- {
- public:
- // Constructor
- explicit Complex (PyObject *pyob, bool owned = false): Object(pyob, owned)
- {
- validate();
- }
-
- Complex (const Complex& f): Object(f)
- {
- validate();
- }
-
- // make from double
- explicit Complex (double v=0.0, double w=0.0)
- :Object(PyComplex_FromDoubles (v, w), true)
- {
- validate();
- }
-
- Complex& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Complex& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Complex_Check (pyob);
- }
- // convert to Py_complex
- operator Py_complex () const
- {
- return PyComplex_AsCComplex (ptr());
- }
- // assign from a Py_complex
- Complex& operator= (const Py_complex& v)
- {
- set(PyComplex_FromCComplex (v), true);
- return *this;
- }
- // assign from a double
- Complex& operator= (double v)
- {
- set(PyComplex_FromDoubles (v, 0.0), true);
- return *this;
- }
- // assign from an int
- Complex& operator= (int v)
- {
- set(PyComplex_FromDoubles (double(v), 0.0), true);
- return *this;
- }
- // assign from long
- Complex& operator= (long v)
- {
- set(PyComplex_FromDoubles (double(v), 0.0), true);
- return *this;
- }
- // assign from an Int
- Complex& operator= (const Int& iob)
- {
- set(PyComplex_FromDoubles (double(long(iob)), 0.0), true);
- return *this;
- }
-
- double real() const
- {
- return PyComplex_RealAsDouble(ptr());
- }
-
- double imag() const
- {
- return PyComplex_ImagAsDouble(ptr());
- }
- };
- // Sequences
- // Sequences are here represented as sequences of items of type T.
- // The base class SeqBase<T> represents that.
- // In basic Python T is always "Object".
-
- // seqref<T> is what you get if you get elements from a non-const SeqBase<T>.
- // Note: seqref<T> could probably be a nested class in SeqBase<T> but that might stress
- // some compilers needlessly. Simlarly for mapref later.
-
- // While this class is not intended for enduser use, it needs some public
- // constructors for the benefit of the STL.
-
- // See Scott Meyer's More Essential C++ for a description of proxies.
- // This application is even more complicated. We are doing an unusual thing
- // in having a double proxy. If we want the STL to work
- // properly we have to compromise by storing the rvalue inside. The
- // entire Object API is repeated so that things like s[i].isList() will
- // work properly.
-
- // Still, once in a while a weird compiler message may occur using expressions like x[i]
- // Changing them to Object(x[i]) helps the compiler to understand that the
- // conversion of a seqref to an Object is wanted.
-
- template<typename T>
- class seqref
- {
- protected:
- SeqBase<T>& s; // the sequence
- int offset; // item number
- T the_item; // lvalue
- public:
-
- seqref (SeqBase<T>& seq, sequence_index_type j)
- : s(seq), offset(j), the_item (s.getItem(j))
- {}
-
- seqref (const seqref<T>& range)
- : s(range.s), offset(range.offset), the_item(range.the_item)
- {}
-
- // TMM: added this seqref ctor for use with STL algorithms
- seqref (Object& obj)
- : s(dynamic_cast< SeqBase<T>&>(obj))
- , offset( NULL )
- , the_item(s.getItem(offset))
- {}
- ~seqref()
- {}
-
- operator T() const
- { // rvalue
- return the_item;
- }
-
- seqref<T>& operator=(const seqref<T>& rhs)
- { //used as lvalue
- the_item = rhs.the_item;
- s.setItem(offset, the_item);
- return *this;
- }
-
- seqref<T>& operator=(const T& ob)
- { // used as lvalue
- the_item = ob;
- s.setItem(offset, ob);
- return *this;
- }
-
- // forward everything else to the item
- PyObject* ptr () const
- {
- return the_item.ptr();
- }
-
- int reference_count () const
- { // the reference count
- return the_item.reference_count();
- }
-
- Type type () const
- {
- return the_item.type();
- }
-
- String str () const;
-
- String repr () const;
-
- bool hasAttr (const std::string& attr_name) const
- {
- return the_item.hasAttr(attr_name);
- }
-
- Object getAttr (const std::string& attr_name) const
- {
- return the_item.getAttr(attr_name);
- }
-
- Object getItem (const Object& key) const
- {
- return the_item.getItem(key);
- }
-
- long hashValue () const
- {
- return the_item.hashValue();
- }
-
- bool isCallable () const
- {
- return the_item.isCallable();
- }
-
- bool isInstance () const
- {
- return the_item.isInstance();
- }
-
- bool isDict () const
- {
- return the_item.isDict();
- }
-
- bool isList () const
- {
- return the_item.isList();
- }
-
- bool isMapping () const
- {
- return the_item.isMapping();
- }
-
- bool isNumeric () const
- {
- return the_item.isNumeric();
- }
-
- bool isSequence () const
- {
- return the_item.isSequence();
- }
-
- bool isTrue () const
- {
- return the_item.isTrue();
- }
-
- bool isType (const Type& t) const
- {
- return the_item.isType (t);
- }
-
- bool isTuple() const
- {
- return the_item.isTuple();
- }
-
- bool isString() const
- {
- return the_item.isString();
- }
- // Commands
- void setAttr (const std::string& attr_name, const Object& value)
- {
- the_item.setAttr(attr_name, value);
- }
-
- void delAttr (const std::string& attr_name)
- {
- the_item.delAttr(attr_name);
- }
-
- void delItem (const Object& key)
- {
- the_item.delItem(key);
- }
-
- bool operator==(const Object& o2) const
- {
- return the_item == o2;
- }
-
- bool operator!=(const Object& o2) const
- {
- return the_item != o2;
- }
-
- bool operator>=(const Object& o2) const
- {
- return the_item >= o2;
- }
-
- bool operator<=(const Object& o2) const
- {
- return the_item <= o2;
- }
-
- bool operator<(const Object& o2) const
- {
- return the_item < o2;
- }
-
- bool operator>(const Object& o2) const
- {
- return the_item > o2;
- }
- }; // end of seqref
-
-
- // class SeqBase<T>
- // ...the base class for all sequence types
-
- template<typename T>
- class SeqBase: public Object
- {
- public:
- // STL definitions
- typedef size_t size_type;
- typedef seqref<T> reference;
- typedef T const_reference;
- typedef seqref<T>* pointer;
- typedef int difference_type;
- typedef T value_type; // TMM: 26Jun'01
-
- virtual size_type max_size() const
- {
- return std::string::npos; // ?
- }
-
- virtual size_type capacity() const
- {
- return size();
- }
-
- virtual void swap(SeqBase<T>& c)
- {
- SeqBase<T> temp = c;
- c = ptr();
- set(temp.ptr());
- }
-
- virtual size_type size () const
- {
- return PySequence_Length (ptr());
- }
-
- explicit SeqBase<T> ()
- :Object(PyTuple_New(0), true)
- {
- validate();
- }
-
- explicit SeqBase<T> (PyObject* pyob, bool owned=false)
- : Object(pyob, owned)
- {
- validate();
- }
-
- SeqBase<T> (const Object& ob): Object(ob)
- {
- validate();
- }
-
- // Assignment acquires new ownership of pointer
-
- SeqBase<T>& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- SeqBase<T>& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
-
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && PySequence_Check (pyob);
- }
-
- size_type length () const
- {
- return PySequence_Length (ptr());
- }
-
- // Element access
- const T operator[](sequence_index_type index) const
- {
- return getItem(index);
- }
-
- seqref<T> operator[](sequence_index_type index)
- {
- return seqref<T>(*this, index);
- }
-
- virtual T getItem (sequence_index_type i) const
- {
- return T(asObject(PySequence_GetItem (ptr(), i)));
- }
-
- virtual void setItem (sequence_index_type i, const T& ob)
- {
- if (PySequence_SetItem (ptr(), i, *ob) == -1)
- {
- throw Exception();
- }
- }
-
- SeqBase<T> repeat (int count) const
- {
- return SeqBase<T> (PySequence_Repeat (ptr(), count), true);
- }
-
- SeqBase<T> concat (const SeqBase<T>& other) const
- {
- return SeqBase<T> (PySequence_Concat(ptr(), *other), true);
- }
-
- // more STL compatability
- const T front () const
- {
- return getItem(0);
- }
-
- seqref<T> front()
- {
- return seqref<T>(this, 0);
- }
-
- const T back () const
- {
- return getItem(size()-1);
- }
-
- seqref<T> back()
- {
- return seqref<T>(this, size()-1);
- }
-
- void verify_length(size_type required_size) const
- {
- if (size() != required_size)
- throw IndexError ("Unexpected SeqBase<T> length.");
- }
-
- void verify_length(size_type min_size, size_type max_size) const
- {
- size_type n = size();
- if (n < min_size || n > max_size)
- throw IndexError ("Unexpected SeqBase<T> length.");
- }
-
- class iterator
- : public random_access_iterator_parent(seqref<T>)
- {
- protected:
- friend class SeqBase<T>;
- SeqBase<T>* seq;
- int count;
-
- public:
- ~iterator ()
- {}
-
- iterator ()
- : seq( 0 )
- , count( 0 )
- {}
-
- iterator (SeqBase<T>* s, int where)
- : seq( s )
- , count( where )
- {}
-
- iterator (const iterator& other)
- : seq( other.seq )
- , count( other.count )
- {}
-
- bool eql (const iterator& other) const
- {
- return (*seq == *other.seq) && (count == other.count);
- }
-
- bool neq (const iterator& other) const
- {
- return (*seq != *other.seq) || (count != other.count);
- }
-
- bool lss (const iterator& other) const
- {
- return (count < other.count);
- }
-
- bool gtr (const iterator& other) const
- {
- return (count > other.count);
- }
-
- bool leq (const iterator& other) const
- {
- return (count <= other.count);
- }
-
- bool geq (const iterator& other) const
- {
- return (count >= other.count);
- }
-
- seqref<T> operator*()
- {
- return seqref<T>(*seq, count);
- }
-
- seqref<T> operator[] (sequence_index_type i)
- {
- return seqref<T>(*seq, count + i);
- }
-
- iterator& operator=(const iterator& other)
- {
- if (this == &other) return *this;
- seq = other.seq;
- count = other.count;
- return *this;
- }
-
- iterator operator+(int n) const
- {
- return iterator(seq, count + n);
- }
-
- iterator operator-(int n) const
- {
- return iterator(seq, count - n);
- }
-
- iterator& operator+=(int n)
- {
- count = count + n;
- return *this;
- }
-
- iterator& operator-=(int n)
- {
- count = count - n;
- return *this;
- }
-
- int operator-(const iterator& other) const
- {
- if (*seq != *other.seq)
- throw RuntimeError ("SeqBase<T>::iterator comparison error");
- return count - other.count;
- }
-
- // prefix ++
- iterator& operator++ ()
- { count++; return *this;}
- // postfix ++
- iterator operator++ (int)
- { return iterator(seq, count++);}
- // prefix --
- iterator& operator-- ()
- { count--; return *this;}
- // postfix --
- iterator operator-- (int)
- { return iterator(seq, count--);}
-
- std::string diagnose() const
- {
- std::ostringstream oss;
- oss << "iterator diagnosis " << seq << ", " << count << std::ends;
- return std::string(oss.str());
- }
- }; // end of class SeqBase<T>::iterator
-
- iterator begin ()
- {
- return iterator(this, 0);
- }
-
- iterator end ()
- {
- return iterator(this, length());
- }
-
- class const_iterator
- : public random_access_iterator_parent(const Object)
- {
- protected:
- friend class SeqBase<T>;
- const SeqBase<T>* seq;
- sequence_index_type count;
-
- public:
- ~const_iterator ()
- {}
-
- const_iterator ()
- : seq( 0 )
- , count( 0 )
- {}
-
- const_iterator (const SeqBase<T>* s, int where)
- : seq( s )
- , count( where )
- {}
-
- const_iterator(const const_iterator& other)
- : seq( other.seq )
- , count( other.count )
- {}
-
- const T operator*() const
- {
- return seq->getItem(count);
- }
-
- const T operator[] (sequence_index_type i) const
- {
- return seq->getItem(count + i);
- }
-
- const_iterator& operator=(const const_iterator& other)
- {
- if (this == &other) return *this;
- seq = other.seq;
- count = other.count;
- return *this;
- }
-
- const_iterator operator+(int n) const
- {
- return const_iterator(seq, count + n);
- }
-
- bool eql (const const_iterator& other) const
- {
- return (*seq == *other.seq) && (count == other.count);
- }
-
- bool neq (const const_iterator& other) const
- {
- return (*seq != *other.seq) || (count != other.count);
- }
-
- bool lss (const const_iterator& other) const
- {
- return (count < other.count);
- }
-
- bool gtr (const const_iterator& other) const
- {
- return (count > other.count);
- }
-
- bool leq (const const_iterator& other) const
- {
- return (count <= other.count);
- }
-
- bool geq (const const_iterator& other) const
- {
- return (count >= other.count);
- }
-
- const_iterator operator-(int n)
- {
- return const_iterator(seq, count - n);
- }
-
- const_iterator& operator+=(int n)
- {
- count = count + n;
- return *this;
- }
-
- const_iterator& operator-=(int n)
- {
- count = count - n;
- return *this;
- }
-
- int operator-(const const_iterator& other) const
- {
- if (*seq != *other.seq)
- throw RuntimeError ("SeqBase<T>::const_iterator::- error");
- return count - other.count;
- }
- // prefix ++
- const_iterator& operator++ ()
- { count++; return *this;}
- // postfix ++
- const_iterator operator++ (int)
- { return const_iterator(seq, count++);}
- // prefix --
- const_iterator& operator-- ()
- { count--; return *this;}
- // postfix --
- const_iterator operator-- (int)
- { return const_iterator(seq, count--);}
- }; // end of class SeqBase<T>::const_iterator
-
- const_iterator begin () const
- {
- return const_iterator(this, 0);
- }
-
- const_iterator end () const
- {
- return const_iterator(this, length());
- }
- };
-
- // Here's an important typedef you might miss if reading too fast...
- typedef SeqBase<Object> Sequence;
-
- template <typename T> bool operator==(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
- template <typename T> bool operator!=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
- template <typename T> bool operator< (const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
- template <typename T> bool operator> (const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
- template <typename T> bool operator<=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
- template <typename T> bool operator>=(const typename SeqBase<T>::iterator& left, const typename SeqBase<T>::iterator& right);
-
- template <typename T> bool operator==(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
- template <typename T> bool operator!=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
- template <typename T> bool operator< (const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
- template <typename T> bool operator> (const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
- template <typename T> bool operator<=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
- template <typename T> bool operator>=(const typename SeqBase<T>::const_iterator& left, const typename SeqBase<T>::const_iterator& right);
-
-
- extern bool operator==(const Sequence::iterator& left, const Sequence::iterator& right);
- extern bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right);
- extern bool operator< (const Sequence::iterator& left, const Sequence::iterator& right);
- extern bool operator> (const Sequence::iterator& left, const Sequence::iterator& right);
- extern bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right);
- extern bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right);
-
- extern bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
- extern bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
- extern bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right);
- extern bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right);
- extern bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
- extern bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right);
-
- // ==================================================
- // class Char
- // Python strings return strings as individual elements.
- // I'll try having a class Char which is a String of length 1
- //
- typedef std::basic_string<Py_UNICODE> unicodestring;
- extern Py_UNICODE unicode_null_string[1];
-
- class Char: public Object
- {
- public:
- explicit Char (PyObject *pyob, bool owned = false): Object(pyob, owned)
- {
- validate();
- }
-
- Char (const Object& ob): Object(ob)
- {
- validate();
- }
-
- Char (const std::string& v = "")
- :Object(PyString_FromStringAndSize (const_cast<char*>(v.c_str()),1), true)
- {
- validate();
- }
-
- Char (char v)
- : Object(PyString_FromStringAndSize (&v, 1), true)
- {
- validate();
- }
-
- Char (Py_UNICODE v)
- : Object(PyUnicode_FromUnicode (&v, 1), true)
- {
- validate();
- }
- // Assignment acquires new ownership of pointer
- Char& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Char& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
-
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob)) && PySequence_Length (pyob) == 1;
- }
-
- // Assignment from C string
- Char& operator= (const std::string& v)
- {
- set(PyString_FromStringAndSize (const_cast<char*>(v.c_str()),1), true);
- return *this;
- }
-
- Char& operator= (char v)
- {
- set(PyString_FromStringAndSize (&v, 1), true);
- return *this;
- }
-
- Char& operator= (const unicodestring& v)
- {
- set(PyUnicode_FromUnicode (const_cast<Py_UNICODE*>(v.data()),1), true);
- return *this;
- }
-
- Char& operator= (Py_UNICODE v)
- {
- set(PyUnicode_FromUnicode (&v, 1), true);
- return *this;
- }
-
- // Conversion
- operator String() const;
-
- operator std::string () const
- {
- return std::string(PyString_AsString (ptr()));
- }
- };
-
- class String: public SeqBase<Char>
- {
- public:
- virtual size_type capacity() const
- {
- return max_size();
- }
-
- explicit String (PyObject *pyob, bool owned = false): SeqBase<Char>(pyob, owned)
- {
- validate();
- }
-
- String (const Object& ob): SeqBase<Char>(ob)
- {
- validate();
- }
-
- String()
- : SeqBase<Char>( PyString_FromStringAndSize( "", 0 ), true )
- {
- validate();
- }
-
- String( const std::string& v )
- : SeqBase<Char>( PyString_FromStringAndSize( const_cast<char*>(v.data()),
- static_cast<int>( v.length() ) ), true )
- {
- validate();
- }
-
- String( const char *s, const char *encoding, const char *error="strict" )
- : SeqBase<Char>( PyUnicode_Decode( s, strlen( s ), encoding, error ), true )
- {
- validate();
- }
-
- String( const char *s, int len, const char *encoding, const char *error="strict" )
- : SeqBase<Char>( PyUnicode_Decode( s, len, encoding, error ), true )
- {
- validate();
- }
-
- String( const std::string &s, const char *encoding, const char *error="strict" )
- : SeqBase<Char>( PyUnicode_Decode( s.c_str(), s.length(), encoding, error ), true )
- {
- validate();
- }
-
- String( const std::string& v, std::string::size_type vsize )
- : SeqBase<Char>(PyString_FromStringAndSize( const_cast<char*>(v.data()),
- static_cast<int>( vsize ) ), true)
- {
- validate();
- }
-
- String( const char *v, int vsize )
- : SeqBase<Char>(PyString_FromStringAndSize( const_cast<char*>(v), vsize ), true )
- {
- validate();
- }
-
- String( const char* v )
- : SeqBase<Char>( PyString_FromString( v ), true )
- {
- validate();
- }
-
- // Assignment acquires new ownership of pointer
- String& operator= ( const Object& rhs )
- {
- return *this = *rhs;
- }
-
- String& operator= (PyObject* rhsp)
- {
- if( ptr() == rhsp )
- return *this;
- set (rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && (Py::_String_Check(pyob) || Py::_Unicode_Check(pyob));
- }
-
- // Assignment from C string
- String& operator= (const std::string& v)
- {
- set( PyString_FromStringAndSize( const_cast<char*>( v.data() ),
- static_cast<int>( v.length() ) ), true );
- return *this;
- }
- String& operator= (const unicodestring& v)
- {
- set( PyUnicode_FromUnicode( const_cast<Py_UNICODE*>( v.data() ),
- static_cast<int>( v.length() ) ), true );
- return *this;
- }
-
-
- // Encode
- String encode( const char *encoding, const char *error="strict" )
- {
- if( isUnicode() )
- {
- return String( PyUnicode_AsEncodedString( ptr(), encoding, error ) );
- }
- else
- {
- return String( PyString_AsEncodedObject( ptr(), encoding, error ) );
- }
- }
-
- String decode( const char *encoding, const char *error="strict" )
- {
- return Object( PyString_AsDecodedObject( ptr(), encoding, error ) );
- }
-
- // Queries
- virtual size_type size () const
- {
- if( isUnicode() )
- {
- return static_cast<size_type>( PyUnicode_GET_SIZE (ptr()) );
- }
- else
- {
- return static_cast<size_type>( PyString_Size (ptr()) );
- }
- }
-
- operator std::string () const
- {
- return as_std_string();
- }
-
- std::string as_std_string() const
- {
- if( isUnicode() )
- {
- throw TypeError("cannot return std::string from Unicode object");
- }
- else
- {
- return std::string( PyString_AsString( ptr() ), static_cast<size_type>( PyString_Size( ptr() ) ) );
- }
- }
-
- unicodestring as_unicodestring() const
- {
- if( isUnicode() )
- {
- return unicodestring( PyUnicode_AS_UNICODE( ptr() ),
- static_cast<size_type>( PyUnicode_GET_SIZE( ptr() ) ) );
- }
- else
- {
- throw TypeError("can only return unicodestring from Unicode object");
- }
- }
- };
-
- // ==================================================
- // class Tuple
- class Tuple: public Sequence
- {
- public:
- virtual void setItem (sequence_index_type offset, const Object&ob)
- {
- // note PyTuple_SetItem is a thief...
- if(PyTuple_SetItem (ptr(), offset, new_reference_to(ob)) == -1)
- {
- throw Exception();
- }
- }
-
- // Constructor
- explicit Tuple (PyObject *pyob, bool owned = false): Sequence (pyob, owned)
- {
- validate();
- }
-
- Tuple (const Object& ob): Sequence(ob)
- {
- validate();
- }
-
- // New tuple of a given size
- explicit Tuple (int size = 0)
- {
- set(PyTuple_New (size), true);
- validate ();
- for (sequence_index_type i=0; i < size; i++)
- {
- if(PyTuple_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1)
- {
- throw Exception();
- }
- }
- }
- // Tuple from any sequence
- explicit Tuple (const Sequence& s)
- {
- sequence_index_type limit( sequence_index_type( s.length() ) );
-
- set(PyTuple_New (limit), true);
- validate();
-
- for(sequence_index_type i=0; i < limit; i++)
- {
- if(PyTuple_SetItem (ptr(), i, new_reference_to(s[i])) == -1)
- {
- throw Exception();
- }
- }
- }
- // Assignment acquires new ownership of pointer
-
- Tuple& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Tuple& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Tuple_Check (pyob);
- }
-
- Tuple getSlice (int i, int j) const
- {
- return Tuple (PySequence_GetSlice (ptr(), i, j), true);
- }
-
- };
-
- // ==================================================
- // class List
-
- class List: public Sequence
- {
- public:
- // Constructor
- explicit List (PyObject *pyob, bool owned = false): Sequence(pyob, owned)
- {
- validate();
- }
- List (const Object& ob): Sequence(ob)
- {
- validate();
- }
- // Creation at a fixed size
- List (int size = 0)
- {
- set(PyList_New (size), true);
- validate();
- for (sequence_index_type i=0; i < size; i++)
- {
- if(PyList_SetItem (ptr(), i, new_reference_to(Py::_None())) == -1)
- {
- throw Exception();
- }
- }
- }
-
- // List from a sequence
- List (const Sequence& s): Sequence()
- {
- int n = s.length();
- set(PyList_New (n), true);
- validate();
- for (sequence_index_type i=0; i < n; i++)
- {
- if(PyList_SetItem (ptr(), i, new_reference_to(s[i])) == -1)
- {
- throw Exception();
- }
- }
- }
-
- virtual size_type capacity() const
- {
- return max_size();
- }
- // Assignment acquires new ownership of pointer
-
- List& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- List& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_List_Check (pyob);
- }
-
- List getSlice (int i, int j) const
- {
- return List (PyList_GetSlice (ptr(), i, j), true);
- }
-
- void setSlice (int i, int j, const Object& v)
- {
- if(PyList_SetSlice (ptr(), i, j, *v) == -1)
- {
- throw Exception();
- }
- }
-
- void append (const Object& ob)
- {
- if(PyList_Append (ptr(), *ob) == -1)
- {
- throw Exception();
- }
- }
-
- void insert (int i, const Object& ob)
- {
- if(PyList_Insert (ptr(), i, *ob) == -1)
- {
- throw Exception();
- }
- }
-
- void sort ()
- {
- if(PyList_Sort(ptr()) == -1)
- {
- throw Exception();
- }
- }
-
- void reverse ()
- {
- if(PyList_Reverse(ptr()) == -1)
- {
- throw Exception();
- }
- }
- };
-
-
- // Mappings
- // ==================================================
- template<typename T>
- class mapref
- {
- protected:
- MapBase<T>& s; // the map
- Object key; // item key
- T the_item;
-
- public:
- mapref<T> (MapBase<T>& map, const std::string& k)
- : s(map), the_item()
- {
- key = String(k);
- if(map.hasKey(key)) the_item = map.getItem(key);
- };
-
- mapref<T> (MapBase<T>& map, const Object& k)
- : s(map), key(k), the_item()
- {
- if(map.hasKey(key)) the_item = map.getItem(key);
- };
-
- ~mapref()
- {}
-
- // MapBase<T> stuff
- // lvalue
- mapref<T>& operator=(const mapref<T>& other)
- {
- if(this == &other) return *this;
- the_item = other.the_item;
- s.setItem(key, other.the_item);
- return *this;
- };
-
- mapref<T>& operator= (const T& ob)
- {
- the_item = ob;
- s.setItem (key, ob);
- return *this;
- }
-
- // rvalue
- operator T() const
- {
- return the_item;
- }
-
- // forward everything else to the_item
- PyObject* ptr () const
- {
- return the_item.ptr();
- }
-
- int reference_count () const
- { // the mapref count
- return the_item.reference_count();
- }
-
- Type type () const
- {
- return the_item.type();
- }
-
- String str () const
- {
- return the_item.str();
- }
-
- String repr () const
- {
- return the_item.repr();
- }
-
- bool hasAttr (const std::string& attr_name) const
- {
- return the_item.hasAttr(attr_name);
- }
-
- Object getAttr (const std::string& attr_name) const
- {
- return the_item.getAttr(attr_name);
- }
-
- Object getItem (const Object& k) const
- {
- return the_item.getItem(k);
- }
-
- long hashValue () const
- {
- return the_item.hashValue();
- }
-
- bool isCallable () const
- {
- return the_item.isCallable();
- }
-
- bool isList () const
- {
- return the_item.isList();
- }
-
- bool isMapping () const
- {
- return the_item.isMapping();
- }
-
- bool isNumeric () const
- {
- return the_item.isNumeric();
- }
-
- bool isSequence () const
- {
- return the_item.isSequence();
- }
-
- bool isTrue () const
- {
- return the_item.isTrue();
- }
-
- bool isType (const Type& t) const
- {
- return the_item.isType (t);
- }
-
- bool isTuple() const
- {
- return the_item.isTuple();
- }
-
- bool isString() const
- {
- return the_item.isString();
- }
-
- // Commands
- void setAttr (const std::string& attr_name, const Object& value)
- {
- the_item.setAttr(attr_name, value);
- }
-
- void delAttr (const std::string& attr_name)
- {
- the_item.delAttr(attr_name);
- }
-
- void delItem (const Object& k)
- {
- the_item.delItem(k);
- }
- }; // end of mapref
-
- // TMM: now for mapref<T>
- template< class T >
- bool operator==(const mapref<T>& left, const mapref<T>& right)
- {
- return true; // NOT completed.
- }
-
- template< class T >
- bool operator!=(const mapref<T>& left, const mapref<T>& right)
- {
- return true; // not completed.
- }
-
- template<typename T>
- class MapBase: public Object
- {
- protected:
- explicit MapBase<T>()
- {}
- public:
- // reference: proxy class for implementing []
- // TMM: 26Jun'01 - the types
- // If you assume that Python mapping is a hash_map...
- // hash_map::value_type is not assignable, but
- // (*it).second = data must be a valid expression
- typedef size_t size_type;
- typedef Object key_type;
- typedef mapref<T> data_type;
- typedef std::pair< const T, T > value_type;
- typedef std::pair< const T, mapref<T> > reference;
- typedef const std::pair< const T, const T > const_reference;
- typedef std::pair< const T, mapref<T> > pointer;
-
- // Constructor
- explicit MapBase<T> (PyObject *pyob, bool owned = false): Object(pyob, owned)
- {
- validate();
- }
-
- // TMM: 02Jul'01 - changed MapBase<T> to Object in next line
- MapBase<T> (const Object& ob): Object(ob)
- {
- validate();
- }
-
- // Assignment acquires new ownership of pointer
- MapBase<T>& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- MapBase<T>& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && PyMapping_Check(pyob);
- }
-
- // Clear -- PyMapping Clear is missing
- //
-
- void clear ()
- {
- List k = keys();
- for(List::iterator i = k.begin(); i != k.end(); i++)
- {
- delItem(*i);
- }
- }
-
- virtual size_type size() const
- {
- return PyMapping_Length (ptr());
- }
-
- // Element Access
- T operator[](const std::string& key) const
- {
- return getItem(key);
- }
-
- T operator[](const Object& key) const
- {
- return getItem(key);
- }
-
- mapref<T> operator[](const std::string& key)
- {
- return mapref<T>(*this, key);
- }
-
- mapref<T> operator[](const Object& key)
- {
- return mapref<T>(*this, key);
- }
-
- int length () const
- {
- return PyMapping_Length (ptr());
- }
-
- bool hasKey (const std::string& s) const
- {
- return PyMapping_HasKeyString (ptr(),const_cast<char*>(s.c_str())) != 0;
- }
-
- bool hasKey (const Object& s) const
- {
- return PyMapping_HasKey (ptr(), s.ptr()) != 0;
- }
-
- T getItem (const std::string& s) const
- {
- return T(
- asObject(PyMapping_GetItemString (ptr(),const_cast<char*>(s.c_str())))
- );
- }
-
- T getItem (const Object& s) const
- {
- return T(
- asObject(PyObject_GetItem (ptr(), s.ptr()))
- );
- }
-
- virtual void setItem (const char *s, const Object& ob)
- {
- if (PyMapping_SetItemString (ptr(), const_cast<char*>(s), *ob) == -1)
- {
- throw Exception();
- }
- }
-
- virtual void setItem (const std::string& s, const Object& ob)
- {
- if (PyMapping_SetItemString (ptr(), const_cast<char*>(s.c_str()), *ob) == -1)
- {
- throw Exception();
- }
- }
-
- virtual void setItem (const Object& s, const Object& ob)
- {
- if (PyObject_SetItem (ptr(), s.ptr(), ob.ptr()) == -1)
- {
- throw Exception();
- }
- }
-
- void delItem (const std::string& s)
- {
- if (PyMapping_DelItemString (ptr(), const_cast<char*>(s.c_str())) == -1)
- {
- throw Exception();
- }
- }
-
- void delItem (const Object& s)
- {
- if (PyMapping_DelItem (ptr(), *s) == -1)
- {
- throw Exception();
- }
- }
- // Queries
- List keys () const
- {
- return List(PyMapping_Keys(ptr()), true);
- }
-
- List values () const
- { // each returned item is a (key, value) pair
- return List(PyMapping_Values(ptr()), true);
- }
-
- List items () const
- {
- return List(PyMapping_Items(ptr()), true);
- }
-
- // iterators for MapBase<T>
- // Added by TMM: 2Jul'01 - NOT COMPLETED
- // There is still a bug. I decided to stop, before fixing the bug, because
- // this can't be halfway efficient until Python gets built-in iterators.
- // My current soln is to iterate over the map by getting a copy of its keys
- // and iterating over that. Not a good solution.
-
- // The iterator holds a MapBase<T>* rather than a MapBase<T> because that's
- // how the sequence iterator is implemented and it works. But it does seem
- // odd to me - we are iterating over the map object, not the reference.
-
-#if 0 // here is the test code with which I found the (still existing) bug
- typedef cxx::Dict d_t;
- d_t d;
- cxx::String s1("blah");
- cxx::String s2("gorf");
- d[ "one" ] = s1;
- d[ "two" ] = s1;
- d[ "three" ] = s2;
- d[ "four" ] = s2;
-
- d_t::iterator it;
- it = d.begin(); // this (using the assignment operator) is causing
- // a problem; if I just use the copy ctor it works fine.
- for( ; it != d.end(); ++it )
- {
- d_t::value_type vt( *it );
- cxx::String rs = vt.second.repr();
- std::string ls = rs.operator std::string();
- fprintf( stderr, "%s\n", ls );
- }
-#endif // 0
-
- class iterator
- {
- // : public forward_iterator_parent( std::pair<const T,T> ) {
- protected:
- typedef std::forward_iterator_tag iterator_category;
- typedef std::pair< const T, T > value_type;
- typedef int difference_type;
- typedef std::pair< const T, mapref<T> > pointer;
- typedef std::pair< const T, mapref<T> > reference;
-
- friend class MapBase<T>;
- //
- MapBase<T>* map;
- List keys; // for iterating over the map
- List::iterator pos; // index into the keys
-
- public:
- ~iterator ()
- {}
-
- iterator ()
- : map( 0 )
- , keys()
- , pos()
- {}
-
- iterator (MapBase<T>* m, bool end = false )
- : map( m )
- , keys( m->keys() )
- , pos( end ? keys.end() : keys.begin() )
- {}
-
- iterator (const iterator& other)
- : map( other.map )
- , keys( other.keys )
- , pos( other.pos )
- {}
-
- reference operator*()
- {
- Object key = *pos;
- return std::make_pair(key, mapref<T>(*map,key));
- }
-
- iterator& operator=(const iterator& other)
- {
- if (this == &other)
- return *this;
- map = other.map;
- keys = other.keys;
- pos = other.pos;
- return *this;
- }
-
- bool eql(const iterator& right) const
- {
- return *map == *right.map && pos == right.pos;
- }
- bool neq( const iterator& right ) const
- {
- return *map != *right.map || pos != right.pos;
- }
-
- // pointer operator->() {
- // return ;
- // }
-
- // prefix ++
- iterator& operator++ ()
- { pos++; return *this;}
- // postfix ++
- iterator operator++ (int)
- { return iterator(map, keys, pos++);}
- // prefix --
- iterator& operator-- ()
- { pos--; return *this;}
- // postfix --
- iterator operator-- (int)
- { return iterator(map, keys, pos--);}
-
- std::string diagnose() const
- {
- std::ostringstream oss;
- oss << "iterator diagnosis " << map << ", " << pos << std::ends;
- return std::string(oss.str());
- }
- }; // end of class MapBase<T>::iterator
-
- iterator begin ()
- {
- return iterator(this);
- }
-
- iterator end ()
- {
- return iterator(this, true);
- }
-
- class const_iterator
- {
- protected:
- typedef std::forward_iterator_tag iterator_category;
- typedef const std::pair< const T, T > value_type;
- typedef int difference_type;
- typedef const std::pair< const T, T > pointer;
- typedef const std::pair< const T, T > reference;
-
- friend class MapBase<T>;
- const MapBase<T>* map;
- List keys; // for iterating over the map
- List::iterator pos; // index into the keys
-
- public:
- ~const_iterator ()
- {}
-
- const_iterator ()
- : map( 0 )
- , keys()
- , pos()
- {}
-
- const_iterator (const MapBase<T>* m, List k, List::iterator p )
- : map( m )
- , keys( k )
- , pos( p )
- {}
-
- const_iterator(const const_iterator& other)
- : map( other.map )
- , keys( other.keys )
- , pos( other.pos )
- {}
-
- bool eql(const const_iterator& right) const
- {
- return *map == *right.map && pos == right.pos;
- }
- bool neq( const const_iterator& right ) const
- {
- return *map != *right.map || pos != right.pos;
- }
-
-
- // const_reference operator*() {
- // Object key = *pos;
- // return std::make_pair( key, map->[key] );
- // GCC < 3 barfes on this line at the '['.
- // }
-
- const_iterator& operator=(const const_iterator& other)
- {
- if (this == &other) return *this;
- map = other.map;
- keys = other.keys;
- pos = other.pos;
- return *this;
- }
-
- // prefix ++
- const_iterator& operator++ ()
- { pos++; return *this;}
- // postfix ++
- const_iterator operator++ (int)
- { return const_iterator(map, keys, pos++);}
- // prefix --
- const_iterator& operator-- ()
- { pos--; return *this;}
- // postfix --
- const_iterator operator-- (int)
- { return const_iterator(map, keys, pos--);}
- }; // end of class MapBase<T>::const_iterator
-
- const_iterator begin () const
- {
- return const_iterator(this, 0);
- }
-
- const_iterator end () const
- {
- return const_iterator(this, length());
- }
-
- }; // end of MapBase<T>
-
- typedef MapBase<Object> Mapping;
-
- template <typename T> bool operator==(const typename MapBase<T>::iterator& left, const typename MapBase<T>::iterator& right);
- template <typename T> bool operator!=(const typename MapBase<T>::iterator& left, const typename MapBase<T>::iterator& right);
- template <typename T> bool operator==(const typename MapBase<T>::const_iterator& left, const typename MapBase<T>::const_iterator& right);
- template <typename T> bool operator!=(const typename MapBase<T>::const_iterator& left, const typename MapBase<T>::const_iterator& right);
-
- extern bool operator==(const Mapping::iterator& left, const Mapping::iterator& right);
- extern bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right);
- extern bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right);
- extern bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right);
-
-
- // ==================================================
- // class Dict
- class Dict: public Mapping
- {
- public:
- // Constructor
- explicit Dict (PyObject *pyob, bool owned=false): Mapping (pyob, owned)
- {
- validate();
- }
- Dict (const Dict& ob): Mapping(ob)
- {
- validate();
- }
- // Creation
- Dict ()
- {
- set(PyDict_New (), true);
- validate();
- }
- // Assignment acquires new ownership of pointer
-
- Dict& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Dict& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set(rhsp);
- return *this;
- }
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && Py::_Dict_Check (pyob);
- }
- };
-
- class Callable: public Object
- {
- protected:
- explicit Callable (): Object()
- {}
- public:
- // Constructor
- explicit Callable (PyObject *pyob, bool owned = false): Object (pyob, owned)
- {
- validate();
- }
-
- Callable (const Object& ob): Object(ob)
- {
- validate();
- }
-
- // Assignment acquires new ownership of pointer
-
- Callable& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Callable& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set (rhsp);
- return *this;
- }
-
- // Membership
- virtual bool accepts (PyObject *pyob) const
- {
- return pyob && PyCallable_Check (pyob);
- }
-
- // Call
- Object apply(const Tuple& args) const
- {
- return asObject(PyObject_CallObject(ptr(), args.ptr()));
- }
-
- // Call with keywords
- Object apply(const Tuple& args, const Dict& kw) const
- {
- return asObject( PyEval_CallObjectWithKeywords( ptr(), args.ptr(), kw.ptr() ) );
- }
-
- Object apply(PyObject* pargs = 0) const
- {
- return apply (Tuple(pargs));
- }
- };
-
- class Module: public Object
- {
- public:
- explicit Module (PyObject* pyob, bool owned = false): Object (pyob, owned)
- {
- validate();
- }
-
- // Construct from module name
- explicit Module (const std::string&s): Object()
- {
- PyObject *m = PyImport_AddModule( const_cast<char *>(s.c_str()) );
- set( m, false );
- validate ();
- }
-
- // Copy constructor acquires new ownership of pointer
- Module (const Module& ob): Object(*ob)
- {
- validate();
- }
-
- Module& operator= (const Object& rhs)
- {
- return (*this = *rhs);
- }
-
- Module& operator= (PyObject* rhsp)
- {
- if(ptr() == rhsp) return *this;
- set(rhsp);
- return *this;
- }
-
- Dict getDict()
- {
- return Dict(PyModule_GetDict(ptr()));
- // Caution -- PyModule_GetDict returns borrowed reference!
- }
- };
-
- // Numeric interface
- inline Object operator+ (const Object& a)
- {
- return asObject(PyNumber_Positive(*a));
- }
- inline Object operator- (const Object& a)
- {
- return asObject(PyNumber_Negative(*a));
- }
-
- inline Object abs(const Object& a)
- {
- return asObject(PyNumber_Absolute(*a));
- }
-
- inline std::pair<Object,Object> coerce(const Object& a, const Object& b)
- {
- PyObject *p1, *p2;
- p1 = *a;
- p2 = *b;
- if(PyNumber_Coerce(&p1,&p2) == -1)
- {
- throw Exception();
- }
- return std::pair<Object,Object>(asObject(p1), asObject(p2));
- }
-
- inline Object operator+ (const Object& a, const Object& b)
- {
- return asObject(PyNumber_Add(*a, *b));
- }
- inline Object operator+ (const Object& a, int j)
- {
- return asObject(PyNumber_Add(*a, *Int(j)));
- }
- inline Object operator+ (const Object& a, double v)
- {
- return asObject(PyNumber_Add(*a, *Float(v)));
- }
- inline Object operator+ (int j, const Object& b)
- {
- return asObject(PyNumber_Add(*Int(j), *b));
- }
- inline Object operator+ (double v, const Object& b)
- {
- return asObject(PyNumber_Add(*Float(v), *b));
- }
-
- inline Object operator- (const Object& a, const Object& b)
- {
- return asObject(PyNumber_Subtract(*a, *b));
- }
- inline Object operator- (const Object& a, int j)
- {
- return asObject(PyNumber_Subtract(*a, *Int(j)));
- }
- inline Object operator- (const Object& a, double v)
- {
- return asObject(PyNumber_Subtract(*a, *Float(v)));
- }
- inline Object operator- (int j, const Object& b)
- {
- return asObject(PyNumber_Subtract(*Int(j), *b));
- }
- inline Object operator- (double v, const Object& b)
- {
- return asObject(PyNumber_Subtract(*Float(v), *b));
- }
-
- inline Object operator* (const Object& a, const Object& b)
- {
- return asObject(PyNumber_Multiply(*a, *b));
- }
- inline Object operator* (const Object& a, int j)
- {
- return asObject(PyNumber_Multiply(*a, *Int(j)));
- }
- inline Object operator* (const Object& a, double v)
- {
- return asObject(PyNumber_Multiply(*a, *Float(v)));
- }
- inline Object operator* (int j, const Object& b)
- {
- return asObject(PyNumber_Multiply(*Int(j), *b));
- }
- inline Object operator* (double v, const Object& b)
- {
- return asObject(PyNumber_Multiply(*Float(v), *b));
- }
-
- inline Object operator/ (const Object& a, const Object& b)
- {
- return asObject(PyNumber_Divide(*a, *b));
- }
- inline Object operator/ (const Object& a, int j)
- {
- return asObject(PyNumber_Divide(*a, *Int(j)));
- }
- inline Object operator/ (const Object& a, double v)
- {
- return asObject(PyNumber_Divide(*a, *Float(v)));
- }
- inline Object operator/ (int j, const Object& b)
- {
- return asObject(PyNumber_Divide(*Int(j), *b));
- }
- inline Object operator/ (double v, const Object& b)
- {
- return asObject(PyNumber_Divide(*Float(v), *b));
- }
-
- inline Object operator% (const Object& a, const Object& b)
- {
- return asObject(PyNumber_Remainder(*a, *b));
- }
- inline Object operator% (const Object& a, int j)
- {
- return asObject(PyNumber_Remainder(*a, *Int(j)));
- }
- inline Object operator% (const Object& a, double v)
- {
- return asObject(PyNumber_Remainder(*a, *Float(v)));
- }
- inline Object operator% (int j, const Object& b)
- {
- return asObject(PyNumber_Remainder(*Int(j), *b));
- }
- inline Object operator% (double v, const Object& b)
- {
- return asObject(PyNumber_Remainder(*Float(v), *b));
- }
-
- inline Object type(const Exception&) // return the type of the error
- {
- PyObject *ptype, *pvalue, *ptrace;
- PyErr_Fetch(&ptype, &pvalue, &ptrace);
- Object result(ptype);
- PyErr_Restore(ptype, pvalue, ptrace);
- return result;
- }
-
- inline Object value(const Exception&) // return the value of the error
- {
- PyObject *ptype, *pvalue, *ptrace;
- PyErr_Fetch(&ptype, &pvalue, &ptrace);
- Object result;
- if(pvalue) result = pvalue;
- PyErr_Restore(ptype, pvalue, ptrace);
- return result;
- }
-
- inline Object trace(const Exception&) // return the traceback of the error
- {
- PyObject *ptype, *pvalue, *ptrace;
- PyErr_Fetch(&ptype, &pvalue, &ptrace);
- Object result;
- if(ptrace) result = ptrace;
- PyErr_Restore(ptype, pvalue, ptrace);
- return result;
- }
-
-
-
-template<typename T>
-String seqref<T>::str () const
- {
- return the_item.str();
- }
-
-template<typename T>
-String seqref<T>::repr () const
- {
- return the_item.repr();
- }
-
-
- } // namespace Py
-#endif // __CXX_Objects__h
diff --git a/lib/kross/python/cxx/PyCXX.html b/lib/kross/python/cxx/PyCXX.html
index 566974c14..0c7172a1a 100644
--- a/lib/kross/python/cxx/PyCXX.html
+++ b/lib/kross/python/cxx/PyCXX.html
@@ -83,7 +83,7 @@ Unix: <cite>/usr/local/PyCXX</cite>
Windows: <cite>cl /I=C:\PyCXX ...</cite><br>
Unix: <cite>g++ -I/usr/local/PyCXX ...</cite>
<li>Include PyCXX headers files in your code using the CXX prefix:<br>
-<cite>#include &quot;CXX/Object.hxx&quot;</cite>
+<cite>#include &quot;CXX/Object.h&quot;</cite>
</ul>
<p>The header file CXX/config.h may need to be adjusted for the
@@ -100,7 +100,7 @@ the Py:: prefix when referring to them, or include the statement:</p>
<h2>Wrappers for standard objects: CXX_Objects.h</h2>
-<p>Header file CXX_Objects.h requires adding file Src/cxxsupport.cxx to
+<p>Header file CXX_Objects.h requires adding file Src/cxxsupport.cpp to
your module sources. CXX_Objects provides a set of wrapper classes that allow you access
to most of the Python C API using a C++ notation that closely resembles Python. For
example, this Python:</p>
@@ -121,7 +121,7 @@ alist = d.keys();
std::cout &lt;&lt; alist &lt;&lt; std::endl;
</pre>
-<p>You can optionally use the CXX/Extensions.hxx facility described later
+<p>You can optionally use the CXX/Extensions.h facility described later
to define Python extension modules and extension objects.</p>
<h3>We avoid programming with Python object pointers</h3>
@@ -165,8 +165,8 @@ integer argument, that will create a Python <cite>dict</cite>
<p>If you have written a significant Python extension, this tedium looks all too familiar.
The vast bulk of the coding is error checking and cleanup. Now compare the same thing
-written in C++ using CXX/Objects.hxx. The things with Python-like names (Int, Dict, Tuple) are
-from CXX/Objects.hxx.</p>
+written in C++ using CXX/Objects.h. The things with Python-like names (Int, Dict, Tuple) are
+from CXX/Objects.h.</p>
<pre>static PyObject* mymodule_addvalue (PyObject* self, PyObject* pargs)
{
@@ -211,7 +211,7 @@ Object addvalue (Object &amp; self, const Tuple &amp; args)
<h2>The basic concept is to wrap Python pointers</h2>
-<p>The basic concept of CXX/Objects.hxx is to create a wrapper around
+<p>The basic concept of CXX/Objects.h is to create a wrapper around
each <cite>PyObject *</cite> so that the reference counting can be
done automatically, thus eliminating the most frequent source of errors. In addition, we
can then add methods and operators so that Python objects can be manipulated in C++
@@ -223,7 +223,7 @@ the pointer. Since C++ calls the destructors on objects that are about to go out
we are guaranteed that we will keep the reference counts right even if we unexpectedly
leave a routine with an exception.</p>
-<p>As a matter of philosophy, CXX/Objects.hxx prevents the creation of instances of its
+<p>As a matter of philosophy, CXX/Objects.h prevents the creation of instances of its
classes unless the instance will be a valid instance of its class. When an attempt is made
to create an object that will not be valid, an exception is thrown.</p>
@@ -1713,17 +1713,17 @@ Exception to clear it.:</p>
<h2>Extension Facilities</h2>
-<p>CXX/Extensions.hxx provides facilities for:
+<p>CXX/Extensions.h provides facilities for:
<ul>
<li>Creating a Python extension module</li>
<li>Creating new Python extension types</li>
</ul>
-<p>These facilities use CXX/Objects.hxx and its support file cxxsupport.cxx.</p>
+<p>These facilities use CXX/Objects.h and its support file cxxsupport.cpp.</p>
-<p>If you use CXX/Extensions.hxx you must also include source files cxxextensions.c and
-cxx_extensions.cxx</p>
+<p>If you use CXX/Extensions.h you must also include source files cxxextensions.c and
+cxx_extensions.cpp</p>
<h3>Creating an Python extension module</h3>
@@ -1745,7 +1745,7 @@ details are necessary:
<p>To create an extension module, you inherit from class ExtensionModule templated on
yourself: In the constructor, you make calls to register methods of this class with Python
as extension module methods. In this example, two methods are added (this is a simplified
-form of the example in Demo/example.cxx):</p>
+form of the example in Demo/example.cpp):</p>
<pre>class example_module : public ExtensionModule&lt;example_module&gt;
{
@@ -1859,7 +1859,7 @@ addresses of functions can be added in order to give the object the desired beha
<p>Creating extension objects is of course harder since you must specify
how the object behaves and give it methods. This is shown in some detail in the example
-range.h and range.cxx, with the test routine rangetest.cxx, in directory Demo. If you have never
+range.h and range.cpp, with the test routine rangetest.cpp, in directory Demo. If you have never
created a Python extension before, you should read the Extension manual first and be very
familiar with Python's &quot;special class methods&quot;. Then what follows will make more
sense.</p>
diff --git a/lib/kross/python/cxx/README.html b/lib/kross/python/cxx/README.html
index d698725a2..b29f5b159 100644
--- a/lib/kross/python/cxx/README.html
+++ b/lib/kross/python/cxx/README.html
@@ -176,8 +176,8 @@ is not compiled and linked to support C and C++.</p>
<p>New in this release:</p>
<ul>
<li>Support for the Windows Linker /DELAYLOAD feature. Enable this feature by
-defining PY_WIN32_DELAYLOAD_PYTHON_DLL when compiling IndirectPythonInterface.cxx
-<li>Remove "CXX/Array.hxx" and associated code - its does not belong in PyCXX
+defining PY_WIN32_DELAYLOAD_PYTHON_DLL when compiling IndirectPythonInterface.cpp
+<li>Remove "CXX/Array.h" and associated code - its does not belong in PyCXX
<li>Work on the docs. Mostly to clean up the HTML to allow more extensive work.
<li>Reformated the sources to a consistent style. The mix of styles and tabs sizes
was making working on the sources error prone.
@@ -193,10 +193,10 @@ C++ header files.
<p>
<table cellspacing=0 cellpadding=3px>
<tr><th>Old</th><th>New</th></tr>
-<tr><td>#include "CXX_Config.h"</td><td>#include "CXX/Config.hxx"</td>
-<tr><td>#include "CXX_Exception.h"</td><td>#include "CXX/Exception.hxx"</td>
-<tr><td>#include "CXX_Extensions.h"</td><td>#include "CXX/Extensions.hxx"</td>
-<tr><td>#include "CXX_Objects.h"</td><td>#include "CXX/Objects.hxx"</td>
+<tr><td>#include "CXX_Config.h"</td><td>#include "CXX/Config.h"</td>
+<tr><td>#include "CXX_Exception.h"</td><td>#include "CXX/Exception.h"</td>
+<tr><td>#include "CXX_Extensions.h"</td><td>#include "CXX/Extensions.h"</td>
+<tr><td>#include "CXX_Objects.h"</td><td>#include "CXX/Objects.h"</td>
</table>
<h3>Version 5 (May 18, 2000)</h3>
@@ -254,7 +254,7 @@ coding so much that we think it is worth the disruption.</p>
<p>To create an extension module, you inherit from class ExtensionModule templated on
yourself: In the constructor, you make calls to register methods of this class with Python
as extension module methods. In this example, two methods are added (this is a simplified
-form of the example in Demo/example.cxx):</p>
+form of the example in Demo/example.cpp):</p>
<pre>class example_module : public ExtensionModule&lt;example_module&gt;
{
@@ -309,8 +309,8 @@ return its dictionary.</p>
<h4>Creating extension objects</h4>
<p>Creating extension objects is of course harder since you must specify how the object
-behaves and give it methods. This is shown in some detail in the example range.h and range.cxx,
-with the test routine rangetest.cxx, in directory Demo.</p>
+behaves and give it methods. This is shown in some detail in the example range.h and range.cpp,
+with the test routine rangetest.cpp, in directory Demo.</p>
<p>Here is a brief overview. You create a class that inherits from PythonExtension
templated upon itself. You override various methods from PythonExtension to implement
@@ -426,8 +426,8 @@ setenv CCC &quot;KCC -x&quot;
<p>before running makethis.py.</p>
-<p>There is also a python.cxx file for making a stand-alone Python containing this
-example, as well as a similar file arraytest.cxx for testing Array.</p>
+<p>There is also a python.cpp file for making a stand-alone Python containing this
+example, as well as a similar file arraytest.cpp for testing Array.</p>
<p>Comments to barry@barrys-emacs.org, please.</p>
diff --git a/lib/kross/python/cxx/cxx_extensions.cpp b/lib/kross/python/cxx/cxx_extensions.cpp
new file mode 100644
index 000000000..6bbe12785
--- /dev/null
+++ b/lib/kross/python/cxx/cxx_extensions.cpp
@@ -0,0 +1,1287 @@
+#include "Extensions.h"
+#include "Exception.h"
+
+#include <assert.h>
+
+namespace Py
+{
+
+//================================================================================
+//
+// Implementation of MethodTable
+//
+//================================================================================
+
+PyMethodDef MethodTable::method( const char* method_name, PyCFunction f, int flags, const char* doc )
+ {
+ PyMethodDef m;
+ m.ml_name = const_cast<char*>( method_name );
+ m.ml_meth = f;
+ m.ml_flags = flags;
+ m.ml_doc = const_cast<char*>( doc );
+ return m;
+ }
+
+MethodTable::MethodTable()
+ {
+ t.push_back( method( 0, 0, 0, 0 ) );
+ mt = 0;
+ }
+
+MethodTable::~MethodTable()
+ {
+ delete [] mt;
+ }
+
+void MethodTable::add( const char* method_name, PyCFunction f, const char* doc, int flag )
+ {
+ if( !mt )
+ {
+ t.insert( t.end()-1, method( method_name, f, flag, doc ) );
+ }
+ else
+ {
+ throw RuntimeError( "Too late to add a module method!" );
+ }
+ }
+
+PyMethodDef* MethodTable::table()
+ {
+ if( !mt )
+ {
+ int t1size = t.size();
+ mt = new PyMethodDef[t1size];
+ int j = 0;
+ for( std::vector<PyMethodDef>::iterator i = t.begin(); i != t.end(); i++ )
+ {
+ mt[j++] = *i;
+ }
+ }
+ return mt;
+ }
+
+//================================================================================
+//
+// Implementation of ExtensionModule
+//
+//================================================================================
+ExtensionModuleBase::ExtensionModuleBase( const char *name )
+ : module_name( name )
+ , full_module_name( __Py_PackageContext() != NULL ? std::string( __Py_PackageContext() ) : module_name )
+ , method_table()
+ {}
+
+ExtensionModuleBase::~ExtensionModuleBase()
+ {}
+
+const std::string &ExtensionModuleBase::name() const
+ {
+ return module_name;
+ }
+
+const std::string &ExtensionModuleBase::fullName() const
+ {
+ return full_module_name;
+ }
+
+class ExtensionModuleBasePtr : public PythonExtension<ExtensionModuleBasePtr>
+ {
+public:
+ ExtensionModuleBasePtr( ExtensionModuleBase *_module )
+ : module( _module )
+ {}
+ virtual ~ExtensionModuleBasePtr()
+ {}
+
+ ExtensionModuleBase *module;
+ };
+
+
+void ExtensionModuleBase::initialize( const char *module_doc )
+ {
+ PyObject *module_ptr = new ExtensionModuleBasePtr( this );
+
+ Py_InitModule4
+ (
+ const_cast<char *>( module_name.c_str() ), // name
+ method_table.table(), // methods
+ const_cast<char *>( module_doc ), // docs
+ module_ptr, // pass to functions as "self"
+ PYTHON_API_VERSION // API version
+ );
+ }
+
+Py::Module ExtensionModuleBase::module(void) const
+ {
+ return Module( full_module_name );
+ }
+
+Py::Dict ExtensionModuleBase::moduleDictionary(void) const
+ {
+ return module().getDict();
+ }
+
+//--------------------------------------------------------------------------------
+
+//================================================================================
+//
+// Implementation of PythonType
+//
+//================================================================================
+
+extern "C"
+ {
+ static void standard_dealloc(PyObject* p);
+ //
+ // All the following functions redirect the call from Python
+ // onto the matching virtual function in PythonExtensionBase
+ //
+ static int print_handler (PyObject*, FILE *, int);
+ static PyObject* getattr_handler (PyObject*, char*);
+ static int setattr_handler (PyObject*, char*, PyObject*);
+ static PyObject* getattro_handler (PyObject*, PyObject*);
+ static int setattro_handler (PyObject*, PyObject*, PyObject*);
+ static int compare_handler (PyObject*, PyObject*);
+ static PyObject* repr_handler (PyObject*);
+ static PyObject* str_handler (PyObject*);
+ static long hash_handler (PyObject*);
+ static PyObject* call_handler (PyObject*, PyObject*, PyObject*);
+
+#if PY_VERSION_HEX < 0x02050000
+ typedef int Py_ssize_t;
+#endif
+ // Sequence methods
+ static Py_ssize_t sequence_length_handler(PyObject*);
+ static PyObject* sequence_concat_handler(PyObject*,PyObject*);
+ static PyObject* sequence_repeat_handler(PyObject*, Py_ssize_t);
+ static PyObject* sequence_item_handler(PyObject*, Py_ssize_t);
+ static PyObject* sequence_slice_handler(PyObject*, Py_ssize_t, Py_ssize_t);
+ static int sequence_ass_item_handler(PyObject*, Py_ssize_t, PyObject*);
+ static int sequence_ass_slice_handler(PyObject*, Py_ssize_t, Py_ssize_t, PyObject*);
+ // Mapping
+ static Py_ssize_t mapping_length_handler(PyObject*);
+ static PyObject* mapping_subscript_handler(PyObject*, PyObject*);
+ static int mapping_ass_subscript_handler(PyObject*, PyObject*, PyObject*);
+
+ // Numeric methods
+ static int number_nonzero_handler (PyObject*);
+ static PyObject* number_negative_handler (PyObject*);
+ static PyObject* number_positive_handler (PyObject*);
+ static PyObject* number_absolute_handler (PyObject*);
+ static PyObject* number_invert_handler (PyObject*);
+ static PyObject* number_int_handler (PyObject*);
+ static PyObject* number_float_handler (PyObject*);
+ static PyObject* number_long_handler (PyObject*);
+ static PyObject* number_oct_handler (PyObject*);
+ static PyObject* number_hex_handler (PyObject*);
+ static PyObject* number_add_handler (PyObject*, PyObject*);
+ static PyObject* number_subtract_handler (PyObject*, PyObject*);
+ static PyObject* number_multiply_handler (PyObject*, PyObject*);
+ static PyObject* number_divide_handler (PyObject*, PyObject*);
+ static PyObject* number_remainder_handler (PyObject*, PyObject*);
+ static PyObject* number_divmod_handler (PyObject*, PyObject*);
+ static PyObject* number_lshift_handler (PyObject*, PyObject*);
+ static PyObject* number_rshift_handler (PyObject*, PyObject*);
+ static PyObject* number_and_handler (PyObject*, PyObject*);
+ static PyObject* number_xor_handler (PyObject*, PyObject*);
+ static PyObject* number_or_handler (PyObject*, PyObject*);
+ static PyObject* number_power_handler(PyObject*, PyObject*, PyObject*);
+
+ // Buffer
+ static Py_ssize_t buffer_getreadbuffer_handler (PyObject*, Py_ssize_t, void**);
+ static Py_ssize_t buffer_getwritebuffer_handler (PyObject*, Py_ssize_t, void**);
+ static Py_ssize_t buffer_getsegcount_handler (PyObject*, Py_ssize_t*);
+ }
+
+
+extern "C" void standard_dealloc( PyObject* p )
+ {
+ PyMem_DEL( p );
+ }
+
+void PythonType::supportSequenceType()
+ {
+ if( !sequence_table )
+ {
+ sequence_table = new PySequenceMethods;
+ table->tp_as_sequence = sequence_table;
+ sequence_table->sq_length = sequence_length_handler;
+ sequence_table->sq_concat = sequence_concat_handler;
+ sequence_table->sq_repeat = sequence_repeat_handler;
+ sequence_table->sq_item = sequence_item_handler;
+ sequence_table->sq_slice = sequence_slice_handler;
+
+ sequence_table->sq_ass_item = sequence_ass_item_handler; // BAS setup seperately?
+ sequence_table->sq_ass_slice = sequence_ass_slice_handler; // BAS setup seperately?
+ }
+ }
+
+void PythonType::supportMappingType()
+ {
+ if( !mapping_table )
+ {
+ mapping_table = new PyMappingMethods;
+ table->tp_as_mapping = mapping_table;
+ mapping_table->mp_length = mapping_length_handler;
+ mapping_table->mp_subscript = mapping_subscript_handler;
+ mapping_table->mp_ass_subscript = mapping_ass_subscript_handler; // BAS setup seperately?
+ }
+ }
+
+void PythonType::supportNumberType()
+ {
+ if( !number_table )
+ {
+ number_table = new PyNumberMethods;
+ table->tp_as_number = number_table;
+ number_table->nb_add = number_add_handler;
+ number_table->nb_subtract = number_subtract_handler;
+ number_table->nb_multiply = number_multiply_handler;
+ number_table->nb_divide = number_divide_handler;
+ number_table->nb_remainder = number_remainder_handler;
+ number_table->nb_divmod = number_divmod_handler;
+ number_table->nb_power = number_power_handler;
+ number_table->nb_negative = number_negative_handler;
+ number_table->nb_positive = number_positive_handler;
+ number_table->nb_absolute = number_absolute_handler;
+ number_table->nb_nonzero = number_nonzero_handler;
+ number_table->nb_invert = number_invert_handler;
+ number_table->nb_lshift = number_lshift_handler;
+ number_table->nb_rshift = number_rshift_handler;
+ number_table->nb_and = number_and_handler;
+ number_table->nb_xor = number_xor_handler;
+ number_table->nb_or = number_or_handler;
+ number_table->nb_coerce = 0;
+ number_table->nb_int = number_int_handler;
+ number_table->nb_long = number_long_handler;
+ number_table->nb_float = number_float_handler;
+ number_table->nb_oct = number_oct_handler;
+ number_table->nb_hex = number_hex_handler;
+ }
+ }
+
+void PythonType::supportBufferType()
+ {
+ if( !buffer_table )
+ {
+ buffer_table = new PyBufferProcs;
+ table->tp_as_buffer = buffer_table;
+ buffer_table->bf_getreadbuffer = buffer_getreadbuffer_handler;
+ buffer_table->bf_getwritebuffer = buffer_getwritebuffer_handler;
+ buffer_table->bf_getsegcount = buffer_getsegcount_handler;
+ }
+ }
+
+// if you define one sequence method you must define
+// all of them except the assigns
+
+PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name )
+ : table( new PyTypeObject )
+ , sequence_table( NULL )
+ , mapping_table( NULL )
+ , number_table( NULL )
+ , buffer_table( NULL )
+ {
+ *reinterpret_cast<PyObject*>( table ) = py_object_initializer;
+ table->ob_type = _Type_Type();
+ table->ob_size = 0;
+ table->tp_name = const_cast<char *>( default_name );
+ table->tp_basicsize = basic_size;
+ table->tp_itemsize = itemsize;
+ table->tp_dealloc = ( destructor ) standard_dealloc;
+ table->tp_print = 0;
+ table->tp_getattr = 0;
+ table->tp_setattr = 0;
+ table->tp_compare = 0;
+ table->tp_repr = 0;
+ table->tp_as_number = 0;
+ table->tp_as_sequence = 0;
+ table->tp_as_mapping = 0;
+ table->tp_hash = 0;
+ table->tp_call = 0;
+ table->tp_str = 0;
+ table->tp_getattro = 0;
+ table->tp_setattro = 0;
+ table->tp_as_buffer = 0;
+ table->tp_flags = 0L;
+ table->tp_doc = 0;
+#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 0)
+ // first use in 2.0
+ table->tp_traverse = 0L;
+ table->tp_clear = 0L;
+#else
+ table->tp_xxx5 = 0L;
+ table->tp_xxx6 = 0L;
+#endif
+#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1)
+ // first defined in 2.1
+ table->tp_richcompare = 0L;
+ table->tp_weaklistoffset = 0L;
+#else
+ table->tp_xxx7 = 0L;
+ table->tp_xxx8 = 0L;
+#endif
+
+#ifdef COUNT_ALLOCS
+ table->tp_alloc = 0;
+ table->tp_free = 0;
+ table->tp_maxalloc = 0;
+ table->tp_next = 0;
+#endif
+ }
+
+PythonType::~PythonType( )
+ {
+ delete table;
+ delete sequence_table;
+ delete mapping_table;
+ delete number_table;
+ delete buffer_table;
+ }
+
+PyTypeObject* PythonType::type_object( ) const
+ {return table;}
+
+void PythonType::name( const char* nam )
+ {
+ table->tp_name = const_cast<char *>( nam );
+ }
+
+const char *PythonType::getName() const
+ {
+ return table->tp_name;
+ }
+
+void PythonType::doc( const char* d )
+ {
+ table->tp_doc = const_cast<char *>( d );
+ }
+
+const char *PythonType::getDoc() const
+ {
+ return table->tp_doc;
+ }
+
+void PythonType::dealloc( void( *f )( PyObject* ))
+ {
+ table->tp_dealloc = f;
+ }
+
+void PythonType::supportPrint()
+ {
+ table->tp_print = print_handler;
+ }
+
+void PythonType::supportGetattr()
+ {
+ table->tp_getattr = getattr_handler;
+ }
+
+void PythonType::supportSetattr()
+ {
+ table->tp_setattr = setattr_handler;
+ }
+
+void PythonType::supportGetattro()
+ {
+ table->tp_getattro = getattro_handler;
+ }
+
+void PythonType::supportSetattro()
+ {
+ table->tp_setattro = setattro_handler;
+ }
+
+void PythonType::supportCompare()
+ {
+ table->tp_compare = compare_handler;
+ }
+
+void PythonType::supportRepr()
+ {
+ table->tp_repr = repr_handler;
+ }
+
+void PythonType::supportStr()
+ {
+ table->tp_str = str_handler;
+ }
+
+void PythonType::supportHash()
+ {
+ table->tp_hash = hash_handler;
+ }
+
+void PythonType::supportCall()
+ {
+ table->tp_call = call_handler;
+ }
+
+//--------------------------------------------------------------------------------
+//
+// Handlers
+//
+//--------------------------------------------------------------------------------
+extern "C" int print_handler( PyObject *self, FILE *fp, int flags )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->print( fp, flags );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* getattr_handler( PyObject *self, char *name )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->getattr( name ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" int setattr_handler( PyObject *self, char *name, PyObject *value )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->setattr( name, Py::Object( value ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* getattro_handler( PyObject *self, PyObject *name )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->getattro( Py::Object( name ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" int setattro_handler( PyObject *self, PyObject *name, PyObject *value )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->setattro( Py::Object( name ), Py::Object( value ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" int compare_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->compare( Py::Object( other ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* repr_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->repr() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* str_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->str() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" long hash_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->hash();
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* call_handler( PyObject *self, PyObject *args, PyObject *kw )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) );
+ if( kw != NULL )
+ return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) );
+ else
+ return new_reference_to( p->call( Py::Object( args ), Py::Object() ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+
+// Sequence methods
+extern "C" Py_ssize_t sequence_length_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->sequence_length();
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* sequence_concat_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->sequence_concat( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* sequence_repeat_handler( PyObject *self, Py_ssize_t count )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->sequence_repeat( count ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* sequence_item_handler( PyObject *self, Py_ssize_t index )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->sequence_item( index ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* sequence_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->sequence_slice( first, last ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" int sequence_ass_item_handler( PyObject *self, Py_ssize_t index, PyObject *value )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->sequence_ass_item( index, Py::Object( value ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" int sequence_ass_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *value )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->sequence_ass_slice( first, last, Py::Object( value ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+// Mapping
+extern "C" Py_ssize_t mapping_length_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->mapping_length();
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* mapping_subscript_handler( PyObject *self, PyObject *key )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->mapping_subscript( Py::Object( key ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" int mapping_ass_subscript_handler( PyObject *self, PyObject *key, PyObject *value )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->mapping_ass_subscript( Py::Object( key ), Py::Object( value ) );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+// Number
+extern "C" int number_nonzero_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->number_nonzero();
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_negative_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_negative() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_positive_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_positive() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_absolute_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_absolute() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_invert_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_invert() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_int_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_int() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_float_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_float() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_long_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_long() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_oct_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_oct() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_hex_handler( PyObject *self )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_hex() );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_add_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_add( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_subtract_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_subtract( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_multiply_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_multiply( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_divide_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_divide( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_remainder_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_remainder( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_divmod_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_divmod( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_lshift_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_lshift( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_rshift_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_rshift( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_and_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_and( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_xor_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_xor( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_or_handler( PyObject *self, PyObject *other )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_or( Py::Object( other ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+extern "C" PyObject* number_power_handler( PyObject *self, PyObject *x1, PyObject *x2 )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return new_reference_to( p->number_power( Py::Object( x1 ), Py::Object( x2 ) ) );
+ }
+ catch( Py::Exception & )
+ {
+ return NULL; // indicate error
+ }
+ }
+
+// Buffer
+extern "C" Py_ssize_t buffer_getreadbuffer_handler( PyObject *self, Py_ssize_t index, void **pp )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->buffer_getreadbuffer( index, pp );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" Py_ssize_t buffer_getwritebuffer_handler( PyObject *self, Py_ssize_t index, void **pp )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ return p->buffer_getwritebuffer( index, pp );
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+extern "C" Py_ssize_t buffer_getsegcount_handler( PyObject *self, Py_ssize_t *count )
+ {
+ try
+ {
+ PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
+ int i_count = *count;
+ Py_ssize_t r = p->buffer_getsegcount( &i_count );
+ *count = i_count;
+ return r;
+ }
+ catch( Py::Exception & )
+ {
+ return -1; // indicate error
+ }
+ }
+
+
+//================================================================================
+//
+// Implementation of PythonExtensionBase
+//
+//================================================================================
+#define missing_method( method ) \
+throw RuntimeError( "Extension object does not support method " #method );
+
+PythonExtensionBase::PythonExtensionBase()
+ {
+ }
+
+PythonExtensionBase::~PythonExtensionBase()
+ {
+ assert( ob_refcnt == 0 );
+ }
+
+int PythonExtensionBase::print( FILE *, int )
+ { missing_method( print ); return -1; }
+
+int PythonExtensionBase::setattr( const char*, const Py::Object & )
+ { missing_method( setattr ); return -1; }
+
+Py::Object PythonExtensionBase::getattro( const Py::Object & )
+ { missing_method( getattro ); return Py::Nothing(); }
+
+int PythonExtensionBase::setattro( const Py::Object &, const Py::Object & )
+ { missing_method( setattro ); return -1; }
+
+int PythonExtensionBase::compare( const Py::Object & )
+ { missing_method( compare ); return -1; }
+
+Py::Object PythonExtensionBase::repr()
+ { missing_method( repr ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::str()
+ { missing_method( str ); return Py::Nothing(); }
+
+long PythonExtensionBase::hash()
+ { missing_method( hash ); return -1; }
+
+Py::Object PythonExtensionBase::call( const Py::Object &, const Py::Object & )
+ { missing_method( call ); return Py::Nothing(); }
+
+
+// Sequence methods
+int PythonExtensionBase::sequence_length()
+ { missing_method( sequence_length ); return -1; }
+
+Py::Object PythonExtensionBase::sequence_concat( const Py::Object & )
+ { missing_method( sequence_concat ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::sequence_repeat( int )
+ { missing_method( sequence_repeat ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::sequence_item( int )
+ { missing_method( sequence_item ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::sequence_slice( int, int )
+ { missing_method( sequence_slice ); return Py::Nothing(); }
+
+int PythonExtensionBase::sequence_ass_item( int, const Py::Object & )
+ { missing_method( sequence_ass_item ); return -1; }
+
+int PythonExtensionBase::sequence_ass_slice( int, int, const Py::Object & )
+ { missing_method( sequence_ass_slice ); return -1; }
+
+
+// Mapping
+int PythonExtensionBase::mapping_length()
+ { missing_method( mapping_length ); return -1; }
+
+Py::Object PythonExtensionBase::mapping_subscript( const Py::Object & )
+ { missing_method( mapping_subscript ); return Py::Nothing(); }
+
+int PythonExtensionBase::mapping_ass_subscript( const Py::Object &, const Py::Object & )
+ { missing_method( mapping_ass_subscript ); return -1; }
+
+
+// Number
+int PythonExtensionBase::number_nonzero()
+ { missing_method( number_nonzero ); return -1; }
+
+Py::Object PythonExtensionBase::number_negative()
+ { missing_method( number_negative ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_positive()
+ { missing_method( number_positive ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_absolute()
+ { missing_method( number_absolute ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_invert()
+ { missing_method( number_invert ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_int()
+ { missing_method( number_int ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_float()
+ { missing_method( number_float ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_long()
+ { missing_method( number_long ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_oct()
+ { missing_method( number_oct ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_hex()
+ { missing_method( number_hex ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_add( const Py::Object & )
+ { missing_method( number_add ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_subtract( const Py::Object & )
+ { missing_method( number_subtract ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_multiply( const Py::Object & )
+ { missing_method( number_multiply ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_divide( const Py::Object & )
+ { missing_method( number_divide ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_remainder( const Py::Object & )
+ { missing_method( number_remainder ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_divmod( const Py::Object & )
+ { missing_method( number_divmod ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_lshift( const Py::Object & )
+ { missing_method( number_lshift ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_rshift( const Py::Object & )
+ { missing_method( number_rshift ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_and( const Py::Object & )
+ { missing_method( number_and ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_xor( const Py::Object & )
+ { missing_method( number_xor ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_or( const Py::Object & )
+ { missing_method( number_or ); return Py::Nothing(); }
+
+Py::Object PythonExtensionBase::number_power( const Py::Object &, const Py::Object & )
+ { missing_method( number_power ); return Py::Nothing(); }
+
+
+// Buffer
+int PythonExtensionBase::buffer_getreadbuffer( int, void** )
+ { missing_method( buffer_getreadbuffer ); return -1; }
+
+int PythonExtensionBase::buffer_getwritebuffer( int, void** )
+ { missing_method( buffer_getwritebuffer ); return -1; }
+
+int PythonExtensionBase::buffer_getsegcount( int* )
+ { missing_method( buffer_getsegcount ); return -1; }
+
+//--------------------------------------------------------------------------------
+//
+// Method call handlers for
+// PythonExtensionBase
+// ExtensionModuleBase
+//
+//--------------------------------------------------------------------------------
+
+extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
+ {
+ try
+ {
+ Tuple self_and_name_tuple( _self_and_name_tuple );
+
+ PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
+ void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject );
+ if( self_as_void == NULL )
+ return NULL;
+
+ ExtensionModuleBase *self = static_cast<ExtensionModuleBase *>( self_as_void );
+
+ String py_name( self_and_name_tuple[1] );
+ std::string name( py_name.as_std_string() );
+
+ Tuple args( _args );
+ if( _keywords == NULL )
+ {
+ Dict keywords; // pass an empty dict
+
+ Object result( self->invoke_method_keyword( name, args, keywords ) );
+ return new_reference_to( result.ptr() );
+ }
+ else
+ {
+ Dict keywords( _keywords );
+
+ Object result( self->invoke_method_keyword( name, args, keywords ) );
+ return new_reference_to( result.ptr() );
+ }
+ }
+ catch( Exception & )
+ {
+ return 0;
+ }
+ }
+
+extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
+ {
+ try
+ {
+ Tuple self_and_name_tuple( _self_and_name_tuple );
+
+ PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
+ void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject );
+ if( self_as_void == NULL )
+ return NULL;
+
+ ExtensionModuleBase *self = static_cast<ExtensionModuleBase *>( self_as_void );
+
+ String py_name( self_and_name_tuple[1] );
+ std::string name( py_name.as_std_string() );
+
+ Tuple args( _args );
+
+ Object result( self->invoke_method_varargs( name, args ) );
+
+ return new_reference_to( result.ptr() );
+ }
+ catch( Exception & )
+ {
+ return 0;
+ }
+ }
+
+extern "C" void do_not_dealloc( void * )
+ {}
+
+
+//--------------------------------------------------------------------------------
+//
+// ExtensionExceptionType
+//
+//--------------------------------------------------------------------------------
+ExtensionExceptionType::ExtensionExceptionType()
+ : Py::Object()
+ {
+ }
+
+void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name )
+ {
+ std::string module_name( module.fullName() );
+ module_name += ".";
+ module_name += name;
+
+ set( PyErr_NewException( const_cast<char *>( module_name.c_str() ), NULL, NULL ), true );
+ }
+
+ExtensionExceptionType::~ExtensionExceptionType()
+ {
+ }
+
+Exception::Exception( ExtensionExceptionType &exception, const std::string& reason )
+ {
+ PyErr_SetString (exception.ptr(), reason.c_str());
+ }
+
+
+} // end of namespace Py
diff --git a/lib/kross/python/cxx/cxx_extensions.cxx b/lib/kross/python/cxx/cxx_extensions.cxx
deleted file mode 100644
index f9c942adf..000000000
--- a/lib/kross/python/cxx/cxx_extensions.cxx
+++ /dev/null
@@ -1,1287 +0,0 @@
-#include "Extensions.hxx"
-#include "Exception.hxx"
-
-#include <assert.h>
-
-namespace Py
-{
-
-//================================================================================
-//
-// Implementation of MethodTable
-//
-//================================================================================
-
-PyMethodDef MethodTable::method( const char* method_name, PyCFunction f, int flags, const char* doc )
- {
- PyMethodDef m;
- m.ml_name = const_cast<char*>( method_name );
- m.ml_meth = f;
- m.ml_flags = flags;
- m.ml_doc = const_cast<char*>( doc );
- return m;
- }
-
-MethodTable::MethodTable()
- {
- t.push_back( method( 0, 0, 0, 0 ) );
- mt = 0;
- }
-
-MethodTable::~MethodTable()
- {
- delete [] mt;
- }
-
-void MethodTable::add( const char* method_name, PyCFunction f, const char* doc, int flag )
- {
- if( !mt )
- {
- t.insert( t.end()-1, method( method_name, f, flag, doc ) );
- }
- else
- {
- throw RuntimeError( "Too late to add a module method!" );
- }
- }
-
-PyMethodDef* MethodTable::table()
- {
- if( !mt )
- {
- int t1size = t.size();
- mt = new PyMethodDef[t1size];
- int j = 0;
- for( std::vector<PyMethodDef>::iterator i = t.begin(); i != t.end(); i++ )
- {
- mt[j++] = *i;
- }
- }
- return mt;
- }
-
-//================================================================================
-//
-// Implementation of ExtensionModule
-//
-//================================================================================
-ExtensionModuleBase::ExtensionModuleBase( const char *name )
- : module_name( name )
- , full_module_name( __Py_PackageContext() != NULL ? std::string( __Py_PackageContext() ) : module_name )
- , method_table()
- {}
-
-ExtensionModuleBase::~ExtensionModuleBase()
- {}
-
-const std::string &ExtensionModuleBase::name() const
- {
- return module_name;
- }
-
-const std::string &ExtensionModuleBase::fullName() const
- {
- return full_module_name;
- }
-
-class ExtensionModuleBasePtr : public PythonExtension<ExtensionModuleBasePtr>
- {
-public:
- ExtensionModuleBasePtr( ExtensionModuleBase *_module )
- : module( _module )
- {}
- virtual ~ExtensionModuleBasePtr()
- {}
-
- ExtensionModuleBase *module;
- };
-
-
-void ExtensionModuleBase::initialize( const char *module_doc )
- {
- PyObject *module_ptr = new ExtensionModuleBasePtr( this );
-
- Py_InitModule4
- (
- const_cast<char *>( module_name.c_str() ), // name
- method_table.table(), // methods
- const_cast<char *>( module_doc ), // docs
- module_ptr, // pass to functions as "self"
- PYTHON_API_VERSION // API version
- );
- }
-
-Py::Module ExtensionModuleBase::module(void) const
- {
- return Module( full_module_name );
- }
-
-Py::Dict ExtensionModuleBase::moduleDictionary(void) const
- {
- return module().getDict();
- }
-
-//--------------------------------------------------------------------------------
-
-//================================================================================
-//
-// Implementation of PythonType
-//
-//================================================================================
-
-extern "C"
- {
- static void standard_dealloc(PyObject* p);
- //
- // All the following functions redirect the call from Python
- // onto the matching virtual function in PythonExtensionBase
- //
- static int print_handler (PyObject*, FILE *, int);
- static PyObject* getattr_handler (PyObject*, char*);
- static int setattr_handler (PyObject*, char*, PyObject*);
- static PyObject* getattro_handler (PyObject*, PyObject*);
- static int setattro_handler (PyObject*, PyObject*, PyObject*);
- static int compare_handler (PyObject*, PyObject*);
- static PyObject* repr_handler (PyObject*);
- static PyObject* str_handler (PyObject*);
- static long hash_handler (PyObject*);
- static PyObject* call_handler (PyObject*, PyObject*, PyObject*);
-
-#if PY_VERSION_HEX < 0x02050000
- typedef int Py_ssize_t;
-#endif
- // Sequence methods
- static Py_ssize_t sequence_length_handler(PyObject*);
- static PyObject* sequence_concat_handler(PyObject*,PyObject*);
- static PyObject* sequence_repeat_handler(PyObject*, Py_ssize_t);
- static PyObject* sequence_item_handler(PyObject*, Py_ssize_t);
- static PyObject* sequence_slice_handler(PyObject*, Py_ssize_t, Py_ssize_t);
- static int sequence_ass_item_handler(PyObject*, Py_ssize_t, PyObject*);
- static int sequence_ass_slice_handler(PyObject*, Py_ssize_t, Py_ssize_t, PyObject*);
- // Mapping
- static Py_ssize_t mapping_length_handler(PyObject*);
- static PyObject* mapping_subscript_handler(PyObject*, PyObject*);
- static int mapping_ass_subscript_handler(PyObject*, PyObject*, PyObject*);
-
- // Numeric methods
- static int number_nonzero_handler (PyObject*);
- static PyObject* number_negative_handler (PyObject*);
- static PyObject* number_positive_handler (PyObject*);
- static PyObject* number_absolute_handler (PyObject*);
- static PyObject* number_invert_handler (PyObject*);
- static PyObject* number_int_handler (PyObject*);
- static PyObject* number_float_handler (PyObject*);
- static PyObject* number_long_handler (PyObject*);
- static PyObject* number_oct_handler (PyObject*);
- static PyObject* number_hex_handler (PyObject*);
- static PyObject* number_add_handler (PyObject*, PyObject*);
- static PyObject* number_subtract_handler (PyObject*, PyObject*);
- static PyObject* number_multiply_handler (PyObject*, PyObject*);
- static PyObject* number_divide_handler (PyObject*, PyObject*);
- static PyObject* number_remainder_handler (PyObject*, PyObject*);
- static PyObject* number_divmod_handler (PyObject*, PyObject*);
- static PyObject* number_lshift_handler (PyObject*, PyObject*);
- static PyObject* number_rshift_handler (PyObject*, PyObject*);
- static PyObject* number_and_handler (PyObject*, PyObject*);
- static PyObject* number_xor_handler (PyObject*, PyObject*);
- static PyObject* number_or_handler (PyObject*, PyObject*);
- static PyObject* number_power_handler(PyObject*, PyObject*, PyObject*);
-
- // Buffer
- static Py_ssize_t buffer_getreadbuffer_handler (PyObject*, Py_ssize_t, void**);
- static Py_ssize_t buffer_getwritebuffer_handler (PyObject*, Py_ssize_t, void**);
- static Py_ssize_t buffer_getsegcount_handler (PyObject*, Py_ssize_t*);
- }
-
-
-extern "C" void standard_dealloc( PyObject* p )
- {
- PyMem_DEL( p );
- }
-
-void PythonType::supportSequenceType()
- {
- if( !sequence_table )
- {
- sequence_table = new PySequenceMethods;
- table->tp_as_sequence = sequence_table;
- sequence_table->sq_length = sequence_length_handler;
- sequence_table->sq_concat = sequence_concat_handler;
- sequence_table->sq_repeat = sequence_repeat_handler;
- sequence_table->sq_item = sequence_item_handler;
- sequence_table->sq_slice = sequence_slice_handler;
-
- sequence_table->sq_ass_item = sequence_ass_item_handler; // BAS setup seperately?
- sequence_table->sq_ass_slice = sequence_ass_slice_handler; // BAS setup seperately?
- }
- }
-
-void PythonType::supportMappingType()
- {
- if( !mapping_table )
- {
- mapping_table = new PyMappingMethods;
- table->tp_as_mapping = mapping_table;
- mapping_table->mp_length = mapping_length_handler;
- mapping_table->mp_subscript = mapping_subscript_handler;
- mapping_table->mp_ass_subscript = mapping_ass_subscript_handler; // BAS setup seperately?
- }
- }
-
-void PythonType::supportNumberType()
- {
- if( !number_table )
- {
- number_table = new PyNumberMethods;
- table->tp_as_number = number_table;
- number_table->nb_add = number_add_handler;
- number_table->nb_subtract = number_subtract_handler;
- number_table->nb_multiply = number_multiply_handler;
- number_table->nb_divide = number_divide_handler;
- number_table->nb_remainder = number_remainder_handler;
- number_table->nb_divmod = number_divmod_handler;
- number_table->nb_power = number_power_handler;
- number_table->nb_negative = number_negative_handler;
- number_table->nb_positive = number_positive_handler;
- number_table->nb_absolute = number_absolute_handler;
- number_table->nb_nonzero = number_nonzero_handler;
- number_table->nb_invert = number_invert_handler;
- number_table->nb_lshift = number_lshift_handler;
- number_table->nb_rshift = number_rshift_handler;
- number_table->nb_and = number_and_handler;
- number_table->nb_xor = number_xor_handler;
- number_table->nb_or = number_or_handler;
- number_table->nb_coerce = 0;
- number_table->nb_int = number_int_handler;
- number_table->nb_long = number_long_handler;
- number_table->nb_float = number_float_handler;
- number_table->nb_oct = number_oct_handler;
- number_table->nb_hex = number_hex_handler;
- }
- }
-
-void PythonType::supportBufferType()
- {
- if( !buffer_table )
- {
- buffer_table = new PyBufferProcs;
- table->tp_as_buffer = buffer_table;
- buffer_table->bf_getreadbuffer = buffer_getreadbuffer_handler;
- buffer_table->bf_getwritebuffer = buffer_getwritebuffer_handler;
- buffer_table->bf_getsegcount = buffer_getsegcount_handler;
- }
- }
-
-// if you define one sequence method you must define
-// all of them except the assigns
-
-PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name )
- : table( new PyTypeObject )
- , sequence_table( NULL )
- , mapping_table( NULL )
- , number_table( NULL )
- , buffer_table( NULL )
- {
- *reinterpret_cast<PyObject*>( table ) = py_object_initializer;
- table->ob_type = _Type_Type();
- table->ob_size = 0;
- table->tp_name = const_cast<char *>( default_name );
- table->tp_basicsize = basic_size;
- table->tp_itemsize = itemsize;
- table->tp_dealloc = ( destructor ) standard_dealloc;
- table->tp_print = 0;
- table->tp_getattr = 0;
- table->tp_setattr = 0;
- table->tp_compare = 0;
- table->tp_repr = 0;
- table->tp_as_number = 0;
- table->tp_as_sequence = 0;
- table->tp_as_mapping = 0;
- table->tp_hash = 0;
- table->tp_call = 0;
- table->tp_str = 0;
- table->tp_getattro = 0;
- table->tp_setattro = 0;
- table->tp_as_buffer = 0;
- table->tp_flags = 0L;
- table->tp_doc = 0;
-#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 0)
- // first use in 2.0
- table->tp_traverse = 0L;
- table->tp_clear = 0L;
-#else
- table->tp_xxx5 = 0L;
- table->tp_xxx6 = 0L;
-#endif
-#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 1)
- // first defined in 2.1
- table->tp_richcompare = 0L;
- table->tp_weaklistoffset = 0L;
-#else
- table->tp_xxx7 = 0L;
- table->tp_xxx8 = 0L;
-#endif
-
-#ifdef COUNT_ALLOCS
- table->tp_alloc = 0;
- table->tp_free = 0;
- table->tp_maxalloc = 0;
- table->tp_next = 0;
-#endif
- }
-
-PythonType::~PythonType( )
- {
- delete table;
- delete sequence_table;
- delete mapping_table;
- delete number_table;
- delete buffer_table;
- }
-
-PyTypeObject* PythonType::type_object( ) const
- {return table;}
-
-void PythonType::name( const char* nam )
- {
- table->tp_name = const_cast<char *>( nam );
- }
-
-const char *PythonType::getName() const
- {
- return table->tp_name;
- }
-
-void PythonType::doc( const char* d )
- {
- table->tp_doc = const_cast<char *>( d );
- }
-
-const char *PythonType::getDoc() const
- {
- return table->tp_doc;
- }
-
-void PythonType::dealloc( void( *f )( PyObject* ))
- {
- table->tp_dealloc = f;
- }
-
-void PythonType::supportPrint()
- {
- table->tp_print = print_handler;
- }
-
-void PythonType::supportGetattr()
- {
- table->tp_getattr = getattr_handler;
- }
-
-void PythonType::supportSetattr()
- {
- table->tp_setattr = setattr_handler;
- }
-
-void PythonType::supportGetattro()
- {
- table->tp_getattro = getattro_handler;
- }
-
-void PythonType::supportSetattro()
- {
- table->tp_setattro = setattro_handler;
- }
-
-void PythonType::supportCompare()
- {
- table->tp_compare = compare_handler;
- }
-
-void PythonType::supportRepr()
- {
- table->tp_repr = repr_handler;
- }
-
-void PythonType::supportStr()
- {
- table->tp_str = str_handler;
- }
-
-void PythonType::supportHash()
- {
- table->tp_hash = hash_handler;
- }
-
-void PythonType::supportCall()
- {
- table->tp_call = call_handler;
- }
-
-//--------------------------------------------------------------------------------
-//
-// Handlers
-//
-//--------------------------------------------------------------------------------
-extern "C" int print_handler( PyObject *self, FILE *fp, int flags )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->print( fp, flags );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* getattr_handler( PyObject *self, char *name )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->getattr( name ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" int setattr_handler( PyObject *self, char *name, PyObject *value )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->setattr( name, Py::Object( value ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* getattro_handler( PyObject *self, PyObject *name )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->getattro( Py::Object( name ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" int setattro_handler( PyObject *self, PyObject *name, PyObject *value )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->setattro( Py::Object( name ), Py::Object( value ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" int compare_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->compare( Py::Object( other ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* repr_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->repr() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* str_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->str() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" long hash_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->hash();
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* call_handler( PyObject *self, PyObject *args, PyObject *kw )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) );
- if( kw != NULL )
- return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) );
- else
- return new_reference_to( p->call( Py::Object( args ), Py::Object() ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-
-// Sequence methods
-extern "C" Py_ssize_t sequence_length_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->sequence_length();
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* sequence_concat_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->sequence_concat( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* sequence_repeat_handler( PyObject *self, Py_ssize_t count )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->sequence_repeat( count ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* sequence_item_handler( PyObject *self, Py_ssize_t index )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->sequence_item( index ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* sequence_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->sequence_slice( first, last ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" int sequence_ass_item_handler( PyObject *self, Py_ssize_t index, PyObject *value )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->sequence_ass_item( index, Py::Object( value ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" int sequence_ass_slice_handler( PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *value )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->sequence_ass_slice( first, last, Py::Object( value ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-// Mapping
-extern "C" Py_ssize_t mapping_length_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->mapping_length();
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* mapping_subscript_handler( PyObject *self, PyObject *key )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->mapping_subscript( Py::Object( key ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" int mapping_ass_subscript_handler( PyObject *self, PyObject *key, PyObject *value )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->mapping_ass_subscript( Py::Object( key ), Py::Object( value ) );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-// Number
-extern "C" int number_nonzero_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->number_nonzero();
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" PyObject* number_negative_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_negative() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_positive_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_positive() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_absolute_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_absolute() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_invert_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_invert() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_int_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_int() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_float_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_float() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_long_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_long() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_oct_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_oct() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_hex_handler( PyObject *self )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_hex() );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_add_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_add( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_subtract_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_subtract( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_multiply_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_multiply( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_divide_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_divide( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_remainder_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_remainder( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_divmod_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_divmod( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_lshift_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_lshift( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_rshift_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_rshift( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_and_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_and( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_xor_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_xor( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_or_handler( PyObject *self, PyObject *other )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_or( Py::Object( other ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-extern "C" PyObject* number_power_handler( PyObject *self, PyObject *x1, PyObject *x2 )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return new_reference_to( p->number_power( Py::Object( x1 ), Py::Object( x2 ) ) );
- }
- catch( Py::Exception & )
- {
- return NULL; // indicate error
- }
- }
-
-// Buffer
-extern "C" Py_ssize_t buffer_getreadbuffer_handler( PyObject *self, Py_ssize_t index, void **pp )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->buffer_getreadbuffer( index, pp );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" Py_ssize_t buffer_getwritebuffer_handler( PyObject *self, Py_ssize_t index, void **pp )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- return p->buffer_getwritebuffer( index, pp );
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-extern "C" Py_ssize_t buffer_getsegcount_handler( PyObject *self, Py_ssize_t *count )
- {
- try
- {
- PythonExtensionBase *p = static_cast<PythonExtensionBase *>( self );
- int i_count = *count;
- Py_ssize_t r = p->buffer_getsegcount( &i_count );
- *count = i_count;
- return r;
- }
- catch( Py::Exception & )
- {
- return -1; // indicate error
- }
- }
-
-
-//================================================================================
-//
-// Implementation of PythonExtensionBase
-//
-//================================================================================
-#define missing_method( method ) \
-throw RuntimeError( "Extension object does not support method " #method );
-
-PythonExtensionBase::PythonExtensionBase()
- {
- }
-
-PythonExtensionBase::~PythonExtensionBase()
- {
- assert( ob_refcnt == 0 );
- }
-
-int PythonExtensionBase::print( FILE *, int )
- { missing_method( print ); return -1; }
-
-int PythonExtensionBase::setattr( const char*, const Py::Object & )
- { missing_method( setattr ); return -1; }
-
-Py::Object PythonExtensionBase::getattro( const Py::Object & )
- { missing_method( getattro ); return Py::Nothing(); }
-
-int PythonExtensionBase::setattro( const Py::Object &, const Py::Object & )
- { missing_method( setattro ); return -1; }
-
-int PythonExtensionBase::compare( const Py::Object & )
- { missing_method( compare ); return -1; }
-
-Py::Object PythonExtensionBase::repr()
- { missing_method( repr ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::str()
- { missing_method( str ); return Py::Nothing(); }
-
-long PythonExtensionBase::hash()
- { missing_method( hash ); return -1; }
-
-Py::Object PythonExtensionBase::call( const Py::Object &, const Py::Object & )
- { missing_method( call ); return Py::Nothing(); }
-
-
-// Sequence methods
-int PythonExtensionBase::sequence_length()
- { missing_method( sequence_length ); return -1; }
-
-Py::Object PythonExtensionBase::sequence_concat( const Py::Object & )
- { missing_method( sequence_concat ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::sequence_repeat( int )
- { missing_method( sequence_repeat ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::sequence_item( int )
- { missing_method( sequence_item ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::sequence_slice( int, int )
- { missing_method( sequence_slice ); return Py::Nothing(); }
-
-int PythonExtensionBase::sequence_ass_item( int, const Py::Object & )
- { missing_method( sequence_ass_item ); return -1; }
-
-int PythonExtensionBase::sequence_ass_slice( int, int, const Py::Object & )
- { missing_method( sequence_ass_slice ); return -1; }
-
-
-// Mapping
-int PythonExtensionBase::mapping_length()
- { missing_method( mapping_length ); return -1; }
-
-Py::Object PythonExtensionBase::mapping_subscript( const Py::Object & )
- { missing_method( mapping_subscript ); return Py::Nothing(); }
-
-int PythonExtensionBase::mapping_ass_subscript( const Py::Object &, const Py::Object & )
- { missing_method( mapping_ass_subscript ); return -1; }
-
-
-// Number
-int PythonExtensionBase::number_nonzero()
- { missing_method( number_nonzero ); return -1; }
-
-Py::Object PythonExtensionBase::number_negative()
- { missing_method( number_negative ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_positive()
- { missing_method( number_positive ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_absolute()
- { missing_method( number_absolute ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_invert()
- { missing_method( number_invert ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_int()
- { missing_method( number_int ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_float()
- { missing_method( number_float ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_long()
- { missing_method( number_long ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_oct()
- { missing_method( number_oct ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_hex()
- { missing_method( number_hex ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_add( const Py::Object & )
- { missing_method( number_add ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_subtract( const Py::Object & )
- { missing_method( number_subtract ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_multiply( const Py::Object & )
- { missing_method( number_multiply ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_divide( const Py::Object & )
- { missing_method( number_divide ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_remainder( const Py::Object & )
- { missing_method( number_remainder ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_divmod( const Py::Object & )
- { missing_method( number_divmod ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_lshift( const Py::Object & )
- { missing_method( number_lshift ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_rshift( const Py::Object & )
- { missing_method( number_rshift ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_and( const Py::Object & )
- { missing_method( number_and ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_xor( const Py::Object & )
- { missing_method( number_xor ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_or( const Py::Object & )
- { missing_method( number_or ); return Py::Nothing(); }
-
-Py::Object PythonExtensionBase::number_power( const Py::Object &, const Py::Object & )
- { missing_method( number_power ); return Py::Nothing(); }
-
-
-// Buffer
-int PythonExtensionBase::buffer_getreadbuffer( int, void** )
- { missing_method( buffer_getreadbuffer ); return -1; }
-
-int PythonExtensionBase::buffer_getwritebuffer( int, void** )
- { missing_method( buffer_getwritebuffer ); return -1; }
-
-int PythonExtensionBase::buffer_getsegcount( int* )
- { missing_method( buffer_getsegcount ); return -1; }
-
-//--------------------------------------------------------------------------------
-//
-// Method call handlers for
-// PythonExtensionBase
-// ExtensionModuleBase
-//
-//--------------------------------------------------------------------------------
-
-extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
- {
- try
- {
- Tuple self_and_name_tuple( _self_and_name_tuple );
-
- PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
- void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject );
- if( self_as_void == NULL )
- return NULL;
-
- ExtensionModuleBase *self = static_cast<ExtensionModuleBase *>( self_as_void );
-
- String py_name( self_and_name_tuple[1] );
- std::string name( py_name.as_std_string() );
-
- Tuple args( _args );
- if( _keywords == NULL )
- {
- Dict keywords; // pass an empty dict
-
- Object result( self->invoke_method_keyword( name, args, keywords ) );
- return new_reference_to( result.ptr() );
- }
- else
- {
- Dict keywords( _keywords );
-
- Object result( self->invoke_method_keyword( name, args, keywords ) );
- return new_reference_to( result.ptr() );
- }
- }
- catch( Exception & )
- {
- return 0;
- }
- }
-
-extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
- {
- try
- {
- Tuple self_and_name_tuple( _self_and_name_tuple );
-
- PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
- void *self_as_void = PyCObject_AsVoidPtr( self_in_cobject );
- if( self_as_void == NULL )
- return NULL;
-
- ExtensionModuleBase *self = static_cast<ExtensionModuleBase *>( self_as_void );
-
- String py_name( self_and_name_tuple[1] );
- std::string name( py_name.as_std_string() );
-
- Tuple args( _args );
-
- Object result( self->invoke_method_varargs( name, args ) );
-
- return new_reference_to( result.ptr() );
- }
- catch( Exception & )
- {
- return 0;
- }
- }
-
-extern "C" void do_not_dealloc( void * )
- {}
-
-
-//--------------------------------------------------------------------------------
-//
-// ExtensionExceptionType
-//
-//--------------------------------------------------------------------------------
-ExtensionExceptionType::ExtensionExceptionType()
- : Py::Object()
- {
- }
-
-void ExtensionExceptionType::init( ExtensionModuleBase &module, const std::string& name )
- {
- std::string module_name( module.fullName() );
- module_name += ".";
- module_name += name;
-
- set( PyErr_NewException( const_cast<char *>( module_name.c_str() ), NULL, NULL ), true );
- }
-
-ExtensionExceptionType::~ExtensionExceptionType()
- {
- }
-
-Exception::Exception( ExtensionExceptionType &exception, const std::string& reason )
- {
- PyErr_SetString (exception.ptr(), reason.c_str());
- }
-
-
-} // end of namespace Py
diff --git a/lib/kross/python/cxx/cxxsupport.cpp b/lib/kross/python/cxx/cxxsupport.cpp
new file mode 100644
index 000000000..6f2234b26
--- /dev/null
+++ b/lib/kross/python/cxx/cxxsupport.cpp
@@ -0,0 +1,142 @@
+//---------------------------------------------------------------------------//
+// Copyright 1998 The Regents of the University of California.
+// All rights reserved. See Legal.htm for full text and disclaimer.
+//---------------------------------------------------------------------------//
+
+#include "Objects.h"
+namespace Py {
+
+Py_UNICODE unicode_null_string[1] = { 0 };
+
+Type Object::type () const
+ {
+ return Type (PyObject_Type (p), true);
+ }
+
+String Object::str () const
+ {
+ return String (PyObject_Str (p), true);
+ }
+
+String Object::repr () const
+ {
+ return String (PyObject_Repr (p), true);
+ }
+
+std::string Object::as_string() const
+ {
+ return static_cast<std::string>(str());
+ }
+
+List Object::dir () const
+ {
+ return List (PyObject_Dir (p), true);
+ }
+
+bool Object::isType (const Type& t) const
+ {
+ return type ().ptr() == t.ptr();
+ }
+
+Char::operator String() const
+ {
+ return String(ptr());
+ }
+
+// TMM: non-member operaters for iterators - see above
+// I've also made a bug fix in respect to the cxx code
+// (dereffed the left.seq and right.seq comparison)
+bool operator==(const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.eql( right );
+ }
+
+bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.neq( right );
+ }
+
+bool operator< (const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.lss( right );
+ }
+
+bool operator> (const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.gtr( right );
+ }
+
+bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.leq( right );
+ }
+
+bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right)
+ {
+ return left.geq( right );
+ }
+
+// now for const_iterator
+bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.eql( right );
+ }
+
+bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.neq( right );
+ }
+
+bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.lss( right );
+ }
+
+bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.gtr( right );
+ }
+
+bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.leq( right );
+ }
+
+bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
+ {
+ return left.geq( right );
+ }
+
+// For mappings:
+bool operator==(const Mapping::iterator& left, const Mapping::iterator& right)
+ {
+ return left.eql( right );
+ }
+
+bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right)
+ {
+ return left.neq( right );
+ }
+
+// now for const_iterator
+bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right)
+ {
+ return left.eql( right );
+ }
+
+bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right)
+ {
+ return left.neq( right );
+ }
+
+// TMM: 31May'01 - Added the #ifndef so I can exclude iostreams.
+#ifndef CXX_NO_IOSTREAMS
+// output
+
+std::ostream& operator<< (std::ostream& os, const Object& ob)
+ {
+ return (os << static_cast<std::string>(ob.str()));
+ }
+#endif
+
+} // Py
diff --git a/lib/kross/python/cxx/cxxsupport.cxx b/lib/kross/python/cxx/cxxsupport.cxx
deleted file mode 100644
index 7bab6cc37..000000000
--- a/lib/kross/python/cxx/cxxsupport.cxx
+++ /dev/null
@@ -1,142 +0,0 @@
-//---------------------------------------------------------------------------//
-// Copyright 1998 The Regents of the University of California.
-// All rights reserved. See Legal.htm for full text and disclaimer.
-//---------------------------------------------------------------------------//
-
-#include "Objects.hxx"
-namespace Py {
-
-Py_UNICODE unicode_null_string[1] = { 0 };
-
-Type Object::type () const
- {
- return Type (PyObject_Type (p), true);
- }
-
-String Object::str () const
- {
- return String (PyObject_Str (p), true);
- }
-
-String Object::repr () const
- {
- return String (PyObject_Repr (p), true);
- }
-
-std::string Object::as_string() const
- {
- return static_cast<std::string>(str());
- }
-
-List Object::dir () const
- {
- return List (PyObject_Dir (p), true);
- }
-
-bool Object::isType (const Type& t) const
- {
- return type ().ptr() == t.ptr();
- }
-
-Char::operator String() const
- {
- return String(ptr());
- }
-
-// TMM: non-member operaters for iterators - see above
-// I've also made a bug fix in respect to the cxx code
-// (dereffed the left.seq and right.seq comparison)
-bool operator==(const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.eql( right );
- }
-
-bool operator!=(const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.neq( right );
- }
-
-bool operator< (const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.lss( right );
- }
-
-bool operator> (const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.gtr( right );
- }
-
-bool operator<=(const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.leq( right );
- }
-
-bool operator>=(const Sequence::iterator& left, const Sequence::iterator& right)
- {
- return left.geq( right );
- }
-
-// now for const_iterator
-bool operator==(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.eql( right );
- }
-
-bool operator!=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.neq( right );
- }
-
-bool operator< (const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.lss( right );
- }
-
-bool operator> (const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.gtr( right );
- }
-
-bool operator<=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.leq( right );
- }
-
-bool operator>=(const Sequence::const_iterator& left, const Sequence::const_iterator& right)
- {
- return left.geq( right );
- }
-
-// For mappings:
-bool operator==(const Mapping::iterator& left, const Mapping::iterator& right)
- {
- return left.eql( right );
- }
-
-bool operator!=(const Mapping::iterator& left, const Mapping::iterator& right)
- {
- return left.neq( right );
- }
-
-// now for const_iterator
-bool operator==(const Mapping::const_iterator& left, const Mapping::const_iterator& right)
- {
- return left.eql( right );
- }
-
-bool operator!=(const Mapping::const_iterator& left, const Mapping::const_iterator& right)
- {
- return left.neq( right );
- }
-
-// TMM: 31May'01 - Added the #ifndef so I can exclude iostreams.
-#ifndef CXX_NO_IOSTREAMS
-// output
-
-std::ostream& operator<< (std::ostream& os, const Object& ob)
- {
- return (os << static_cast<std::string>(ob.str()));
- }
-#endif
-
-} // Py
diff --git a/lib/kross/python/pythonconfig.h b/lib/kross/python/pythonconfig.h
index 64b4eefb7..349d838b0 100644
--- a/lib/kross/python/pythonconfig.h
+++ b/lib/kross/python/pythonconfig.h
@@ -38,9 +38,9 @@
#include <frameobject.h>
// Include the PyCXX stuff.
-#include "cxx/Config.hxx"
-#include "cxx/Objects.hxx"
-#include "cxx/Extensions.hxx"
+#include "cxx/Config.h"
+#include "cxx/Objects.h"
+#include "cxx/Extensions.h"
namespace Kross {
diff --git a/lib/kwmf/Makefile.am b/lib/kwmf/Makefile.am
index 5e0c0bf7e..7bcd95129 100644
--- a/lib/kwmf/Makefile.am
+++ b/lib/kwmf/Makefile.am
@@ -9,11 +9,11 @@ libkwmf_la_LIBADD = $(LIB_TDECORE) $(LIB_TQT)
lib_LTLIBRARIES = libkwmf.la libkowmf.la
-libkwmf_la_SOURCES = kwmf.cc qwmf.cc
+libkwmf_la_SOURCES = kwmf.cpp qwmf.cpp
#include_HEADERS = kowmfread.h kowmfwrite.h kowmfpaint.h
noinst_HEADERS = kwmf.h qwmf.h metafuncs.h wmfstruct.h kowmfreadprivate.h kowmfstack.h kowmfstruct.h
-libkowmf_la_SOURCES = kowmfreadprivate.cc kowmfstack.cc kowmfread.cc kowmfwrite.cc kowmfpaint.cc
+libkowmf_la_SOURCES = kowmfreadprivate.cpp kowmfstack.cpp kowmfread.cpp kowmfwrite.cpp kowmfpaint.cpp
libkowmf_la_LDFLAGS = $(all_libraries) -version-info 2:0:0 -no-undefined
libkowmf_la_LIBADD = $(LIB_TDECORE) $(LIB_TQT)
diff --git a/lib/kwmf/kowmfpaint.cc b/lib/kwmf/kowmfpaint.cpp
index 430672731..430672731 100644
--- a/lib/kwmf/kowmfpaint.cc
+++ b/lib/kwmf/kowmfpaint.cpp
diff --git a/lib/kwmf/kowmfread.cc b/lib/kwmf/kowmfread.cpp
index f932ae3a3..f932ae3a3 100644
--- a/lib/kwmf/kowmfread.cc
+++ b/lib/kwmf/kowmfread.cpp
diff --git a/lib/kwmf/kowmfreadprivate.cc b/lib/kwmf/kowmfreadprivate.cpp
index f812b7660..f812b7660 100644
--- a/lib/kwmf/kowmfreadprivate.cc
+++ b/lib/kwmf/kowmfreadprivate.cpp
diff --git a/lib/kwmf/kowmfstack.cc b/lib/kwmf/kowmfstack.cpp
index 80896690f..80896690f 100644
--- a/lib/kwmf/kowmfstack.cc
+++ b/lib/kwmf/kowmfstack.cpp
diff --git a/lib/kwmf/kowmfwrite.cc b/lib/kwmf/kowmfwrite.cpp
index 22a0d131e..22a0d131e 100644
--- a/lib/kwmf/kowmfwrite.cc
+++ b/lib/kwmf/kowmfwrite.cpp
diff --git a/lib/kwmf/kwmf.cc b/lib/kwmf/kwmf.cpp
index 06092a825..06092a825 100644
--- a/lib/kwmf/kwmf.cc
+++ b/lib/kwmf/kwmf.cpp
diff --git a/lib/kwmf/qwmf.cc b/lib/kwmf/qwmf.cpp
index 8b6572aee..8b6572aee 100644
--- a/lib/kwmf/qwmf.cc
+++ b/lib/kwmf/qwmf.cpp
diff --git a/tools/converter/koconverter.cpp b/tools/converter/koconverter.cpp
index 9bad2fb57..86063f4e0 100644
--- a/tools/converter/koconverter.cpp
+++ b/tools/converter/koconverter.cpp
@@ -102,7 +102,7 @@ int main( int argc, char **argv )
if ( args->isSet("backup") )
{
- // Code form koDocument.cc
+ // Code form koDocument.cpp
TDEIO::UDSEntry entry;
if ( TDEIO::NetAccess::stat( uOut, entry, 0L ) ) // this file exists => backup
{
diff --git a/tools/kthesaurus/Makefile.am b/tools/kthesaurus/Makefile.am
index 95d0acb4e..82a53e5b6 100644
--- a/tools/kthesaurus/Makefile.am
+++ b/tools/kthesaurus/Makefile.am
@@ -6,13 +6,13 @@ lib_LTLIBRARIES =
tdeinit_LTLIBRARIES = kthesaurus.la
kthesaurus_la_LDFLAGS = $(all_libraries) $(KDE_RPATH) -module -avoid-version
-kthesaurus_la_SOURCES = main.cc
+kthesaurus_la_SOURCES = main.cpp
kthesaurus_la_LIBADD = $(LIB_TDESYCOCA)
appsdir = $(kde_appsdir)/Office
apps_DATA = KThesaurus.desktop
messages:
- $(XGETTEXT) *.cc -o $(podir)/kthesaurus.pot
+ $(XGETTEXT) *.cpp -o $(podir)/kthesaurus.pot
KDE_ICON = kthesaurus
diff --git a/tools/kthesaurus/main.cc b/tools/kthesaurus/main.cc
deleted file mode 100644
index f94373f84..000000000
--- a/tools/kthesaurus/main.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-/***************************************************************************
- main.cc - using the thesaurus KDataTool stand alone
- -------------------
- begin : 2001-12-22
- copyright : (C) 2001 by Daniel Naber
- email : daniel.naber@t-online.de
- $Id: main.cc 381440 2005-01-23 07:53:34Z mlaurent $
- ***************************************************************************/
-
-/***************************************************************************
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 2 of the License, or *
- * (at your option) any later version. *
- * *
- ***************************************************************************/
-
-#include <tqstring.h>
-
-#include <tdeaboutdata.h>
-#include <tdeapplication.h>
-#include <tdecmdlineargs.h>
-#include <kdatatool.h>
-#include <kdebug.h>
-#include <tdeglobal.h>
-#include <tdelocale.h>
-#include <koffice_export.h>
-static TDECmdLineOptions options[] =
-{
- { "+[term]", I18N_NOOP("Term to search for when starting up"), 0 },
- TDECmdLineLastOption
-};
-
-extern "C" KOFFICETOOLS_EXPORT int kdemain(int argc, char **argv)
-{
-
- TDEAboutData aboutData("kthesaurus", I18N_NOOP("KThesaurus"), "1.0",
- I18N_NOOP( "KThesaurus - List synonyms" ), TDEAboutData::License_GPL,
- I18N_NOOP( "(c) 2001 Daniel Naber" ) );
-
- TDECmdLineArgs::init(argc, argv, &aboutData);
- TDECmdLineArgs::addCmdLineOptions(options);
- TDEApplication a; // KDataTool needs an instance
-
- // TODO: take term from command line!
-
- KService::Ptr service = KService::serviceByDesktopName("thesaurustool");
- if( ! service ) {
- kdWarning() << "Could not find Service/KDataTool 'thesaurustool'!" << endl;
- return 1;
- }
-
- KDataToolInfo *info = new KDataToolInfo(service, 0);
- KDataTool *tool = info->createTool();
- if ( !tool ) {
- kdWarning() << "Could not create tool 'thesaurustool'!" << endl;
- return 2;
- }
-
-/* TODO: get selection(), not only clipboard!
- TQClipboard *cb = TQApplication::clipboard();
- TQString text = cb->text();
- if( text.isNull() || text.length() > 50 ) {
- // long texts are probably not supposed to be searched for
- text = "";
- }
-*/
- TQString text = "";
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
- if ( args->count() > 0 ) {
- text = args->arg(0);
- }
-
- TQString command = "thesaurus_standalone"; // 'standalone' will give us different buttons
- TQString mimetype = "text/plain";
- TQString datatype = TQSTRING_OBJECT_NAME_STRING;
-
- //kdDebug() << "KThesaurus command=" << command
- // << " dataType=" << info->dataType() << endl;
-
- tool->run(command, &text, datatype, mimetype);
-
- delete tool;
-
- return 0;
-}
diff --git a/tools/kthesaurus/main.cpp b/tools/kthesaurus/main.cpp
new file mode 100644
index 000000000..9db6e571b
--- /dev/null
+++ b/tools/kthesaurus/main.cpp
@@ -0,0 +1,87 @@
+/***************************************************************************
+ main.cpp - using the thesaurus KDataTool stand alone
+ -------------------
+ begin : 2001-12-22
+ copyright : (C) 2001 by Daniel Naber
+ email : daniel.naber@t-online.de
+ $Id: main.cpp 381440 2005-01-23 07:53:34Z mlaurent $
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include <tqstring.h>
+
+#include <tdeaboutdata.h>
+#include <tdeapplication.h>
+#include <tdecmdlineargs.h>
+#include <kdatatool.h>
+#include <kdebug.h>
+#include <tdeglobal.h>
+#include <tdelocale.h>
+#include <koffice_export.h>
+static TDECmdLineOptions options[] =
+{
+ { "+[term]", I18N_NOOP("Term to search for when starting up"), 0 },
+ TDECmdLineLastOption
+};
+
+extern "C" KOFFICETOOLS_EXPORT int kdemain(int argc, char **argv)
+{
+
+ TDEAboutData aboutData("kthesaurus", I18N_NOOP("KThesaurus"), "1.0",
+ I18N_NOOP( "KThesaurus - List synonyms" ), TDEAboutData::License_GPL,
+ I18N_NOOP( "(c) 2001 Daniel Naber" ) );
+
+ TDECmdLineArgs::init(argc, argv, &aboutData);
+ TDECmdLineArgs::addCmdLineOptions(options);
+ TDEApplication a; // KDataTool needs an instance
+
+ // TODO: take term from command line!
+
+ KService::Ptr service = KService::serviceByDesktopName("thesaurustool");
+ if( ! service ) {
+ kdWarning() << "Could not find Service/KDataTool 'thesaurustool'!" << endl;
+ return 1;
+ }
+
+ KDataToolInfo *info = new KDataToolInfo(service, 0);
+ KDataTool *tool = info->createTool();
+ if ( !tool ) {
+ kdWarning() << "Could not create tool 'thesaurustool'!" << endl;
+ return 2;
+ }
+
+/* TODO: get selection(), not only clipboard!
+ TQClipboard *cb = TQApplication::clipboard();
+ TQString text = cb->text();
+ if( text.isNull() || text.length() > 50 ) {
+ // long texts are probably not supposed to be searched for
+ text = "";
+ }
+*/
+ TQString text = "";
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+ if ( args->count() > 0 ) {
+ text = args->arg(0);
+ }
+
+ TQString command = "thesaurus_standalone"; // 'standalone' will give us different buttons
+ TQString mimetype = "text/plain";
+ TQString datatype = TQSTRING_OBJECT_NAME_STRING;
+
+ //kdDebug() << "KThesaurus command=" << command
+ // << " dataType=" << info->dataType() << endl;
+
+ tool->run(command, &text, datatype, mimetype);
+
+ delete tool;
+
+ return 0;
+}
diff --git a/tools/spell/Makefile.am b/tools/spell/Makefile.am
index 7c90d34b9..826f32f71 100644
--- a/tools/spell/Makefile.am
+++ b/tools/spell/Makefile.am
@@ -7,7 +7,7 @@
#kde_module_LTLIBRARIES = libtdespelltool.la
-#libtdespelltool_la_SOURCES = main.cc
+#libtdespelltool_la_SOURCES = main.cpp
#libtdespelltool_la_LDFLAGS = $(all_libraries) -avoid-version -module -no-undefined
diff --git a/tools/spell/main.cc b/tools/spell/main.cpp
index 564f66622..564f66622 100644
--- a/tools/spell/main.cc
+++ b/tools/spell/main.cpp
diff --git a/tools/thesaurus/Makefile.am b/tools/thesaurus/Makefile.am
index 927c7245b..6a57a1c43 100644
--- a/tools/thesaurus/Makefile.am
+++ b/tools/thesaurus/Makefile.am
@@ -6,7 +6,7 @@ libthesaurustool_la_LIBADD = $(LIB_TDESYCOCA)
kde_module_LTLIBRARIES = libthesaurustool.la
-libthesaurustool_la_SOURCES = main.cc
+libthesaurustool_la_SOURCES = main.cpp
libthesaurustool_la_LDFLAGS = $(all_libraries) -avoid-version -module -no-undefined
@@ -21,4 +21,4 @@ thesaurusdir = $(kde_datadir)/thesaurus
thesaurus_DATA = thesaurus.txt
messages:
- $(XGETTEXT) *.cc -o $(podir)/thesaurus_tool.pot
+ $(XGETTEXT) *.cpp -o $(podir)/thesaurus_tool.pot
diff --git a/tools/thesaurus/main.cc b/tools/thesaurus/main.cc
deleted file mode 100644
index 57b1d7790..000000000
--- a/tools/thesaurus/main.cc
+++ /dev/null
@@ -1,817 +0,0 @@
-/*
- $Id: main.cc 466447 2005-10-02 17:54:10Z zander $
- This file is part of the KDE project
- Copyright (C) 2001,2002,2003 Daniel Naber <daniel.naber@t-online.de>
- This is a thesaurus based on a subset of WordNet. It also offers an
- almost complete WordNet 1.7 frontend (WordNet is a powerful lexical
- database/thesaurus)
-*/
-/***************************************************************************
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- ***************************************************************************/
-
-/*
-TODO:
--Be more verbose if the result is empty
--See the TODO's in the source below
-
--If no match was found, use KSpell to offer alternative spellings?
--Don't start WordNet before its tab is activated?
--Maybe remove more uncommon words. However, the "polysemy/familiarity
- count" is sometimes very low for quite common word, e.g. "sky".
-
--Fix "no mimesource" warning of TQTextBrowser? Seems really harmless.
-
-NOT TODO:
--Add part of speech information -- I think this would blow up the
- filesize too much
-*/
-
-#include "main.h"
-
-#include <tqfile.h>
-#include <tqtoolbutton.h>
-#include <kiconloader.h>
-#include <tdefiledialog.h>
-#include <tdeversion.h>
-
-/***************************************************
- *
- * Factory
- *
- ***************************************************/
-
-typedef KGenericFactory<Thesaurus, KDataTool> ThesaurusFactory;
-K_EXPORT_COMPONENT_FACTORY( libthesaurustool, ThesaurusFactory("thesaurus_tool") )
-
-/***************************************************
- *
- * Thesaurus *
- ***************************************************/
-
-Thesaurus::Thesaurus(TQObject* parent, const char* name, const TQStringList &)
- : KDataTool(parent, name)
-{
-
- m_dialog = new KDialogBase(KJanusWidget::Plain, TQString(),
- KDialogBase::Help|KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
- m_dialog->setHelp(TQString(), "thesaurus");
- m_dialog->resize(600, 400);
-
- m_config = new TDEConfig("kthesaurusrc");
- m_data_file = m_config->readPathEntry("datafile");
- if( ! m_data_file ) {
- m_data_file = TDEGlobal::dirs()->findResourceDir("data", "thesaurus/")
- + "thesaurus/thesaurus.txt";
- }
- setCaption();
-
- m_no_match = i18n("(No match)");
-
- m_replacement = false;
- m_history_pos = 1;
-
- m_page = m_dialog->plainPage();
- TQVBoxLayout *m_top_layout = new TQVBoxLayout(m_page, KDialog::marginHint(), KDialog::spacingHint());
-
- TQHBoxLayout *row1 = new TQHBoxLayout(m_top_layout);
- m_edit = new KHistoryCombo(m_page);
- m_edit_label = new TQLabel(m_edit, i18n("&Search for:"), m_page);
- m_search = new KPushButton(i18n("S&earch"), m_page);
- connect(m_search, TQT_SIGNAL(clicked()),
- this, TQT_SLOT(slotFindTerm()));
- row1->addWidget(m_edit_label, 0);
- row1->addWidget(m_edit, 1);
- row1->addWidget(m_search, 0);
- m_back = new TQToolButton(m_page);
- m_back->setIconSet(BarIconSet(TQString::fromLatin1("back")));
- TQToolTip::add(m_back, i18n("Back"));
- row1->addWidget(m_back, 0);
- m_forward = new TQToolButton(m_page);
- m_forward->setIconSet(BarIconSet(TQString::fromLatin1("forward")));
- TQToolTip::add(m_forward, i18n("Forward"));
- row1->addWidget(m_forward, 0);
- m_lang = new KPushButton(i18n("Change Language..."), m_page);
- connect(m_lang, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotChangeLanguage()));
- row1->addWidget(m_lang, 0);
-
- connect(m_back, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotBack()));
- connect(m_forward, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotForward()));
-
- m_tab = new TQTabWidget(m_page);
- m_top_layout->addWidget(m_tab);
-
- //
- // Thesaurus Tab
- //
-
- vbox = new TQVBox(m_tab);
- m_tab->addTab(vbox, i18n("&Thesaurus"));
- vbox->setMargin(KDialog::marginHint());
- vbox->setSpacing(KDialog::spacingHint());
-
- TQHBox *hbox = new TQHBox(vbox);
- hbox->setSpacing(KDialog::spacingHint());
-
- grpbox_syn = new TQGroupBox( 1, Qt::Horizontal, i18n("Synonyms"), hbox);
- m_thes_syn = new TQListBox(grpbox_syn);
-
- grpbox_hyper = new TQGroupBox( 1, Qt::Horizontal, i18n("More General Words"), hbox);
- m_thes_hyper = new TQListBox(grpbox_hyper);
-
- grpbox_hypo = new TQGroupBox( 1, Qt::Horizontal, i18n("More Specific Words"), hbox);
- m_thes_hypo = new TQListBox(grpbox_hypo);
-
- // single click -- keep display unambiguous by removing other selections:
-
- connect(m_thes_syn, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hyper, TQT_SLOT(clearSelection()));
- connect(m_thes_syn, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hypo, TQT_SLOT(clearSelection()));
- connect(m_thes_syn, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
- this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
-
- connect(m_thes_hyper, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_syn, TQT_SLOT(clearSelection()));
- connect(m_thes_hyper, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hypo, TQT_SLOT(clearSelection()));
- connect(m_thes_hyper, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
- this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
-
- connect(m_thes_hypo, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_syn, TQT_SLOT(clearSelection()));
- connect(m_thes_hypo, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hyper, TQT_SLOT(clearSelection()));
- connect(m_thes_hypo, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
- this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
-
- // double click:
- connect(m_thes_syn, TQT_SIGNAL(selected(const TQString &)),
- this, TQT_SLOT(slotFindTerm(const TQString &)));
- connect(m_thes_hyper, TQT_SIGNAL(selected(const TQString &)),
- this, TQT_SLOT(slotFindTerm(const TQString &)));
- connect(m_thes_hypo, TQT_SIGNAL(selected(const TQString &)),
- this, TQT_SLOT(slotFindTerm(const TQString &)));
-
- //
- // WordNet Tab
- //
-
- vbox2 = new TQVBox(m_tab);
- m_tab->addTab(vbox2, i18n("&WordNet"));
- vbox2->setMargin(KDialog::marginHint());
- vbox2->setSpacing(KDialog::spacingHint());
-
- m_combobox = new TQComboBox(vbox2);
- m_combobox->setEditable(false);
- connect(m_combobox, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotFindTerm()));
-
- m_resultbox = new TQTextBrowser(vbox2);
- m_resultbox->setTextFormat(TQt::RichText);
- // TODO?: m_resultbox->setMimeSourceFactory(...); to avoid warning
- connect(m_resultbox, TQT_SIGNAL(linkClicked(const TQString &)),
- this, TQT_SLOT(slotFindTerm(const TQString &)));
-
- // Connect for the history box
- m_edit->setTrapReturnKey(true); // Do not use Return as default key...
- connect(m_edit, TQT_SIGNAL(returnPressed(const TQString&)), this, TQT_SLOT(slotFindTerm(const TQString&)));
- connect(m_edit, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotGotoHistory(int)));
-
- TQHBoxLayout *row2 = new TQHBoxLayout( m_top_layout );
- m_replace = new KLineEdit(m_page);
- m_replace_label = new TQLabel(m_replace, i18n("&Replace with:"), m_page);
- row2->addWidget(m_replace_label, 0);
- row2->addWidget(m_replace, 1);
-
- // Set focus
- m_edit->setFocus();
- slotUpdateNavButtons();
-
- //
- // The external command stuff
- //
-
- // calling the 'wn' binary
- m_wnproc = new TDEProcess;
- connect(m_wnproc, TQT_SIGNAL(processExited(TDEProcess*)), this, TQT_SLOT(wnExited(TDEProcess*)));
- connect(m_wnproc, TQT_SIGNAL(receivedStdout(TDEProcess*,char*,int)),
- this, TQT_SLOT(receivedWnStdout(TDEProcess*, char*, int)));
- connect(m_wnproc, TQT_SIGNAL(receivedStderr(TDEProcess*,char*,int)),
- this, TQT_SLOT(receivedWnStderr(TDEProcess*, char*, int)));
-
- // grep'ing the text file
- m_thesproc = new TDEProcess;
- connect(m_thesproc, TQT_SIGNAL(processExited(TDEProcess*)), this, TQT_SLOT(thesExited(TDEProcess*)));
- connect(m_thesproc, TQT_SIGNAL(receivedStdout(TDEProcess*,char*,int)),
- this, TQT_SLOT(receivedThesStdout(TDEProcess*, char*, int)));
- connect(m_thesproc, TQT_SIGNAL(receivedStderr(TDEProcess*,char*,int)),
- this, TQT_SLOT(receivedThesStderr(TDEProcess*, char*, int)));
-
-}
-
-
-Thesaurus::~Thesaurus()
-{
- m_config->writePathEntry("datafile", m_data_file);
- m_config->sync();
- delete m_config;
- // FIXME?: this hopefully fixes the problem of a wrong cursor
- // and a crash (when closing e.g. konqueror) when the thesaurus dialog
- // gets close while it was still working and showing the wait cursor
- TQApplication::restoreOverrideCursor();
- delete m_thesproc;
- delete m_wnproc;
- delete m_dialog;
-}
-
-
-bool Thesaurus::run(const TQString& command, void* data, const TQString& datatype, const TQString& mimetype)
-{
-
- // Check whether we can accept the data
- if ( datatype != TQSTRING_OBJECT_NAME_STRING ) {
- kdDebug(31000) << "Thesaurus only accepts datatype TQString" << endl;
- return FALSE;
- }
- if ( mimetype != "text/plain" ) {
- kdDebug(31000) << "Thesaurus only accepts mimetype text/plain" << endl;
- return FALSE;
- }
-
- if ( command == "thesaurus" ) {
- // not called from an application like KWord, so make it possible
- // to replace text:
- m_replacement = true;
- m_dialog->setButtonOKText(i18n("&Replace"));
- } else if ( command == "thesaurus_standalone" ) {
- // not called from any application, but from KThesaurus
- m_replacement = false;
- m_dialog->showButtonOK(false);
- m_dialog->setButtonCancelText(i18n("&Close"));
- m_replace->setEnabled(false);
- m_replace_label->setEnabled(false);
- } else {
- kdDebug(31000) << "Thesaurus does only accept the command 'thesaurus' or 'thesaurus_standalone'" << endl;
- kdDebug(31000) << "The command " << command << " is not accepted" << endl;
- return FALSE;
- }
-
- // Get data and clean it up:
- TQString buffer = *((TQString *)data);
- buffer = buffer.stripWhiteSpace();
- TQRegExp re("[.,;!?\"'()\\[\\]]");
- buffer.remove(re);
- buffer = buffer.left(100); // limit maximum length
-
- m_wnproc_stdout = "";
- m_wnproc_stderr = "";
-
- m_thesproc_stdout = "";
- m_thesproc_stderr = "";
-
- if( ! buffer.isEmpty() ) {
- slotFindTerm(buffer);
- }
-
- if( m_dialog->exec() == TQDialog::Accepted ) { // "Replace"
- *((TQString*)data) = m_replace->text();
- }
-
- return TRUE;
-}
-
-
-void Thesaurus::slotChangeLanguage()
-{
- TQString filename = KFileDialog::getOpenFileName(
- TDEGlobal::dirs()->findResourceDir("data", "thesaurus/")+"thesaurus/");
- if( !filename.isNull() ) {
- m_data_file = filename;
- setCaption();
- }
-}
-
-void Thesaurus::setCaption()
-{
- KURL url = KURL();
- url.setPath(m_data_file);
- m_dialog->setCaption(i18n("Related Words - %1").arg(url.fileName()));
-}
-
-// Enbale or disable back and forward button
-void Thesaurus::slotUpdateNavButtons()
-{
- if( m_history_pos <= 1 ) { // 1 = first position
- m_back->setEnabled(false);
- } else {
- m_back->setEnabled(true);
- }
- if( m_history_pos >= m_edit->count() ) {
- m_forward->setEnabled(false);
- } else {
- m_forward->setEnabled(true);
- }
-}
-
-// Go to an item from the editbale combo box.
-void Thesaurus::slotGotoHistory(int index)
-{
- m_history_pos = m_edit->count() - index;
- slotFindTerm(m_edit->text(index), false);
-}
-
-// Triggered when the back button is clicked.
-void Thesaurus::slotBack()
-{
- m_history_pos--;
- int pos = m_edit->count() - m_history_pos;
- m_edit->setCurrentItem(pos);
- slotFindTerm(m_edit->text(pos), false);
-}
-
-// Triggered when the forward button is clicked.
-void Thesaurus::slotForward()
-{
- m_history_pos++;
- int pos = m_edit->count() - m_history_pos;
- m_edit->setCurrentItem(pos);
- slotFindTerm(m_edit->text(pos), false);
-}
-
-// Triggered when a word is selected in the list box.
-void Thesaurus::slotSetReplaceTerm(TQListBoxItem *item)
-{
- if( ! item )
- return;
- m_replace->setText(item->text());
-}
-
-void Thesaurus::slotSetReplaceTerm(const TQString &term)
-{
- if( m_replacement && term != m_no_match ) {
- m_replace->setText(term);
- }
-}
-
-// Triggered when Return is pressed.
-void Thesaurus::slotFindTerm()
-{
- findTerm(m_edit->currentText());
-}
-
-// Triggered when a word is clicked / a list item is double-clicked.
-void Thesaurus::slotFindTerm(const TQString &term, bool add_to_history)
-{
- slotSetReplaceTerm(term);
- if( term.startsWith("http://") ) {
- (void) new KRun(KURL(term));
- } else {
- if( add_to_history ) {
- m_edit->insertItem(term, 0);
- m_history_pos = m_edit->count();
- m_edit->setCurrentItem(0);
- }
- slotUpdateNavButtons();
- findTerm(term);
- }
-}
-
-void Thesaurus::findTerm(const TQString &term)
-{
- findTermThesaurus(term);
- findTermWordnet(term);
-}
-
-
-//
-// Thesaurus
-//
-void Thesaurus::findTermThesaurus(const TQString &term)
-{
-
- if( !TQFile::exists(m_data_file) ) {
- KMessageBox::error(0, i18n("The thesaurus file '%1' was not found. "
- "Please use 'Change Language...' to select a thesaurus file.").
- arg(m_data_file));
- return;
- }
-
- TQApplication::setOverrideCursor(KCursor::waitCursor());
-
- m_thesproc_stdout = "";
- m_thesproc_stderr = "";
-
- // Find only whole words. Looks clumsy, but this way we don't have to rely on
- // features that might only be in certain versions of grep:
- TQString term_tmp = ";" + term.stripWhiteSpace() + ";";
- m_thesproc->clearArguments();
- *m_thesproc << "grep" << "-i" << term_tmp;
- *m_thesproc << m_data_file;
-
- if( !m_thesproc->start(TDEProcess::NotifyOnExit, TDEProcess::AllOutput) ) {
- KMessageBox::error(0, i18n("Failed to execute grep."));
- TQApplication::restoreOverrideCursor();
- return;
- }
-}
-
-// The external process has ended, so we parse its result and put it in
-// the list box.
-void Thesaurus::thesExited(TDEProcess *)
-{
-
- if( !m_thesproc_stderr.isEmpty() ) {
- KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute grep. "
- "Output:<br>%1").arg(m_thesproc_stderr));
- TQApplication::restoreOverrideCursor();
- return;
- }
-
- TQString search_term = m_edit->currentText().stripWhiteSpace();
-
- TQStringList syn;
- TQStringList hyper;
- TQStringList hypo;
-
- TQStringList lines = lines.split(TQChar('\n'), m_thesproc_stdout, false);
- for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
- TQString line = (*it);
- if( line.startsWith(" ") ) { // ignore license (two spaces)
- continue;
- }
- int sep_pos = line.find("#");
- TQString syn_part = line.left(sep_pos);
- TQString hyper_part = line.right(line.length()-sep_pos-1);
- TQStringList syn_tmp = TQStringList::split(TQChar(';'), syn_part);
- TQStringList hyper_tmp = TQStringList::split(TQChar(';'), hyper_part);
- if( syn_tmp.grep(search_term, false).size() > 0 ) {
- // match on the left side of the '#' -- synonyms
- for ( TQStringList::Iterator it2 = syn_tmp.begin(); it2 != syn_tmp.end(); ++it2 ) {
- // add if it's not the term itself and if it's not yet in the list
- TQString term = (*it2);
- if( term.lower() != search_term.lower() && syn.contains(term) == 0 ) {
- syn.append(term);
- }
- }
- for ( TQStringList::Iterator it2 = hyper_tmp.begin(); it2 != hyper_tmp.end(); ++it2 ) {
- TQString term = (*it2);
- if( term.lower() != search_term.lower() && hyper.contains(term) == 0 ) {
- hyper.append(term);
- }
- }
- }
- if( hyper_tmp.grep(search_term, false).size() > 0 ) {
- // match on the right side of the '#' -- hypernyms
- for ( TQStringList::Iterator it2 = syn_tmp.begin(); it2 != syn_tmp.end(); ++it2 ) {
- TQString term = (*it2);
- if( term.lower() != search_term && hypo.contains(term) == 0 ) {
- hypo.append(term);
- }
- }
- }
- }
-
- m_thes_syn->clear();
- if( syn.size() > 0 ) {
- syn = sortTQStringList(syn);
- m_thes_syn->insertStringList(syn);
- m_thes_syn->setEnabled(true);
- } else {
- m_thes_syn->insertItem(m_no_match);
- m_thes_syn->setEnabled(false);
- }
-
- m_thes_hyper->clear();
- if( hyper.size() > 0 ) {
- hyper = sortTQStringList(hyper);
- m_thes_hyper->insertStringList(hyper);
- m_thes_hyper->setEnabled(true);
- } else {
- m_thes_hyper->insertItem(m_no_match);
- m_thes_hyper->setEnabled(false);
- }
-
- m_thes_hypo->clear();
- if( hypo.size() > 0 ) {
- hypo = sortTQStringList(hypo);
- m_thes_hypo->insertStringList(hypo);
- m_thes_hypo->setEnabled(true);
- } else {
- m_thes_hypo->insertItem(m_no_match);
- m_thes_hypo->setEnabled(false);
- }
-
- TQApplication::restoreOverrideCursor();
-}
-
-void Thesaurus::receivedThesStdout(TDEProcess *, char *result, int len)
-{
- m_thesproc_stdout += TQString::fromLocal8Bit( TQCString(result, len+1) );
-}
-
-void Thesaurus::receivedThesStderr(TDEProcess *, char *result, int len)
-{
- m_thesproc_stderr += TQString::fromLocal8Bit( TQCString(result, len+1) );
-}
-
-
-//
-// WordNet
-//
-void Thesaurus::findTermWordnet(const TQString &term)
-{
- TQApplication::setOverrideCursor(KCursor::waitCursor());
-
- m_wnproc_stdout = "";
- m_wnproc_stderr = "";
-
- m_wnproc->clearArguments();
- *m_wnproc << "wn";
- *m_wnproc << term;
-
- // get all results: nouns, verbs, adjectives, adverbs (see below for order):
- if( m_combobox->currentItem() == 0 ) {
- *m_wnproc << "-synsn" << "-synsv" << "-synsa" << "-synsr";
- m_mode = other;
- } else if( m_combobox->currentItem() == 1 ) {
- *m_wnproc << "-simsv";
- m_mode = other;
- } else if( m_combobox->currentItem() == 2 ) {
- *m_wnproc << "-antsn" << "-antsv" << "-antsa" << "-antsr";
- m_mode = other;
- } else if( m_combobox->currentItem() == 3 ) {
- *m_wnproc << "-hypon" << "-hypov";
- m_mode = other;
- } else if( m_combobox->currentItem() == 4 ) {
- *m_wnproc << "-meron";
- m_mode = other;
- } else if( m_combobox->currentItem() == 5 ) {
- *m_wnproc << "-holon";
- m_mode = other;
- } else if( m_combobox->currentItem() == 6 ) {
- // e.g. "size -> large/small"
- *m_wnproc << "-attrn" << "-attra";
- m_mode = other;
- } else if( m_combobox->currentItem() == 7 ) {
- // e.g. "kill -> die"
- *m_wnproc << "-causv";
- m_mode = other;
- } else if( m_combobox->currentItem() == 8 ) {
- // e.g. "walk -> step"
- *m_wnproc << "-entav";
- m_mode = other;
- } else if( m_combobox->currentItem() == 9 ) {
- *m_wnproc << "-famln" << "-famlv" << "-famla" << "-famlr";
- m_mode = other;
- } else if( m_combobox->currentItem() == 10 ) {
- *m_wnproc << "-framv";
- m_mode = other;
- } else if( m_combobox->currentItem() == 11 ) {
- *m_wnproc << "-grepn" << "-grepv" << "-grepa" << "-grepr";
- m_mode = grep;
- } else if( m_combobox->currentItem() == 12 ) {
- *m_wnproc << "-over";
- m_mode = other;
- }
- *m_wnproc << "-g"; // "Display gloss"
-
- int current = m_combobox->currentItem(); // remember current position
- m_combobox->clear();
-
- // warning: order matters!
- // 0:
- m_combobox->insertItem(i18n("Synonyms/Hypernyms - Ordered by Frequency"));
- m_combobox->insertItem(i18n("Synonyms - Ordered by Similarity of Meaning (verbs only)"));
- m_combobox->insertItem(i18n("Antonyms - Words with Opposite Meanings"));
- m_combobox->insertItem(i18n("Hyponyms - ... is a (kind of) %1").arg(m_edit->currentText()));
- m_combobox->insertItem(i18n("Meronyms - %1 has a ...").arg(m_edit->currentText()));
- // 5:
- m_combobox->insertItem(i18n("Holonyms - ... has a %1").arg(m_edit->currentText()));
- m_combobox->insertItem(i18n("Attributes"));
- m_combobox->insertItem(i18n("Cause To (for some verbs only)"));
- m_combobox->insertItem(i18n("Verb Entailment (for some verbs only)"));
- m_combobox->insertItem(i18n("Familiarity & Polysemy Count"));
- // 10:
- m_combobox->insertItem(i18n("Verb Frames (examples of use)"));
- m_combobox->insertItem(i18n("List of Compound Words"));
- m_combobox->insertItem(i18n("Overview of Senses"));
-
- /** NOT todo:
- * -Hypernym tree: layout is difficult, you can get the same information
- * by following links
- * -Coordinate terms (sisters): just go to synset and then use hyponyms
- * -Has Part Meronyms, Has Substance Meronyms, Has Member Meronyms,
- * Member of Holonyms, Substance of Holonyms, Part of Holonyms:
- * these are just subsets of Meronyms/Holonyms
- * -hmern, hholn: these are just compact versions, you can get the
- * same information by following some links
- */
-
- /** TODO?:
- * -pert (e.g. nuclear -> nuclues, but "=>" are nested, difficult to display)
- * -nomn(n|v), e.g. deny -> denial, but this doesn't seem to work?
- */
-
- m_combobox->setCurrentItem(current); // reset previous position
-
- if( m_wnproc->isRunning() ) {
- // should never happen
- kdDebug(31000) << "Warning: findTerm(): process is already running?!" << endl;
- TQApplication::restoreOverrideCursor();
- return;
- }
-
- if( !m_wnproc->start(TDEProcess::NotifyOnExit, TDEProcess::AllOutput) ) {
- m_resultbox->setText(i18n("<b>Error:</b> Failed to execute the WordNet program 'wn'. "
- "WordNet has to be installed on your computer to use this component of kthesaurus, "
- "and 'wn' has to be available in your $PATH environment variable. "
- "Look for a WordNet package from your upstream distro package repository. "
- "Or you can obtain WordNet at <a href=\"http://wordnet.princeton.edu/wordnet/download/current-version/\">"
- "http://wordnet.princeton.edu/wordnet/download/current-version/</a>. "
- "Notice that WordNet only supports the English language."));
- m_combobox->setEnabled(false);
- TQApplication::restoreOverrideCursor();
- return;
- }
-
-}
-
-// The process has ended, so parse its result and display it as TQt richtext.
-void Thesaurus::wnExited(TDEProcess *)
-{
-
- if( !m_wnproc_stderr.isEmpty() ) {
- m_resultbox->setText(i18n("<b>Error:</b> Failed to execute WordNet program 'wn'. "
- "Output:<br>%1").arg(m_wnproc_stderr));
- TQApplication::restoreOverrideCursor();
- return;
- }
-
- if( m_wnproc_stdout.isEmpty() ) {
- m_resultbox->setText(i18n("No match for '%1'.").arg(m_edit->currentText()));
- } else {
- // render in a table, each line one row:
- TQStringList lines = lines.split(TQChar('\n'), m_wnproc_stdout, false);
- TQString result = "<qt><table>\n";
- // TODO in TQt > 3.01: try without the following line (it's necessary to ensure the
- // first column is really always quite small):
- result += "<tr><td width=\"10%\"></td><td width=\"90%\"></td></tr>\n";
- uint ct = 0;
- for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
- TQString l = (*it);
- // Remove some lines:
- TQRegExp re("^\\d+( of \\d+)? senses? of \\w+");
- if( re.search(l) != -1 ) {
- continue;
- }
- // Escape XML:
- l = l.replace('&', "&amp;");
- l = l.replace('<', "&lt;");
- l = l.replace('>', "&gt;");
- // TODO?:
- // move "=>" in own column?
- l = formatLine(l);
- // Table layout:
- result += "<tr>";
- if( l.startsWith(" ") ) {
- result += "\t<td width=\"15\"></td>";
- l = l.stripWhiteSpace();
- result += "\t<td>" + l + "</td>";
- } else {
- l = l.stripWhiteSpace();
- result += "<td colspan=\"2\">" + l + "</td>";
- }
- result += "</tr>\n";
- ct++;
- }
- result += "\n</table></qt>\n";
- m_resultbox->setText(result);
- m_resultbox->setContentsPos(0,0);
- //kdDebug() << result << endl;
- }
-
- TQApplication::restoreOverrideCursor();
-}
-
-void Thesaurus::receivedWnStdout(TDEProcess *, char *result, int len)
-{
- m_wnproc_stdout += TQString::fromLocal8Bit( TQCString(result, len+1) );
-}
-
-void Thesaurus::receivedWnStderr(TDEProcess *, char *result, int len)
-{
- m_wnproc_stderr += TQString::fromLocal8Bit( TQCString(result, len+1) );
-}
-
-
-//
-// Tools
-//
-
-// Format lines using TQt's simple richtext.
-TQString Thesaurus::formatLine(TQString l)
-{
-
- if( l == "--------------" ) {
- return TQString("<hr>");
- }
-
- TQRegExp re;
-
- re.setPattern("^(\\d+\\.)(.*)$");
- if( re.search(l) != -1 ) {
- l = "<b>" +re.cap(1)+ "</b>" +re.cap(2);
- return l;
- }
-
- re.setPattern("^.* of (noun|verb|adj|adv) .*");
- if( re.search(l) != -1 ) {
- l = "<font size=\"5\">" +re.cap()+ "</font>\n\n";
- return l;
- }
-
- if( m_mode == grep ) {
- l = l.stripWhiteSpace();
- return TQString("<a href=\"" +l+ "\">" +l+ "</a>");
- }
-
- re.setPattern("^(Sense \\d+)");
- if( re.search(l) != -1 ) {
- l = "<b>" +re.cap()+ "</b>\n";
- return l;
- }
-
- re.setPattern("(.*)(Also See-&gt;)(.*)");
- // Example: first sense of verb "keep"
- if( re.search(l) != -1 ) {
- l = re.cap(1);
- l += re.cap(2);
- TQStringList links = links.split(TQChar(';'), re.cap(3), false);
- for ( TQStringList::Iterator it = links.begin(); it != links.end(); ++it ) {
- TQString link = (*it);
- if( it != links.begin() ) {
- l += ", ";
- }
- link = link.stripWhiteSpace();
- link = link.remove(TQRegExp("#\\d+"));
- l += "<a href=\"" +link+ "\">" +link+ "</a>";
- }
- l.prepend (' '); // indent in table
- }
-
- re.setPattern("(.*)(=&gt;|HAS \\w+:|PART OF:)(.*) --");
- re.setMinimal(true); // non-greedy
- if( re.search(l) != -1 ) {
- int dash_pos = l.find("--");
- TQString line_end = l.mid(dash_pos+2, l.length()-dash_pos);
- l = re.cap(1);
- l += re.cap(2) + " ";
- TQStringList links = links.split(TQChar(','), re.cap(3), false);
- for ( TQStringList::Iterator it = links.begin(); it != links.end(); ++it ) {
- TQString link = (*it);
- if( it != links.begin() ) {
- l += ", ";
- }
- link = link.stripWhiteSpace();
- l += "<a href=\"" +link+ "\">" +link+ "</a>";
- }
- l += "<font color=\"#777777\">" +line_end+ "</font>";
- l.prepend(' '); // indent in table
- return l;
- }
- re.setMinimal(false); // greedy again
-
- return l;
-}
-
-/**
- * Sort a list case insensitively.
- * Be careful: @p list is modified
- * TODO: use ksortablevaluelist?
- */
-TQStringList Thesaurus::sortTQStringList(TQStringList list)
-{
- // Sort list case-insensitive. This looks strange but using a TQMap
- // is even suggested by the TQt documentation.
- TQMap<TQString,TQString> map_list;
- for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
- TQString str = *it;
- map_list[str.lower()] = str;
- }
- list.clear();
- TQMap<TQString,TQString>::Iterator it;
- // TQt doc: "the items are alphabetically sorted [by key] when iterating over the map":
- for( it = map_list.begin(); it != map_list.end(); ++it ) {
- list.append(it.data());
- }
- return list;
-}
-
-#include "main.moc"
diff --git a/tools/thesaurus/main.cpp b/tools/thesaurus/main.cpp
new file mode 100644
index 000000000..06da26824
--- /dev/null
+++ b/tools/thesaurus/main.cpp
@@ -0,0 +1,817 @@
+/*
+ $Id: main.cpp 466447 2005-10-02 17:54:10Z zander $
+ This file is part of the KDE project
+ Copyright (C) 2001,2002,2003 Daniel Naber <daniel.naber@t-online.de>
+ This is a thesaurus based on a subset of WordNet. It also offers an
+ almost complete WordNet 1.7 frontend (WordNet is a powerful lexical
+ database/thesaurus)
+*/
+/***************************************************************************
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License
+ as published by the Free Software Foundation; either version 2
+ of the License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ ***************************************************************************/
+
+/*
+TODO:
+-Be more verbose if the result is empty
+-See the TODO's in the source below
+
+-If no match was found, use KSpell to offer alternative spellings?
+-Don't start WordNet before its tab is activated?
+-Maybe remove more uncommon words. However, the "polysemy/familiarity
+ count" is sometimes very low for quite common word, e.g. "sky".
+
+-Fix "no mimesource" warning of TQTextBrowser? Seems really harmless.
+
+NOT TODO:
+-Add part of speech information -- I think this would blow up the
+ filesize too much
+*/
+
+#include "main.h"
+
+#include <tqfile.h>
+#include <tqtoolbutton.h>
+#include <kiconloader.h>
+#include <tdefiledialog.h>
+#include <tdeversion.h>
+
+/***************************************************
+ *
+ * Factory
+ *
+ ***************************************************/
+
+typedef KGenericFactory<Thesaurus, KDataTool> ThesaurusFactory;
+K_EXPORT_COMPONENT_FACTORY( libthesaurustool, ThesaurusFactory("thesaurus_tool") )
+
+/***************************************************
+ *
+ * Thesaurus *
+ ***************************************************/
+
+Thesaurus::Thesaurus(TQObject* parent, const char* name, const TQStringList &)
+ : KDataTool(parent, name)
+{
+
+ m_dialog = new KDialogBase(KJanusWidget::Plain, TQString(),
+ KDialogBase::Help|KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
+ m_dialog->setHelp(TQString(), "thesaurus");
+ m_dialog->resize(600, 400);
+
+ m_config = new TDEConfig("kthesaurusrc");
+ m_data_file = m_config->readPathEntry("datafile");
+ if( ! m_data_file ) {
+ m_data_file = TDEGlobal::dirs()->findResourceDir("data", "thesaurus/")
+ + "thesaurus/thesaurus.txt";
+ }
+ setCaption();
+
+ m_no_match = i18n("(No match)");
+
+ m_replacement = false;
+ m_history_pos = 1;
+
+ m_page = m_dialog->plainPage();
+ TQVBoxLayout *m_top_layout = new TQVBoxLayout(m_page, KDialog::marginHint(), KDialog::spacingHint());
+
+ TQHBoxLayout *row1 = new TQHBoxLayout(m_top_layout);
+ m_edit = new KHistoryCombo(m_page);
+ m_edit_label = new TQLabel(m_edit, i18n("&Search for:"), m_page);
+ m_search = new KPushButton(i18n("S&earch"), m_page);
+ connect(m_search, TQT_SIGNAL(clicked()),
+ this, TQT_SLOT(slotFindTerm()));
+ row1->addWidget(m_edit_label, 0);
+ row1->addWidget(m_edit, 1);
+ row1->addWidget(m_search, 0);
+ m_back = new TQToolButton(m_page);
+ m_back->setIconSet(BarIconSet(TQString::fromLatin1("back")));
+ TQToolTip::add(m_back, i18n("Back"));
+ row1->addWidget(m_back, 0);
+ m_forward = new TQToolButton(m_page);
+ m_forward->setIconSet(BarIconSet(TQString::fromLatin1("forward")));
+ TQToolTip::add(m_forward, i18n("Forward"));
+ row1->addWidget(m_forward, 0);
+ m_lang = new KPushButton(i18n("Change Language..."), m_page);
+ connect(m_lang, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotChangeLanguage()));
+ row1->addWidget(m_lang, 0);
+
+ connect(m_back, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotBack()));
+ connect(m_forward, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotForward()));
+
+ m_tab = new TQTabWidget(m_page);
+ m_top_layout->addWidget(m_tab);
+
+ //
+ // Thesaurus Tab
+ //
+
+ vbox = new TQVBox(m_tab);
+ m_tab->addTab(vbox, i18n("&Thesaurus"));
+ vbox->setMargin(KDialog::marginHint());
+ vbox->setSpacing(KDialog::spacingHint());
+
+ TQHBox *hbox = new TQHBox(vbox);
+ hbox->setSpacing(KDialog::spacingHint());
+
+ grpbox_syn = new TQGroupBox( 1, Qt::Horizontal, i18n("Synonyms"), hbox);
+ m_thes_syn = new TQListBox(grpbox_syn);
+
+ grpbox_hyper = new TQGroupBox( 1, Qt::Horizontal, i18n("More General Words"), hbox);
+ m_thes_hyper = new TQListBox(grpbox_hyper);
+
+ grpbox_hypo = new TQGroupBox( 1, Qt::Horizontal, i18n("More Specific Words"), hbox);
+ m_thes_hypo = new TQListBox(grpbox_hypo);
+
+ // single click -- keep display unambiguous by removing other selections:
+
+ connect(m_thes_syn, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hyper, TQT_SLOT(clearSelection()));
+ connect(m_thes_syn, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hypo, TQT_SLOT(clearSelection()));
+ connect(m_thes_syn, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
+ this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
+
+ connect(m_thes_hyper, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_syn, TQT_SLOT(clearSelection()));
+ connect(m_thes_hyper, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hypo, TQT_SLOT(clearSelection()));
+ connect(m_thes_hyper, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
+ this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
+
+ connect(m_thes_hypo, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_syn, TQT_SLOT(clearSelection()));
+ connect(m_thes_hypo, TQT_SIGNAL(clicked(TQListBoxItem *)), m_thes_hyper, TQT_SLOT(clearSelection()));
+ connect(m_thes_hypo, TQT_SIGNAL(selectionChanged(TQListBoxItem *)),
+ this, TQT_SLOT(slotSetReplaceTerm(TQListBoxItem *)));
+
+ // double click:
+ connect(m_thes_syn, TQT_SIGNAL(selected(const TQString &)),
+ this, TQT_SLOT(slotFindTerm(const TQString &)));
+ connect(m_thes_hyper, TQT_SIGNAL(selected(const TQString &)),
+ this, TQT_SLOT(slotFindTerm(const TQString &)));
+ connect(m_thes_hypo, TQT_SIGNAL(selected(const TQString &)),
+ this, TQT_SLOT(slotFindTerm(const TQString &)));
+
+ //
+ // WordNet Tab
+ //
+
+ vbox2 = new TQVBox(m_tab);
+ m_tab->addTab(vbox2, i18n("&WordNet"));
+ vbox2->setMargin(KDialog::marginHint());
+ vbox2->setSpacing(KDialog::spacingHint());
+
+ m_combobox = new TQComboBox(vbox2);
+ m_combobox->setEditable(false);
+ connect(m_combobox, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotFindTerm()));
+
+ m_resultbox = new TQTextBrowser(vbox2);
+ m_resultbox->setTextFormat(TQt::RichText);
+ // TODO?: m_resultbox->setMimeSourceFactory(...); to avoid warning
+ connect(m_resultbox, TQT_SIGNAL(linkClicked(const TQString &)),
+ this, TQT_SLOT(slotFindTerm(const TQString &)));
+
+ // Connect for the history box
+ m_edit->setTrapReturnKey(true); // Do not use Return as default key...
+ connect(m_edit, TQT_SIGNAL(returnPressed(const TQString&)), this, TQT_SLOT(slotFindTerm(const TQString&)));
+ connect(m_edit, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotGotoHistory(int)));
+
+ TQHBoxLayout *row2 = new TQHBoxLayout( m_top_layout );
+ m_replace = new KLineEdit(m_page);
+ m_replace_label = new TQLabel(m_replace, i18n("&Replace with:"), m_page);
+ row2->addWidget(m_replace_label, 0);
+ row2->addWidget(m_replace, 1);
+
+ // Set focus
+ m_edit->setFocus();
+ slotUpdateNavButtons();
+
+ //
+ // The external command stuff
+ //
+
+ // calling the 'wn' binary
+ m_wnproc = new TDEProcess;
+ connect(m_wnproc, TQT_SIGNAL(processExited(TDEProcess*)), this, TQT_SLOT(wnExited(TDEProcess*)));
+ connect(m_wnproc, TQT_SIGNAL(receivedStdout(TDEProcess*,char*,int)),
+ this, TQT_SLOT(receivedWnStdout(TDEProcess*, char*, int)));
+ connect(m_wnproc, TQT_SIGNAL(receivedStderr(TDEProcess*,char*,int)),
+ this, TQT_SLOT(receivedWnStderr(TDEProcess*, char*, int)));
+
+ // grep'ing the text file
+ m_thesproc = new TDEProcess;
+ connect(m_thesproc, TQT_SIGNAL(processExited(TDEProcess*)), this, TQT_SLOT(thesExited(TDEProcess*)));
+ connect(m_thesproc, TQT_SIGNAL(receivedStdout(TDEProcess*,char*,int)),
+ this, TQT_SLOT(receivedThesStdout(TDEProcess*, char*, int)));
+ connect(m_thesproc, TQT_SIGNAL(receivedStderr(TDEProcess*,char*,int)),
+ this, TQT_SLOT(receivedThesStderr(TDEProcess*, char*, int)));
+
+}
+
+
+Thesaurus::~Thesaurus()
+{
+ m_config->writePathEntry("datafile", m_data_file);
+ m_config->sync();
+ delete m_config;
+ // FIXME?: this hopefully fixes the problem of a wrong cursor
+ // and a crash (when closing e.g. konqueror) when the thesaurus dialog
+ // gets close while it was still working and showing the wait cursor
+ TQApplication::restoreOverrideCursor();
+ delete m_thesproc;
+ delete m_wnproc;
+ delete m_dialog;
+}
+
+
+bool Thesaurus::run(const TQString& command, void* data, const TQString& datatype, const TQString& mimetype)
+{
+
+ // Check whether we can accept the data
+ if ( datatype != TQSTRING_OBJECT_NAME_STRING ) {
+ kdDebug(31000) << "Thesaurus only accepts datatype TQString" << endl;
+ return FALSE;
+ }
+ if ( mimetype != "text/plain" ) {
+ kdDebug(31000) << "Thesaurus only accepts mimetype text/plain" << endl;
+ return FALSE;
+ }
+
+ if ( command == "thesaurus" ) {
+ // not called from an application like KWord, so make it possible
+ // to replace text:
+ m_replacement = true;
+ m_dialog->setButtonOKText(i18n("&Replace"));
+ } else if ( command == "thesaurus_standalone" ) {
+ // not called from any application, but from KThesaurus
+ m_replacement = false;
+ m_dialog->showButtonOK(false);
+ m_dialog->setButtonCancelText(i18n("&Close"));
+ m_replace->setEnabled(false);
+ m_replace_label->setEnabled(false);
+ } else {
+ kdDebug(31000) << "Thesaurus does only accept the command 'thesaurus' or 'thesaurus_standalone'" << endl;
+ kdDebug(31000) << "The command " << command << " is not accepted" << endl;
+ return FALSE;
+ }
+
+ // Get data and clean it up:
+ TQString buffer = *((TQString *)data);
+ buffer = buffer.stripWhiteSpace();
+ TQRegExp re("[.,;!?\"'()\\[\\]]");
+ buffer.remove(re);
+ buffer = buffer.left(100); // limit maximum length
+
+ m_wnproc_stdout = "";
+ m_wnproc_stderr = "";
+
+ m_thesproc_stdout = "";
+ m_thesproc_stderr = "";
+
+ if( ! buffer.isEmpty() ) {
+ slotFindTerm(buffer);
+ }
+
+ if( m_dialog->exec() == TQDialog::Accepted ) { // "Replace"
+ *((TQString*)data) = m_replace->text();
+ }
+
+ return TRUE;
+}
+
+
+void Thesaurus::slotChangeLanguage()
+{
+ TQString filename = KFileDialog::getOpenFileName(
+ TDEGlobal::dirs()->findResourceDir("data", "thesaurus/")+"thesaurus/");
+ if( !filename.isNull() ) {
+ m_data_file = filename;
+ setCaption();
+ }
+}
+
+void Thesaurus::setCaption()
+{
+ KURL url = KURL();
+ url.setPath(m_data_file);
+ m_dialog->setCaption(i18n("Related Words - %1").arg(url.fileName()));
+}
+
+// Enbale or disable back and forward button
+void Thesaurus::slotUpdateNavButtons()
+{
+ if( m_history_pos <= 1 ) { // 1 = first position
+ m_back->setEnabled(false);
+ } else {
+ m_back->setEnabled(true);
+ }
+ if( m_history_pos >= m_edit->count() ) {
+ m_forward->setEnabled(false);
+ } else {
+ m_forward->setEnabled(true);
+ }
+}
+
+// Go to an item from the editbale combo box.
+void Thesaurus::slotGotoHistory(int index)
+{
+ m_history_pos = m_edit->count() - index;
+ slotFindTerm(m_edit->text(index), false);
+}
+
+// Triggered when the back button is clicked.
+void Thesaurus::slotBack()
+{
+ m_history_pos--;
+ int pos = m_edit->count() - m_history_pos;
+ m_edit->setCurrentItem(pos);
+ slotFindTerm(m_edit->text(pos), false);
+}
+
+// Triggered when the forward button is clicked.
+void Thesaurus::slotForward()
+{
+ m_history_pos++;
+ int pos = m_edit->count() - m_history_pos;
+ m_edit->setCurrentItem(pos);
+ slotFindTerm(m_edit->text(pos), false);
+}
+
+// Triggered when a word is selected in the list box.
+void Thesaurus::slotSetReplaceTerm(TQListBoxItem *item)
+{
+ if( ! item )
+ return;
+ m_replace->setText(item->text());
+}
+
+void Thesaurus::slotSetReplaceTerm(const TQString &term)
+{
+ if( m_replacement && term != m_no_match ) {
+ m_replace->setText(term);
+ }
+}
+
+// Triggered when Return is pressed.
+void Thesaurus::slotFindTerm()
+{
+ findTerm(m_edit->currentText());
+}
+
+// Triggered when a word is clicked / a list item is double-clicked.
+void Thesaurus::slotFindTerm(const TQString &term, bool add_to_history)
+{
+ slotSetReplaceTerm(term);
+ if( term.startsWith("http://") ) {
+ (void) new KRun(KURL(term));
+ } else {
+ if( add_to_history ) {
+ m_edit->insertItem(term, 0);
+ m_history_pos = m_edit->count();
+ m_edit->setCurrentItem(0);
+ }
+ slotUpdateNavButtons();
+ findTerm(term);
+ }
+}
+
+void Thesaurus::findTerm(const TQString &term)
+{
+ findTermThesaurus(term);
+ findTermWordnet(term);
+}
+
+
+//
+// Thesaurus
+//
+void Thesaurus::findTermThesaurus(const TQString &term)
+{
+
+ if( !TQFile::exists(m_data_file) ) {
+ KMessageBox::error(0, i18n("The thesaurus file '%1' was not found. "
+ "Please use 'Change Language...' to select a thesaurus file.").
+ arg(m_data_file));
+ return;
+ }
+
+ TQApplication::setOverrideCursor(KCursor::waitCursor());
+
+ m_thesproc_stdout = "";
+ m_thesproc_stderr = "";
+
+ // Find only whole words. Looks clumsy, but this way we don't have to rely on
+ // features that might only be in certain versions of grep:
+ TQString term_tmp = ";" + term.stripWhiteSpace() + ";";
+ m_thesproc->clearArguments();
+ *m_thesproc << "grep" << "-i" << term_tmp;
+ *m_thesproc << m_data_file;
+
+ if( !m_thesproc->start(TDEProcess::NotifyOnExit, TDEProcess::AllOutput) ) {
+ KMessageBox::error(0, i18n("Failed to execute grep."));
+ TQApplication::restoreOverrideCursor();
+ return;
+ }
+}
+
+// The external process has ended, so we parse its result and put it in
+// the list box.
+void Thesaurus::thesExited(TDEProcess *)
+{
+
+ if( !m_thesproc_stderr.isEmpty() ) {
+ KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute grep. "
+ "Output:<br>%1").arg(m_thesproc_stderr));
+ TQApplication::restoreOverrideCursor();
+ return;
+ }
+
+ TQString search_term = m_edit->currentText().stripWhiteSpace();
+
+ TQStringList syn;
+ TQStringList hyper;
+ TQStringList hypo;
+
+ TQStringList lines = lines.split(TQChar('\n'), m_thesproc_stdout, false);
+ for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
+ TQString line = (*it);
+ if( line.startsWith(" ") ) { // ignore license (two spaces)
+ continue;
+ }
+ int sep_pos = line.find("#");
+ TQString syn_part = line.left(sep_pos);
+ TQString hyper_part = line.right(line.length()-sep_pos-1);
+ TQStringList syn_tmp = TQStringList::split(TQChar(';'), syn_part);
+ TQStringList hyper_tmp = TQStringList::split(TQChar(';'), hyper_part);
+ if( syn_tmp.grep(search_term, false).size() > 0 ) {
+ // match on the left side of the '#' -- synonyms
+ for ( TQStringList::Iterator it2 = syn_tmp.begin(); it2 != syn_tmp.end(); ++it2 ) {
+ // add if it's not the term itself and if it's not yet in the list
+ TQString term = (*it2);
+ if( term.lower() != search_term.lower() && syn.contains(term) == 0 ) {
+ syn.append(term);
+ }
+ }
+ for ( TQStringList::Iterator it2 = hyper_tmp.begin(); it2 != hyper_tmp.end(); ++it2 ) {
+ TQString term = (*it2);
+ if( term.lower() != search_term.lower() && hyper.contains(term) == 0 ) {
+ hyper.append(term);
+ }
+ }
+ }
+ if( hyper_tmp.grep(search_term, false).size() > 0 ) {
+ // match on the right side of the '#' -- hypernyms
+ for ( TQStringList::Iterator it2 = syn_tmp.begin(); it2 != syn_tmp.end(); ++it2 ) {
+ TQString term = (*it2);
+ if( term.lower() != search_term && hypo.contains(term) == 0 ) {
+ hypo.append(term);
+ }
+ }
+ }
+ }
+
+ m_thes_syn->clear();
+ if( syn.size() > 0 ) {
+ syn = sortTQStringList(syn);
+ m_thes_syn->insertStringList(syn);
+ m_thes_syn->setEnabled(true);
+ } else {
+ m_thes_syn->insertItem(m_no_match);
+ m_thes_syn->setEnabled(false);
+ }
+
+ m_thes_hyper->clear();
+ if( hyper.size() > 0 ) {
+ hyper = sortTQStringList(hyper);
+ m_thes_hyper->insertStringList(hyper);
+ m_thes_hyper->setEnabled(true);
+ } else {
+ m_thes_hyper->insertItem(m_no_match);
+ m_thes_hyper->setEnabled(false);
+ }
+
+ m_thes_hypo->clear();
+ if( hypo.size() > 0 ) {
+ hypo = sortTQStringList(hypo);
+ m_thes_hypo->insertStringList(hypo);
+ m_thes_hypo->setEnabled(true);
+ } else {
+ m_thes_hypo->insertItem(m_no_match);
+ m_thes_hypo->setEnabled(false);
+ }
+
+ TQApplication::restoreOverrideCursor();
+}
+
+void Thesaurus::receivedThesStdout(TDEProcess *, char *result, int len)
+{
+ m_thesproc_stdout += TQString::fromLocal8Bit( TQCString(result, len+1) );
+}
+
+void Thesaurus::receivedThesStderr(TDEProcess *, char *result, int len)
+{
+ m_thesproc_stderr += TQString::fromLocal8Bit( TQCString(result, len+1) );
+}
+
+
+//
+// WordNet
+//
+void Thesaurus::findTermWordnet(const TQString &term)
+{
+ TQApplication::setOverrideCursor(KCursor::waitCursor());
+
+ m_wnproc_stdout = "";
+ m_wnproc_stderr = "";
+
+ m_wnproc->clearArguments();
+ *m_wnproc << "wn";
+ *m_wnproc << term;
+
+ // get all results: nouns, verbs, adjectives, adverbs (see below for order):
+ if( m_combobox->currentItem() == 0 ) {
+ *m_wnproc << "-synsn" << "-synsv" << "-synsa" << "-synsr";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 1 ) {
+ *m_wnproc << "-simsv";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 2 ) {
+ *m_wnproc << "-antsn" << "-antsv" << "-antsa" << "-antsr";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 3 ) {
+ *m_wnproc << "-hypon" << "-hypov";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 4 ) {
+ *m_wnproc << "-meron";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 5 ) {
+ *m_wnproc << "-holon";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 6 ) {
+ // e.g. "size -> large/small"
+ *m_wnproc << "-attrn" << "-attra";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 7 ) {
+ // e.g. "kill -> die"
+ *m_wnproc << "-causv";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 8 ) {
+ // e.g. "walk -> step"
+ *m_wnproc << "-entav";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 9 ) {
+ *m_wnproc << "-famln" << "-famlv" << "-famla" << "-famlr";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 10 ) {
+ *m_wnproc << "-framv";
+ m_mode = other;
+ } else if( m_combobox->currentItem() == 11 ) {
+ *m_wnproc << "-grepn" << "-grepv" << "-grepa" << "-grepr";
+ m_mode = grep;
+ } else if( m_combobox->currentItem() == 12 ) {
+ *m_wnproc << "-over";
+ m_mode = other;
+ }
+ *m_wnproc << "-g"; // "Display gloss"
+
+ int current = m_combobox->currentItem(); // remember current position
+ m_combobox->clear();
+
+ // warning: order matters!
+ // 0:
+ m_combobox->insertItem(i18n("Synonyms/Hypernyms - Ordered by Frequency"));
+ m_combobox->insertItem(i18n("Synonyms - Ordered by Similarity of Meaning (verbs only)"));
+ m_combobox->insertItem(i18n("Antonyms - Words with Opposite Meanings"));
+ m_combobox->insertItem(i18n("Hyponyms - ... is a (kind of) %1").arg(m_edit->currentText()));
+ m_combobox->insertItem(i18n("Meronyms - %1 has a ...").arg(m_edit->currentText()));
+ // 5:
+ m_combobox->insertItem(i18n("Holonyms - ... has a %1").arg(m_edit->currentText()));
+ m_combobox->insertItem(i18n("Attributes"));
+ m_combobox->insertItem(i18n("Cause To (for some verbs only)"));
+ m_combobox->insertItem(i18n("Verb Entailment (for some verbs only)"));
+ m_combobox->insertItem(i18n("Familiarity & Polysemy Count"));
+ // 10:
+ m_combobox->insertItem(i18n("Verb Frames (examples of use)"));
+ m_combobox->insertItem(i18n("List of Compound Words"));
+ m_combobox->insertItem(i18n("Overview of Senses"));
+
+ /** NOT todo:
+ * -Hypernym tree: layout is difficult, you can get the same information
+ * by following links
+ * -Coordinate terms (sisters): just go to synset and then use hyponyms
+ * -Has Part Meronyms, Has Substance Meronyms, Has Member Meronyms,
+ * Member of Holonyms, Substance of Holonyms, Part of Holonyms:
+ * these are just subsets of Meronyms/Holonyms
+ * -hmern, hholn: these are just compact versions, you can get the
+ * same information by following some links
+ */
+
+ /** TODO?:
+ * -pert (e.g. nuclear -> nuclues, but "=>" are nested, difficult to display)
+ * -nomn(n|v), e.g. deny -> denial, but this doesn't seem to work?
+ */
+
+ m_combobox->setCurrentItem(current); // reset previous position
+
+ if( m_wnproc->isRunning() ) {
+ // should never happen
+ kdDebug(31000) << "Warning: findTerm(): process is already running?!" << endl;
+ TQApplication::restoreOverrideCursor();
+ return;
+ }
+
+ if( !m_wnproc->start(TDEProcess::NotifyOnExit, TDEProcess::AllOutput) ) {
+ m_resultbox->setText(i18n("<b>Error:</b> Failed to execute the WordNet program 'wn'. "
+ "WordNet has to be installed on your computer to use this component of kthesaurus, "
+ "and 'wn' has to be available in your $PATH environment variable. "
+ "Look for a WordNet package from your upstream distro package repository. "
+ "Or you can obtain WordNet at <a href=\"http://wordnet.princeton.edu/wordnet/download/current-version/\">"
+ "http://wordnet.princeton.edu/wordnet/download/current-version/</a>. "
+ "Notice that WordNet only supports the English language."));
+ m_combobox->setEnabled(false);
+ TQApplication::restoreOverrideCursor();
+ return;
+ }
+
+}
+
+// The process has ended, so parse its result and display it as TQt richtext.
+void Thesaurus::wnExited(TDEProcess *)
+{
+
+ if( !m_wnproc_stderr.isEmpty() ) {
+ m_resultbox->setText(i18n("<b>Error:</b> Failed to execute WordNet program 'wn'. "
+ "Output:<br>%1").arg(m_wnproc_stderr));
+ TQApplication::restoreOverrideCursor();
+ return;
+ }
+
+ if( m_wnproc_stdout.isEmpty() ) {
+ m_resultbox->setText(i18n("No match for '%1'.").arg(m_edit->currentText()));
+ } else {
+ // render in a table, each line one row:
+ TQStringList lines = lines.split(TQChar('\n'), m_wnproc_stdout, false);
+ TQString result = "<qt><table>\n";
+ // TODO in TQt > 3.01: try without the following line (it's necessary to ensure the
+ // first column is really always quite small):
+ result += "<tr><td width=\"10%\"></td><td width=\"90%\"></td></tr>\n";
+ uint ct = 0;
+ for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
+ TQString l = (*it);
+ // Remove some lines:
+ TQRegExp re("^\\d+( of \\d+)? senses? of \\w+");
+ if( re.search(l) != -1 ) {
+ continue;
+ }
+ // Escape XML:
+ l = l.replace('&', "&amp;");
+ l = l.replace('<', "&lt;");
+ l = l.replace('>', "&gt;");
+ // TODO?:
+ // move "=>" in own column?
+ l = formatLine(l);
+ // Table layout:
+ result += "<tr>";
+ if( l.startsWith(" ") ) {
+ result += "\t<td width=\"15\"></td>";
+ l = l.stripWhiteSpace();
+ result += "\t<td>" + l + "</td>";
+ } else {
+ l = l.stripWhiteSpace();
+ result += "<td colspan=\"2\">" + l + "</td>";
+ }
+ result += "</tr>\n";
+ ct++;
+ }
+ result += "\n</table></qt>\n";
+ m_resultbox->setText(result);
+ m_resultbox->setContentsPos(0,0);
+ //kdDebug() << result << endl;
+ }
+
+ TQApplication::restoreOverrideCursor();
+}
+
+void Thesaurus::receivedWnStdout(TDEProcess *, char *result, int len)
+{
+ m_wnproc_stdout += TQString::fromLocal8Bit( TQCString(result, len+1) );
+}
+
+void Thesaurus::receivedWnStderr(TDEProcess *, char *result, int len)
+{
+ m_wnproc_stderr += TQString::fromLocal8Bit( TQCString(result, len+1) );
+}
+
+
+//
+// Tools
+//
+
+// Format lines using TQt's simple richtext.
+TQString Thesaurus::formatLine(TQString l)
+{
+
+ if( l == "--------------" ) {
+ return TQString("<hr>");
+ }
+
+ TQRegExp re;
+
+ re.setPattern("^(\\d+\\.)(.*)$");
+ if( re.search(l) != -1 ) {
+ l = "<b>" +re.cap(1)+ "</b>" +re.cap(2);
+ return l;
+ }
+
+ re.setPattern("^.* of (noun|verb|adj|adv) .*");
+ if( re.search(l) != -1 ) {
+ l = "<font size=\"5\">" +re.cap()+ "</font>\n\n";
+ return l;
+ }
+
+ if( m_mode == grep ) {
+ l = l.stripWhiteSpace();
+ return TQString("<a href=\"" +l+ "\">" +l+ "</a>");
+ }
+
+ re.setPattern("^(Sense \\d+)");
+ if( re.search(l) != -1 ) {
+ l = "<b>" +re.cap()+ "</b>\n";
+ return l;
+ }
+
+ re.setPattern("(.*)(Also See-&gt;)(.*)");
+ // Example: first sense of verb "keep"
+ if( re.search(l) != -1 ) {
+ l = re.cap(1);
+ l += re.cap(2);
+ TQStringList links = links.split(TQChar(';'), re.cap(3), false);
+ for ( TQStringList::Iterator it = links.begin(); it != links.end(); ++it ) {
+ TQString link = (*it);
+ if( it != links.begin() ) {
+ l += ", ";
+ }
+ link = link.stripWhiteSpace();
+ link = link.remove(TQRegExp("#\\d+"));
+ l += "<a href=\"" +link+ "\">" +link+ "</a>";
+ }
+ l.prepend (' '); // indent in table
+ }
+
+ re.setPattern("(.*)(=&gt;|HAS \\w+:|PART OF:)(.*) --");
+ re.setMinimal(true); // non-greedy
+ if( re.search(l) != -1 ) {
+ int dash_pos = l.find("--");
+ TQString line_end = l.mid(dash_pos+2, l.length()-dash_pos);
+ l = re.cap(1);
+ l += re.cap(2) + " ";
+ TQStringList links = links.split(TQChar(','), re.cap(3), false);
+ for ( TQStringList::Iterator it = links.begin(); it != links.end(); ++it ) {
+ TQString link = (*it);
+ if( it != links.begin() ) {
+ l += ", ";
+ }
+ link = link.stripWhiteSpace();
+ l += "<a href=\"" +link+ "\">" +link+ "</a>";
+ }
+ l += "<font color=\"#777777\">" +line_end+ "</font>";
+ l.prepend(' '); // indent in table
+ return l;
+ }
+ re.setMinimal(false); // greedy again
+
+ return l;
+}
+
+/**
+ * Sort a list case insensitively.
+ * Be careful: @p list is modified
+ * TODO: use ksortablevaluelist?
+ */
+TQStringList Thesaurus::sortTQStringList(TQStringList list)
+{
+ // Sort list case-insensitive. This looks strange but using a TQMap
+ // is even suggested by the TQt documentation.
+ TQMap<TQString,TQString> map_list;
+ for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
+ TQString str = *it;
+ map_list[str.lower()] = str;
+ }
+ list.clear();
+ TQMap<TQString,TQString>::Iterator it;
+ // TQt doc: "the items are alphabetically sorted [by key] when iterating over the map":
+ for( it = map_list.begin(); it != map_list.end(); ++it ) {
+ list.append(it.data());
+ }
+ return list;
+}
+
+#include "main.moc"