
    [hR1                     H   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZmZmZmZ ddlmZmZ d	d
lmZ d	dlmZ dZdZdZ G d de      Z G d de       Z!d Z"	 	 	 	 d"dede#dede#de$de%de#fdZ&de#fdZ'de#fdZ(dee#df   defd Z)d#de#fd!Z*y)$zFCore functions, outside of the QGIS Server context for printing atlas.    N)Enum)Path)Union)uuid4)	QgsExpressionQgsExpressionContextQgsExpressionContextUtilsQgsLayoutExporterQgsLayoutItemLabelQgsLayoutItemMapQgsMasterLayoutInterface
QgsProjectQgsSettings)QgsLayerTreeMapCanvasBridgeQgsMapCanvas   )Logger)to_boolzCopyright 2021, 3LizzGPL version 3zinfo@3liz.orgc                       e Zd ZdZdZdZdZy)OutputFormatapplication/pdf	image/png
image/jpeg	image/svgN)__name__
__module____qualname__PdfPngJpegSvg     //var/www/qgis-server/plugins/atlasprint/core.pyr   r       s    
C
CD
Cr#   r   c                       e Zd ZdZy)AtlasPrintExceptionzA wrong input from the user.N)r   r   r   __doc__r"   r#   r$   r&   r&   '   s    &r#   r&   c                      d} t               }|j                  d|       }|j                  d      }g }|D ]?  }|j                  d      }t        |      dk7  r#|j	                  t        |d                A |S )zeRead the global settings about predefined scales.

    :return: List of scales.
    :rtype: list
    zW1:1000000,1:500000,1:250000,1:100000,1:50000,1:25000,1:10000,1:5000,1:2500,1:1000,1:500z
Map/scales,:   r   )r   valuesplitlenappendfloat)default_scalessettingsscales_stringdatascalesscaleitems          r$   global_scalesr8   ,   s    	- 
 }HNN<@Ms#DF &{{3t9>eDGn%	&
 Mr#   projectlayout_nameoutput_formatfeature_filterr5   r6   
request_idc           
      .   t               }t               }	t        | j                         |	      }
|
j	                          | j                         }|j                  |      }|j                  d| d| d       |t        j                  k(  rt        j                         }nK|t        j                  t        j                  fv rt        j                         }nt        j                         }d|_        d}d}d}|st#        d| d| d      |j%                         t&        j(                  k(  r!|j+                         D ]  }|j-                         |k(  s|} n |j/                         }|j1                         st#        d| d| d	      |j3                         }|t#        d| d
| d      t5        |||      }t7        |      }|j9                         rt#        d| d|j;                                t=               }|j?                  tA        jB                                |j?                  tA        jD                  |              |j?                  tA        jF                  |             |j?                  tA        jH                  |             |j?                  tA        jJ                  |             |jM                  |       |jO                         rt#        d| d|jQ                                |jS                  d       |jU                  |       |jW                         r[|rL|jW                         jY                  tZ        j\                         |jW                         j_                  |       |r4|jW                         jY                  tZ        j`                         ||_1        |s|jW                         je                         tZ        j`                  k(  r| jg                         ji                         }| jg                         jk                         }|rtm        |      dk(  r|jo                  d| d       tq               }||_1        n3|j%                         t&        jr                  k(  r|}nt#        d| d      |rt               jo                  d| d       |ju                         D ]  \  }}d}|jw                  |jy                               }t{        |t|              r:|j                  |       |jo                  d| d|jy                          d| d       |rt|jo                  d|jy                          d| d        t               jo                  d| d       t        |       dt                d|j,                  jy                          }t        t        j                               j                  |      }t               jo                  d| d| d|j                          |t        j                  t        j                  fv r6t        |xs |      }|j                  t        |      |      }t        |      }n|t        j                  fv r6t        |xs |      }|j                  t        |      |      }t        |      }nw|rAt        |j                  dd            } t               jo                  d| d|         | |_M        t        j                  |xs |t        |      |      \  }}|}!t        |      }t               jo                  d| d t        |              |t        j                  k7  rt#        d| d!| d"|       |j                         s)|j                  d| d#| d$| d%       t#        d&|       |S )'ac  Generate a PDF for an atlas or a report.

    :param project: The QGIS project.
    :type project: QgsProject

    :param layout_name: Name of the layout of the atlas or report.
    :type layout_name: basestring

    :param feature_filter: QGIS Expression to use to select the feature.
    It can return many features, a multiple pages PDF will be returned.
    This is required to print atlas, not report
    :type feature_filter: basestring

    :param scale: A scale to force in the atlas context. Default to None.
    :type scale: int

    :param scales: A list of predefined list of scales to force in the atlas context.
    Default to None.
    :type scales: list

    :param output_format: The output format, default to PDF if not provided.

    :param request_id: The X-Request-ID for a better debug.

    :return: Path to the PDF.
    :rtype: basestring
    Request-ID z,, preparing settings for the output format ""d   Nz
, layout `z` not foundz, the layout `z` is not enabled for an atlasz4, EXP_FILTER is mandatory to print an atlas layout ``z', expression is invalid, parser error: z%, expression is invalid, eval error: Tr   zR, map scales not found in project, fetching predefined map scales in global configz+, the layout is not supported by the pluginuL   , checking for additional parameters to set in the layout before printing…Fz, additional parameter "z-" found in the layout, setting the value to "zAdditional parameter "z3" has not been found in the layout, the value was "z", skippingz, end of additional parameters_.z, exporting the request in z using 	rasterizez, rasterize = z, export done, result z(, export not generated in QGIS exporter z : zZ, 
No error from QGIS Exporter, but the file does not exist.
Message from QGIS exporter : z
File path : 
z=Export OK from QGIS, but file not found on the file system : )Rr   r   r   layerTreeRootsetCanvasLayerslayoutManagerlayoutByNamedebugr   r!   r
   SvgExportSettingsr   r    ImageExportSettingsPdfExportSettingsdpir&   
layoutTyper   PrintLayoutprintLayoutsnameatlasenabledcoverageLayeroptimize_expressionr   hasParserErrorparserErrorStringr   appendScoper	   globalScopeprojectScopelayoutScope
atlasScope
layerScopepreparehasEvalErrorevalErrorStringsetFilterFeaturessetFilterExpressionreferenceMapsetAtlasScalingModer   FixedsetScale
PredefinedpredefinedMapScalesatlasScalingModeviewSettingsuseProjectScales	mapScalesr.   infor8   ReportitemsitemByIdlower
isinstancer   setTextclean_stringr   r   tempfile
gettempdirjoinpathr,   exportToImagestrresult_messageexportToSvgr   customPropertyrasterizeWholeImageexportToPdfSuccessis_filewarning)"r9   r:   r;   r<   r5   r6   r=   additional_paramsloggercanvasbridgemanagermaster_layoutr2   rT   atlas_layoutreport_layout_print_layoutlayer
expressioncontextuse_project
map_scaleskeyr,   foundr7   	file_nameexport_pathexporterresulterrorrE   rC   s"                                     r$   print_layoutr   D   s9   J XF^F(F ##%G((5M
LL;zl*VWdVeefgh((($668	<++\->->?	?$88: %668 HLELM!*Z}KH
 	
 !%=%I%II$113 	M!!#{2,	
 ""$}}%j\}Dab  ##%!%j\)]^i]jjkl  -UNJO">2
$$&%j\)PQ[QmQmQoPpq  '(5AACD5BB7KL5AA,OP5@@GH5@@GH7#""$%j\)NzOiOiOkNlm  	%!!.1$$&))+??@P@V@VW))+44U;))+??@P@[@[\/5,l779JJLP`PkPkk%224EEG$113==?
"c*o&:KK%j\ 2( ) "/J/9,		!	!	#'?'F'F	F% "K
|;f"ghh*%qr	
 ,113 	JCE((5D$ 23U#!*-Eciik] S--2G16 ,SYY[M9lmrls t  	 	J</MNO,-Quwiq9K9K9Q9Q9S8TUIx**,-66yAK
HMMK
|+F{mSZ[h[n[nZopq))<+<+<==$\%B]C''K(8(Cv&	<++.	.$\%B]C%%c+&6Av&  ; ;K OPIHMMK
|>)MN+4H()55e6L}cR]N^`hiv&
HMMK
|+A.QWBXAYZ["***!*%Mk]Z]^c]de
 	
  * &,,17 3&-r+	
 "$abman"oppr#   returnc                 \   | t         j                  k(  ry| t         j                  k(  ry| t         j                  k(  ry| t         j                  k(  ry| t         j
                  k(  ry| t         j                  k(  ry| t         j                  k(  ryt               j                  d|         d	|  S )
z- Error message according to the enumeration. r   CanceledzMemory errorz
File errorzPrint errorzSVG layer errorzIterator errorz[Check the PyQGIS documentation about this enum, maybe a new item in a newer QGIS version : zUnknown error : )
r
   r   r   MemoryError	FileError
PrintErrorSvgLayerErrorIteratorErrorr   critical)r   s    r$   r|   r|     s    !)))	#,,	,	#//	/	#--	-	#..	.	#11	1 	#11	1ijoipq	
 "%))r#   c                 L   dj                  | D cg c]*  }|j                         s|j                         s|dk(  s)|, c}      j                         } t	        j
                  d|       }|j                  dd      }|j                  d      }|j                  dd      }|S c c}w )z* Clean a string to be used as a file name   NFKDASCIIignorerC   )	joinisalphaisdigitrstripunicodedata	normalizeencodedecodereplace)input_stringc	nfkd_form
only_asciis       r$   rv   rv   %  s    77|^!qyy{aiikUVZ]U]A^_ffhL%%fl;I!!'84J""7+J##C-J _s
   *B!B!outputc                    | t         j                  S | j                         } | dk(  rt         j                  S | dv rt         j                  S | dv rt         j                  S | dv rt         j                  S | dv r)t               j                  d       t         j                  S t               j                  d|  d       t         j                  S )	z< Read the MIME type as string to return the correct format. r   )pdfr   )r   png)r   jpegjpg)svgr   zimage/svg+xmlz)SVG is not well supported. Default to PDFz2Output format is invalid, default to PDF. It was "r@   )r   r   rs   r   r    r   ro   )r   s    r$   parse_output_formatr   /  s     ~\\^F|	-	-	'	'	0	0   	8	8AB HMMFvhaPQr#   c           	         t               }|j                  d      dk  r|j                  d| d       |S | j                         }t	        |      dk7  r(|j                  d| d| j                          d       |S | j                         j                  d      }|j                         s9|j                  d| d|j                          d	| j                          d       |S |j                  dd
|j                          d
      }|j                  d| d|j                          d| j                          d
       |S )zdCheck if we can optimize the expression.

    https://github.com/3liz/qgis-atlasprint/issues/23
    z$idr   r?   zD : $id' not found in the expression, returning the input expression.r   z. : Primary keys are not defined in the layer 'z'.z : The field 'z' is not numeric in layer 'r@   z : $id has been replaced by "z" in layer ")r   findro   primaryKeyAttributesr.   idfieldsat	isNumericrS   r   )r   r   r=   r   primary_keysfields         r$   rW   rW   M  s7   
 XFu!k*-qrs--/L
<Ak*-[\a\d\d\f[ggijkLLNa E??k*^EJJL>Idejememeodpprst##EQuzz|nA+>?J
KK+j\)Fuzz|nT`afaiaiak`llmnor#   )NNNr   )ND)+r'   rw   r   enumr   pathlibr   typingr   uuidr   	qgis.corer   r   r	   r
   r   r   r   r   r   qgis.guir   r   r   r   toolsr   __copyright____license__	__email__r   	Exceptionr&   r8   r{   listintr   r|   rv   r   rW   r"   r#   r$   <module>r      s    L      
 
 
 ?  &	4 	) 	
8 GGG  G 	G
 G G GT*S *.# c4i 0 \ <s r#   