app_Main.py 474 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. # version = "Unstable Version"
  138. version = 8.994
  139. version_date = "2020/10/30"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, qapp, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # declare it here so there is a reference
  224. self.f_handlers = lambda: None
  225. # ############################################################################################################
  226. # ################# Setup the listening thread for another instance launching with args ######################
  227. # ############################################################################################################
  228. if sys.platform == 'win32' or sys.platform == 'linux':
  229. # make sure the thread is stored by using a self. otherwise it's garbage collected
  230. self.listen_th = QtCore.QThread()
  231. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  232. self.new_launch = ArgsThread()
  233. self.new_launch.open_signal[list].connect(self.on_startup_args)
  234. self.new_launch.moveToThread(self.listen_th)
  235. self.new_launch.start.emit()
  236. # ############################################################################################################
  237. # ########################################## OS-specific #####################################################
  238. # ############################################################################################################
  239. portable = False
  240. # Folder for user settings.
  241. if sys.platform == 'win32':
  242. if platform.architecture()[0] == '32bit':
  243. self.log.debug("Win32!")
  244. else:
  245. self.log.debug("Win64!")
  246. # #######################################################################################################
  247. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  248. # #######################################################################################################
  249. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r'):
  252. pass
  253. except FileNotFoundError:
  254. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r') as f:
  257. try:
  258. for line in f:
  259. param = str(line).replace('\n', '').rpartition('=')
  260. if param[0] == 'portable':
  261. try:
  262. portable = eval(param[2])
  263. except NameError:
  264. portable = False
  265. if param[0] == 'headless':
  266. if param[2].lower() == 'true':
  267. self.cmd_line_headless = 1
  268. else:
  269. self.cmd_line_headless = None
  270. except Exception as e:
  271. self.log.debug('App.__init__() -->%s' % str(e))
  272. return
  273. except FileNotFoundError as e:
  274. self.log.debug(str(e))
  275. pass
  276. if portable is False:
  277. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  278. else:
  279. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  280. self.os = 'windows'
  281. else: # Linux/Unix/MacOS
  282. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  283. self.os = 'unix'
  284. # ############################################################################################################
  285. # ################################# Setup folders and files ##################################################
  286. # ############################################################################################################
  287. if not os.path.exists(self.data_path):
  288. os.makedirs(self.data_path)
  289. self.log.debug('Created data folder: ' + self.data_path)
  290. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  291. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  292. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  293. if not os.path.exists(self.preprocessorpaths):
  294. os.makedirs(self.preprocessorpaths)
  295. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  296. # create tools_db.FlatDB file if there is none
  297. try:
  298. f = open(self.data_path + '/tools_db.FlatDB')
  299. f.close()
  300. except IOError:
  301. self.log.debug('Creating empty tools_db.FlatDB')
  302. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  303. json.dump({}, f)
  304. f.close()
  305. # create current_defaults.FlatConfig file if there is none
  306. try:
  307. f = open(self.data_path + '/current_defaults.FlatConfig')
  308. f.close()
  309. except IOError:
  310. self.log.debug('Creating empty current_defaults.FlatConfig')
  311. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  312. json.dump({}, f)
  313. f.close()
  314. # the factory defaults are written only once at the first launch of the application after installation
  315. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  316. # create a recent files json file if there is none
  317. try:
  318. f = open(self.data_path + '/recent.json')
  319. f.close()
  320. except IOError:
  321. self.log.debug('Creating empty recent.json')
  322. f = open(self.data_path + '/recent.json', 'w')
  323. json.dump([], f)
  324. f.close()
  325. # create a recent projects json file if there is none
  326. try:
  327. fp = open(self.data_path + '/recent_projects.json')
  328. fp.close()
  329. except IOError:
  330. self.log.debug('Creating empty recent_projects.json')
  331. fp = open(self.data_path + '/recent_projects.json', 'w')
  332. json.dump([], fp)
  333. fp.close()
  334. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  335. # This will fail under cx_freeze ...
  336. self.app_home = os.path.dirname(os.path.realpath(__file__))
  337. self.log.debug("Application path is " + self.app_home)
  338. self.log.debug("Started in " + os.getcwd())
  339. # cx_freeze workaround
  340. if os.path.isfile(self.app_home):
  341. self.app_home = os.path.dirname(self.app_home)
  342. os.chdir(self.app_home)
  343. # ############################################################################################################
  344. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  345. # ############################################################################################################
  346. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  347. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  348. if user_defaults:
  349. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  350. if self.defaults['units'] == 'MM':
  351. self.decimals = int(self.defaults['decimals_metric'])
  352. else:
  353. self.decimals = int(self.defaults['decimals_inch'])
  354. if self.defaults["global_gray_icons"] is False:
  355. self.resource_location = 'assets/resources'
  356. else:
  357. self.resource_location = 'assets/resources/dark_resources'
  358. self.current_units = self.defaults['units']
  359. # ###########################################################################################################
  360. # #################################### SETUP OBJECT CLASSES #################################################
  361. # ###########################################################################################################
  362. self.setup_obj_classes()
  363. # ###########################################################################################################
  364. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  365. # ###########################################################################################################
  366. self.pool = Pool()
  367. # ###########################################################################################################
  368. # ###################################### Clear GUI Settings - once at first start ###########################
  369. # ###########################################################################################################
  370. if self.defaults["first_run"] is True:
  371. # on first run clear the previous QSettings, therefore clearing the GUI settings
  372. qsettings = QSettings("Open Source", "FlatCAM")
  373. for key in qsettings.allKeys():
  374. qsettings.remove(key)
  375. # This will write the setting to the platform specific storage.
  376. del qsettings
  377. # ###########################################################################################################
  378. # ###################################### Setting the Splash Screen ##########################################
  379. # ###########################################################################################################
  380. splash_settings = QSettings("Open Source", "FlatCAM")
  381. if splash_settings.contains("splash_screen"):
  382. show_splash = splash_settings.value("splash_screen")
  383. else:
  384. splash_settings.setValue('splash_screen', 1)
  385. # This will write the setting to the platform specific storage.
  386. del splash_settings
  387. show_splash = 1
  388. if show_splash and self.cmd_line_headless != 1:
  389. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  390. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  391. # self.splash.setMask(splash_pix.mask())
  392. # move splashscreen to the current monitor
  393. desktop = QtWidgets.QApplication.desktop()
  394. screen = desktop.screenNumber(QtGui.QCursor.pos())
  395. current_screen_center = desktop.availableGeometry(screen).center()
  396. self.splash.move(current_screen_center - self.splash.rect().center())
  397. self.splash.show()
  398. self.splash.showMessage(_("The application is initializing ..."),
  399. alignment=Qt.AlignBottom | Qt.AlignLeft,
  400. color=QtGui.QColor("gray"))
  401. else:
  402. self.splash = None
  403. show_splash = 0
  404. # ###########################################################################################################
  405. # ######################################### Initialize GUI ##################################################
  406. # ###########################################################################################################
  407. # FlatCAM colors used in plotting
  408. self.FC_light_green = '#BBF268BF'
  409. self.FC_dark_green = '#006E20BF'
  410. self.FC_light_blue = '#a5a5ffbf'
  411. self.FC_dark_blue = '#0000ffbf'
  412. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  413. if theme_settings.contains("theme"):
  414. theme = theme_settings.value('theme', type=str)
  415. else:
  416. theme = 'white'
  417. if self.defaults["global_cursor_color_enabled"]:
  418. self.cursor_color_3D = self.defaults["global_cursor_color"]
  419. else:
  420. if theme == 'white':
  421. self.cursor_color_3D = 'black'
  422. else:
  423. self.cursor_color_3D = 'gray'
  424. # update the defaults dict with the setting in QSetting
  425. self.defaults['global_theme'] = theme
  426. self.ui = MainGUI(self)
  427. # set FlatCAM units in the Status bar
  428. self.set_screen_units(self.defaults['units'])
  429. # ###########################################################################################################
  430. # ########################################### AUTOSAVE SETUP ################################################
  431. # ###########################################################################################################
  432. self.block_autosave = False
  433. self.autosave_timer = QtCore.QTimer(self)
  434. self.save_project_auto_update()
  435. self.autosave_timer.timeout.connect(self.save_project_auto)
  436. # ###########################################################################################################
  437. # #################################### LOAD PREPROCESSORS ###################################################
  438. # ###########################################################################################################
  439. # ----------------------------------------- WARNING --------------------------------------------------------
  440. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  441. # That's because the number of preprocessors can vary and here the comboboxes are populated
  442. # -----------------------------------------------------------------------------------------------------------
  443. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  444. # the preprocessor file
  445. self.preprocessors = load_preprocessors(self)
  446. # make sure that always the 'default' preprocessor is the first item in the dictionary
  447. if 'default' in self.preprocessors.keys():
  448. new_ppp_dict = {}
  449. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  450. default_pp = self.preprocessors.pop('default')
  451. new_ppp_dict['default'] = default_pp
  452. # then add the rest of the keys
  453. for name, val_class in self.preprocessors.items():
  454. new_ppp_dict[name] = val_class
  455. # and now put back the ordered dict with 'default' key first
  456. self.preprocessors = new_ppp_dict
  457. # populate the Preprocessor ComboBoxes in the PREFERENCES
  458. for name in list(self.preprocessors.keys()):
  459. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  460. if name.partition('_')[0] == 'Paste':
  461. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  462. continue
  463. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  464. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  465. if name == 'hpgl':
  466. continue
  467. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  468. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  469. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  470. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  471. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  472. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  473. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  474. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  475. QtCore.Qt.ToolTipRole)
  476. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  477. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  478. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  479. QtCore.Qt.ToolTipRole)
  480. # ###########################################################################################################
  481. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  482. # ###########################################################################################################
  483. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  484. inform=self.inform)
  485. self.preferencesUiManager.defaults_write_form()
  486. # When the self.defaults dictionary changes will update the Preferences GUI forms
  487. self.defaults.set_change_callback(self.on_defaults_dict_change)
  488. # ###########################################################################################################
  489. # ##################################### FIRST RUN SECTION ###################################################
  490. # ################################ It's done only once after install #####################################
  491. # ###########################################################################################################
  492. if self.defaults["first_run"] is True:
  493. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  494. initial_lay = 'minimal'
  495. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  496. # Set the combobox in Preferences to the current layout
  497. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  498. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  499. # after the first run, this object should be False
  500. self.defaults["first_run"] = False
  501. self.preferencesUiManager.save_defaults(silent=True)
  502. # ###########################################################################################################
  503. # ############################################ Data #########################################################
  504. # ###########################################################################################################
  505. self.recent = []
  506. self.recent_projects = []
  507. self.clipboard = QtWidgets.QApplication.clipboard()
  508. self.project_filename = None
  509. self.toggle_units_ignore = False
  510. self.main_thread = QtWidgets.QApplication.instance().thread()
  511. # ###########################################################################################################
  512. # ########################################## LOAD LANGUAGES ################################################
  513. # ###########################################################################################################
  514. self.languages = fcTranslate.load_languages()
  515. for name in sorted(self.languages.values()):
  516. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  517. # ###########################################################################################################
  518. # ####################################### APPLY APP LANGUAGE ################################################
  519. # ###########################################################################################################
  520. ret_val = fcTranslate.apply_language('strings')
  521. if ret_val == "no language":
  522. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  523. self.log.debug("Could not find the Language files. The App strings are missing.")
  524. else:
  525. # make the current language the current selection on the language combobox
  526. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  527. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  528. # ###########################################################################################################
  529. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  530. # ###########################################################################################################
  531. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  532. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  533. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  534. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  535. self.defaults.propagate_defaults()
  536. # ###########################################################################################################
  537. # ######################################## UPDATE THE OPTIONS ###############################################
  538. # ###########################################################################################################
  539. self.options = LoudDict()
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Update the self.options from the self.defaults
  542. # The self.defaults holds the application defaults while the self.options holds the object defaults
  543. # -----------------------------------------------------------------------------------------------------------
  544. # Copy app defaults to project options
  545. for def_key, def_val in self.defaults.items():
  546. self.options[def_key] = deepcopy(def_val)
  547. self.preferencesUiManager.show_preferences_gui()
  548. # ### End of Data ####
  549. # ###########################################################################################################
  550. # #################################### SETUP OBJECT COLLECTION ##############################################
  551. # ###########################################################################################################
  552. self.collection = ObjectCollection(app=self)
  553. self.ui.project_tab_layout.addWidget(self.collection.view)
  554. self.app_obj = AppObject(app=self)
  555. # ### Adjust tabs width ## ##
  556. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  557. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  558. self.collection.view.setMinimumWidth(290)
  559. self.log.debug("Finished creating Object Collection.")
  560. # ###########################################################################################################
  561. # ######################################## SETUP Plot Area ##################################################
  562. # ###########################################################################################################
  563. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  564. if self.defaults["global_graphic_engine"] == '3D':
  565. self.is_legacy = False
  566. else:
  567. self.is_legacy = True
  568. # Event signals disconnect id holders
  569. self.mp = None
  570. self.mm = None
  571. self.mr = None
  572. self.mdc = None
  573. self.mp_zc = None
  574. self.kp = None
  575. # Matplotlib axis
  576. self.axes = None
  577. if show_splash:
  578. self.splash.showMessage(_("The application is initializing ...\n"
  579. "Canvas initialization started."),
  580. alignment=Qt.AlignBottom | Qt.AlignLeft,
  581. color=QtGui.QColor("gray"))
  582. start_plot_time = time.time() # debug
  583. self.plotcanvas = None
  584. self.app_cursor = None
  585. self.hover_shapes = None
  586. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  587. # setup the PlotCanvas
  588. self.on_plotcanvas_setup()
  589. end_plot_time = time.time()
  590. self.used_time = end_plot_time - start_plot_time
  591. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  592. if show_splash:
  593. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  594. "Canvas initialization started.\n"
  595. "Canvas initialization finished in"), '%.2f' % self.used_time),
  596. alignment=Qt.AlignBottom | Qt.AlignLeft,
  597. color=QtGui.QColor("gray"))
  598. self.ui.splitter.setStretchFactor(1, 2)
  599. # ###########################################################################################################
  600. # ############################################### Worker SETUP ##############################################
  601. # ###########################################################################################################
  602. if self.defaults["global_worker_number"]:
  603. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  604. else:
  605. self.workers = WorkerStack(workers_number=2)
  606. self.worker_task.connect(self.workers.add_task)
  607. self.log.debug("Finished creating Workers crew.")
  608. # ###########################################################################################################
  609. # ############################################# Activity Monitor ############################################
  610. # ###########################################################################################################
  611. # self.activity_view = FlatCAMActivityView(app=self)
  612. # self.ui.infobar.addWidget(self.activity_view)
  613. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  614. # ###########################################################################################################
  615. # ########################################## Other setups ###################################################
  616. # ###########################################################################################################
  617. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  618. # depending on from where those tools are called different actions can be done
  619. self.call_source = 'app'
  620. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  621. self.tool_tab_locked = False
  622. # decide if to show or hide the Notebook side of the screen at startup
  623. if self.defaults["global_project_at_startup"] is True:
  624. self.ui.splitter.setSizes([1, 1])
  625. else:
  626. self.ui.splitter.setSizes([0, 1])
  627. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  628. self.setup_default_properties_tab()
  629. # ###########################################################################################################
  630. # ####################################### Auto-complete KEYWORDS ############################################
  631. # ###########################################################################################################
  632. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  633. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  634. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  635. 'export_exc',
  636. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  637. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  638. 'interiors', 'isolate', 'join_excellon',
  639. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  640. 'mirror', 'ncc',
  641. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  642. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  643. 'options', 'origin',
  644. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  645. 'save', 'save_project',
  646. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  647. 'skew', 'subtract_poly', 'subtract_rectangle',
  648. 'version', 'write_gcode'
  649. ]
  650. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  651. 'Paste_1',
  652. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  653. 'Toolchange_manual', 'True', 'Users',
  654. 'all', 'auto', 'axis',
  655. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  656. 'contour', 'default',
  657. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  658. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  659. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  660. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  661. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  662. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  663. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  664. 'spacing_columns',
  665. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  666. 'toolchange_xy', 'toolchangez', 'travelz',
  667. 'tooldia', 'use_threads', 'value',
  668. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  669. ]
  670. self.tcl_keywords = [
  671. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  672. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  673. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  674. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  675. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  676. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  677. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  678. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  679. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  680. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  681. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  682. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  683. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  684. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  685. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  686. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  687. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  688. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  689. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  690. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  691. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  692. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  693. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  694. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  695. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  696. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  697. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  698. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  699. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  700. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  701. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  702. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  703. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  704. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  705. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  706. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  707. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  708. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  709. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  710. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  711. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  712. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  713. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  714. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  715. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  716. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  717. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  718. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  719. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  720. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  721. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  722. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  723. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  724. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  725. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  726. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  727. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  728. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  729. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  730. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  731. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  732. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  733. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  734. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  735. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  736. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  737. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  738. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  739. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  740. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  741. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  742. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  743. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  744. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  745. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  746. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  747. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  748. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  749. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  750. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  751. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  752. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  753. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  754. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  755. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  756. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  757. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  758. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  759. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  760. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  761. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  762. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  763. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  764. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  765. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  766. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  767. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  768. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  769. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  770. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  771. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  772. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  773. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  774. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  775. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  776. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  777. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  778. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  779. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  780. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  781. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  782. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  783. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  784. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  785. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  786. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  787. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  788. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  789. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  790. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  791. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  792. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  793. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  794. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  795. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  796. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  797. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  798. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  799. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  800. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  801. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  802. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  803. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  804. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  805. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  806. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  807. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  808. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  809. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  810. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  811. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  812. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  813. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  814. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  815. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  816. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  817. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  818. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  819. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  820. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  821. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  822. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  823. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  824. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  825. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  826. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  827. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  828. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  829. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  830. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  831. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  832. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  833. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  834. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  835. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  836. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  837. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  838. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  839. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  840. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  841. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  842. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  843. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  844. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  845. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  846. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  847. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  848. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  849. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  850. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  851. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  852. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  853. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  854. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  855. ]
  856. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  857. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  858. # ###########################################################################################################
  859. # ########################################## Tools and Plugins ##############################################
  860. # ###########################################################################################################
  861. self.shell = None
  862. self.dblsidedtool = None
  863. self.distance_tool = None
  864. self.distance_min_tool = None
  865. self.panelize_tool = None
  866. self.film_tool = None
  867. self.paste_tool = None
  868. self.calculator_tool = None
  869. self.rules_tool = None
  870. self.sub_tool = None
  871. self.move_tool = None
  872. self.cutout_tool = None
  873. self.ncclear_tool = None
  874. self.paint_tool = None
  875. self.isolation_tool = None
  876. self.drilling_tool = None
  877. self.optimal_tool = None
  878. self.transform_tool = None
  879. self.properties_tool = None
  880. self.pdf_tool = None
  881. self.image_tool = None
  882. self.pcb_wizard_tool = None
  883. self.cal_exc_tool = None
  884. self.qrcode_tool = None
  885. self.copper_thieving_tool = None
  886. self.fiducial_tool = None
  887. self.edrills_tool = None
  888. self.align_objects_tool = None
  889. self.punch_tool = None
  890. self.invert_tool = None
  891. self.corners_tool = None
  892. self.etch_tool = None
  893. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  894. try:
  895. self.install_tools()
  896. except AttributeError as e:
  897. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  898. # ###########################################################################################################
  899. # ######################################### BookMarks Manager ###############################################
  900. # ###########################################################################################################
  901. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  902. self.install_bookmarks()
  903. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  904. # ###########################################################################################################
  905. # ########################################### Tools Database ################################################
  906. # ###########################################################################################################
  907. self.tools_db_tab = None
  908. # ### System Font Parsing ###
  909. # self.f_parse = ParseFont(self)
  910. # self.parse_system_fonts()
  911. # ###########################################################################################################
  912. # ############################################## Shell SETUP ################################################
  913. # ###########################################################################################################
  914. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  915. if self.defaults["global_shell_at_startup"]:
  916. self.ui.shell_dock.show()
  917. else:
  918. self.ui.shell_dock.hide()
  919. # ###########################################################################################################
  920. # ######################################### Check for updates ###############################################
  921. # ###########################################################################################################
  922. # Separate thread (Not worker)
  923. # Check for updates on startup but only if the user consent and the app is not in Beta version
  924. if (self.beta is False or self.beta is None) and \
  925. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  926. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  927. # self.thr2 = QtCore.QThread()
  928. self.worker_task.emit({'fcn': self.version_check,
  929. 'params': []})
  930. # self.thr2.start(QtCore.QThread.LowPriority)
  931. # ###########################################################################################################
  932. # ##################################### Register files with FlatCAM; #######################################
  933. # ################################### It works only for Windows for now ####################################
  934. # ###########################################################################################################
  935. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  936. self.on_register_files()
  937. # ###########################################################################################################
  938. # ######################################## Variables for global usage #######################################
  939. # ###########################################################################################################
  940. # hold the App units
  941. self.units = 'MM'
  942. # coordinates for relative position display
  943. self.rel_point1 = (0, 0)
  944. self.rel_point2 = (0, 0)
  945. # variable to store coordinates
  946. self.pos = (0, 0)
  947. self.pos_canvas = (0, 0)
  948. self.pos_jump = (0, 0)
  949. # variable to store mouse coordinates
  950. self.mouse = [0, 0]
  951. # variable to store the delta positions on cavnas
  952. self.dx = 0
  953. self.dy = 0
  954. # decide if we have a double click or single click
  955. self.doubleclick = False
  956. # store here the is_dragging value
  957. self.event_is_dragging = False
  958. # variable to store if a command is active (then the var is not None) and which one it is
  959. self.command_active = None
  960. # variable to store the status of moving selection action
  961. # None value means that it's not an selection action
  962. # True value = a selection from left to right
  963. # False value = a selection from right to left
  964. self.selection_type = None
  965. # List to store the objects that are currently loaded in FlatCAM
  966. # This list is updated on each object creation or object delete
  967. self.all_objects_list = []
  968. self.objects_under_the_click_list = []
  969. # List to store the objects that are selected
  970. self.sel_objects_list = []
  971. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  972. self.key_modifiers = None
  973. # Variable to store the status of the code editor
  974. self.toggle_codeeditor = False
  975. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  976. self.click_noproject = False
  977. self.cursor = None
  978. # Variable to store the GCODE that was edited
  979. self.gcode_edited = ""
  980. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  981. self.old_state_of_tools_toolbar = False
  982. self.text_editor_tab = None
  983. # reference for the self.ui.code_editor
  984. self.reference_code_editor = None
  985. self.script_code = ''
  986. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  987. self.tools_db_changed_flag = False
  988. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  989. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  990. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  991. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  992. 'tsm']
  993. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  994. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  995. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  996. 'sbp', 'tap', 'xpi']
  997. self.svg_list = ['svg']
  998. self.dxf_list = ['dxf']
  999. self.pdf_list = ['pdf']
  1000. self.prj_list = ['flatprj']
  1001. self.conf_list = ['flatconfig']
  1002. # last used filters
  1003. self.last_op_gerber_filter = None
  1004. self.last_op_excellon_filter = None
  1005. self.last_op_gcode_filter = None
  1006. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1007. # flag for polygons not cleared
  1008. self.poly_not_cleared = False
  1009. # VisPy visuals
  1010. self.isHovering = False
  1011. self.notHovering = True
  1012. # Window geometry
  1013. self.x_pos = None
  1014. self.y_pos = None
  1015. self.width = None
  1016. self.height = None
  1017. # when True, the app has to return from any thread
  1018. self.abort_flag = False
  1019. # set the value used in the Windows Title
  1020. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1021. # this holds a widget that is installed in the Plot Area when View Source option is used
  1022. self.source_editor_tab = None
  1023. self.pagesize = {}
  1024. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1025. # VisPy visuals
  1026. if self.is_legacy is False:
  1027. try:
  1028. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1029. except AttributeError:
  1030. self.tool_shapes = None
  1031. else:
  1032. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1033. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1034. # used in the delayed shutdown self.start_delayed_quit() method
  1035. self.save_timer = None
  1036. # ###########################################################################################################
  1037. # ################################## ADDING FlatCAM EDITORS section #########################################
  1038. # ###########################################################################################################
  1039. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1040. # at the first launch of the App , the editors will not be functional.
  1041. try:
  1042. self.geo_editor = AppGeoEditor(self)
  1043. except Exception as es:
  1044. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1045. try:
  1046. self.exc_editor = AppExcEditor(self)
  1047. except Exception as es:
  1048. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1049. try:
  1050. self.grb_editor = AppGerberEditor(self)
  1051. except Exception as es:
  1052. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1053. try:
  1054. self.gcode_editor = AppGCodeEditor(self)
  1055. except Exception as es:
  1056. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1057. self.log.debug("Finished adding FlatCAM Editor's.")
  1058. self.set_ui_title(name=_("New Project - Not saved"))
  1059. current_platform = platform.architecture()[0]
  1060. if current_platform != '64bit':
  1061. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1062. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1063. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1064. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1065. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1066. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1067. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1068. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1069. # ###########################################################################################################
  1070. # ########################################### EXCLUSION AREAS ###############################################
  1071. # ###########################################################################################################
  1072. self.exc_areas = ExclusionAreas(app=self)
  1073. # ###########################################################################################################
  1074. # ###########################################################################################################
  1075. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1076. # ###########################################################################################################
  1077. # ###########################################################################################################
  1078. self.f_handlers = MenuFileHandlers(app=self)
  1079. # this is calculated in the class above (somehow?)
  1080. self.defaults["root_folder_path"] = self.app_home
  1081. # ###########################################################################################################
  1082. # ############################################### SYS TRAY ##################################################
  1083. # ###########################################################################################################
  1084. if self.defaults["global_systray_icon"]:
  1085. self.parent_w = QtWidgets.QWidget()
  1086. if self.cmd_line_headless == 1:
  1087. self.trayIcon = FlatCAMSystemTray(app=self,
  1088. icon=QtGui.QIcon(self.resource_location +
  1089. '/flatcam_icon32_green.png'),
  1090. headless=True,
  1091. parent=self.parent_w)
  1092. else:
  1093. self.trayIcon = FlatCAMSystemTray(app=self,
  1094. icon=QtGui.QIcon(self.resource_location +
  1095. '/flatcam_icon32_green.png'),
  1096. parent=self.parent_w)
  1097. # ###########################################################################################################
  1098. # ############################################ SETUP RECENT ITEMS ###########################################
  1099. # ###########################################################################################################
  1100. self.setup_recent_items()
  1101. # ###########################################################################################################
  1102. # ###########################################################################################################
  1103. # ############################################# Signal handling #############################################
  1104. # ###########################################################################################################
  1105. # ###########################################################################################################
  1106. # ########################################## Custom signals ################################################
  1107. # signal for displaying messages in status bar
  1108. self.inform[str].connect(self.info)
  1109. self.inform[str, bool].connect(self.info)
  1110. # signal for displaying messages in the shell
  1111. self.inform_shell[str].connect(self.info_shell)
  1112. self.inform_shell[str, bool].connect(self.info_shell)
  1113. # signal to be called when the app is quiting
  1114. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1115. self.message.connect(lambda: message_dialog(parent=self.ui))
  1116. # self.progress.connect(self.set_progress_bar)
  1117. # signals emitted when file state change
  1118. self.file_opened.connect(self.register_recent)
  1119. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1120. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1121. # when the defaults dictionary values change
  1122. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1123. # ########################################## Standard signals ###############################################
  1124. # ### Menu
  1125. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1126. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1127. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1128. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1129. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1130. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1131. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1132. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1133. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1134. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1135. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1136. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1137. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1138. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1139. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1140. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1141. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1142. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1143. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1144. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1145. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1146. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1147. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1148. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1149. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1150. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1151. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1152. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1153. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1154. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1155. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1156. self.ui.menufile_exit.triggered.connect(self.final_save)
  1157. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1158. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1159. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1160. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1161. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1162. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1163. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1164. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1165. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1166. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1167. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1168. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1169. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1170. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1171. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1172. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1173. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1174. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1175. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1176. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1177. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1178. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1179. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1180. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1181. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1182. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1183. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1184. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1185. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1186. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1187. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1188. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1189. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1190. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1191. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1192. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1193. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1194. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1195. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1196. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1197. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1198. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1199. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1200. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1201. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1202. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1203. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1204. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1205. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1206. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1207. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1208. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1209. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1210. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1211. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1212. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1213. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1214. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1215. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1216. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1217. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1218. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1219. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1220. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1221. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1222. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1223. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1224. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1225. # ToolBar signals
  1226. self.connect_toolbar_signals(ui=self.ui)
  1227. # Context Menu
  1228. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1229. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1230. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1231. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1232. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1233. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1234. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1235. self.ui.clearplot.triggered.connect(self.clear_plots)
  1236. self.ui.replot.triggered.connect(self.plot_all)
  1237. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1238. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1239. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1240. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1241. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1242. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1243. # Project Context Menu -> Color Setting
  1244. for act in self.ui.menuprojectcolor.actions():
  1245. act.triggered.connect(self.on_set_color_action_triggered)
  1246. # Notebook tab clicking
  1247. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1248. # ###########################################################################################################
  1249. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1250. # ###########################################################################################################
  1251. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1252. lambda: self.on_toggle_units(no_pref=False))
  1253. # ##################################### Workspace Setting Signals ###########################################
  1254. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1255. self.on_workspace_modified)
  1256. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1257. self.on_workspace_modified
  1258. )
  1259. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1260. # ###########################################################################################################
  1261. # ######################################## GUI SETTINGS SIGNALS #############################################
  1262. # ###########################################################################################################
  1263. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1264. # ######################################## Tools related signals ############################################
  1265. # portability changed signal
  1266. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1267. # Object list
  1268. self.object_status_changed.connect(self.collection.on_collection_updated)
  1269. # when there are arguments at application startup this get launched
  1270. self.args_at_startup[list].connect(self.on_startup_args)
  1271. # ###########################################################################################################
  1272. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1273. # ###########################################################################################################
  1274. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1275. lambda: self.restore_extensions(ext_type='excellon'))
  1276. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1277. lambda: self.restore_extensions(ext_type='gcode'))
  1278. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1279. lambda: self.restore_extensions(ext_type='gerber'))
  1280. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1281. lambda: self.delete_all_extensions(ext_type='excellon'))
  1282. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1283. lambda: self.delete_all_extensions(ext_type='gcode'))
  1284. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1285. lambda: self.delete_all_extensions(ext_type='gerber'))
  1286. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1287. lambda: self.add_extension(ext_type='excellon'))
  1288. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1289. lambda: self.add_extension(ext_type='gcode'))
  1290. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1291. lambda: self.add_extension(ext_type='gerber'))
  1292. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1293. lambda: self.del_extension(ext_type='excellon'))
  1294. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1295. lambda: self.del_extension(ext_type='gcode'))
  1296. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1297. lambda: self.del_extension(ext_type='gerber'))
  1298. # connect the 'Apply' buttons from the Preferences/File Associations
  1299. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1300. lambda: self.on_register_files(obj_type='excellon'))
  1301. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1302. lambda: self.on_register_files(obj_type='gcode'))
  1303. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1304. lambda: self.on_register_files(obj_type='gerber'))
  1305. # ###########################################################################################################
  1306. # ########################################### KEYWORDS SIGNALS ##############################################
  1307. # ###########################################################################################################
  1308. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1309. lambda: self.restore_extensions(ext_type='keyword'))
  1310. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1311. lambda: self.delete_all_extensions(ext_type='keyword'))
  1312. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1313. lambda: self.add_extension(ext_type='keyword'))
  1314. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1315. lambda: self.del_extension(ext_type='keyword'))
  1316. # ###########################################################################################################
  1317. # ########################################### GUI SIGNALS ###################################################
  1318. # ###########################################################################################################
  1319. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1320. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1321. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1322. # ###########################################################################################################
  1323. # ####################################### VARIOUS SIGNALS ###################################################
  1324. # ###########################################################################################################
  1325. # connect the abort_all_tasks related slots to the related signals
  1326. self.proc_container.idle_flag.connect(self.app_is_idle)
  1327. # signal emitted when a tab is closed in the Plot Area
  1328. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1329. # signal to close the application
  1330. self.close_app_signal.connect(self.kill_app)
  1331. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1332. # ###########################################################################################################
  1333. # ###########################################################################################################
  1334. # ###########################################################################################################
  1335. self.log.debug("Finished connecting Signals.")
  1336. # ###########################################################################################################
  1337. # ##################################### Finished the CONSTRUCTOR ############################################
  1338. # ###########################################################################################################
  1339. self.log.debug("END of constructor. Releasing control.")
  1340. # ###########################################################################################################
  1341. # ########################################## SHOW GUI #######################################################
  1342. # ###########################################################################################################
  1343. # if the app is not started as headless, show it
  1344. if self.cmd_line_headless != 1:
  1345. if show_splash:
  1346. # finish the splash
  1347. self.splash.finish(self.ui)
  1348. mgui_settings = QSettings("Open Source", "FlatCAM")
  1349. if mgui_settings.contains("maximized_gui"):
  1350. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1351. if maximized_ui is True:
  1352. self.ui.showMaximized()
  1353. else:
  1354. self.ui.show()
  1355. else:
  1356. self.ui.show()
  1357. if self.defaults["global_systray_icon"]:
  1358. self.trayIcon.show()
  1359. else:
  1360. log.warning("******************* RUNNING HEADLESS *******************")
  1361. # ###########################################################################################################
  1362. # ######################################## START-UP ARGUMENTS ###############################################
  1363. # ###########################################################################################################
  1364. # test if the program was started with a script as parameter
  1365. if self.cmd_line_shellvar:
  1366. try:
  1367. cnt = 0
  1368. command_tcl = 0
  1369. for i in self.cmd_line_shellvar.split(','):
  1370. if i is not None:
  1371. # noinspection PyBroadException
  1372. try:
  1373. command_tcl = eval(i)
  1374. except Exception:
  1375. command_tcl = i
  1376. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1377. cnt += 1
  1378. # if there are Windows paths then replace the path separator with a Unix like one
  1379. if sys.platform == 'win32':
  1380. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1381. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1382. except Exception as ext:
  1383. print("ERROR: ", ext)
  1384. sys.exit(2)
  1385. if self.cmd_line_shellfile:
  1386. if self.cmd_line_headless != 1:
  1387. if self.ui.shell_dock.isHidden():
  1388. self.ui.shell_dock.show()
  1389. try:
  1390. with open(self.cmd_line_shellfile, "r") as myfile:
  1391. # if show_splash:
  1392. # self.splash.showMessage('%s: %ssec\n%s' % (
  1393. # _("Canvas initialization started.\n"
  1394. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1395. # _("Executing Tcl Script ...")),
  1396. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1397. # color=QtGui.QColor("gray"))
  1398. cmd_line_shellfile_text = myfile.read()
  1399. if self.cmd_line_headless != 1:
  1400. self.shell.exec_command(cmd_line_shellfile_text)
  1401. else:
  1402. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1403. except Exception as ext:
  1404. print("ERROR: ", ext)
  1405. sys.exit(2)
  1406. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1407. # the path/file_name must be enclosed in quotes if it contain spaces
  1408. if App.args:
  1409. self.args_at_startup.emit(App.args)
  1410. if self.defaults.old_defaults_found is True:
  1411. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1412. "Please reboot the application to update."))
  1413. self.defaults.old_defaults_found = False
  1414. # ######################################### INIT FINISHED #######################################################
  1415. # #################################################################################################################
  1416. # #################################################################################################################
  1417. # #################################################################################################################
  1418. # #################################################################################################################
  1419. # #################################################################################################################
  1420. @staticmethod
  1421. def copy_and_overwrite(from_path, to_path):
  1422. """
  1423. From here:
  1424. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1425. :param from_path: source path
  1426. :param to_path: destination path
  1427. :return: None
  1428. """
  1429. if os.path.exists(to_path):
  1430. shutil.rmtree(to_path)
  1431. try:
  1432. shutil.copytree(from_path, to_path)
  1433. except FileNotFoundError:
  1434. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1435. shutil.copytree(from_new_path, to_path)
  1436. def on_startup_args(self, args, silent=False):
  1437. """
  1438. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1439. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1440. :param args: a list containing the application args at startup
  1441. :return: None
  1442. """
  1443. if args is not None:
  1444. args_to_process = args
  1445. else:
  1446. args_to_process = App.args
  1447. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1448. for argument in args_to_process:
  1449. if '.FlatPrj'.lower() in argument.lower():
  1450. try:
  1451. project_name = str(argument)
  1452. if project_name == "":
  1453. if silent is False:
  1454. self.inform.emit(_("Cancelled."))
  1455. else:
  1456. # self.open_project(project_name)
  1457. run_from_arg = True
  1458. # self.worker_task.emit({'fcn': self.open_project,
  1459. # 'params': [project_name, run_from_arg]})
  1460. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1461. except Exception as e:
  1462. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1463. elif '.FlatConfig'.lower() in argument.lower():
  1464. try:
  1465. file_name = str(argument)
  1466. if file_name == "":
  1467. if silent is False:
  1468. self.inform.emit(_("Open Config file failed."))
  1469. else:
  1470. run_from_arg = True
  1471. # self.worker_task.emit({'fcn': self.open_config_file,
  1472. # 'params': [file_name, run_from_arg]})
  1473. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1474. except Exception as e:
  1475. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1476. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1477. try:
  1478. file_name = str(argument)
  1479. if file_name == "":
  1480. if silent is False:
  1481. self.inform.emit(_("Open Script file failed."))
  1482. else:
  1483. if silent is False:
  1484. self.on_fileopenscript(name=file_name)
  1485. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1486. self.on_filerunscript(name=file_name)
  1487. except Exception as e:
  1488. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1489. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1490. self.log.debug("App.on_startup_args() --> Quit event.")
  1491. sys.exit()
  1492. elif 'save'.lower() in argument.lower():
  1493. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1494. self.preferencesUiManager.save_defaults()
  1495. else:
  1496. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1497. proc_arg = argument.lower()
  1498. for ext in exc_list:
  1499. proc_ext = ext.replace(' ', '')
  1500. proc_ext = '.%s' % proc_ext
  1501. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1502. file_name = str(argument)
  1503. if file_name == "":
  1504. if silent is False:
  1505. self.inform.emit(_("Open Excellon file failed."))
  1506. else:
  1507. self.on_fileopenexcellon(name=file_name, signal=None)
  1508. return
  1509. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1510. for ext in gco_list:
  1511. proc_ext = ext.replace(' ', '')
  1512. proc_ext = '.%s' % proc_ext
  1513. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1514. file_name = str(argument)
  1515. if file_name == "":
  1516. if silent is False:
  1517. self.inform.emit(_("Open GCode file failed."))
  1518. else:
  1519. self.on_fileopengcode(name=file_name, signal=None)
  1520. return
  1521. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1522. for ext in grb_list:
  1523. proc_ext = ext.replace(' ', '')
  1524. proc_ext = '.%s' % proc_ext
  1525. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1526. file_name = str(argument)
  1527. if file_name == "":
  1528. if silent is False:
  1529. self.inform.emit(_("Open Gerber file failed."))
  1530. else:
  1531. self.on_fileopengerber(name=file_name, signal=None)
  1532. return
  1533. # if it reached here without already returning then the app was registered with a file that it does not
  1534. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1535. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1536. # for arg in args_to_process:
  1537. # if 'FlatCAM.exe' in arg:
  1538. # continue
  1539. # else:
  1540. # sys.exit(2)
  1541. def set_ui_title(self, name):
  1542. """
  1543. Sets the title of the main window.
  1544. :param name: String that store the project path and project name
  1545. :return: None
  1546. """
  1547. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1548. (self.version,
  1549. ('BETA' if self.beta else ''),
  1550. platform.architecture()[0],
  1551. self.engine,
  1552. name)
  1553. )
  1554. def on_app_restart(self):
  1555. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1556. # be left in the SySTray
  1557. try:
  1558. self.trayIcon.hide()
  1559. except Exception:
  1560. pass
  1561. fcTranslate.restart_program(app=self)
  1562. def clear_pool(self):
  1563. """
  1564. Clear the multiprocessing pool and calls garbage collector.
  1565. :return: None
  1566. """
  1567. self.pool.close()
  1568. self.pool = Pool()
  1569. self.pool_recreated.emit(self.pool)
  1570. gc.collect()
  1571. def install_tools(self):
  1572. """
  1573. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1574. Instantiation of the Tools classes.
  1575. The order that the tools are installed is important as they can depend on each other install position.
  1576. :return: None
  1577. """
  1578. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1579. self.shell = FCShell(app=self, version=self.version)
  1580. self.distance_tool = Distance(self)
  1581. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1582. before=self.ui.menueditorigin,
  1583. separator=False)
  1584. self.distance_min_tool = DistanceMin(self)
  1585. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1586. pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin,
  1588. separator=True)
  1589. self.dblsidedtool = DblSidedTool(self)
  1590. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1591. self.cal_exc_tool = ToolCalibration(self)
  1592. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1593. before=self.dblsidedtool.menuAction,
  1594. separator=False)
  1595. self.align_objects_tool = AlignObjects(self)
  1596. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1597. self.edrills_tool = ToolExtractDrills(self)
  1598. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1599. self.panelize_tool = Panelize(self)
  1600. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1601. self.film_tool = Film(self)
  1602. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1603. self.paste_tool = SolderPaste(self)
  1604. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1605. self.calculator_tool = ToolCalculator(self)
  1606. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1607. self.sub_tool = ToolSub(self)
  1608. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1609. pos=self.ui.menutool, separator=True)
  1610. self.rules_tool = RulesCheck(self)
  1611. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1612. pos=self.ui.menutool, separator=False)
  1613. self.optimal_tool = ToolOptimal(self)
  1614. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1615. pos=self.ui.menutool, separator=True)
  1616. self.move_tool = ToolMove(self)
  1617. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1618. before=self.ui.menueditorigin, separator=True)
  1619. self.cutout_tool = CutOut(self)
  1620. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1621. before=self.sub_tool.menuAction)
  1622. self.ncclear_tool = NonCopperClear(self)
  1623. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1624. before=self.sub_tool.menuAction, separator=True)
  1625. self.paint_tool = ToolPaint(self)
  1626. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1627. before=self.sub_tool.menuAction, separator=True)
  1628. self.isolation_tool = ToolIsolation(self)
  1629. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1630. before=self.sub_tool.menuAction, separator=True)
  1631. self.drilling_tool = ToolDrilling(self)
  1632. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1633. before=self.sub_tool.menuAction, separator=True)
  1634. self.copper_thieving_tool = ToolCopperThieving(self)
  1635. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1636. pos=self.ui.menutool)
  1637. self.fiducial_tool = ToolFiducials(self)
  1638. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1639. pos=self.ui.menutool)
  1640. self.qrcode_tool = QRCode(self)
  1641. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1642. pos=self.ui.menutool)
  1643. self.punch_tool = ToolPunchGerber(self)
  1644. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1645. self.invert_tool = ToolInvertGerber(self)
  1646. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1647. self.corners_tool = ToolCorners(self)
  1648. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1649. self.etch_tool = ToolEtchCompensation(self)
  1650. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1651. self.transform_tool = ToolTransform(self)
  1652. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1653. pos=self.ui.menuoptions, separator=True)
  1654. self.properties_tool = Properties(self)
  1655. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1656. pos=self.ui.menuoptions)
  1657. self.pdf_tool = ToolPDF(self)
  1658. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1659. pos=self.ui.menufileimport,
  1660. separator=True)
  1661. self.image_tool = ToolImage(self)
  1662. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1663. pos=self.ui.menufileimport,
  1664. separator=True)
  1665. self.pcb_wizard_tool = PcbWizard(self)
  1666. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1667. pos=self.ui.menufileimport)
  1668. self.log.debug("Tools are installed.")
  1669. def remove_tools(self):
  1670. """
  1671. Will remove all the actions in the Tool menu.
  1672. :return: None
  1673. """
  1674. for act in self.ui.menutool.actions():
  1675. self.ui.menutool.removeAction(act)
  1676. def init_tools(self):
  1677. """
  1678. Initialize the Tool tab in the notebook side of the central widget.
  1679. Remove the actions in the Tools menu.
  1680. Instantiate again the FlatCAM tools (plugins).
  1681. All this is required when changing the layout: standard, compact etc.
  1682. :return: None
  1683. """
  1684. self.log.debug("init_tools()")
  1685. # delete the data currently in the Tools Tab and the Tab itself
  1686. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1687. if widget is not None:
  1688. widget.deleteLater()
  1689. self.ui.notebook.removeTab(2)
  1690. # rebuild the Tools Tab
  1691. self.ui.tool_tab = QtWidgets.QWidget()
  1692. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1693. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1694. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1695. self.ui.tool_scroll_area = VerticalScrollArea()
  1696. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1697. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1698. # first remove all of them
  1699. self.remove_tools()
  1700. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1701. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1702. '&Command Line\tS')
  1703. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1704. # third install all of them
  1705. try:
  1706. self.install_tools()
  1707. except AttributeError:
  1708. pass
  1709. self.log.debug("Tools are initialized.")
  1710. # def parse_system_fonts(self):
  1711. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1712. # 'params': []})
  1713. def connect_tools_signals_to_toolbar(self, ui):
  1714. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1715. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1716. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1717. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1718. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1719. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1720. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1721. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1722. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1723. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1724. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1725. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1726. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1727. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1728. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1729. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1730. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1731. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1732. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1733. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1734. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1735. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1736. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1737. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1738. def connect_toolbar_signals(self, ui):
  1739. """
  1740. Reconnect the signals to the actions in the toolbar.
  1741. This has to be done each time after the FlatCAM tools are removed/installed.
  1742. :return: None
  1743. """
  1744. # Toolbar
  1745. # File Toolbar Signals
  1746. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1747. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1748. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1749. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1750. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1751. # View Toolbar Signals
  1752. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1753. ui.replot_btn.triggered.connect(self.plot_all)
  1754. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1755. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1756. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1757. # Edit Toolbar Signals
  1758. ui.editgeo_btn.triggered.connect(self.object2editor)
  1759. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1760. ui.copy_btn.triggered.connect(self.on_copy_command)
  1761. ui.delete_btn.triggered.connect(self.on_delete)
  1762. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1763. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1764. ui.origin_btn.triggered.connect(self.on_set_origin)
  1765. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1766. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1767. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1768. # Scripting Toolbar Signals
  1769. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1770. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1771. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1772. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1773. # Tools Toolbar Signals
  1774. try:
  1775. self.connect_tools_signals_to_toolbar(ui=ui)
  1776. except Exception as err:
  1777. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1778. def object2editor(self):
  1779. """
  1780. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1781. :return: None
  1782. """
  1783. self.defaults.report_usage("object2editor()")
  1784. # disable the objects menu as it may interfere with the appEditors
  1785. self.ui.menuobjects.setDisabled(True)
  1786. edited_object = self.collection.get_active()
  1787. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1788. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1789. pass
  1790. else:
  1791. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1792. return
  1793. if isinstance(edited_object, GeometryObject):
  1794. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1795. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1796. # we set the notebook to hidden
  1797. # self.ui.splitter.setSizes([0, 1])
  1798. if edited_object.multigeo is True:
  1799. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1800. if len(sel_rows) > 1:
  1801. self.inform.emit('[WARNING_NOTCL] %s' %
  1802. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1803. "is not possible.\n"
  1804. "Edit only one geometry at a time."))
  1805. if not sel_rows:
  1806. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1807. return
  1808. # determine the tool dia of the selected tool
  1809. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1810. # now find the key in the edited_object.tools that has this tooldia
  1811. multi_tool = 1
  1812. for tool in edited_object.tools:
  1813. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1814. multi_tool = tool
  1815. break
  1816. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1817. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1818. else:
  1819. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1820. self.geo_editor.edit_fcgeometry(edited_object)
  1821. # set call source to the Editor we go into
  1822. self.call_source = 'geo_editor'
  1823. elif isinstance(edited_object, ExcellonObject):
  1824. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1825. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1826. if self.ui.splitter.sizes()[0] == 0:
  1827. self.ui.splitter.setSizes([1, 1])
  1828. self.exc_editor.edit_fcexcellon(edited_object)
  1829. # set call source to the Editor we go into
  1830. self.call_source = 'exc_editor'
  1831. elif isinstance(edited_object, GerberObject):
  1832. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1833. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1834. if self.ui.splitter.sizes()[0] == 0:
  1835. self.ui.splitter.setSizes([1, 1])
  1836. self.grb_editor.edit_fcgerber(edited_object)
  1837. # set call source to the Editor we go into
  1838. self.call_source = 'grb_editor'
  1839. # reset the following variables so the UI is built again after edit
  1840. edited_object.ui_build = False
  1841. elif isinstance(edited_object, CNCJobObject):
  1842. if self.ui.splitter.sizes()[0] == 0:
  1843. self.ui.splitter.setSizes([1, 1])
  1844. # set call source to the Editor we go into
  1845. self.call_source = 'gcode_editor'
  1846. self.gcode_editor.edit_fcgcode(edited_object)
  1847. # make sure that we can't select another object while in Editor Mode:
  1848. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1849. self.ui.project_frame.setDisabled(True)
  1850. # delete any selection shape that might be active as they are not relevant in Editor
  1851. self.delete_selection_shape()
  1852. # hide the Tools Toolbar
  1853. tools_tb = self.ui.toolbartools
  1854. if tools_tb.isVisible():
  1855. self.old_state_of_tools_toolbar = True
  1856. tools_tb.hide()
  1857. else:
  1858. self.old_state_of_tools_toolbar = False
  1859. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1860. self.ui.plot_tab_area.protectTab(0)
  1861. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1862. self.should_we_save = True
  1863. def editor2object(self, cleanup=None):
  1864. """
  1865. Transfers the Geometry or Excellon from it's editor to the current object.
  1866. :return: None
  1867. """
  1868. self.defaults.report_usage("editor2object()")
  1869. # re-enable the objects menu that was disabled on entry in Editor mode
  1870. self.ui.menuobjects.setDisabled(False)
  1871. # do not update a geometry or excellon object unless it comes out of an editor
  1872. if self.call_source != 'app':
  1873. edited_obj = self.collection.get_active()
  1874. if cleanup is None:
  1875. msgbox = QtWidgets.QMessageBox()
  1876. msgbox.setText(_("Do you want to save the edited object?"))
  1877. msgbox.setWindowTitle(_("Close Editor"))
  1878. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1879. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1880. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1881. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1882. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1883. msgbox.setDefaultButton(bt_yes)
  1884. msgbox.exec_()
  1885. response = msgbox.clickedButton()
  1886. if response == bt_yes:
  1887. # show the Tools Toolbar
  1888. tools_tb = self.ui.toolbartools
  1889. if self.old_state_of_tools_toolbar is True:
  1890. tools_tb.show()
  1891. # clean the Tools Tab
  1892. self.ui.tool_scroll_area.takeWidget()
  1893. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1894. self.ui.notebook.setTabText(2, _("Tool"))
  1895. if edited_obj.kind == 'geometry':
  1896. obj_type = "Geometry"
  1897. self.geo_editor.update_fcgeometry(edited_obj)
  1898. # self.geo_editor.update_options(edited_obj)
  1899. # restore GUI to the Selected TAB
  1900. # Remove anything else in the appGUI
  1901. self.ui.tool_scroll_area.takeWidget()
  1902. # update the geo object options so it is including the bounding box values
  1903. try:
  1904. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1905. edited_obj.options['xmin'] = xmin
  1906. edited_obj.options['ymin'] = ymin
  1907. edited_obj.options['xmax'] = xmax
  1908. edited_obj.options['ymax'] = ymax
  1909. except AttributeError as e:
  1910. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1911. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1912. edited_obj.build_ui()
  1913. edited_obj.plot()
  1914. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1915. elif edited_obj.kind == 'gerber':
  1916. obj_type = "Gerber"
  1917. self.grb_editor.update_fcgerber()
  1918. # self.grb_editor.update_options(edited_obj)
  1919. # delete the old object (the source object) if it was an empty one
  1920. try:
  1921. if len(edited_obj.solid_geometry) == 0:
  1922. old_name = edited_obj.options['name']
  1923. self.collection.delete_by_name(old_name)
  1924. except TypeError:
  1925. # if the solid_geometry is a single Polygon the len() will not work
  1926. # in any case, falling here means that we have something in the solid_geometry, even if only
  1927. # a single Polygon, therefore we pass this
  1928. pass
  1929. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1930. # restore GUI to the Selected TAB
  1931. # Remove anything else in the GUI
  1932. self.ui.properties_scroll_area.takeWidget()
  1933. elif edited_obj.kind == 'excellon':
  1934. obj_type = "Excellon"
  1935. self.exc_editor.update_fcexcellon(edited_obj)
  1936. # self.exc_editor.update_options(edited_obj)
  1937. # restore GUI to the Selected TAB
  1938. # Remove anything else in the GUI
  1939. self.ui.tool_scroll_area.takeWidget()
  1940. # delete the old object (the source object) if it was an empty one
  1941. # find if we have drills:
  1942. has_drills = None
  1943. for tt in edited_obj.tools:
  1944. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1945. has_drills = True
  1946. break
  1947. # find if we have slots:
  1948. has_slots = None
  1949. for tt in edited_obj.tools:
  1950. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1951. has_slots = True
  1952. break
  1953. if has_drills is None and has_slots is None:
  1954. old_name = edited_obj.options['name']
  1955. self.collection.delete_by_name(name=old_name)
  1956. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1957. elif edited_obj.kind == 'cncjob':
  1958. obj_type = "CNCJob"
  1959. self.gcode_editor.update_fcgcode(edited_obj)
  1960. # self.exc_editor.update_options(edited_obj)
  1961. # restore GUI to the Selected TAB
  1962. # Remove anything else in the GUI
  1963. self.ui.tool_scroll_area.takeWidget()
  1964. edited_obj.build_ui()
  1965. # close the open tab
  1966. for idx in range(self.ui.plot_tab_area.count()):
  1967. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1968. self.ui.plot_tab_area.closeTab(idx)
  1969. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1970. else:
  1971. self.inform.emit('[WARNING_NOTCL] %s' %
  1972. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1973. return
  1974. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1975. elif response == bt_no:
  1976. # show the Tools Toolbar
  1977. tools_tb = self.ui.toolbartools
  1978. if self.old_state_of_tools_toolbar is True:
  1979. tools_tb.show()
  1980. # clean the Tools Tab
  1981. self.ui.tool_scroll_area.takeWidget()
  1982. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1983. self.ui.notebook.setTabText(2, _("Tool"))
  1984. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1985. if edited_obj.kind == 'geometry':
  1986. self.geo_editor.deactivate()
  1987. edited_obj.build_ui()
  1988. edited_obj.plot()
  1989. elif edited_obj.kind == 'gerber':
  1990. self.grb_editor.deactivate_grb_editor()
  1991. edited_obj.build_ui()
  1992. elif edited_obj.kind == 'excellon':
  1993. self.exc_editor.deactivate()
  1994. edited_obj.build_ui()
  1995. elif edited_obj.kind == 'cncjob':
  1996. self.gcode_editor.deactivate()
  1997. edited_obj.build_ui()
  1998. # close the open tab
  1999. for idx in range(self.ui.plot_tab_area.count()):
  2000. try:
  2001. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2002. self.ui.plot_tab_area.closeTab(idx)
  2003. except AttributeError:
  2004. continue
  2005. else:
  2006. self.inform.emit('[WARNING_NOTCL] %s' %
  2007. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2008. return
  2009. elif response == bt_cancel:
  2010. return
  2011. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2012. # edited_obj.build_ui()
  2013. # Switch notebook to Properties page
  2014. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2015. else:
  2016. # show the Tools Toolbar
  2017. tools_tb = self.ui.toolbartools
  2018. if self.old_state_of_tools_toolbar is True:
  2019. tools_tb.show()
  2020. if isinstance(edited_obj, GeometryObject):
  2021. self.geo_editor.deactivate()
  2022. elif isinstance(edited_obj, GerberObject):
  2023. self.grb_editor.deactivate_grb_editor()
  2024. elif isinstance(edited_obj, ExcellonObject):
  2025. self.exc_editor.deactivate()
  2026. else:
  2027. self.inform.emit('[WARNING_NOTCL] %s' %
  2028. _("Select a Gerber, Geometry or Excellon Object to update."))
  2029. return
  2030. # if notebook is hidden we show it
  2031. if self.ui.splitter.sizes()[0] == 0:
  2032. self.ui.splitter.setSizes([1, 1])
  2033. # restore the call_source to app
  2034. self.call_source = 'app'
  2035. # edited_obj.plot()
  2036. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2037. self.ui.plot_tab_area.protectTab(0)
  2038. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2039. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2040. self.ui.project_frame.setDisabled(False)
  2041. def get_last_folder(self):
  2042. """
  2043. Get the folder path from where the last file was opened.
  2044. :return: String, last opened folder path
  2045. """
  2046. return self.defaults["global_last_folder"]
  2047. def get_last_save_folder(self):
  2048. """
  2049. Get the folder path from where the last file was saved.
  2050. :return: String, last saved folder path
  2051. """
  2052. loc = self.defaults["global_last_save_folder"]
  2053. if loc is None:
  2054. loc = self.defaults["global_last_folder"]
  2055. if loc is None:
  2056. loc = os.path.dirname(__file__)
  2057. return loc
  2058. @QtCore.pyqtSlot(str)
  2059. @QtCore.pyqtSlot(str, bool)
  2060. def info(self, msg, shell_echo=True):
  2061. """
  2062. Informs the user. Normally on the status bar, optionally
  2063. also on the shell.
  2064. :param msg: Text to write.
  2065. :type msg: str
  2066. :param shell_echo: Control if to display the message msg in the Shell
  2067. :type shell_echo: bool
  2068. :return: None
  2069. """
  2070. # Type of message in brackets at the beginning of the message.
  2071. match = re.search(r"\[(.*)\](.*)", msg)
  2072. if match:
  2073. level = match.group(1)
  2074. msg_ = match.group(2)
  2075. self.ui.fcinfo.set_status(str(msg_), level=level)
  2076. if shell_echo is True:
  2077. if level.lower() == "error":
  2078. self.shell_message(msg, error=True, show=True)
  2079. elif level.lower() == "warning":
  2080. self.shell_message(msg, warning=True, show=True)
  2081. elif level.lower() == "error_notcl":
  2082. self.shell_message(msg, error=True, show=False)
  2083. elif level.lower() == "warning_notcl":
  2084. self.shell_message(msg, warning=True, show=False)
  2085. elif level.lower() == "success":
  2086. self.shell_message(msg, success=True, show=False)
  2087. elif level.lower() == "selected":
  2088. self.shell_message(msg, selected=True, show=False)
  2089. else:
  2090. self.shell_message(msg, show=False)
  2091. else:
  2092. self.ui.fcinfo.set_status(str(msg), level="info")
  2093. # make sure that if the message is to clear the infobar with a space
  2094. # is not printed over and over on the shell
  2095. if msg != '' and shell_echo is True:
  2096. self.shell_message(msg)
  2097. def info_shell(self, msg, new_line=True):
  2098. self.shell_message(msg=msg, new_line=new_line)
  2099. def save_to_file(self, content_to_save, txt_content):
  2100. """
  2101. Save something to a file.
  2102. :return: None
  2103. """
  2104. self.defaults.report_usage("save_to_file")
  2105. self.log.debug("save_to_file()")
  2106. self.date = str(datetime.today()).rpartition('.')[0]
  2107. self.date = ''.join(c for c in self.date if c not in ':-')
  2108. self.date = self.date.replace(' ', '_')
  2109. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2110. path_to_save = self.defaults["global_last_save_folder"] if \
  2111. self.defaults["global_last_save_folder"] is not None else self.data_path
  2112. try:
  2113. filename, _f = FCFileSaveDialog.get_saved_filename(
  2114. caption=_("Save to file"),
  2115. directory=path_to_save + '/file_' + self.date,
  2116. ext_filter=filter__
  2117. )
  2118. except TypeError:
  2119. filename, _f = FCFileSaveDialog.get_saved_filename(
  2120. caption=_("Save to file"),
  2121. ext_filter=filter__)
  2122. filename = str(filename)
  2123. if filename == "":
  2124. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2125. return
  2126. else:
  2127. try:
  2128. with open(filename, 'w') as f:
  2129. ___ = f.read()
  2130. except PermissionError:
  2131. self.inform.emit('[WARNING] %s' %
  2132. _("Permission denied, saving not possible.\n"
  2133. "Most likely another app is holding the file open and not accessible."))
  2134. return
  2135. except IOError:
  2136. self.log.debug('Creating a new file ...')
  2137. f = open(filename, 'w')
  2138. f.close()
  2139. except Exception:
  2140. e = sys.exc_info()[0]
  2141. App.log.error("Could not load the file.")
  2142. App.log.error(str(e))
  2143. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2144. return
  2145. # Save content
  2146. if filename.rpartition('.')[2].lower() == 'html':
  2147. file_content = content_to_save
  2148. else:
  2149. file_content = txt_content
  2150. try:
  2151. with open(filename, "w") as f:
  2152. f.write(file_content)
  2153. except Exception:
  2154. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2155. return
  2156. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2157. def register_recent(self, kind, filename):
  2158. """
  2159. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2160. dictionary.
  2161. :param kind: type of file that was opened
  2162. :param filename: the path and file name for the file that was opened
  2163. :return:
  2164. """
  2165. self.log.debug("register_recent()")
  2166. self.log.debug(" %s" % kind)
  2167. self.log.debug(" %s" % filename)
  2168. record = {'kind': str(kind), 'filename': str(filename)}
  2169. if record in self.recent:
  2170. return
  2171. if record in self.recent_projects:
  2172. return
  2173. if record['kind'] == 'project':
  2174. self.recent_projects.insert(0, record)
  2175. else:
  2176. self.recent.insert(0, record)
  2177. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2178. self.recent.pop()
  2179. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2180. self.recent_projects.pop()
  2181. try:
  2182. f = open(self.data_path + '/recent.json', 'w')
  2183. except IOError:
  2184. App.log.error("Failed to open recent items file for writing.")
  2185. self.inform.emit('[ERROR_NOTCL] %s' %
  2186. _('Failed to open recent files file for writing.'))
  2187. return
  2188. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2189. f.close()
  2190. try:
  2191. fp = open(self.data_path + '/recent_projects.json', 'w')
  2192. except IOError:
  2193. App.log.error("Failed to open recent items file for writing.")
  2194. self.inform.emit('[ERROR_NOTCL] %s' %
  2195. _('Failed to open recent projects file for writing.'))
  2196. return
  2197. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2198. fp.close()
  2199. # Re-build the recent items menu
  2200. self.setup_recent_items()
  2201. def on_about(self):
  2202. """
  2203. Displays the "about" dialog found in the Menu --> Help.
  2204. :return: None
  2205. """
  2206. self.defaults.report_usage("on_about")
  2207. version = self.version
  2208. version_date = self.version_date
  2209. beta = self.beta
  2210. class AboutDialog(QtWidgets.QDialog):
  2211. def __init__(self, app, parent=None):
  2212. QtWidgets.QDialog.__init__(self, parent)
  2213. self.app = app
  2214. # Icon and title
  2215. self.setWindowIcon(parent.app_icon)
  2216. self.setWindowTitle(_("About"))
  2217. self.resize(600, 200)
  2218. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2219. # self.setStyleSheet(
  2220. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2221. # "background-attachment: fixed"
  2222. # )
  2223. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2224. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2225. # palette = QtGui.QPalette()
  2226. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2227. # self.setPalette(palette)
  2228. logo = QtWidgets.QLabel()
  2229. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2230. title = QtWidgets.QLabel(
  2231. "<font size=8><B>FlatCAM</B></font><BR>"
  2232. "{title}<BR>"
  2233. "<BR>"
  2234. "<BR>"
  2235. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2236. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2237. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2238. "<B>{issue}</B></a><BR>".format(
  2239. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2240. devel=_("Development"),
  2241. down=_("DOWNLOAD"),
  2242. issue=_("Issue tracker"))
  2243. )
  2244. title.setOpenExternalLinks(True)
  2245. closebtn = QtWidgets.QPushButton(_("Close"))
  2246. tab_widget = QtWidgets.QTabWidget()
  2247. description_label = QtWidgets.QLabel(
  2248. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2249. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2250. version=version,
  2251. beta=('BETA' if beta else ''),
  2252. date=version_date,
  2253. arch=platform.architecture()[0])
  2254. )
  2255. description_label.setOpenExternalLinks(True)
  2256. lic_lbl_header = QtWidgets.QLabel(
  2257. '%s:<br>%s<br>' % (
  2258. _('Licensed under the MIT license'),
  2259. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2260. "http://www.opensource.org/licenses/mit-license.php</a>"
  2261. )
  2262. )
  2263. lic_lbl_header.setOpenExternalLinks(True)
  2264. lic_lbl_body = QtWidgets.QLabel(
  2265. _(
  2266. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2267. 'of this software and associated documentation files (the "Software"), to deal\n'
  2268. 'in the Software without restriction, including without limitation the rights\n'
  2269. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2270. 'copies of the Software, and to permit persons to whom the Software is\n'
  2271. 'furnished to do so, subject to the following conditions:\n\n'
  2272. 'The above copyright notice and this permission notice shall be included in\n'
  2273. 'all copies or substantial portions of the Software.\n\n'
  2274. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2275. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2276. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2277. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2278. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2279. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2280. 'THE SOFTWARE.'
  2281. )
  2282. )
  2283. attributions_label = QtWidgets.QLabel(
  2284. _(
  2285. 'Some of the icons used are from the following sources:<br>'
  2286. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2287. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2288. 'title="Flaticon">www.flaticon.com</a></div>'
  2289. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2290. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2291. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2292. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2293. 'title="Flaticon">www.flaticon.com</a></div>'
  2294. )
  2295. )
  2296. attributions_label.setOpenExternalLinks(True)
  2297. # layouts
  2298. layout1 = QtWidgets.QVBoxLayout()
  2299. layout1_1 = QtWidgets.QHBoxLayout()
  2300. layout1_2 = QtWidgets.QHBoxLayout()
  2301. layout2 = QtWidgets.QHBoxLayout()
  2302. layout3 = QtWidgets.QHBoxLayout()
  2303. self.setLayout(layout1)
  2304. layout1.addLayout(layout1_1)
  2305. layout1.addLayout(layout1_2)
  2306. layout1.addLayout(layout2)
  2307. layout1.addLayout(layout3)
  2308. layout1_1.addStretch()
  2309. layout1_1.addWidget(description_label)
  2310. layout1_2.addWidget(tab_widget)
  2311. self.splash_tab = QtWidgets.QWidget()
  2312. self.splash_tab.setObjectName("splash_about")
  2313. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2314. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2315. tab_widget.addTab(self.splash_tab, _("Splash"))
  2316. self.programmmers_tab = QtWidgets.QWidget()
  2317. self.programmmers_tab.setObjectName("programmers_about")
  2318. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2319. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2320. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2321. self.translators_tab = QtWidgets.QWidget()
  2322. self.translators_tab.setObjectName("translators_about")
  2323. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2324. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2325. tab_widget.addTab(self.translators_tab, _("Translators"))
  2326. self.license_tab = QtWidgets.QWidget()
  2327. self.license_tab.setObjectName("license_about")
  2328. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2329. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2330. tab_widget.addTab(self.license_tab, _("License"))
  2331. self.attributions_tab = QtWidgets.QWidget()
  2332. self.attributions_tab.setObjectName("attributions_about")
  2333. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2334. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2335. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2336. self.splash_tab_layout.addWidget(logo, stretch=0)
  2337. self.splash_tab_layout.addWidget(title, stretch=1)
  2338. pal = QtGui.QPalette()
  2339. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2340. self.prog_grid_lay = QtWidgets.QGridLayout()
  2341. self.prog_grid_lay.setHorizontalSpacing(20)
  2342. self.prog_grid_lay.setColumnStretch(0, 0)
  2343. self.prog_grid_lay.setColumnStretch(2, 1)
  2344. prog_widget = QtWidgets.QWidget()
  2345. prog_widget.setLayout(self.prog_grid_lay)
  2346. prog_scroll = QtWidgets.QScrollArea()
  2347. prog_scroll.setWidget(prog_widget)
  2348. prog_scroll.setWidgetResizable(True)
  2349. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2350. prog_scroll.setPalette(pal)
  2351. self.programmmers_tab_layout.addWidget(prog_scroll)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2399. self.translator_grid_lay = QtWidgets.QGridLayout()
  2400. self.translator_grid_lay.setColumnStretch(0, 0)
  2401. self.translator_grid_lay.setColumnStretch(1, 0)
  2402. self.translator_grid_lay.setColumnStretch(2, 1)
  2403. self.translator_grid_lay.setColumnStretch(3, 0)
  2404. # trans_widget = QtWidgets.QWidget()
  2405. # trans_widget.setLayout(self.translator_grid_lay)
  2406. # self.translators_tab_layout.addWidget(trans_widget)
  2407. # self.translators_tab_layout.addStretch()
  2408. trans_widget = QtWidgets.QWidget()
  2409. trans_widget.setLayout(self.translator_grid_lay)
  2410. trans_scroll = QtWidgets.QScrollArea()
  2411. trans_scroll.setWidget(trans_widget)
  2412. trans_scroll.setWidgetResizable(True)
  2413. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2414. trans_scroll.setPalette(pal)
  2415. self.translators_tab_layout.addWidget(trans_scroll)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2427. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2428. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2429. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2430. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2450. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2451. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2452. self.translator_grid_lay.setColumnStretch(0, 0)
  2453. self.translators_tab_layout.addStretch()
  2454. self.license_tab_layout.addWidget(lic_lbl_header)
  2455. self.license_tab_layout.addWidget(lic_lbl_body)
  2456. self.license_tab_layout.addStretch()
  2457. self.attributions_tab_layout.addWidget(attributions_label)
  2458. self.attributions_tab_layout.addStretch()
  2459. layout3.addStretch()
  2460. layout3.addWidget(closebtn)
  2461. closebtn.clicked.connect(self.accept)
  2462. AboutDialog(app=self, parent=self.ui).exec_()
  2463. def on_howto(self):
  2464. """
  2465. Displays the "about" dialog found in the Menu --> Help.
  2466. :return: None
  2467. """
  2468. class HowtoDialog(QtWidgets.QDialog):
  2469. def __init__(self, app, parent=None):
  2470. QtWidgets.QDialog.__init__(self, parent)
  2471. self.app = app
  2472. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2473. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2474. "<b>click</b></a>"
  2475. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2476. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2477. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2478. # Icon and title
  2479. self.setWindowIcon(parent.app_icon)
  2480. self.setWindowTitle('%s ...' % _("How To"))
  2481. self.resize(750, 375)
  2482. logo = QtWidgets.QLabel()
  2483. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2484. # content = QtWidgets.QLabel(
  2485. # "%s<br>"
  2486. # "%s<br><br>"
  2487. # "%s,<br>"
  2488. # "%s<br>"
  2489. # "<ul>"
  2490. # "<li> &nbsp;%s %s</li>"
  2491. # "<li> &nbsp;%s %s</li>"
  2492. # "</ul>"
  2493. # "%s %s.<br>"
  2494. # "%s"
  2495. # "<ul>"
  2496. # "<li> &nbsp;%s &#128077;</li>"
  2497. # "<li> &nbsp;%s &#128513;</li>"
  2498. # "</ul>" %
  2499. # (
  2500. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2501. # _("Yet it cannot evolve without <b>contributions</b>."),
  2502. # _("If you want to see this application grow and become better and better"),
  2503. # _("you can <b>contribute</b> to the development yourself by:"),
  2504. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2505. # new_features_link,
  2506. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2507. # bugs_link,
  2508. # _("If you like or use this program you can make a donation"),
  2509. # donation_link,
  2510. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2511. # _("it will be welcomed with joy"),
  2512. # _("it will give me a reason to continue")
  2513. # )
  2514. # )
  2515. # font-weight: bold;
  2516. content = QtWidgets.QLabel(
  2517. "%s<br>"
  2518. "%s<br><br>"
  2519. "%s,<br>"
  2520. "%s<br>"
  2521. "<ul>"
  2522. "<li> &nbsp;%s %s</li>"
  2523. "<li> &nbsp;%s %s</li>"
  2524. "</ul>"
  2525. "<br><br>"
  2526. "%s <br>"
  2527. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2528. (
  2529. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2530. _("Yet it cannot evolve without <b>contributions</b>."),
  2531. _("If you want to see this application grow and become better and better"),
  2532. _("you can <b>contribute</b> to the development yourself by:"),
  2533. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2534. new_features_link,
  2535. _("Bug Reports by providing the steps required to reproduce the bug"),
  2536. bugs_link,
  2537. _("If you like what you have seen so far ..."),
  2538. _("Donations are NOT required."), _("But they are welcomed"),
  2539. donation_link
  2540. )
  2541. )
  2542. content.setOpenExternalLinks(True)
  2543. # palette
  2544. pal = QtGui.QPalette()
  2545. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2546. # layouts
  2547. main_layout = QtWidgets.QVBoxLayout()
  2548. self.setLayout(main_layout)
  2549. tab_layout = QtWidgets.QHBoxLayout()
  2550. buttons_hlay = QtWidgets.QHBoxLayout()
  2551. main_layout.addLayout(tab_layout)
  2552. main_layout.addLayout(buttons_hlay)
  2553. tab_widget = QtWidgets.QTabWidget()
  2554. tab_layout.addWidget(tab_widget)
  2555. closebtn = QtWidgets.QPushButton(_("Close"))
  2556. buttons_hlay.addStretch()
  2557. buttons_hlay.addWidget(closebtn)
  2558. # CONTRIBUTE section
  2559. self.intro_tab = QtWidgets.QWidget()
  2560. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2561. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2562. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2563. self.grid_lay = QtWidgets.QGridLayout()
  2564. self.grid_lay.setHorizontalSpacing(20)
  2565. self.grid_lay.setColumnStretch(0, 0)
  2566. self.grid_lay.setColumnStretch(1, 1)
  2567. intro_wdg = QtWidgets.QWidget()
  2568. intro_wdg.setLayout(self.grid_lay)
  2569. intro_scroll_area = QtWidgets.QScrollArea()
  2570. intro_scroll_area.setWidget(intro_wdg)
  2571. intro_scroll_area.setWidgetResizable(True)
  2572. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2573. intro_scroll_area.setPalette(pal)
  2574. self.grid_lay.addWidget(logo, 0, 0)
  2575. self.grid_lay.addWidget(content, 0, 1)
  2576. self.intro_tab_layout.addWidget(intro_scroll_area)
  2577. # LINKS EXCHANGE section
  2578. self.links_tab = QtWidgets.QWidget()
  2579. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2580. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2581. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2582. self.links_lay = QtWidgets.QHBoxLayout()
  2583. links_wdg = QtWidgets.QWidget()
  2584. links_wdg.setLayout(self.links_lay)
  2585. links_scroll_area = QtWidgets.QScrollArea()
  2586. links_scroll_area.setWidget(links_wdg)
  2587. links_scroll_area.setWidgetResizable(True)
  2588. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2589. links_scroll_area.setPalette(pal)
  2590. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2591. self.links_tab_layout.addWidget(links_scroll_area)
  2592. # HOW TO section
  2593. self.howto_tab = QtWidgets.QWidget()
  2594. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2595. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2596. tab_widget.addTab(self.howto_tab, _("How To's"))
  2597. self.howto_lay = QtWidgets.QHBoxLayout()
  2598. howto_wdg = QtWidgets.QWidget()
  2599. howto_wdg.setLayout(self.howto_lay)
  2600. howto_scroll_area = QtWidgets.QScrollArea()
  2601. howto_scroll_area.setWidget(howto_wdg)
  2602. howto_scroll_area.setWidgetResizable(True)
  2603. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2604. howto_scroll_area.setPalette(pal)
  2605. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2606. self.howto_tab_layout.addWidget(howto_scroll_area)
  2607. # BUTTONS section
  2608. closebtn.clicked.connect(self.accept)
  2609. HowtoDialog(app=self, parent=self.ui).exec_()
  2610. def install_bookmarks(self, book_dict=None):
  2611. """
  2612. Install the bookmarks actions in the Help menu -> Bookmarks
  2613. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2614. :return: None
  2615. """
  2616. if book_dict is None:
  2617. self.defaults["global_bookmarks"].update(
  2618. {
  2619. '1': ['FlatCAM', "http://flatcam.org"],
  2620. '2': [_('Backup Site'), ""]
  2621. }
  2622. )
  2623. else:
  2624. self.defaults["global_bookmarks"].clear()
  2625. self.defaults["global_bookmarks"].update(book_dict)
  2626. # first try to disconnect if somehow they get connected from elsewhere
  2627. for act in self.ui.menuhelp_bookmarks.actions():
  2628. try:
  2629. act.triggered.disconnect()
  2630. except TypeError:
  2631. pass
  2632. # clear all actions except the last one who is the Bookmark manager
  2633. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2634. pass
  2635. else:
  2636. self.ui.menuhelp_bookmarks.removeAction(act)
  2637. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2638. if self.defaults["global_bookmarks"]:
  2639. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2640. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2641. # the JSON is first making the keys as strings (therefore I have to use strings too
  2642. # or do the conversion :(
  2643. # )
  2644. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2645. # the '10' entry jsut after '1' therefore ordering as strings
  2646. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2647. key=lambda x: int(x[0]))
  2648. for entry, bookmark in sorted_bookmarks:
  2649. title = bookmark[0]
  2650. weblink = bookmark[1]
  2651. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2652. act.setText(title)
  2653. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2654. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2655. if title == _('Backup Site') and weblink == "":
  2656. act.triggered.connect(self.on_backup_site)
  2657. else:
  2658. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2659. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2660. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2661. def on_bookmarks_manager(self):
  2662. """
  2663. Adds the bookmark manager in a Tab in Plot Area
  2664. :return:
  2665. """
  2666. for idx in range(self.ui.plot_tab_area.count()):
  2667. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2668. # there can be only one instance of Bookmark Manager at one time
  2669. return
  2670. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2671. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2672. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2673. # add the tab if it was closed
  2674. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2675. # delete the absolute and relative position and messages in the infobar
  2676. # self.ui.position_label.setText("")
  2677. # self.ui.rel_position_label.setText("")
  2678. # hide coordinates toolbars in the infobar while in DB
  2679. self.ui.coords_toolbar.hide()
  2680. self.ui.delta_coords_toolbar.hide()
  2681. # Switch plot_area to preferences page
  2682. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2683. def on_backup_site(self):
  2684. msgbox = QtWidgets.QMessageBox()
  2685. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2686. "1. FlatCAM.org website is down\n"
  2687. "2. Someone forked FlatCAM project and wants to point\n"
  2688. "to his own website\n\n"
  2689. "If you can't get any informations about the application\n"
  2690. "use the YouTube channel link from the Help menu."))
  2691. msgbox.setWindowTitle(_("Alternative website"))
  2692. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2693. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2694. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2695. msgbox.setDefaultButton(bt_yes)
  2696. msgbox.exec_()
  2697. # response = msgbox.clickedButton()
  2698. def final_save(self):
  2699. """
  2700. Callback for doing a preferences save to file whenever the application is about to quit.
  2701. If the project has changes, it will ask the user to save the project.
  2702. :return: None
  2703. """
  2704. if self.save_in_progress:
  2705. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2706. return
  2707. if self.should_we_save and self.collection.get_list():
  2708. msgbox = QtWidgets.QMessageBox()
  2709. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2710. "\n"
  2711. "Do you want to Save the project?"))
  2712. msgbox.setWindowTitle(_("Save changes"))
  2713. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2714. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2715. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2716. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2717. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2718. msgbox.setDefaultButton(bt_yes)
  2719. msgbox.exec_()
  2720. response = msgbox.clickedButton()
  2721. if response == bt_yes:
  2722. try:
  2723. self.trayIcon.hide()
  2724. except Exception:
  2725. pass
  2726. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2727. elif response == bt_no:
  2728. try:
  2729. self.trayIcon.hide()
  2730. except Exception:
  2731. pass
  2732. self.quit_application()
  2733. elif response == bt_cancel:
  2734. return
  2735. else:
  2736. try:
  2737. self.trayIcon.hide()
  2738. except Exception:
  2739. pass
  2740. self.quit_application()
  2741. def quit_application(self):
  2742. """
  2743. Called (as a pyslot or not) when the application is quit.
  2744. :return: None
  2745. """
  2746. # close editors before quiting the app, if they are open
  2747. if self.geo_editor.editor_active is True:
  2748. self.geo_editor.deactivate()
  2749. try:
  2750. self.geo_editor.disconnect()
  2751. except TypeError:
  2752. pass
  2753. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2754. if self.exc_editor.editor_active is True:
  2755. self.exc_editor.deactivate()
  2756. try:
  2757. self.grb_editor.disconnect()
  2758. except TypeError:
  2759. pass
  2760. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2761. if self.grb_editor.editor_active is True:
  2762. self.grb_editor.deactivate_grb_editor()
  2763. try:
  2764. self.exc_editor.disconnect()
  2765. except TypeError:
  2766. pass
  2767. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2768. # disconnect the mouse events
  2769. if self.is_legacy:
  2770. self.plotcanvas.graph_event_disconnect(self.mm)
  2771. self.plotcanvas.graph_event_disconnect(self.mp)
  2772. self.plotcanvas.graph_event_disconnect(self.mr)
  2773. self.plotcanvas.graph_event_disconnect(self.mdc)
  2774. self.plotcanvas.graph_event_disconnect(self.kp)
  2775. else:
  2776. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2777. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2778. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2779. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2780. self.on_mouse_double_click_over_plot)
  2781. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2782. self.preferencesUiManager.save_defaults(silent=True)
  2783. self.log.debug("App.quit_application() --> App Defaults saved.")
  2784. if self.cmd_line_headless != 1:
  2785. # save app state to file
  2786. stgs = QSettings("Open Source", "FlatCAM")
  2787. stgs.setValue('saved_gui_state', self.ui.saveState())
  2788. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2789. stgs.setValue(
  2790. 'language',
  2791. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2792. )
  2793. stgs.setValue(
  2794. 'notebook_font_size',
  2795. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2796. )
  2797. stgs.setValue(
  2798. 'axis_font_size',
  2799. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2800. )
  2801. stgs.setValue(
  2802. 'textbox_font_size',
  2803. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2804. )
  2805. stgs.setValue(
  2806. 'hud_font_size',
  2807. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2808. )
  2809. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2810. stgs.setValue(
  2811. 'machinist',
  2812. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2813. )
  2814. # This will write the setting to the platform specific storage.
  2815. del stgs
  2816. self.log.debug("App.quit_application() --> App UI state saved.")
  2817. # try to quit the Socket opened by ArgsThread class
  2818. try:
  2819. # self.new_launch.thread_exit = True
  2820. # self.new_launch.listener.close()
  2821. self.new_launch.stop.emit()
  2822. except Exception as err:
  2823. self.log.debug("App.quit_application() --> %s" % str(err))
  2824. # try to quit the QThread that run ArgsThread class
  2825. try:
  2826. # del self.new_launch
  2827. self.listen_th.quit()
  2828. except Exception as e:
  2829. self.log.debug("App.quit_application() --> %s" % str(e))
  2830. # terminate workers
  2831. # self.workers.__del__()
  2832. self.clear_pool()
  2833. # quit app by signalling for self.kill_app() method
  2834. # self.close_app_signal.emit()
  2835. QtWidgets.qApp.quit()
  2836. sys.exit(0)
  2837. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2838. # we use the following command
  2839. # minor_v = sys.version_info.minor
  2840. # if minor_v < 8:
  2841. # # make sure that the app closes
  2842. # sys.exit(0)
  2843. # else:
  2844. # os._exit(0) # fix to work with Python 3.8
  2845. @staticmethod
  2846. def kill_app():
  2847. QtWidgets.qApp.quit()
  2848. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2849. # we use the following command
  2850. sys.exit(0)
  2851. def on_portable_checked(self, state):
  2852. """
  2853. Callback called when the checkbox in Preferences GUI is checked.
  2854. It will set the application as portable by creating the preferences and recent files in the
  2855. 'config' folder found in the FlatCAM installation folder.
  2856. :param state: boolean, the state of the checkbox when clicked/checked
  2857. :return:
  2858. """
  2859. line_no = 0
  2860. data = None
  2861. if sys.platform != 'win32':
  2862. # this won't work in Linux or MacOS
  2863. return
  2864. # test if the app was frozen and choose the path for the configuration file
  2865. if getattr(sys, "frozen", False) is True:
  2866. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2867. else:
  2868. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2869. config_file = current_data_path + '\\configuration.txt'
  2870. try:
  2871. with open(config_file, 'r') as f:
  2872. try:
  2873. data = f.readlines()
  2874. except Exception as e:
  2875. self.log.debug('App.__init__() -->%s' % str(e))
  2876. return
  2877. except FileNotFoundError:
  2878. pass
  2879. for line in data:
  2880. line = line.strip('\n')
  2881. param = str(line).rpartition('=')
  2882. if param[0] == 'portable':
  2883. break
  2884. line_no += 1
  2885. if state:
  2886. data[line_no] = 'portable=True\n'
  2887. # create the new defauults files
  2888. # create current_defaults.FlatConfig file if there is none
  2889. try:
  2890. f = open(current_data_path + '/current_defaults.FlatConfig')
  2891. f.close()
  2892. except IOError:
  2893. self.log.debug('Creating empty current_defaults.FlatConfig')
  2894. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2895. json.dump({}, f)
  2896. f.close()
  2897. # create factory_defaults.FlatConfig file if there is none
  2898. try:
  2899. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2900. f.close()
  2901. except IOError:
  2902. self.log.debug('Creating empty factory_defaults.FlatConfig')
  2903. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2904. json.dump({}, f)
  2905. f.close()
  2906. try:
  2907. f = open(current_data_path + '/recent.json')
  2908. f.close()
  2909. except IOError:
  2910. self.log.debug('Creating empty recent.json')
  2911. f = open(current_data_path + '/recent.json', 'w')
  2912. json.dump([], f)
  2913. f.close()
  2914. try:
  2915. fp = open(current_data_path + '/recent_projects.json')
  2916. fp.close()
  2917. except IOError:
  2918. self.log.debug('Creating empty recent_projects.json')
  2919. fp = open(current_data_path + '/recent_projects.json', 'w')
  2920. json.dump([], fp)
  2921. fp.close()
  2922. # save the current defaults to the new defaults file
  2923. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2924. else:
  2925. data[line_no] = 'portable=False\n'
  2926. with open(config_file, 'w') as f:
  2927. f.writelines(data)
  2928. def on_register_files(self, obj_type=None):
  2929. """
  2930. Called whenever there is a need to register file extensions with FlatCAM.
  2931. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2932. :param obj_type: the type of object to be register for.
  2933. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2934. :return: None
  2935. """
  2936. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2937. new_reg_path = 'Software\\Classes\\'
  2938. # find if the current user is admin
  2939. try:
  2940. is_admin = os.getuid() == 0
  2941. except AttributeError:
  2942. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2943. if is_admin is True:
  2944. root_path = winreg.HKEY_LOCAL_MACHINE
  2945. else:
  2946. root_path = winreg.HKEY_CURRENT_USER
  2947. # create the keys
  2948. def set_reg(name, root_pth, new_reg_path_par, value):
  2949. try:
  2950. winreg.CreateKey(root_pth, new_reg_path_par)
  2951. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  2952. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2953. return True
  2954. except WindowsError:
  2955. return False
  2956. # delete key in registry
  2957. def delete_reg(root_pth, reg_path, key_to_del):
  2958. key_to_del_path = reg_path + key_to_del
  2959. try:
  2960. winreg.DeleteKey(root_pth, key_to_del_path)
  2961. return True
  2962. except WindowsError:
  2963. return False
  2964. if obj_type is None or obj_type == 'excellon':
  2965. exc_list = \
  2966. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2967. exc_list = [x for x in exc_list if x != '']
  2968. # register all keys in the Preferences window
  2969. for ext in exc_list:
  2970. new_k = new_reg_path + '.%s' % ext
  2971. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2972. # and unregister those that are no longer in the Preferences windows but are in the file
  2973. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2974. if ext not in exc_list:
  2975. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2976. # now write the updated extensions to the self.defaults
  2977. # new_ext = ''
  2978. # for ext in exc_list:
  2979. # new_ext = new_ext + ext + ', '
  2980. # self.defaults["fa_excellon"] = new_ext
  2981. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2982. if obj_type is None or obj_type == 'gcode':
  2983. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2984. gco_list = [x for x in gco_list if x != '']
  2985. # register all keys in the Preferences window
  2986. for ext in gco_list:
  2987. new_k = new_reg_path + '.%s' % ext
  2988. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2989. # and unregister those that are no longer in the Preferences windows but are in the file
  2990. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2991. if ext not in gco_list:
  2992. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2993. # now write the updated extensions to the self.defaults
  2994. # new_ext = ''
  2995. # for ext in gco_list:
  2996. # new_ext = new_ext + ext + ', '
  2997. # self.defaults["fa_gcode"] = new_ext
  2998. self.inform.emit('[success] %s' %
  2999. _("Selected GCode file extensions registered with FlatCAM."))
  3000. if obj_type is None or obj_type == 'gerber':
  3001. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3002. grb_list = [x for x in grb_list if x != '']
  3003. # register all keys in the Preferences window
  3004. for ext in grb_list:
  3005. new_k = new_reg_path + '.%s' % ext
  3006. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3007. # and unregister those that are no longer in the Preferences windows but are in the file
  3008. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3009. if ext not in grb_list:
  3010. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3011. # now write the updated extensions to the self.defaults
  3012. # new_ext = ''
  3013. # for ext in grb_list:
  3014. # new_ext = new_ext + ext + ', '
  3015. # self.defaults["fa_gerber"] = new_ext
  3016. self.inform.emit('[success] %s' %
  3017. _("Selected Gerber file extensions registered with FlatCAM."))
  3018. def add_extension(self, ext_type):
  3019. """
  3020. Add a file extension to the list for a specific object
  3021. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3022. :return:
  3023. """
  3024. if ext_type == 'excellon':
  3025. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3026. if new_ext == '':
  3027. return
  3028. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3029. if new_ext in old_val:
  3030. return
  3031. old_val.append(new_ext)
  3032. old_val.sort()
  3033. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3034. if ext_type == 'gcode':
  3035. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3036. if new_ext == '':
  3037. return
  3038. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3039. if new_ext in old_val:
  3040. return
  3041. old_val.append(new_ext)
  3042. old_val.sort()
  3043. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3044. if ext_type == 'gerber':
  3045. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3046. if new_ext == '':
  3047. return
  3048. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3049. if new_ext in old_val:
  3050. return
  3051. old_val.append(new_ext)
  3052. old_val.sort()
  3053. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3054. if ext_type == 'keyword':
  3055. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3056. if new_kw == '':
  3057. return
  3058. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3059. if new_kw in old_val:
  3060. return
  3061. old_val.append(new_kw)
  3062. old_val.sort()
  3063. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3064. # update the self.myKeywords so the model is updated
  3065. self.autocomplete_kw_list = \
  3066. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3067. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3068. self.shell.command_line().set_model_data(self.myKeywords)
  3069. def del_extension(self, ext_type):
  3070. """
  3071. Remove a file extension from the list for a specific object
  3072. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3073. :return:
  3074. """
  3075. if ext_type == 'excellon':
  3076. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3077. if new_ext == '':
  3078. return
  3079. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3080. if new_ext not in old_val:
  3081. return
  3082. old_val.remove(new_ext)
  3083. old_val.sort()
  3084. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3085. if ext_type == 'gcode':
  3086. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3087. if new_ext == '':
  3088. return
  3089. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3090. if new_ext not in old_val:
  3091. return
  3092. old_val.remove(new_ext)
  3093. old_val.sort()
  3094. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3095. if ext_type == 'gerber':
  3096. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3097. if new_ext == '':
  3098. return
  3099. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3100. if new_ext not in old_val:
  3101. return
  3102. old_val.remove(new_ext)
  3103. old_val.sort()
  3104. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3105. if ext_type == 'keyword':
  3106. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3107. if new_kw == '':
  3108. return
  3109. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3110. if new_kw not in old_val:
  3111. return
  3112. old_val.remove(new_kw)
  3113. old_val.sort()
  3114. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3115. # update the self.myKeywords so the model is updated
  3116. self.autocomplete_kw_list = \
  3117. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3118. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3119. self.shell.command_line().set_model_data(self.myKeywords)
  3120. def restore_extensions(self, ext_type):
  3121. """
  3122. Restore all file extensions associations with FlatCAM, for a specific object
  3123. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3124. :return:
  3125. """
  3126. if ext_type == 'excellon':
  3127. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3128. # for the ability to open Excellon files with .txt extension
  3129. new_exc_list = deepcopy(self.exc_list)
  3130. try:
  3131. new_exc_list.remove('txt')
  3132. except ValueError:
  3133. pass
  3134. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3135. if ext_type == 'gcode':
  3136. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3137. if ext_type == 'gerber':
  3138. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3139. if ext_type == 'keyword':
  3140. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3141. # update the self.myKeywords so the model is updated
  3142. self.autocomplete_kw_list = self.default_keywords
  3143. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3144. self.shell.commnad_line().set_model_data(self.myKeywords)
  3145. def delete_all_extensions(self, ext_type):
  3146. """
  3147. Delete all file extensions associations with FlatCAM, for a specific object
  3148. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3149. :return:
  3150. """
  3151. if ext_type == 'excellon':
  3152. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3153. if ext_type == 'gcode':
  3154. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3155. if ext_type == 'gerber':
  3156. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3157. if ext_type == 'keyword':
  3158. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3159. # update the self.myKeywords so the model is updated
  3160. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3161. self.shell.command_line().set_model_data(self.myKeywords)
  3162. def on_edit_join(self, name=None):
  3163. """
  3164. Callback for Edit->Join. Joins the selected geometry objects into
  3165. a new one.
  3166. :return: None
  3167. """
  3168. self.defaults.report_usage("on_edit_join()")
  3169. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3170. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3171. geo_type_set = set()
  3172. objs = self.collection.get_selected()
  3173. if len(objs) < 2:
  3174. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3175. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3176. return 'fail'
  3177. for obj in objs:
  3178. geo_type_set.add(obj.multigeo)
  3179. # if len(geo_type_list) == 1 means that all list elements are the same
  3180. if len(geo_type_set) != 1:
  3181. self.inform.emit('[ERROR] %s' %
  3182. _("Failed join. The Geometry objects are of different types.\n"
  3183. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3184. "convert from one to another and retry joining \n"
  3185. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3186. "the result may not be what was expected. \n"
  3187. "Check the generated GCODE."))
  3188. return
  3189. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3190. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3191. if True in geo_type_set:
  3192. def initialize(geo_obj, app):
  3193. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3194. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3195. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3196. for v in geo_obj.tools.values():
  3197. v['data']['name'] = obj_name_multi
  3198. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3199. else:
  3200. def initialize(geo_obj, app):
  3201. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3202. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3203. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3204. for v in geo_obj.tools.values():
  3205. v['data']['name'] = obj_name_single
  3206. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3207. self.should_we_save = True
  3208. def on_edit_join_exc(self):
  3209. """
  3210. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3211. a new Excellon.
  3212. :return: None
  3213. """
  3214. self.defaults.report_usage("on_edit_join_exc()")
  3215. objs = self.collection.get_selected()
  3216. for obj in objs:
  3217. if not isinstance(obj, ExcellonObject):
  3218. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3219. return
  3220. if len(objs) < 2:
  3221. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3222. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3223. return 'fail'
  3224. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3225. def initialize(exc_obj, app):
  3226. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3227. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3228. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3229. self.should_we_save = True
  3230. def on_edit_join_grb(self):
  3231. """
  3232. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3233. a new Gerber object.
  3234. :return: None
  3235. """
  3236. self.defaults.report_usage("on_edit_join_grb()")
  3237. objs = self.collection.get_selected()
  3238. for obj in objs:
  3239. if not isinstance(obj, GerberObject):
  3240. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3241. return
  3242. if len(objs) < 2:
  3243. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3244. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3245. return 'fail'
  3246. def initialize(grb_obj, app):
  3247. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3248. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3249. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3250. self.should_we_save = True
  3251. def on_convert_singlegeo_to_multigeo(self):
  3252. """
  3253. Called for converting a Geometry object from single-geo to multi-geo.
  3254. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3255. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3256. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3257. the solid-geometry of that tool.
  3258. :return: None
  3259. """
  3260. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3261. obj = self.collection.get_active()
  3262. if obj is None:
  3263. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3264. return
  3265. if not isinstance(obj, GeometryObject):
  3266. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3267. return
  3268. obj.multigeo = True
  3269. for tooluid, dict_value in obj.tools.items():
  3270. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3271. if not isinstance(obj.solid_geometry, list):
  3272. obj.solid_geometry = [obj.solid_geometry]
  3273. # obj.solid_geometry[:] = []
  3274. obj.plot()
  3275. self.should_we_save = True
  3276. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3277. def on_convert_multigeo_to_singlegeo(self):
  3278. """
  3279. Called for converting a Geometry object from multi-geo to single-geo.
  3280. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3281. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3282. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3283. the solid-geometry of that tool.
  3284. :return: None
  3285. """
  3286. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3287. obj = self.collection.get_active()
  3288. if obj is None:
  3289. self.inform.emit('[ERROR_NOTCL] %s' %
  3290. _("Failed. Select a Geometry Object and try again."))
  3291. return
  3292. if not isinstance(obj, GeometryObject):
  3293. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3294. (_("Expected a GeometryObject, got"), type(obj)))
  3295. return
  3296. obj.multigeo = False
  3297. total_solid_geometry = []
  3298. for tooluid, dict_value in obj.tools.items():
  3299. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3300. # clear the original geometry
  3301. dict_value['solid_geometry'][:] = []
  3302. obj.solid_geometry = deepcopy(total_solid_geometry)
  3303. obj.plot()
  3304. self.should_we_save = True
  3305. self.inform.emit('[success] %s' %
  3306. _("A Geometry object was converted to SingleGeo type."))
  3307. def on_defaults_dict_change(self, field):
  3308. """
  3309. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3310. Edit -> Preferences tab window.
  3311. :param field: the key of the self.defaults dictionary that was changed.
  3312. :return: None
  3313. """
  3314. self.preferencesUiManager.defaults_write_form_field(field=field)
  3315. if field == "units":
  3316. self.set_screen_units(self.defaults['units'])
  3317. def set_screen_units(self, units):
  3318. """
  3319. Set the FlatCAM units on the status bar.
  3320. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3321. :return: None
  3322. """
  3323. self.ui.units_label.setText("[" + units.lower() + "]")
  3324. def on_toggle_units_click(self):
  3325. try:
  3326. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3327. except (TypeError, AttributeError):
  3328. pass
  3329. if self.defaults["units"] == 'MM':
  3330. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3331. else:
  3332. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3333. self.on_toggle_units(no_pref=True)
  3334. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3335. lambda: self.on_toggle_units(no_pref=False))
  3336. def scale_defaults(self, sfactor, dimensions):
  3337. for dim in dimensions:
  3338. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3339. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3340. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3341. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3342. if not self.defaults[dim] or self.defaults[dim] == '':
  3343. continue
  3344. if isinstance(self.defaults[dim], str):
  3345. try:
  3346. tools_diameters = eval(self.defaults[dim])
  3347. except Exception as e:
  3348. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3349. continue
  3350. elif isinstance(self.defaults[dim], (float, int)):
  3351. tools_diameters = [self.defaults[dim]]
  3352. else:
  3353. tools_diameters = list(self.defaults[dim])
  3354. if isinstance(tools_diameters, (tuple, list)):
  3355. pass
  3356. elif isinstance(tools_diameters, (int, float)):
  3357. tools_diameters = [self.defaults[dim]]
  3358. else:
  3359. continue
  3360. td_len = len(tools_diameters)
  3361. conv_list = []
  3362. for t in range(td_len):
  3363. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3364. self.defaults[dim] = conv_list
  3365. elif dim in ['global_gridx', 'global_gridy']:
  3366. # format the number of decimals to the one specified in self.decimals
  3367. try:
  3368. val = float(self.defaults[dim]) * sfactor
  3369. except Exception as e:
  3370. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3371. continue
  3372. self.defaults[dim] = self.dec_format(val, self.decimals)
  3373. else:
  3374. # the number of decimals for the rest is kept unchanged
  3375. if self.defaults[dim]:
  3376. try:
  3377. val = float(self.defaults[dim]) * sfactor
  3378. except Exception as e:
  3379. self.log.debug(
  3380. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3381. )
  3382. continue
  3383. self.defaults[dim] = self.dec_format(val, self.decimals)
  3384. def on_toggle_units(self, no_pref=False):
  3385. """
  3386. Callback for the Units radio-button change in the Preferences tab.
  3387. Changes the application's default units adn for the project too.
  3388. If changing the project's units, the change propagates to all of
  3389. the objects in the project.
  3390. :return: None
  3391. """
  3392. self.defaults.report_usage("on_toggle_units")
  3393. if self.toggle_units_ignore:
  3394. return
  3395. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3396. # If option is the same, then ignore
  3397. if new_units == self.defaults["units"].upper():
  3398. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3399. return
  3400. # Keys in self.defaults for which to scale their values
  3401. dimensions = [
  3402. # Global
  3403. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3404. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3405. # Gerber Object
  3406. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3407. # Gerber Editor
  3408. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3409. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3410. # Excellon Object
  3411. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3412. # Excellon Editor
  3413. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3414. "excellon_editor_slot_length",
  3415. # Geometry Object
  3416. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3417. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3418. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3419. "geometry_extracut_length", "geometry_z_pdepth",
  3420. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3421. # CNCJob Object
  3422. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3423. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3424. # Isolation Tool
  3425. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3426. # Drilling Tool
  3427. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3428. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3429. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3430. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3431. # NCC Tool
  3432. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3433. "tools_ncc_newdia",
  3434. # Cutout Tool
  3435. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3436. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3437. # Paint Tool
  3438. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3439. # 2Sided Tool
  3440. "tools_2sided_drilldia",
  3441. # Film Tool
  3442. "tools_film_boundary", "tools_film_scale_stroke",
  3443. # Panel Tool
  3444. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3445. "tools_panelize_constrainy",
  3446. # Calculators Tool
  3447. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3448. # Transform Tool
  3449. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3450. "tools_transform_buffer_dis",
  3451. # SolderPaste Tool
  3452. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3453. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3454. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3455. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3456. # Corner Markers Tool
  3457. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3458. # Check Rules Tool
  3459. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3460. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3461. # QRCode Tool
  3462. "tools_qrcode_border_size",
  3463. # Copper Thieving Tool
  3464. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3465. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3466. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3467. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3468. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3469. "tools_copper_thieving_mask_clearance",
  3470. # Fiducials Tool
  3471. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3472. # Calibration Tool
  3473. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3474. # Drills Extraction Tool
  3475. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3476. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3477. # Punch Gerber Tool
  3478. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3479. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3480. # Invert Gerber Tool
  3481. "tools_invert_margin",
  3482. ]
  3483. # The scaling factor depending on choice of units.
  3484. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3485. # Changing project units. Warn user.
  3486. msgbox = QtWidgets.QMessageBox()
  3487. msgbox.setWindowTitle(_("Toggle Units"))
  3488. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3489. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3490. msgbox.setText(_("Changing the units of the project\n"
  3491. "will scale all objects.\n\n"
  3492. "Do you want to continue?"))
  3493. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3494. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3495. msgbox.setDefaultButton(bt_ok)
  3496. msgbox.exec_()
  3497. response = msgbox.clickedButton()
  3498. if response == bt_ok:
  3499. if no_pref is False:
  3500. self.preferencesUiManager.defaults_read_form()
  3501. self.scale_defaults(factor, dimensions)
  3502. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3503. self.defaults["units"] = new_units
  3504. # update the defaults from form, some may assume that the conversion is enough and it's not
  3505. self.on_options_app2project()
  3506. # update the objects
  3507. for obj in self.collection.get_list():
  3508. obj.convert_units(new_units)
  3509. # make that the properties stored in the object are also updated
  3510. self.app_obj.object_changed.emit(obj)
  3511. # rebuild the object UI
  3512. obj.build_ui()
  3513. # change this only if the workspace is active
  3514. if self.defaults['global_workspace'] is True:
  3515. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3516. # adjust the grid values on the main toolbar
  3517. val_x = float(self.defaults['global_gridx']) * factor
  3518. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3519. current = self.collection.get_active()
  3520. if current is not None:
  3521. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3522. if not isinstance(current, GeometryObject):
  3523. current.to_form()
  3524. # replot all objects
  3525. self.plot_all()
  3526. # set the status labels to reflect the current FlatCAM units
  3527. self.set_screen_units(new_units)
  3528. # signal to the app that we changed the object properties and it should save the project
  3529. self.should_we_save = True
  3530. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3531. else:
  3532. # Undo toggling
  3533. self.toggle_units_ignore = True
  3534. if self.defaults['units'].upper() == 'MM':
  3535. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3536. else:
  3537. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3538. self.toggle_units_ignore = False
  3539. # store the grid values so they are not changed in the next step
  3540. val_x = float(self.defaults['global_gridx'])
  3541. val_y = float(self.defaults['global_gridy'])
  3542. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3543. self.preferencesUiManager.defaults_read_form()
  3544. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3545. # in self.defaults from the GUI elements but
  3546. # I don't want it for the grid values, so I update them here
  3547. self.defaults['global_gridx'] = val_x
  3548. self.defaults['global_gridy'] = val_y
  3549. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3550. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3551. def on_deselect_all(self):
  3552. self.collection.set_all_inactive()
  3553. self.delete_selection_shape()
  3554. def on_workspace_modified(self):
  3555. # self.save_defaults(silent=True)
  3556. self.plotcanvas.delete_workspace()
  3557. self.preferencesUiManager.defaults_read_form()
  3558. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3559. def on_workspace(self):
  3560. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3561. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3562. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3563. else:
  3564. self.plotcanvas.delete_workspace()
  3565. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3566. self.preferencesUiManager.defaults_read_form()
  3567. # self.save_defaults(silent=True)
  3568. def on_workspace_toggle(self):
  3569. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3570. try:
  3571. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3572. except TypeError:
  3573. pass
  3574. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3575. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3576. self.on_workspace()
  3577. def on_cursor_type(self, val):
  3578. """
  3579. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3580. :return: None
  3581. """
  3582. self.app_cursor.enabled = False
  3583. if val == 'small':
  3584. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3585. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3586. self.app_cursor = self.plotcanvas.new_cursor()
  3587. else:
  3588. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3589. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3590. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3591. if self.ui.grid_snap_btn.isChecked():
  3592. self.app_cursor.enabled = True
  3593. else:
  3594. self.app_cursor.enabled = False
  3595. def on_tool_add_keypress(self):
  3596. # ## Current application units in Upper Case
  3597. self.units = self.defaults['units'].upper()
  3598. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3599. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3600. if notebook_widget_name == 'properties_tab':
  3601. if self.collection.get_active().kind == 'geometry':
  3602. # Tool add works for Geometry only if Advanced is True in Preferences
  3603. if self.defaults["global_app_level"] == 'a':
  3604. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3605. text='%s:' % _('Enter a Tool Diameter'),
  3606. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3607. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3608. val, ok = tool_add_popup.get_value()
  3609. if ok:
  3610. if float(val) == 0:
  3611. self.inform.emit('[WARNING_NOTCL] %s' %
  3612. _("Please enter a tool diameter with non-zero value, in Float format."))
  3613. return
  3614. self.collection.get_active().on_tool_add(dia=float(val))
  3615. else:
  3616. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3617. else:
  3618. msgbox = QtWidgets.QMessageBox()
  3619. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3620. "Go to Preferences -> General - Show Advanced Options."))
  3621. msgbox.setWindowTitle("Tool adding ...")
  3622. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3623. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3624. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3625. msgbox.setDefaultButton(bt_ok)
  3626. msgbox.exec_()
  3627. # work only if the notebook tab on focus is the Tools_Tab
  3628. if notebook_widget_name == 'tool_tab':
  3629. try:
  3630. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3631. except AttributeError:
  3632. return
  3633. # and only if the tool is NCC Tool
  3634. if tool_widget == self.ncclear_tool.toolName:
  3635. self.ncclear_tool.on_add_tool_by_key()
  3636. # and only if the tool is Paint Area Tool
  3637. elif tool_widget == self.paint_tool.toolName:
  3638. self.paint_tool.on_add_tool_by_key()
  3639. # and only if the tool is Solder Paste Dispensing Tool
  3640. elif tool_widget == self.paste_tool.toolName:
  3641. self.paste_tool.on_add_tool_by_key()
  3642. # and only if the tool is Isolation Tool
  3643. elif tool_widget == self.isolation_tool.toolName:
  3644. self.isolation_tool.on_add_tool_by_key()
  3645. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3646. # See description below.
  3647. def on_delete_keypress(self):
  3648. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3649. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3650. if notebook_widget_name == 'properties_tab':
  3651. if self.collection.get_active().kind == 'geometry':
  3652. self.collection.get_active().on_tool_delete()
  3653. # work only if the notebook tab on focus is the Tools_Tab
  3654. elif notebook_widget_name == 'tool_tab':
  3655. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3656. # and only if the tool is NCC Tool
  3657. if tool_widget == self.ncclear_tool.toolName:
  3658. self.ncclear_tool.on_tool_delete()
  3659. # and only if the tool is Paint Tool
  3660. elif tool_widget == self.paint_tool.toolName:
  3661. self.paint_tool.on_tool_delete()
  3662. # and only if the tool is Solder Paste Dispensing Tool
  3663. elif tool_widget == self.paste_tool.toolName:
  3664. self.paste_tool.on_tool_delete()
  3665. # and only if the tool is Isolation Tool
  3666. elif tool_widget == self.isolation_tool.toolName:
  3667. self.isolation_tool.on_tool_delete()
  3668. else:
  3669. self.on_delete()
  3670. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3671. # some screens you have to be careful where you hover with your mouse.
  3672. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3673. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3674. # Complicated, I know :)
  3675. def on_delete(self, force_deletion=False):
  3676. """
  3677. Delete the currently selected FlatCAMObjs.
  3678. :param force_deletion: used by Tcl command
  3679. :return: None
  3680. """
  3681. self.defaults.report_usage("on_delete()")
  3682. response = None
  3683. bt_ok = None
  3684. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3685. # a geometry object before we update it.
  3686. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3687. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3688. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3689. msgbox = QtWidgets.QMessageBox()
  3690. msgbox.setWindowTitle(_("Delete objects"))
  3691. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3692. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3693. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3694. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3695. "the selected objects?"))
  3696. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3697. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3698. msgbox.setDefaultButton(bt_ok)
  3699. msgbox.exec_()
  3700. response = msgbox.clickedButton()
  3701. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3702. response = bt_ok
  3703. if response == bt_ok:
  3704. if self.collection.get_active():
  3705. self.log.debug("App.on_delete()")
  3706. for obj_active in self.collection.get_selected():
  3707. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3708. if obj_active.kind == 'gerber':
  3709. obj_active.mark_shapes_storage.clear()
  3710. obj_active.mark_shapes.clear(update=True)
  3711. obj_active.mark_shapes.enabled = False
  3712. elif obj_active.kind == 'cncjob':
  3713. try:
  3714. obj_active.text_col.enabled = False
  3715. del obj_active.text_col
  3716. obj_active.annotation.clear(update=True)
  3717. del obj_active.annotation
  3718. obj_active.probing_shapes.clear(update=True)
  3719. except AttributeError as e:
  3720. self.log.debug(
  3721. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3722. )
  3723. while self.collection.get_selected():
  3724. self.delete_first_selected()
  3725. # make sure that the selection shape is deleted, too
  3726. self.delete_selection_shape()
  3727. # if there are no longer objects delete also the exclusion areas shapes
  3728. if not self.collection.get_list():
  3729. self.exc_areas.clear_shapes()
  3730. self.inform.emit('%s...' % _("Object(s) deleted"))
  3731. else:
  3732. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3733. else:
  3734. self.inform.emit(_("Save the work in Editor and try again ..."))
  3735. def delete_first_selected(self):
  3736. # Keep this for later
  3737. try:
  3738. sel_obj = self.collection.get_active()
  3739. name = sel_obj.options["name"]
  3740. isPlotted = sel_obj.options["plot"]
  3741. except AttributeError:
  3742. self.log.debug("Nothing selected for deletion")
  3743. return
  3744. if self.is_legacy is True:
  3745. # Remove plot only if the object was plotted otherwise delaxes will fail
  3746. if isPlotted:
  3747. try:
  3748. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3749. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3750. except Exception as e:
  3751. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3752. self.plotcanvas.auto_adjust_axes()
  3753. # Remove from dictionary
  3754. self.collection.delete_active()
  3755. # Clear form
  3756. self.setup_default_properties_tab()
  3757. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3758. def on_set_origin(self):
  3759. """
  3760. Set the origin to the left mouse click position
  3761. :return: None
  3762. """
  3763. # display the message for the user
  3764. # and ask him to click on the desired position
  3765. self.defaults.report_usage("on_set_origin()")
  3766. def origin_replot():
  3767. def worker_task():
  3768. with self.proc_container.new('%s...' % _("Plotting")):
  3769. for obj in self.collection.get_list():
  3770. obj.plot()
  3771. self.plotcanvas.fit_view()
  3772. if self.is_legacy:
  3773. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3774. else:
  3775. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3776. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3777. self.inform.emit(_('Click to set the origin ...'))
  3778. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3779. # first disconnect it as it may have been used by something else
  3780. try:
  3781. self.replot_signal.disconnect()
  3782. except TypeError:
  3783. pass
  3784. self.replot_signal[list].connect(origin_replot)
  3785. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3786. """
  3787. :param event:
  3788. :param location:
  3789. :param noplot:
  3790. :param use_thread:
  3791. :return:
  3792. """
  3793. noplot_sig = noplot
  3794. def worker_task():
  3795. with self.proc_container.new(_("Setting Origin...")):
  3796. obj_list = self.collection.get_list()
  3797. for obj in obj_list:
  3798. obj.offset((x, y))
  3799. self.app_obj.object_changed.emit(obj)
  3800. # Update the object bounding box options
  3801. a, b, c, d = obj.bounds()
  3802. obj.options['xmin'] = a
  3803. obj.options['ymin'] = b
  3804. obj.options['xmax'] = c
  3805. obj.options['ymax'] = d
  3806. self.inform.emit('[success] %s...' % _('Origin set'))
  3807. for obj in obj_list:
  3808. out_name = obj.options["name"]
  3809. if obj.kind == 'gerber':
  3810. obj.source_file = self.f_handlers.export_gerber(
  3811. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3812. elif obj.kind == 'excellon':
  3813. obj.source_file = self.f_handlers.export_excellon(
  3814. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3815. if noplot_sig is False:
  3816. self.replot_signal.emit([])
  3817. if location is not None:
  3818. if len(location) != 2:
  3819. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3820. return 'fail'
  3821. x, y = location
  3822. if use_thread is True:
  3823. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3824. else:
  3825. worker_task()
  3826. self.should_we_save = True
  3827. return
  3828. if event is not None and event.button == 1:
  3829. if self.is_legacy is False:
  3830. event_pos = event.pos
  3831. else:
  3832. event_pos = (event.xdata, event.ydata)
  3833. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3834. if self.grid_status():
  3835. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3836. else:
  3837. pos = pos_canvas
  3838. x = 0 - pos[0]
  3839. y = 0 - pos[1]
  3840. if use_thread is True:
  3841. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3842. else:
  3843. worker_task()
  3844. self.should_we_save = True
  3845. def on_move2origin(self, use_thread=True):
  3846. """
  3847. Move selected objects to origin.
  3848. :param use_thread: Control if to use threaded operation. Boolean.
  3849. :return:
  3850. """
  3851. def worker_task():
  3852. with self.proc_container.new(_("Moving to Origin...")):
  3853. obj_list = self.collection.get_selected()
  3854. if not obj_list:
  3855. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3856. return
  3857. xminlist = []
  3858. yminlist = []
  3859. # first get a bounding box to fit all
  3860. for obj in obj_list:
  3861. xmin, ymin, xmax, ymax = obj.bounds()
  3862. xminlist.append(xmin)
  3863. yminlist.append(ymin)
  3864. # get the minimum x,y for all objects selected
  3865. x = min(xminlist)
  3866. y = min(yminlist)
  3867. for obj in obj_list:
  3868. obj.offset((-x, -y))
  3869. self.app_obj.object_changed.emit(obj)
  3870. # Update the object bounding box options
  3871. a, b, c, d = obj.bounds()
  3872. obj.options['xmin'] = a
  3873. obj.options['ymin'] = b
  3874. obj.options['xmax'] = c
  3875. obj.options['ymax'] = d
  3876. for obj in obj_list:
  3877. obj.plot()
  3878. for obj in obj_list:
  3879. out_name = obj.options["name"]
  3880. if obj.kind == 'gerber':
  3881. obj.source_file = self.f_handlers.export_gerber(
  3882. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3883. elif obj.kind == 'excellon':
  3884. obj.source_file = self.f_handlers.export_excellon(
  3885. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3886. self.inform.emit('[success] %s...' % _('Origin set'))
  3887. if use_thread is True:
  3888. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3889. else:
  3890. worker_task()
  3891. self.should_we_save = True
  3892. def on_jump_to(self, custom_location=None, fit_center=True):
  3893. """
  3894. Jump to a location by setting the mouse cursor location.
  3895. :param custom_location: Jump to a specified point. (x, y) tuple.
  3896. :param fit_center: If to fit view. Boolean.
  3897. :return:
  3898. """
  3899. self.defaults.report_usage("on_jump_to()")
  3900. if not custom_location:
  3901. dia_box_location = None
  3902. try:
  3903. dia_box_location = eval(self.clipboard.text())
  3904. except Exception:
  3905. pass
  3906. if type(dia_box_location) == tuple:
  3907. dia_box_location = str(dia_box_location)
  3908. else:
  3909. dia_box_location = None
  3910. # dia_box = Dialog_box(title=_("Jump to ..."),
  3911. # label=_("Enter the coordinates in format X,Y:"),
  3912. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3913. # initial_text=dia_box_location)
  3914. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3915. label=_("Enter the coordinates in format X,Y:"),
  3916. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3917. initial_text=dia_box_location,
  3918. reference=self.defaults['global_jump_ref'])
  3919. if dia_box.ok is True:
  3920. try:
  3921. location = eval(dia_box.location)
  3922. if not isinstance(location, tuple):
  3923. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3924. return
  3925. if dia_box.reference == 'rel':
  3926. rel_x = self.mouse[0] + location[0]
  3927. rel_y = self.mouse[1] + location[1]
  3928. location = (rel_x, rel_y)
  3929. self.defaults['global_jump_ref'] = dia_box.reference
  3930. except Exception:
  3931. return
  3932. else:
  3933. return
  3934. else:
  3935. location = custom_location
  3936. self.jump_signal.emit(location)
  3937. if fit_center:
  3938. self.plotcanvas.fit_center(loc=location)
  3939. cursor = QtGui.QCursor()
  3940. if self.is_legacy is False:
  3941. # I don't know where those differences come from but they are constant for the current
  3942. # execution of the application and they are multiples of a value around 0.0263mm.
  3943. # In a random way sometimes they are more sometimes they are less
  3944. # if units == 'MM':
  3945. # cal_factor = 0.0263
  3946. # else:
  3947. # cal_factor = 0.0263 / 25.4
  3948. cal_location = (location[0], location[1])
  3949. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3950. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3951. j_pos = (
  3952. int(canvas_origin.x() + round(jump_loc[0])),
  3953. int(canvas_origin.y() + round(jump_loc[1]))
  3954. )
  3955. cursor.setPos(j_pos[0], j_pos[1])
  3956. else:
  3957. # find the canvas origin which is in the top left corner
  3958. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3959. # determine the coordinates for the lowest left point of the canvas
  3960. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3961. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3962. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3963. # canvas) and the point (width, height) is in the top-right location
  3964. loc = self.plotcanvas.axes.transData.transform_point(location)
  3965. j_pos = (
  3966. int(x0 + loc[0]),
  3967. int(y0 - loc[1])
  3968. )
  3969. cursor.setPos(j_pos[0], j_pos[1])
  3970. self.plotcanvas.mouse = [location[0], location[1]]
  3971. if self.defaults["global_cursor_color_enabled"] is True:
  3972. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3973. else:
  3974. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3975. if self.grid_status():
  3976. # Update cursor
  3977. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3978. symbol='++', edge_color=self.cursor_color_3D,
  3979. edge_width=self.defaults["global_cursor_width"],
  3980. size=self.defaults["global_cursor_size"])
  3981. # Set the relative position label
  3982. dx = location[0] - float(self.rel_point1[0])
  3983. dy = location[1] - float(self.rel_point1[1])
  3984. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3985. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3986. # Set the position label
  3987. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3988. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3989. units = self.defaults["units"].lower()
  3990. self.plotcanvas.text_hud.text = \
  3991. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3992. dx, units, dy, units, location[0], units, location[1], units)
  3993. self.inform.emit('[success] %s' % _("Done."))
  3994. return location
  3995. def on_locate(self, obj, fit_center=True):
  3996. """
  3997. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3998. :param obj: The object on which to locate certain points
  3999. :param fit_center: If to fit view. Boolean.
  4000. :return: A point location. (x, y) tuple.
  4001. """
  4002. self.defaults.report_usage("on_locate()")
  4003. if obj is None:
  4004. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4005. return 'fail'
  4006. class DialogBoxChoice(QtWidgets.QDialog):
  4007. def __init__(self, title=None, icon=None, choice='bl'):
  4008. """
  4009. :param title: string with the window title
  4010. """
  4011. super(DialogBoxChoice, self).__init__()
  4012. self.ok = False
  4013. self.setWindowIcon(icon)
  4014. self.setWindowTitle(str(title))
  4015. self.form = QtWidgets.QFormLayout(self)
  4016. self.ref_radio = RadioSet([
  4017. {"label": _("Bottom-Left"), "value": "bl"},
  4018. {"label": _("Top-Left"), "value": "tl"},
  4019. {"label": _("Bottom-Right"), "value": "br"},
  4020. {"label": _("Top-Right"), "value": "tr"},
  4021. {"label": _("Center"), "value": "c"}
  4022. ], orientation='vertical', stretch=False)
  4023. self.ref_radio.set_value(choice)
  4024. self.form.addRow(self.ref_radio)
  4025. self.button_box = QtWidgets.QDialogButtonBox(
  4026. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4027. Qt.Horizontal, parent=self)
  4028. self.form.addRow(self.button_box)
  4029. self.button_box.accepted.connect(self.accept)
  4030. self.button_box.rejected.connect(self.reject)
  4031. if self.exec_() == QtWidgets.QDialog.Accepted:
  4032. self.ok = True
  4033. self.location_point = self.ref_radio.get_value()
  4034. else:
  4035. self.ok = False
  4036. self.location_point = None
  4037. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4038. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4039. choice=self.defaults['global_locate_pt'])
  4040. if dia_box.ok is True:
  4041. try:
  4042. location_point = dia_box.location_point
  4043. self.defaults['global_locate_pt'] = dia_box.location_point
  4044. except Exception:
  4045. return
  4046. else:
  4047. return
  4048. loc_b = obj.bounds()
  4049. if location_point == 'bl':
  4050. location = (loc_b[0], loc_b[1])
  4051. elif location_point == 'tl':
  4052. location = (loc_b[0], loc_b[3])
  4053. elif location_point == 'br':
  4054. location = (loc_b[2], loc_b[1])
  4055. elif location_point == 'tr':
  4056. location = (loc_b[2], loc_b[3])
  4057. else:
  4058. # center
  4059. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4060. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4061. location = (cx, cy)
  4062. self.locate_signal.emit(location, location_point)
  4063. if fit_center:
  4064. self.plotcanvas.fit_center(loc=location)
  4065. cursor = QtGui.QCursor()
  4066. if self.is_legacy is False:
  4067. # I don't know where those differences come from but they are constant for the current
  4068. # execution of the application and they are multiples of a value around 0.0263mm.
  4069. # In a random way sometimes they are more sometimes they are less
  4070. # if units == 'MM':
  4071. # cal_factor = 0.0263
  4072. # else:
  4073. # cal_factor = 0.0263 / 25.4
  4074. cal_location = (location[0], location[1])
  4075. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4076. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4077. j_pos = (
  4078. int(canvas_origin.x() + round(jump_loc[0])),
  4079. int(canvas_origin.y() + round(jump_loc[1]))
  4080. )
  4081. cursor.setPos(j_pos[0], j_pos[1])
  4082. else:
  4083. # find the canvas origin which is in the top left corner
  4084. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4085. # determine the coordinates for the lowest left point of the canvas
  4086. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4087. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4088. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4089. # canvas) and the point (width, height) is in the top-right location
  4090. loc = self.plotcanvas.axes.transData.transform_point(location)
  4091. j_pos = (
  4092. int(x0 + loc[0]),
  4093. int(y0 - loc[1])
  4094. )
  4095. cursor.setPos(j_pos[0], j_pos[1])
  4096. self.plotcanvas.mouse = [location[0], location[1]]
  4097. if self.defaults["global_cursor_color_enabled"] is True:
  4098. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4099. else:
  4100. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4101. if self.grid_status():
  4102. # Update cursor
  4103. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4104. symbol='++', edge_color=self.cursor_color_3D,
  4105. edge_width=self.defaults["global_cursor_width"],
  4106. size=self.defaults["global_cursor_size"])
  4107. # Set the relative position label
  4108. self.dx = location[0] - float(self.rel_point1[0])
  4109. self.dy = location[1] - float(self.rel_point1[1])
  4110. # Set the position label
  4111. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4112. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4113. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4114. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4115. units = self.defaults["units"].lower()
  4116. self.plotcanvas.text_hud.text = \
  4117. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4118. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4119. self.inform.emit('[success] %s' % _("Done."))
  4120. return location
  4121. def on_copy_command(self):
  4122. """
  4123. Will copy a selection of objects, creating new objects.
  4124. :return:
  4125. """
  4126. self.defaults.report_usage("on_copy_command()")
  4127. def initialize(obj_init, app_obj):
  4128. """
  4129. :param obj_init: the new object
  4130. :type obj_init: class
  4131. :param app_obj: An instance of the App class
  4132. :type app_obj: App
  4133. :return: None
  4134. :rtype:
  4135. """
  4136. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4137. try:
  4138. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4139. except AttributeError:
  4140. pass
  4141. try:
  4142. obj_init.apertures = deepcopy(obj.apertures)
  4143. except AttributeError:
  4144. pass
  4145. try:
  4146. if obj.tools:
  4147. obj_init.tools = deepcopy(obj.tools)
  4148. except Exception as err:
  4149. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4150. try:
  4151. obj_init.source_file = deepcopy(obj.source_file)
  4152. except (AttributeError, TypeError):
  4153. pass
  4154. def initialize_excellon(obj_init, app_obj):
  4155. obj_init.source_file = deepcopy(obj.source_file)
  4156. obj_init.tools = deepcopy(obj.tools)
  4157. # drills are offset, so they need to be deep copied
  4158. obj_init.drills = deepcopy(obj.drills)
  4159. # slots are offset, so they need to be deep copied
  4160. obj_init.slots = deepcopy(obj.slots)
  4161. obj_init.create_geometry()
  4162. if not obj_init.tools:
  4163. app_obj.debug("on_copy_command() --> no excellon tools")
  4164. return 'fail'
  4165. def initialize_script(obj_init, app_obj):
  4166. obj_init.source_file = deepcopy(obj.source_file)
  4167. def initialize_document(obj_init, app_obj):
  4168. obj_init.source_file = deepcopy(obj.source_file)
  4169. for obj in self.collection.get_selected():
  4170. obj_name = obj.options["name"]
  4171. try:
  4172. if isinstance(obj, ExcellonObject):
  4173. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4174. elif isinstance(obj, GerberObject):
  4175. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4176. elif isinstance(obj, GeometryObject):
  4177. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4178. elif isinstance(obj, ScriptObject):
  4179. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4180. elif isinstance(obj, DocumentObject):
  4181. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4182. except Exception as e:
  4183. return "Operation failed: %s" % str(e)
  4184. def on_copy_object2(self, custom_name):
  4185. def initialize_geometry(obj_init, app_obj):
  4186. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4187. try:
  4188. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4189. except AttributeError:
  4190. pass
  4191. try:
  4192. obj_init.apertures = deepcopy(obj.apertures)
  4193. except AttributeError:
  4194. pass
  4195. try:
  4196. if obj.tools:
  4197. obj_init.tools = deepcopy(obj.tools)
  4198. except Exception as ee:
  4199. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4200. def initialize_gerber(obj_init, app_obj):
  4201. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4202. obj_init.apertures = deepcopy(obj.apertures)
  4203. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4204. if not obj_init.apertures:
  4205. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4206. return 'fail'
  4207. def initialize_excellon(obj_init, app_obj):
  4208. obj_init.tools = deepcopy(obj.tools)
  4209. # drills are offset, so they need to be deep copied
  4210. obj_init.drills = deepcopy(obj.drills)
  4211. # slots are offset, so they need to be deep copied
  4212. obj_init.slots = deepcopy(obj.slots)
  4213. obj_init.create_geometry()
  4214. if not obj_init.tools:
  4215. app_obj.debug("on_copy_object2() --> no excellon tools")
  4216. return 'fail'
  4217. for obj in self.collection.get_selected():
  4218. obj_name = obj.options["name"]
  4219. try:
  4220. if isinstance(obj, ExcellonObject):
  4221. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4222. elif isinstance(obj, GerberObject):
  4223. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4224. elif isinstance(obj, GeometryObject):
  4225. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4226. except Exception as er:
  4227. return "Operation failed: %s" % str(er)
  4228. def on_rename_object(self, text):
  4229. """
  4230. Will rename an object.
  4231. :param text: New name for the object.
  4232. :return:
  4233. """
  4234. self.defaults.report_usage("on_rename_object()")
  4235. named_obj = self.collection.get_active()
  4236. for obj in named_obj:
  4237. if obj is list:
  4238. self.on_rename_object(text)
  4239. else:
  4240. try:
  4241. obj.options['name'] = text
  4242. except Exception as e:
  4243. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4244. def convert_any2geo(self):
  4245. """
  4246. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4247. :return:
  4248. """
  4249. self.defaults.report_usage("convert_any2geo()")
  4250. def initialize(obj_init, app):
  4251. obj_init.solid_geometry = obj.solid_geometry
  4252. try:
  4253. obj_init.follow_geometry = obj.follow_geometry
  4254. except AttributeError:
  4255. pass
  4256. try:
  4257. obj_init.apertures = obj.apertures
  4258. except AttributeError:
  4259. pass
  4260. try:
  4261. if obj.tools:
  4262. obj_init.tools = obj.tools
  4263. except AttributeError:
  4264. pass
  4265. def initialize_excellon(obj_init, app_obj):
  4266. # objs = self.collection.get_selected()
  4267. # GeometryObject.merge(objs, obj)
  4268. solid_geo = []
  4269. for tool in obj.tools:
  4270. for geo in obj.tools[tool]['solid_geometry']:
  4271. solid_geo.append(geo)
  4272. obj_init.solid_geometry = deepcopy(solid_geo)
  4273. if not obj_init.solid_geometry:
  4274. app_obj.log("convert_any2geo() failed")
  4275. return 'fail'
  4276. if not self.collection.get_selected():
  4277. log.warning("App.convert_any2geo --> No object selected")
  4278. self.inform.emit('[WARNING_NOTCL] %s' %
  4279. _("No object is selected. Select an object and try again."))
  4280. return
  4281. for obj in self.collection.get_selected():
  4282. obj_name = obj.options["name"]
  4283. try:
  4284. if obj.kind == 'excellon':
  4285. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4286. else:
  4287. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4288. except Exception as e:
  4289. return "Operation failed: %s" % str(e)
  4290. def convert_any2gerber(self):
  4291. """
  4292. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4293. :return:
  4294. """
  4295. def initialize_geometry(obj_init, app_obj):
  4296. apertures = {}
  4297. apid = 0
  4298. apertures[str(apid)] = {}
  4299. apertures[str(apid)]['geometry'] = []
  4300. for obj_orig in obj.solid_geometry:
  4301. new_elem = {}
  4302. new_elem['solid'] = obj_orig
  4303. try:
  4304. new_elem['follow'] = obj_orig.exterior
  4305. except AttributeError:
  4306. pass
  4307. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4308. apertures[str(apid)]['size'] = 0.0
  4309. apertures[str(apid)]['type'] = 'C'
  4310. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4311. obj_init.apertures = deepcopy(apertures)
  4312. if not obj_init.apertures:
  4313. app_obj.log("convert_any2gerber() failed")
  4314. return 'fail'
  4315. def initialize_excellon(obj_init, app_obj):
  4316. apertures = {}
  4317. apid = 10
  4318. for tool in obj.tools:
  4319. apertures[str(apid)] = {}
  4320. apertures[str(apid)]['geometry'] = []
  4321. for geo in obj.tools[tool]['solid_geometry']:
  4322. new_el = {}
  4323. new_el['solid'] = geo
  4324. new_el['follow'] = geo.exterior
  4325. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4326. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4327. apertures[str(apid)]['type'] = 'C'
  4328. apid += 1
  4329. # create solid_geometry
  4330. solid_geometry = []
  4331. for apid in apertures:
  4332. for geo_el in apertures[apid]['geometry']:
  4333. solid_geometry.append(geo_el['solid'])
  4334. solid_geometry = MultiPolygon(solid_geometry)
  4335. solid_geometry = solid_geometry.buffer(0.0000001)
  4336. obj_init.solid_geometry = deepcopy(solid_geometry)
  4337. obj_init.apertures = deepcopy(apertures)
  4338. if not obj_init.apertures:
  4339. app_obj.log("convert_any2gerber() failed")
  4340. return 'fail'
  4341. if not self.collection.get_selected():
  4342. log.warning("App.convert_any2gerber --> No object selected")
  4343. self.inform.emit('[WARNING_NOTCL] %s' %
  4344. _("No object is selected. Select an object and try again."))
  4345. return
  4346. for obj in self.collection.get_selected():
  4347. obj_name = obj.options["name"]
  4348. try:
  4349. if obj.kind == 'excellon':
  4350. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4351. elif obj.kind == 'geometry':
  4352. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4353. else:
  4354. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4355. except Exception as e:
  4356. return "Operation failed: %s" % str(e)
  4357. def convert_any2excellon(self):
  4358. """
  4359. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4360. :return:
  4361. """
  4362. def initialize_geometry(obj_init, app_obj):
  4363. tools = {}
  4364. tooluid = 1
  4365. obj_init.solid_geometry = []
  4366. for geo in obj.solid_geometry:
  4367. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4368. continue
  4369. minx, miny, maxx, maxy = geo.bounds
  4370. new_dia = min([maxx-minx, maxy-miny])
  4371. new_drill = geo.centroid
  4372. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4373. current_tooldias = []
  4374. if tools:
  4375. for tool in tools:
  4376. if tools[tool] and 'tooldia' in tools[tool]:
  4377. current_tooldias.append(tools[tool]['tooldia'])
  4378. if new_dia in current_tooldias:
  4379. digits = app_obj.decimals
  4380. for tool in tools:
  4381. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4382. tools[tool]['drills'].append(new_drill)
  4383. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4384. else:
  4385. tools[tooluid] = {}
  4386. tools[tooluid]['tooldia'] = new_dia
  4387. tools[tooluid]['drills'] = [new_drill]
  4388. tools[tooluid]['slots'] = []
  4389. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4390. tooluid += 1
  4391. try:
  4392. obj_init.solid_geometry.append(new_drill_geo)
  4393. except (TypeError, AttributeError):
  4394. obj_init.solid_geometry = [new_drill_geo]
  4395. obj_init.tools = deepcopy(tools)
  4396. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4397. if not obj_init.solid_geometry:
  4398. return 'fail'
  4399. def initialize_gerber(obj_init, app_obj):
  4400. tools = {}
  4401. tooluid = 1
  4402. digits = app_obj.decimals
  4403. obj_init.solid_geometry = []
  4404. for apid in obj.apertures:
  4405. if 'geometry' in obj.apertures[apid]:
  4406. for geo_dict in obj.apertures[apid]['geometry']:
  4407. if 'follow' in geo_dict:
  4408. if isinstance(geo_dict['follow'], Point):
  4409. geo = geo_dict['solid']
  4410. minx, miny, maxx, maxy = geo.bounds
  4411. new_dia = min([maxx - minx, maxy - miny])
  4412. new_drill = geo.centroid
  4413. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4414. current_tooldias = []
  4415. if tools:
  4416. for tool in tools:
  4417. if tools[tool] and 'tooldia' in tools[tool]:
  4418. current_tooldias.append(
  4419. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4420. )
  4421. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4422. if formatted_new_dia in current_tooldias:
  4423. for tool in tools:
  4424. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4425. if new_drill not in tools[tool]['drills']:
  4426. tools[tool]['drills'].append(new_drill)
  4427. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4428. else:
  4429. tools[tooluid] = {}
  4430. tools[tooluid]['tooldia'] = new_dia
  4431. tools[tooluid]['drills'] = [new_drill]
  4432. tools[tooluid]['slots'] = []
  4433. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4434. tooluid += 1
  4435. try:
  4436. obj_init.solid_geometry.append(new_drill_geo)
  4437. except (TypeError, AttributeError):
  4438. obj_init.solid_geometry = [new_drill_geo]
  4439. elif isinstance(geo_dict['follow'], LineString):
  4440. geo_coords = list(geo_dict['follow'].coords)
  4441. # slots can have only a start and stop point and no intermediate points
  4442. if len(geo_coords) != 2:
  4443. continue
  4444. geo = geo_dict['solid']
  4445. try:
  4446. new_dia = obj.apertures[apid]['size']
  4447. except Exception:
  4448. continue
  4449. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4450. new_slot_geo = geo
  4451. current_tooldias = []
  4452. if tools:
  4453. for tool in tools:
  4454. if tools[tool] and 'tooldia' in tools[tool]:
  4455. current_tooldias.append(
  4456. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4457. )
  4458. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4459. for tool in tools:
  4460. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4461. '%.*f' % (self.decimals, new_dia)):
  4462. if new_slot not in tools[tool]['slots']:
  4463. tools[tool]['slots'].append(new_slot)
  4464. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4465. else:
  4466. tools[tooluid] = {}
  4467. tools[tooluid]['tooldia'] = new_dia
  4468. tools[tooluid]['drills'] = []
  4469. tools[tooluid]['slots'] = [new_slot]
  4470. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4471. tooluid += 1
  4472. try:
  4473. obj_init.solid_geometry.append(new_slot_geo)
  4474. except (TypeError, AttributeError):
  4475. obj_init.solid_geometry = [new_slot_geo]
  4476. obj_init.tools = deepcopy(tools)
  4477. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4478. if not obj_init.solid_geometry:
  4479. return 'fail'
  4480. if not self.collection.get_selected():
  4481. log.warning("App.convert_any2excellon--> No object selected")
  4482. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4483. return
  4484. for obj in self.collection.get_selected():
  4485. obj_name = obj.options["name"]
  4486. try:
  4487. if obj.kind == 'gerber':
  4488. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4489. elif obj.kind == 'geometry':
  4490. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4491. else:
  4492. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4493. except Exception as e:
  4494. return "Operation failed: %s" % str(e)
  4495. def abort_all_tasks(self):
  4496. """
  4497. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4498. on the first possible occasion.
  4499. :return:
  4500. """
  4501. if self.abort_flag is False:
  4502. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4503. self.abort_flag = True
  4504. self.cleanup.emit()
  4505. def app_is_idle(self):
  4506. if self.abort_flag:
  4507. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4508. self.abort_flag = False
  4509. def on_selectall(self):
  4510. """
  4511. Will draw a selection box shape around the selected objects.
  4512. :return:
  4513. """
  4514. self.defaults.report_usage("on_selectall()")
  4515. # delete the possible selection box around a possible selected object
  4516. self.delete_selection_shape()
  4517. for name in self.collection.get_names():
  4518. self.collection.set_active(name)
  4519. curr_sel_obj = self.collection.get_by_name(name)
  4520. # create the selection box around the selected object
  4521. if self.defaults['global_selection_shape'] is True:
  4522. self.draw_selection_shape(curr_sel_obj)
  4523. def on_toggle_preferences(self):
  4524. pref_open = False
  4525. for idx in range(self.ui.plot_tab_area.count()):
  4526. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4527. pref_open = True
  4528. if pref_open:
  4529. for idx in range(self.ui.plot_tab_area.count()):
  4530. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4531. self.ui.plot_tab_area.removeTab(idx)
  4532. break
  4533. self.ui.pref_status_label.setStyleSheet("")
  4534. else:
  4535. self.on_preferences()
  4536. def on_preferences(self):
  4537. """
  4538. Adds the Preferences in a Tab in Plot Area
  4539. :return:
  4540. """
  4541. # add the tab if it was closed
  4542. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4543. # delete the absolute and relative position and messages in the infobar
  4544. # self.ui.position_label.setText("")
  4545. # self.ui.rel_position_label.setText("")
  4546. # hide coordinates toolbars in the infobar while in DB
  4547. self.ui.coords_toolbar.hide()
  4548. self.ui.delta_coords_toolbar.hide()
  4549. # Switch plot_area to preferences page
  4550. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4551. # self.ui.show()
  4552. self.ui.pref_status_label.setStyleSheet("""
  4553. QLabel
  4554. {
  4555. color: black;
  4556. background-color: lightseagreen;
  4557. }
  4558. """
  4559. )
  4560. # detect changes in the preferences
  4561. for idx in range(self.ui.pref_tab_area.count()):
  4562. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4563. try:
  4564. try:
  4565. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4566. except (TypeError, AttributeError):
  4567. pass
  4568. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4569. except AttributeError:
  4570. pass
  4571. try:
  4572. try:
  4573. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4574. except (TypeError, AttributeError):
  4575. pass
  4576. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4577. except AttributeError:
  4578. pass
  4579. try:
  4580. try:
  4581. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4582. except (TypeError, AttributeError):
  4583. pass
  4584. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4585. except AttributeError:
  4586. pass
  4587. try:
  4588. try:
  4589. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4590. except (TypeError, AttributeError):
  4591. pass
  4592. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4593. except AttributeError:
  4594. pass
  4595. try:
  4596. try:
  4597. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4598. except (TypeError, AttributeError):
  4599. pass
  4600. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4601. except AttributeError:
  4602. pass
  4603. def on_tools_database(self, source='app'):
  4604. """
  4605. Adds the Tools Database in a Tab in Plot Area.
  4606. :return:
  4607. """
  4608. filename = self.data_path + '\\tools_db.FlatDB'
  4609. # load the database tools from the file
  4610. try:
  4611. with open(filename) as f:
  4612. __ = f.read()
  4613. except Exception as eros:
  4614. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4615. log.error("Could not access tools DB file. The file may be locked,\n"
  4616. "not existing or doesn't have the read permissions.\n"
  4617. "Check to see if exists, it should be here: %s\n"
  4618. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4619. self.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  4620. return 'fail'
  4621. for idx in range(self.ui.plot_tab_area.count()):
  4622. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4623. # there can be only one instance of Tools Database at one time
  4624. return
  4625. if source == 'app':
  4626. self.tools_db_tab = ToolsDB2(
  4627. app=self,
  4628. parent=self.ui,
  4629. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4630. )
  4631. elif source == 'ncc':
  4632. self.tools_db_tab = ToolsDB2(
  4633. app=self,
  4634. parent=self.ui,
  4635. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4636. )
  4637. elif source == 'paint':
  4638. self.tools_db_tab = ToolsDB2(
  4639. app=self,
  4640. parent=self.ui,
  4641. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4642. )
  4643. elif source == 'iso':
  4644. self.tools_db_tab = ToolsDB2(
  4645. app=self,
  4646. parent=self.ui,
  4647. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4648. )
  4649. elif source == 'cutout':
  4650. self.tools_db_tab = ToolsDB2(
  4651. app=self,
  4652. parent=self.ui,
  4653. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4654. )
  4655. # add the tab if it was closed
  4656. try:
  4657. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4658. self.tools_db_tab.setObjectName("database_tab")
  4659. except Exception as e:
  4660. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4661. return
  4662. # delete the absolute and relative position and messages in the infobar
  4663. # self.ui.position_label.setText("")
  4664. # self.ui.rel_position_label.setText("")
  4665. # hide coordinates toolbars in the infobar while in DB
  4666. self.ui.coords_toolbar.hide()
  4667. self.ui.delta_coords_toolbar.hide()
  4668. # Switch plot_area to preferences page
  4669. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4670. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4671. self.tools_db_tab.ui_connect()
  4672. def on_geometry_tool_add_from_db_executed(self, tool):
  4673. """
  4674. Here add the tool from DB in the selected geometry object.
  4675. :return:
  4676. """
  4677. tool_from_db = deepcopy(tool)
  4678. obj = self.collection.get_active()
  4679. if obj.kind == 'geometry':
  4680. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4681. # close the tab and delete it
  4682. for idx in range(self.ui.plot_tab_area.count()):
  4683. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4684. wdg = self.ui.plot_tab_area.widget(idx)
  4685. wdg.deleteLater()
  4686. self.ui.plot_tab_area.removeTab(idx)
  4687. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4688. elif obj.kind == 'gerber':
  4689. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4690. # close the tab and delete it
  4691. for idx in range(self.ui.plot_tab_area.count()):
  4692. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4693. wdg = self.ui.plot_tab_area.widget(idx)
  4694. wdg.deleteLater()
  4695. self.ui.plot_tab_area.removeTab(idx)
  4696. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4697. else:
  4698. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4699. def on_plot_area_tab_closed(self, tab_obj_name):
  4700. """
  4701. Executed whenever a QTab is closed in the Plot Area.
  4702. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4703. :return:
  4704. """
  4705. if tab_obj_name == "preferences_tab":
  4706. self.preferencesUiManager.on_close_preferences_tab()
  4707. elif tab_obj_name == "database_tab":
  4708. # disconnect the signals from the table widget in tab
  4709. self.tools_db_tab.ui_disconnect()
  4710. if self.tools_db_changed_flag is True:
  4711. msgbox = QtWidgets.QMessageBox()
  4712. msgbox.setText(_("One or more Tools are edited.\n"
  4713. "Do you want to update the Tools Database?"))
  4714. msgbox.setWindowTitle(_("Save Tools Database"))
  4715. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4716. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4717. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4718. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4719. msgbox.setDefaultButton(bt_yes)
  4720. msgbox.exec_()
  4721. response = msgbox.clickedButton()
  4722. if response == bt_yes:
  4723. self.tools_db_tab.on_save_tools_db()
  4724. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4725. else:
  4726. self.tools_db_changed_flag = False
  4727. self.inform.emit('')
  4728. return
  4729. self.tools_db_tab.deleteLater()
  4730. elif tab_obj_name == "text_editor_tab":
  4731. self.toggle_codeeditor = False
  4732. elif tab_obj_name == "bookmarks_tab":
  4733. self.book_dialog_tab.rebuild_actions()
  4734. self.book_dialog_tab.deleteLater()
  4735. else:
  4736. pass
  4737. # restore the coords toolbars
  4738. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4739. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4740. def on_flipy(self):
  4741. """
  4742. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4743. :return:
  4744. """
  4745. self.defaults.report_usage("on_flipy()")
  4746. obj_list = self.collection.get_selected()
  4747. xminlist = []
  4748. yminlist = []
  4749. xmaxlist = []
  4750. ymaxlist = []
  4751. if not obj_list:
  4752. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4753. else:
  4754. try:
  4755. # first get a bounding box to fit all
  4756. for obj in obj_list:
  4757. xmin, ymin, xmax, ymax = obj.bounds()
  4758. xminlist.append(xmin)
  4759. yminlist.append(ymin)
  4760. xmaxlist.append(xmax)
  4761. ymaxlist.append(ymax)
  4762. # get the minimum x,y and maximum x,y for all objects selected
  4763. xminimal = min(xminlist)
  4764. yminimal = min(yminlist)
  4765. xmaximal = max(xmaxlist)
  4766. ymaximal = max(ymaxlist)
  4767. px = 0.5 * (xminimal + xmaximal)
  4768. py = 0.5 * (yminimal + ymaximal)
  4769. # execute mirroring
  4770. for obj in obj_list:
  4771. obj.mirror('X', [px, py])
  4772. obj.plot()
  4773. self.app_obj.object_changed.emit(obj)
  4774. self.inform.emit('[success] %s' %
  4775. _("Flip on Y axis done."))
  4776. except Exception as e:
  4777. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4778. return
  4779. def on_flipx(self):
  4780. """
  4781. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4782. :return:
  4783. """
  4784. self.defaults.report_usage("on_flipx()")
  4785. obj_list = self.collection.get_selected()
  4786. xminlist = []
  4787. yminlist = []
  4788. xmaxlist = []
  4789. ymaxlist = []
  4790. if not obj_list:
  4791. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on X axis."))
  4792. else:
  4793. try:
  4794. # first get a bounding box to fit all
  4795. for obj in obj_list:
  4796. xmin, ymin, xmax, ymax = obj.bounds()
  4797. xminlist.append(xmin)
  4798. yminlist.append(ymin)
  4799. xmaxlist.append(xmax)
  4800. ymaxlist.append(ymax)
  4801. # get the minimum x,y and maximum x,y for all objects selected
  4802. xminimal = min(xminlist)
  4803. yminimal = min(yminlist)
  4804. xmaximal = max(xmaxlist)
  4805. ymaximal = max(ymaxlist)
  4806. px = 0.5 * (xminimal + xmaximal)
  4807. py = 0.5 * (yminimal + ymaximal)
  4808. # execute mirroring
  4809. for obj in obj_list:
  4810. obj.mirror('Y', [px, py])
  4811. obj.plot()
  4812. self.app_obj.object_changed.emit(obj)
  4813. self.inform.emit('[success] %s' %
  4814. _("Flip on X axis done."))
  4815. except Exception as e:
  4816. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4817. return
  4818. def on_rotate(self, silent=False, preset=None):
  4819. """
  4820. Executed when Options -> Rotate Selection menu entry is clicked.
  4821. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4822. :param preset: A value to be used as predefined angle for rotation.
  4823. :return:
  4824. """
  4825. self.defaults.report_usage("on_rotate()")
  4826. obj_list = self.collection.get_selected()
  4827. xminlist = []
  4828. yminlist = []
  4829. xmaxlist = []
  4830. ymaxlist = []
  4831. if not obj_list:
  4832. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4833. else:
  4834. if silent is False:
  4835. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4836. min=-360, max=360, decimals=4,
  4837. init_val=float(self.defaults['tools_transform_rotate']))
  4838. num, ok = rotatebox.get_value()
  4839. else:
  4840. num = preset
  4841. ok = True
  4842. if ok:
  4843. try:
  4844. # first get a bounding box to fit all
  4845. for obj in obj_list:
  4846. xmin, ymin, xmax, ymax = obj.bounds()
  4847. xminlist.append(xmin)
  4848. yminlist.append(ymin)
  4849. xmaxlist.append(xmax)
  4850. ymaxlist.append(ymax)
  4851. # get the minimum x,y and maximum x,y for all objects selected
  4852. xminimal = min(xminlist)
  4853. yminimal = min(yminlist)
  4854. xmaximal = max(xmaxlist)
  4855. ymaximal = max(ymaxlist)
  4856. px = 0.5 * (xminimal + xmaximal)
  4857. py = 0.5 * (yminimal + ymaximal)
  4858. for sel_obj in obj_list:
  4859. sel_obj.rotate(-float(num), point=(px, py))
  4860. sel_obj.plot()
  4861. self.app_obj.object_changed.emit(sel_obj)
  4862. self.inform.emit('[success] %s' % _("Rotation done."))
  4863. except Exception as e:
  4864. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4865. return
  4866. def on_skewx(self):
  4867. """
  4868. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4869. :return:
  4870. """
  4871. self.defaults.report_usage("on_skewx()")
  4872. obj_list = self.collection.get_selected()
  4873. xminlist = []
  4874. yminlist = []
  4875. if not obj_list:
  4876. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4877. else:
  4878. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4879. min=-360, max=360, decimals=4,
  4880. init_val=float(self.defaults['tools_transform_skew_x']))
  4881. num, ok = skewxbox.get_value()
  4882. if ok:
  4883. # first get a bounding box to fit all
  4884. for obj in obj_list:
  4885. xmin, ymin, xmax, ymax = obj.bounds()
  4886. xminlist.append(xmin)
  4887. yminlist.append(ymin)
  4888. # get the minimum x,y and maximum x,y for all objects selected
  4889. xminimal = min(xminlist)
  4890. yminimal = min(yminlist)
  4891. for obj in obj_list:
  4892. obj.skew(num, 0, point=(xminimal, yminimal))
  4893. obj.plot()
  4894. self.app_obj.object_changed.emit(obj)
  4895. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4896. def on_skewy(self):
  4897. """
  4898. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4899. :return:
  4900. """
  4901. self.defaults.report_usage("on_skewy()")
  4902. obj_list = self.collection.get_selected()
  4903. xminlist = []
  4904. yminlist = []
  4905. if not obj_list:
  4906. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4907. else:
  4908. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4909. min=-360, max=360, decimals=4,
  4910. init_val=float(self.defaults['tools_transform_skew_y']))
  4911. num, ok = skewybox.get_value()
  4912. if ok:
  4913. # first get a bounding box to fit all
  4914. for obj in obj_list:
  4915. xmin, ymin, xmax, ymax = obj.bounds()
  4916. xminlist.append(xmin)
  4917. yminlist.append(ymin)
  4918. # get the minimum x,y and maximum x,y for all objects selected
  4919. xminimal = min(xminlist)
  4920. yminimal = min(yminlist)
  4921. for obj in obj_list:
  4922. obj.skew(0, num, point=(xminimal, yminimal))
  4923. obj.plot()
  4924. self.app_obj.object_changed.emit(obj)
  4925. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4926. def on_plots_updated(self):
  4927. """
  4928. Callback used to report when the plots have changed.
  4929. Adjust axes and zooms to fit.
  4930. :return: None
  4931. """
  4932. if self.is_legacy is False:
  4933. self.plotcanvas.update()
  4934. else:
  4935. self.plotcanvas.auto_adjust_axes()
  4936. self.on_zoom_fit()
  4937. self.collection.update_view()
  4938. # self.inform.emit(_("Plots updated ..."))
  4939. def on_toolbar_replot(self):
  4940. """
  4941. Callback for toolbar button. Re-plots all objects.
  4942. :return: None
  4943. """
  4944. self.log.debug("on_toolbar_replot()")
  4945. try:
  4946. obj = self.collection.get_active()
  4947. if obj:
  4948. obj.read_form()
  4949. else:
  4950. self.on_zoom_fit()
  4951. except AttributeError as e:
  4952. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  4953. pass
  4954. self.plot_all()
  4955. def grid_status(self):
  4956. return True if self.ui.grid_snap_btn.isChecked() else False
  4957. def populate_cmenu_grids(self):
  4958. units = self.defaults['units'].lower()
  4959. # for act in self.ui.cmenu_gridmenu.actions():
  4960. # act.triggered.disconnect()
  4961. self.ui.cmenu_gridmenu.clear()
  4962. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4963. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4964. _("Grid On/Off"))
  4965. grid_toggle.setCheckable(True)
  4966. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4967. self.ui.cmenu_gridmenu.addSeparator()
  4968. for grid in sorted_list:
  4969. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4970. "%s" % str(grid))
  4971. action.triggered.connect(self.set_grid)
  4972. self.ui.cmenu_gridmenu.addSeparator()
  4973. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4974. _("Add"))
  4975. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4976. _("Delete"))
  4977. grid_add.triggered.connect(self.on_grid_add)
  4978. grid_delete.triggered.connect(self.on_grid_delete)
  4979. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4980. def set_grid(self):
  4981. menu_action = self.sender()
  4982. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4983. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4984. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4985. def on_grid_add(self):
  4986. # ## Current application units in lower Case
  4987. units = self.defaults['units'].lower()
  4988. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4989. text=_('Enter a Grid Value:'),
  4990. min=0.0000, max=99.9999, decimals=4)
  4991. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4992. val, ok = grid_add_popup.get_value()
  4993. if ok:
  4994. if float(val) == 0:
  4995. self.inform.emit('[WARNING_NOTCL] %s' %
  4996. _("Please enter a grid value with non-zero value, in Float format."))
  4997. return
  4998. else:
  4999. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5000. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5001. self.inform.emit('[success] %s...' % _("New Grid added"))
  5002. else:
  5003. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5004. else:
  5005. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5006. def on_grid_delete(self):
  5007. # ## Current application units in lower Case
  5008. units = self.defaults['units'].lower()
  5009. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5010. text='Enter a Grid Value:',
  5011. min=0.0000, max=99.9999, decimals=4)
  5012. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5013. val, ok = grid_del_popup.get_value()
  5014. if ok:
  5015. if float(val) == 0:
  5016. self.inform.emit('[WARNING_NOTCL] %s' %
  5017. _("Please enter a grid value with non-zero value, in Float format."))
  5018. return
  5019. else:
  5020. try:
  5021. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5022. except ValueError:
  5023. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5024. return
  5025. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5026. else:
  5027. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5028. def on_shortcut_list(self):
  5029. self.defaults.report_usage("on_shortcut_list()")
  5030. # add the tab if it was closed
  5031. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5032. # delete the absolute and relative position and messages in the infobar
  5033. # self.ui.position_label.setText("")
  5034. # self.ui.rel_position_label.setText("")
  5035. # hide coordinates toolbars in the infobar while in DB
  5036. self.ui.coords_toolbar.hide()
  5037. self.ui.delta_coords_toolbar.hide()
  5038. # Switch plot_area to preferences page
  5039. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5040. # self.ui.show()
  5041. def on_select_tab(self, name):
  5042. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5043. if self.ui.splitter.sizes()[0] == 0:
  5044. self.ui.splitter.setSizes([1, 1])
  5045. else:
  5046. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5047. self.ui.splitter.setSizes([0, 1])
  5048. if name == 'project':
  5049. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5050. elif name == 'properties':
  5051. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5052. elif name == 'tool':
  5053. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5054. def on_copy_name(self):
  5055. self.defaults.report_usage("on_copy_name()")
  5056. obj = self.collection.get_active()
  5057. try:
  5058. name = obj.options["name"]
  5059. except AttributeError:
  5060. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5061. self.inform.emit('[WARNING_NOTCL] %s' %
  5062. _(" No object selected to copy it's name"))
  5063. return
  5064. self.clipboard.setText(name)
  5065. self.inform.emit(_("Name copied on clipboard ..."))
  5066. def on_mouse_click_over_plot(self, event):
  5067. """
  5068. Default actions are:
  5069. :param event: Contains information about the event, like which button
  5070. was clicked, the pixel coordinates and the axes coordinates.
  5071. :return: None
  5072. """
  5073. self.pos = []
  5074. if self.is_legacy is False:
  5075. event_pos = event.pos
  5076. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5077. # # Set the mouse button for panning
  5078. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5079. else:
  5080. event_pos = (event.xdata, event.ydata)
  5081. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5082. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5083. # So it can receive key presses
  5084. self.plotcanvas.native.setFocus()
  5085. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5086. if self.grid_status():
  5087. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5088. else:
  5089. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5090. try:
  5091. if event.button == 1:
  5092. # Reset here the relative coordinates so there is a new reference on the click position
  5093. if self.rel_point1 is None:
  5094. self.rel_point1 = self.pos
  5095. else:
  5096. self.rel_point2 = copy(self.rel_point1)
  5097. self.rel_point1 = self.pos
  5098. self.on_mouse_move_over_plot(event, origin_click=True)
  5099. except Exception as e:
  5100. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5101. def on_mouse_double_click_over_plot(self, event):
  5102. if event.button == 1:
  5103. self.doubleclick = True
  5104. def on_mouse_move_over_plot(self, event, origin_click=None):
  5105. """
  5106. Callback for the mouse motion event over the plot.
  5107. :param event: Contains information about the event.
  5108. :param origin_click
  5109. :return: None
  5110. """
  5111. if self.is_legacy is False:
  5112. event_pos = event.pos
  5113. if self.defaults["global_pan_button"] == '2':
  5114. pan_button = 2
  5115. else:
  5116. pan_button = 3
  5117. self.event_is_dragging = event.is_dragging
  5118. else:
  5119. event_pos = (event.xdata, event.ydata)
  5120. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5121. if self.defaults["global_pan_button"] == '2':
  5122. pan_button = 3
  5123. else:
  5124. pan_button = 2
  5125. self.event_is_dragging = self.plotcanvas.is_dragging
  5126. # So it can receive key presses but not when the Tcl Shell is active
  5127. if not self.ui.shell_dock.isVisible():
  5128. if not self.plotcanvas.native.hasFocus():
  5129. self.plotcanvas.native.setFocus()
  5130. self.pos_jump = event_pos
  5131. self.ui.popMenu.mouse_is_panning = False
  5132. if origin_click is None:
  5133. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5134. if event.button == pan_button and self.event_is_dragging == 1:
  5135. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5136. if self.ui.popMenu.popup_active:
  5137. self.ui.popMenu.popup_active = False
  5138. return
  5139. self.ui.popMenu.mouse_is_panning = True
  5140. return
  5141. if self.rel_point1 is not None:
  5142. try: # May fail in case mouse not within axes
  5143. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5144. if pos_canvas[0] is None or pos_canvas[1] is None:
  5145. return
  5146. if self.grid_status():
  5147. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5148. # Update cursor
  5149. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5150. symbol='++', edge_color=self.cursor_color_3D,
  5151. edge_width=self.defaults["global_cursor_width"],
  5152. size=self.defaults["global_cursor_size"])
  5153. else:
  5154. pos = (pos_canvas[0], pos_canvas[1])
  5155. self.dx = pos[0] - float(self.rel_point1[0])
  5156. self.dy = pos[1] - float(self.rel_point1[1])
  5157. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5158. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5159. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5160. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5161. units = self.defaults["units"].lower()
  5162. self.plotcanvas.text_hud.text = \
  5163. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5164. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5165. self.mouse = [pos[0], pos[1]]
  5166. if self.defaults['global_selection_shape'] is False:
  5167. self.selection_type = None
  5168. return
  5169. # if the mouse is moved and the LMB is clicked then the action is a selection
  5170. if self.event_is_dragging == 1 and event.button == 1:
  5171. self.delete_selection_shape()
  5172. if self.dx < 0:
  5173. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5174. face_color=self.defaults['global_alt_sel_fill'])
  5175. self.selection_type = False
  5176. elif self.dx >= 0:
  5177. self.draw_moving_selection_shape(self.pos, pos)
  5178. self.selection_type = True
  5179. else:
  5180. self.selection_type = None
  5181. else:
  5182. self.selection_type = None
  5183. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5184. if self.defaults['global_hover']:
  5185. for obj in self.collection.get_list():
  5186. try:
  5187. # select the object(s) only if it is enabled (plotted)
  5188. if obj.options['plot']:
  5189. if obj not in self.collection.get_selected():
  5190. poly_obj = Polygon(
  5191. [(obj.options['xmin'], obj.options['ymin']),
  5192. (obj.options['xmax'], obj.options['ymin']),
  5193. (obj.options['xmax'], obj.options['ymax']),
  5194. (obj.options['xmin'], obj.options['ymax'])]
  5195. )
  5196. if Point(pos).within(poly_obj):
  5197. if obj.isHovering is False:
  5198. obj.isHovering = True
  5199. obj.notHovering = True
  5200. # create the selection box around the selected object
  5201. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5202. else:
  5203. if obj.notHovering is True:
  5204. obj.notHovering = False
  5205. obj.isHovering = False
  5206. self.delete_hover_shape()
  5207. except Exception:
  5208. # the Exception here will happen if we try to select on screen and we have an
  5209. # newly (and empty) just created Geometry or Excellon object that do not have the
  5210. # xmin, xmax, ymin, ymax options.
  5211. # In this case poly_obj creation (see above) will fail
  5212. pass
  5213. except Exception as e:
  5214. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5215. self.ui.position_label.setText("")
  5216. self.ui.rel_position_label.setText("")
  5217. self.mouse = None
  5218. def on_mouse_click_release_over_plot(self, event):
  5219. """
  5220. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5221. and has been registered in ''self.__init__()''.
  5222. :param event: contains information about the event.
  5223. :return:
  5224. """
  5225. if self.is_legacy is False:
  5226. event_pos = event.pos
  5227. right_button = 2
  5228. else:
  5229. event_pos = (event.xdata, event.ydata)
  5230. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5231. right_button = 3
  5232. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5233. if self.grid_status():
  5234. try:
  5235. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5236. except TypeError:
  5237. return
  5238. else:
  5239. pos = (pos_canvas[0], pos_canvas[1])
  5240. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5241. # canvas menu
  5242. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5243. self.ui.popMenu.mouse_is_panning = False
  5244. self.cursor = QtGui.QCursor()
  5245. self.populate_cmenu_grids()
  5246. self.ui.popMenu.popup(self.cursor.pos())
  5247. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5248. # selection and then select a type of selection ("enclosing" or "touching")
  5249. if event.button == 1: # left click
  5250. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5251. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5252. if modifiers == QtCore.Qt.ShiftModifier:
  5253. # do not auto open the Project Tab
  5254. self.click_noproject = True
  5255. self.clipboard.setText(
  5256. self.defaults["global_point_clipboard_format"] %
  5257. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5258. )
  5259. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5260. return
  5261. if self.doubleclick is True:
  5262. self.doubleclick = False
  5263. if self.collection.get_selected():
  5264. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5265. if self.ui.splitter.sizes()[0] == 0:
  5266. self.ui.splitter.setSizes([1, 1])
  5267. try:
  5268. # delete the selection shape(S) as it may be in the way
  5269. self.delete_selection_shape()
  5270. self.delete_hover_shape()
  5271. except Exception as e:
  5272. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5273. return
  5274. else:
  5275. # WORKAROUND for LEGACY MODE
  5276. if self.is_legacy is True:
  5277. # if there is no move on canvas then we have no dragging selection
  5278. if self.dx == 0 or self.dy == 0:
  5279. self.selection_type = None
  5280. if self.selection_type is not None:
  5281. try:
  5282. self.selection_area_handler(self.pos, pos, self.selection_type)
  5283. self.selection_type = None
  5284. except Exception as e:
  5285. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5286. return
  5287. else:
  5288. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5289. if key_modifier == QtCore.Qt.ShiftModifier:
  5290. mod_key = 'Shift'
  5291. elif key_modifier == QtCore.Qt.ControlModifier:
  5292. mod_key = 'Control'
  5293. else:
  5294. mod_key = None
  5295. try:
  5296. if self.command_active is None:
  5297. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5298. # deselect, and if it's not selected then it will be selected
  5299. # If there is no active command (self.command_active is None) then we check if we clicked
  5300. # on a object by checking the bounding limits against mouse click position
  5301. if mod_key == self.defaults["global_mselect_key"]:
  5302. self.select_objects(key='multisel')
  5303. else:
  5304. # If there is no active command (self.command_active is None) then we check if
  5305. # we clicked on a object by checking the bounding limits against mouse click position
  5306. self.select_objects()
  5307. self.delete_hover_shape()
  5308. except Exception as e:
  5309. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5310. return
  5311. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5312. """
  5313. :param start_pos: mouse position when the selection LMB click was done
  5314. :param end_pos: mouse position when the left mouse button is released
  5315. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5316. :return:
  5317. """
  5318. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5319. # delete previous selection shape
  5320. self.delete_selection_shape()
  5321. # make all objects inactive
  5322. self.collection.set_all_inactive()
  5323. for obj in self.collection.get_list():
  5324. try:
  5325. # select the object(s) only if it is enabled (plotted)
  5326. if obj.options['plot']:
  5327. # it's a line without area
  5328. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5329. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5330. # it's a geometry with area
  5331. else:
  5332. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5333. (obj.options['xmax'], obj.options['ymin']),
  5334. (obj.options['xmax'], obj.options['ymax']),
  5335. (obj.options['xmin'], obj.options['ymax'])])
  5336. if poly_obj.is_empty or not poly_obj.is_valid:
  5337. continue
  5338. if sel_type is True:
  5339. if poly_obj.within(poly_selection):
  5340. # create the selection box around the selected object
  5341. if self.defaults['global_selection_shape'] is True:
  5342. self.draw_selection_shape(obj)
  5343. self.collection.set_active(obj.options['name'])
  5344. else:
  5345. if poly_selection.intersects(poly_obj):
  5346. # create the selection box around the selected object
  5347. if self.defaults['global_selection_shape'] is True:
  5348. self.draw_selection_shape(obj)
  5349. self.collection.set_active(obj.options['name'])
  5350. obj.selection_shape_drawn = True
  5351. except Exception as e:
  5352. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5353. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5354. # In this case poly_obj creation (see above) will fail
  5355. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5356. def select_objects(self, key=None):
  5357. """
  5358. Will select objects clicked on canvas
  5359. :param key: for future use in cumulative selection
  5360. :return:
  5361. """
  5362. # list where we store the overlapped objects under our mouse left click position
  5363. if key is None:
  5364. self.objects_under_the_click_list = []
  5365. # Populate the list with the overlapped objects on the click position
  5366. curr_x, curr_y = self.pos
  5367. for obj in self.all_objects_list:
  5368. # ScriptObject and DocumentObject objects can't be selected
  5369. if obj.kind == 'script' or obj.kind == 'document':
  5370. continue
  5371. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5372. continue
  5373. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5374. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5375. if obj.options['name'] not in self.objects_under_the_click_list:
  5376. if obj.options['plot']:
  5377. # add objects to the objects_under_the_click list only if the object is plotted
  5378. # (active and not disabled)
  5379. self.objects_under_the_click_list.append(obj.options['name'])
  5380. try:
  5381. if self.objects_under_the_click_list:
  5382. curr_sel_obj = self.collection.get_active()
  5383. # case when there is only an object under the click and we toggle it
  5384. if len(self.objects_under_the_click_list) == 1:
  5385. if curr_sel_obj is None:
  5386. self.collection.set_active(self.objects_under_the_click_list[0])
  5387. curr_sel_obj = self.collection.get_active()
  5388. # create the selection box around the selected object
  5389. if self.defaults['global_selection_shape'] is True:
  5390. self.draw_selection_shape(curr_sel_obj)
  5391. curr_sel_obj.selection_shape_drawn = True
  5392. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5393. self.collection.on_objects_selection(False)
  5394. self.delete_selection_shape()
  5395. curr_sel_obj.selection_shape_drawn = False
  5396. self.collection.set_active(self.objects_under_the_click_list[0])
  5397. curr_sel_obj = self.collection.get_active()
  5398. # create the selection box around the selected object
  5399. if self.defaults['global_selection_shape'] is True:
  5400. self.draw_selection_shape(curr_sel_obj)
  5401. curr_sel_obj.selection_shape_drawn = True
  5402. self.selected_message(curr_sel_obj=curr_sel_obj)
  5403. elif curr_sel_obj.selection_shape_drawn is False:
  5404. if self.defaults['global_selection_shape'] is True:
  5405. self.draw_selection_shape(curr_sel_obj)
  5406. curr_sel_obj.selection_shape_drawn = True
  5407. else:
  5408. self.collection.on_objects_selection(False)
  5409. self.delete_selection_shape()
  5410. if self.call_source != 'app':
  5411. self.call_source = 'app'
  5412. self.selected_message(curr_sel_obj=curr_sel_obj)
  5413. else:
  5414. # If there is no selected object
  5415. # make active the first element of the overlapped objects list
  5416. if self.collection.get_active() is None:
  5417. self.collection.set_active(self.objects_under_the_click_list[0])
  5418. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5419. name_sel_obj = self.collection.get_active().options['name']
  5420. # In case that there is a selected object but it is not in the overlapped object list
  5421. # make that object inactive and activate the first element in the overlapped object list
  5422. if name_sel_obj not in self.objects_under_the_click_list:
  5423. self.collection.set_inactive(name_sel_obj)
  5424. name_sel_obj = self.objects_under_the_click_list[0]
  5425. self.collection.set_active(name_sel_obj)
  5426. else:
  5427. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5428. self.collection.set_all_inactive()
  5429. self.collection.set_active(
  5430. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5431. curr_sel_obj = self.collection.get_active()
  5432. # delete the possible selection box around a possible selected object
  5433. self.delete_selection_shape()
  5434. curr_sel_obj.selection_shape_drawn = False
  5435. # create the selection box around the selected object
  5436. if self.defaults['global_selection_shape'] is True:
  5437. self.draw_selection_shape(curr_sel_obj)
  5438. curr_sel_obj.selection_shape_drawn = True
  5439. self.selected_message(curr_sel_obj=curr_sel_obj)
  5440. else:
  5441. # deselect everything
  5442. self.collection.on_objects_selection(False)
  5443. # delete the possible selection box around a possible selected object
  5444. self.delete_selection_shape()
  5445. for o in self.collection.get_list():
  5446. o.selection_shape_drawn = False
  5447. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5448. # only when working on App
  5449. if self.call_source == 'app':
  5450. if self.click_noproject is False:
  5451. # if the Tool Tab is in focus don't change focus to Project Tab
  5452. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5453. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5454. else:
  5455. # restore auto open the Project Tab
  5456. self.click_noproject = False
  5457. # delete any text in the status bar, implicitly the last object name that was selected
  5458. # self.inform.emit("")
  5459. else:
  5460. self.call_source = 'app'
  5461. except Exception as e:
  5462. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5463. def selected_message(self, curr_sel_obj):
  5464. if curr_sel_obj:
  5465. if curr_sel_obj.kind == 'gerber':
  5466. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5467. color='green',
  5468. name=str(curr_sel_obj.options['name']),
  5469. tx=_("selected"))
  5470. )
  5471. elif curr_sel_obj.kind == 'excellon':
  5472. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5473. color='brown',
  5474. name=str(curr_sel_obj.options['name']),
  5475. tx=_("selected"))
  5476. )
  5477. elif curr_sel_obj.kind == 'cncjob':
  5478. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5479. color='blue',
  5480. name=str(curr_sel_obj.options['name']),
  5481. tx=_("selected"))
  5482. )
  5483. elif curr_sel_obj.kind == 'geometry':
  5484. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5485. color='red',
  5486. name=str(curr_sel_obj.options['name']),
  5487. tx=_("selected"))
  5488. )
  5489. def delete_hover_shape(self):
  5490. self.hover_shapes.clear()
  5491. self.hover_shapes.redraw()
  5492. def draw_hover_shape(self, sel_obj, color=None):
  5493. """
  5494. :param sel_obj: The object for which the hover shape must be drawn
  5495. :param color: The color of the hover shape
  5496. :return: None
  5497. """
  5498. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5499. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5500. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5501. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5502. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5503. if self.defaults['units'].upper() == 'MM':
  5504. hover_rect = hover_rect.buffer(-0.1)
  5505. hover_rect = hover_rect.buffer(0.2)
  5506. else:
  5507. hover_rect = hover_rect.buffer(-0.00393)
  5508. hover_rect = hover_rect.buffer(0.00787)
  5509. # if color:
  5510. # face = Color(color)
  5511. # face.alpha = 0.2
  5512. # outline = Color(color, alpha=0.8)
  5513. # else:
  5514. # face = Color(self.defaults['global_sel_fill'])
  5515. # face.alpha = 0.2
  5516. # outline = self.defaults['global_sel_line']
  5517. if color:
  5518. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5519. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5520. else:
  5521. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5522. outline = self.defaults['global_sel_line']
  5523. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5524. if self.is_legacy is True:
  5525. self.hover_shapes.redraw()
  5526. def delete_selection_shape(self):
  5527. self.move_tool.sel_shapes.clear()
  5528. self.move_tool.sel_shapes.redraw()
  5529. def draw_selection_shape(self, sel_obj, color=None):
  5530. """
  5531. Will draw a selection shape around the selected object.
  5532. :param sel_obj: The object for which the selection shape must be drawn
  5533. :param color: The color for the selection shape.
  5534. :return: None
  5535. """
  5536. if sel_obj is None:
  5537. return
  5538. # it's a line without area
  5539. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5540. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5541. # it's a geometry with area
  5542. else:
  5543. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5544. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5545. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5546. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5547. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5548. b_sel_rect = None
  5549. try:
  5550. if self.defaults['units'].upper() == 'MM':
  5551. b_sel_rect = sel_rect.buffer(-0.1)
  5552. b_sel_rect = b_sel_rect.buffer(0.2)
  5553. else:
  5554. b_sel_rect = sel_rect.buffer(-0.00393)
  5555. b_sel_rect = b_sel_rect.buffer(0.00787)
  5556. except Exception:
  5557. pass
  5558. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5559. b_sel_rect = sel_rect
  5560. if color:
  5561. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5562. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5563. else:
  5564. if self.is_legacy is False:
  5565. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5566. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5567. else:
  5568. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5569. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5570. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5571. color=outline,
  5572. face_color=face,
  5573. update=True,
  5574. layer=0,
  5575. tolerance=None))
  5576. if self.is_legacy is True:
  5577. self.move_tool.sel_shapes.redraw()
  5578. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5579. """
  5580. Will draw a selection shape when dragging mouse on canvas.
  5581. :param old_coords: Old coordinates
  5582. :param coords: New coordinates
  5583. :param kwargs: Keyword arguments
  5584. :return:
  5585. """
  5586. if 'color' in kwargs:
  5587. color = kwargs['color']
  5588. else:
  5589. color = self.defaults['global_sel_line']
  5590. if 'face_color' in kwargs:
  5591. face_color = kwargs['face_color']
  5592. else:
  5593. face_color = self.defaults['global_sel_fill']
  5594. if 'face_alpha' in kwargs:
  5595. face_alpha = kwargs['face_alpha']
  5596. else:
  5597. face_alpha = 0.3
  5598. x0, y0 = old_coords
  5599. x1, y1 = coords
  5600. pt1 = (x0, y0)
  5601. pt2 = (x1, y0)
  5602. pt3 = (x1, y1)
  5603. pt4 = (x0, y1)
  5604. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5605. # color_t = Color(face_color)
  5606. # color_t.alpha = face_alpha
  5607. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5608. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5609. layer=0, tolerance=None)
  5610. if self.is_legacy is True:
  5611. self.move_tool.sel_shapes.redraw()
  5612. def obj_properties(self):
  5613. """
  5614. Will launch the object Properties Tool
  5615. :return:
  5616. """
  5617. self.defaults.report_usage("obj_properties()")
  5618. self.properties_tool.run(toggle=False)
  5619. def on_project_context_save(self):
  5620. """
  5621. Wrapper, will save the object function of it's type
  5622. :return:
  5623. """
  5624. sel_objects = self.collection.get_selected()
  5625. len_objects = len(sel_objects)
  5626. cnt = 0
  5627. if len_objects > 1:
  5628. for o in sel_objects:
  5629. if o.kind == 'cncjob':
  5630. cnt += 1
  5631. if len_objects == cnt:
  5632. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5633. _filter_ = self.defaults['cncjob_save_filters'] + \
  5634. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5635. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5636. try:
  5637. filename, _f = FCFileSaveDialog.get_saved_filename(
  5638. caption=_("Export Code ..."),
  5639. directory=dir_file_to_save,
  5640. ext_filter=_filter_
  5641. )
  5642. except TypeError:
  5643. filename, _f = FCFileSaveDialog.get_saved_filename(
  5644. caption=_("Export Code ..."),
  5645. ext_filter=_filter_)
  5646. filename = filename.rpartition('/')[0]
  5647. for ob in sel_objects:
  5648. ob.read_form()
  5649. fname = '%s/%s' % (filename, ob.options['name'])
  5650. ob.export_gcode_handler(fname, is_gcode=True)
  5651. return
  5652. obj = self.collection.get_active()
  5653. if type(obj) == GeometryObject:
  5654. self.on_file_exportdxf()
  5655. elif type(obj) == ExcellonObject:
  5656. self.on_file_saveexcellon()
  5657. elif type(obj) == CNCJobObject:
  5658. obj.on_exportgcode_button_click()
  5659. elif type(obj) == GerberObject:
  5660. self.on_file_savegerber()
  5661. elif type(obj) == ScriptObject:
  5662. self.on_file_savescript()
  5663. elif type(obj) == DocumentObject:
  5664. self.on_file_savedocument()
  5665. def obj_move(self):
  5666. """
  5667. Callback for the Move menu entry in various Context Menu's.
  5668. :return:
  5669. """
  5670. self.defaults.report_usage("obj_move()")
  5671. self.move_tool.run(toggle=False)
  5672. # ###############################################################################################################
  5673. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5674. # ###############################################################################################################
  5675. def init_code_editor(self, name):
  5676. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5677. # add the tab if it was closed
  5678. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5679. self.text_editor_tab.setObjectName('text_editor_tab')
  5680. # delete the absolute and relative position and messages in the infobar
  5681. # self.ui.position_label.setText("")
  5682. # self.ui.rel_position_label.setText("")
  5683. # hide coordinates toolbars in the infobar while in DB
  5684. self.ui.coords_toolbar.hide()
  5685. self.ui.delta_coords_toolbar.hide()
  5686. self.toggle_codeeditor = True
  5687. self.text_editor_tab.code_editor.completer_enable = False
  5688. self.text_editor_tab.buttonRun.hide()
  5689. # make sure to keep a reference to the code editor
  5690. self.reference_code_editor = self.text_editor_tab.code_editor
  5691. # Switch plot_area to CNCJob tab
  5692. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5693. def on_view_source(self):
  5694. """
  5695. Called when the user wants to see the source file of the selected object
  5696. :return:
  5697. """
  5698. try:
  5699. obj = self.collection.get_active()
  5700. except Exception as e:
  5701. self.log.debug("App.on_view_source() --> %s" % str(e))
  5702. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5703. return 'fail'
  5704. if obj is None:
  5705. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5706. return 'fail'
  5707. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5708. self.proc_container.view.set_busy(_("Loading..."))
  5709. flt = "All Files (*.*)"
  5710. if obj.kind == 'gerber':
  5711. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5712. elif obj.kind == 'excellon':
  5713. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5714. elif obj.kind == 'cncjob':
  5715. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5716. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5717. # add the tab if it was closed
  5718. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5719. self.source_editor_tab.setObjectName('source_editor_tab')
  5720. # delete the absolute and relative position and messages in the infobar
  5721. # self.ui.position_label.setText("")
  5722. # self.ui.rel_position_label.setText("")
  5723. # hide coordinates toolbars in the infobar while in DB
  5724. self.ui.coords_toolbar.hide()
  5725. self.ui.delta_coords_toolbar.hide()
  5726. self.source_editor_tab.code_editor.completer_enable = False
  5727. self.source_editor_tab.buttonRun.hide()
  5728. # Switch plot_area to CNCJob tab
  5729. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5730. try:
  5731. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5732. except TypeError:
  5733. pass
  5734. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5735. try:
  5736. self.source_editor_tab.buttonSave.clicked.disconnect()
  5737. except TypeError:
  5738. pass
  5739. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5740. # then append the text from GCode to the text editor
  5741. if obj.kind == 'cncjob':
  5742. try:
  5743. file = obj.export_gcode(to_file=True)
  5744. if file == 'fail':
  5745. return 'fail'
  5746. except AttributeError:
  5747. self.inform.emit('[WARNING_NOTCL] %s' %
  5748. _("There is no selected object for which to see it's source file code."))
  5749. return 'fail'
  5750. else:
  5751. try:
  5752. file = StringIO(obj.source_file)
  5753. except (AttributeError, TypeError):
  5754. self.inform.emit('[WARNING_NOTCL] %s' %
  5755. _("There is no selected object for which to see it's source file code."))
  5756. return 'fail'
  5757. self.source_editor_tab.t_frame.hide()
  5758. try:
  5759. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5760. except Exception as e:
  5761. self.log.debug('App.on_view_source() -->%s' % str(e))
  5762. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5763. return
  5764. self.source_editor_tab.t_frame.show()
  5765. self.proc_container.view.set_idle()
  5766. # self.ui.show()
  5767. def on_toggle_code_editor(self):
  5768. self.defaults.report_usage("on_toggle_code_editor()")
  5769. if self.toggle_codeeditor is False:
  5770. self.init_code_editor(name=_("Code Editor"))
  5771. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5772. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5773. self.text_editor_tab.buttonSave.clicked.disconnect()
  5774. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5775. else:
  5776. for idx in range(self.ui.plot_tab_area.count()):
  5777. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5778. self.ui.plot_tab_area.closeTab(idx)
  5779. break
  5780. self.toggle_codeeditor = False
  5781. def on_code_editor_close(self):
  5782. self.toggle_codeeditor = False
  5783. def goto_text_line(self):
  5784. """
  5785. Will scroll a text to the specified text line.
  5786. :return: None
  5787. """
  5788. dia_box = Dialog_box(title=_("Go to Line ..."),
  5789. label=_("Line:"),
  5790. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5791. initial_text='')
  5792. try:
  5793. line = int(dia_box.location) - 1
  5794. except (ValueError, TypeError):
  5795. line = 0
  5796. if dia_box.ok:
  5797. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5798. # at the top of the window
  5799. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5800. # get the document() of the AppTextEditor
  5801. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5802. # create a Text Cursor based on the searched line
  5803. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5804. # set cursor of the code editor with the cursor at the searcehd line
  5805. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5806. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5807. """
  5808. Re-generates all plots from all objects.
  5809. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5810. :param muted: if True don't print messages
  5811. :param use_thread: if True will use threading for plotting the objects
  5812. :return: None
  5813. """
  5814. self.log.debug("Plot_all()")
  5815. if muted is not True:
  5816. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5817. for plot_obj in self.collection.get_list():
  5818. def worker_task(obj):
  5819. with self.proc_container.new("Plotting"):
  5820. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5821. if fit_view is True:
  5822. self.app_obj.object_plotted.emit(obj)
  5823. if use_thread is True:
  5824. # Send to worker
  5825. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5826. else:
  5827. worker_task(plot_obj)
  5828. def register_folder(self, filename):
  5829. """
  5830. Register the last folder used by the app to open something
  5831. :param filename: the last folder is extracted from the filename
  5832. :return: None
  5833. """
  5834. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5835. def register_save_folder(self, filename):
  5836. """
  5837. Register the last folder used by the app to save something
  5838. :param filename: the last folder is extracted from the filename
  5839. :return: None
  5840. """
  5841. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5842. # def set_progress_bar(self, percentage, text=""):
  5843. # """
  5844. # Set a progress bar to a value (percentage)
  5845. #
  5846. # :param percentage: Value set to the progressbar
  5847. # :param text: Not used
  5848. # :return: None
  5849. # """
  5850. # self.ui.progress_bar.setValue(int(percentage))
  5851. def setup_recent_items(self):
  5852. """
  5853. Setup a dictionary with the recent files accessed, organized by type
  5854. :return:
  5855. """
  5856. icons = {
  5857. "gerber": self.resource_location + "/flatcam_icon16.png",
  5858. "excellon": self.resource_location + "/drill16.png",
  5859. 'geometry': self.resource_location + "/geometry16.png",
  5860. "cncjob": self.resource_location + "/cnc16.png",
  5861. "script": self.resource_location + "/script_new24.png",
  5862. "document": self.resource_location + "/notes16_1.png",
  5863. "project": self.resource_location + "/project16.png",
  5864. "svg": self.resource_location + "/geometry16.png",
  5865. "dxf": self.resource_location + "/dxf16.png",
  5866. "pdf": self.resource_location + "/pdf32.png",
  5867. "image": self.resource_location + "/image16.png"
  5868. }
  5869. try:
  5870. image_opener = self.image_tool.import_image
  5871. except AttributeError:
  5872. image_opener = None
  5873. openers = {
  5874. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5875. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5876. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5877. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5878. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5879. "document": None,
  5880. 'project': self.f_handlers.open_project,
  5881. 'svg': self.f_handlers.import_svg,
  5882. 'dxf': self.f_handlers.import_dxf,
  5883. 'image': image_opener,
  5884. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5885. }
  5886. # Open recent file for files
  5887. try:
  5888. f = open(self.data_path + '/recent.json')
  5889. except IOError:
  5890. App.log.error("Failed to load recent item list.")
  5891. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5892. return
  5893. try:
  5894. self.recent = json.load(f)
  5895. except json.errors.JSONDecodeError:
  5896. App.log.error("Failed to parse recent item list.")
  5897. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5898. f.close()
  5899. return
  5900. f.close()
  5901. # Open recent file for projects
  5902. try:
  5903. fp = open(self.data_path + '/recent_projects.json')
  5904. except IOError:
  5905. App.log.error("Failed to load recent project item list.")
  5906. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5907. return
  5908. try:
  5909. self.recent_projects = json.load(fp)
  5910. except json.errors.JSONDecodeError:
  5911. App.log.error("Failed to parse recent project item list.")
  5912. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5913. fp.close()
  5914. return
  5915. fp.close()
  5916. # Closure needed to create callbacks in a loop.
  5917. # Otherwise late binding occurs.
  5918. def make_callback(func, fname):
  5919. def opener():
  5920. func(fname)
  5921. return opener
  5922. def reset_recent_files():
  5923. # Reset menu
  5924. self.ui.recent.clear()
  5925. self.recent = []
  5926. try:
  5927. ff = open(self.data_path + '/recent.json', 'w')
  5928. except IOError:
  5929. App.log.error("Failed to open recent items file for writing.")
  5930. return
  5931. json.dump(self.recent, ff)
  5932. def reset_recent_projects():
  5933. # Reset menu
  5934. self.ui.recent_projects.clear()
  5935. self.recent_projects = []
  5936. try:
  5937. frp = open(self.data_path + '/recent_projects.json', 'w')
  5938. except IOError:
  5939. App.log.error("Failed to open recent projects items file for writing.")
  5940. return
  5941. json.dump(self.recent, frp)
  5942. # Reset menu
  5943. self.ui.recent.clear()
  5944. self.ui.recent_projects.clear()
  5945. # Create menu items for projects
  5946. for recent in self.recent_projects:
  5947. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5948. if recent['kind'] == 'project':
  5949. try:
  5950. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5951. # Attach callback
  5952. o = make_callback(openers[recent["kind"]], recent['filename'])
  5953. action.triggered.connect(o)
  5954. self.ui.recent_projects.addAction(action)
  5955. except KeyError:
  5956. App.log.error("Unsupported file type: %s" % recent["kind"])
  5957. # Last action in Recent Files menu is one that Clear the content
  5958. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5959. (_("Clear Recent projects")), self)
  5960. clear_action_proj.triggered.connect(reset_recent_projects)
  5961. self.ui.recent_projects.addSeparator()
  5962. self.ui.recent_projects.addAction(clear_action_proj)
  5963. # Create menu items for files
  5964. for recent in self.recent:
  5965. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5966. if recent['kind'] != 'project':
  5967. try:
  5968. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5969. # Attach callback
  5970. o = make_callback(openers[recent["kind"]], recent['filename'])
  5971. action.triggered.connect(o)
  5972. self.ui.recent.addAction(action)
  5973. except KeyError:
  5974. App.log.error("Unsupported file type: %s" % recent["kind"])
  5975. # Last action in Recent Files menu is one that Clear the content
  5976. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5977. (_("Clear Recent files")), self)
  5978. clear_action.triggered.connect(reset_recent_files)
  5979. self.ui.recent.addSeparator()
  5980. self.ui.recent.addAction(clear_action)
  5981. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5982. # self.ui.menufilerecent.set_submenu(recent_menu)
  5983. # recent_menu.show_all()
  5984. # self.ui.recent.show()
  5985. self.log.debug("Recent items list has been populated.")
  5986. def on_properties_tab_click(self, index):
  5987. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  5988. self.setup_default_properties_tab()
  5989. def setup_default_properties_tab(self):
  5990. """
  5991. Default text for the Properties tab when is not taken by the Object UI.
  5992. :return:
  5993. """
  5994. # label = QtWidgets.QLabel("Choose an item from Project")
  5995. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5996. # sel_title = QtWidgets.QTextEdit()
  5997. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5998. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5999. #
  6000. # f_settings = QSettings("Open Source", "FlatCAM")
  6001. # if f_settings.contains("notebook_font_size"):
  6002. # fsize = f_settings.value('notebook_font_size', type=int)
  6003. # else:
  6004. # fsize = 12
  6005. #
  6006. # tsize = fsize + int(fsize / 2)
  6007. #
  6008. # selected_text = ''
  6009. #
  6010. # sel_title.setText(selected_text)
  6011. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6012. # Tree Widget
  6013. d_properties_tw = FCTree(columns=2)
  6014. d_properties_tw.setObjectName("default_properties")
  6015. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6016. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6017. root = d_properties_tw.invisibleRootItem()
  6018. font = QtGui.QFont()
  6019. font.setBold(True)
  6020. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6021. # main Items categories
  6022. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6023. d_properties_tw.addChild(parent=general_cat,
  6024. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6025. d_properties_tw.addChild(parent=general_cat,
  6026. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6027. d_properties_tw.addChild(parent=general_cat,
  6028. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6029. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6030. d_properties_tw.addChild(parent=grid_cat,
  6031. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6032. column1=True)
  6033. d_properties_tw.addChild(parent=grid_cat,
  6034. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6035. column1=True)
  6036. d_properties_tw.addChild(parent=grid_cat,
  6037. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6038. column1=True)
  6039. d_properties_tw.addChild(parent=grid_cat,
  6040. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6041. column1=True)
  6042. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6043. d_properties_tw.addChild(parent=canvas_cat,
  6044. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6045. column1=True)
  6046. d_properties_tw.addChild(parent=canvas_cat,
  6047. title=['%s:' % _("Workspace active"),
  6048. '%s' % str(self.defaults['global_workspace'])],
  6049. column1=True)
  6050. d_properties_tw.addChild(parent=canvas_cat,
  6051. title=['%s:' % _("Workspace size"),
  6052. '%s' % str(self.defaults['global_workspaceT'])],
  6053. column1=True)
  6054. d_properties_tw.addChild(parent=canvas_cat,
  6055. title=['%s:' % _("Workspace orientation"),
  6056. '%s' % _("Portrait") if self.defaults[
  6057. 'global_workspace_orientation'] == 'p' else
  6058. _("Landscape")],
  6059. column1=True)
  6060. d_properties_tw.addChild(parent=canvas_cat,
  6061. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6062. column1=True)
  6063. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6064. def setup_obj_classes(self):
  6065. """
  6066. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6067. class.
  6068. :return: None
  6069. """
  6070. FlatCAMObj.app = self
  6071. ObjectCollection.app = self
  6072. Gerber.app = self
  6073. Excellon.app = self
  6074. Geometry.app = self
  6075. CNCjob.app = self
  6076. FCProcess.app = self
  6077. FCProcessContainer.app = self
  6078. OptionsGroupUI.app = self
  6079. def version_check(self):
  6080. """
  6081. Checks for the latest version of the program. Alerts the
  6082. user if theirs is outdated. This method is meant to be run
  6083. in a separate thread.
  6084. :return: None
  6085. """
  6086. self.log.debug("version_check()")
  6087. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6088. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6089. App.version_url,
  6090. str(self.defaults['global_serial']),
  6091. str(self.version),
  6092. str(self.os),
  6093. urllib.parse.urlencode(self.defaults["global_stats"])
  6094. )
  6095. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6096. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6097. # urllib.parse.urlencode(self.defaults["global_stats"])
  6098. else:
  6099. # no_stats dict; just so it won't break things on website
  6100. no_ststs_dict = {}
  6101. no_ststs_dict["global_ststs"] = {}
  6102. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6103. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6104. self.log.debug("Checking for updates @ %s" % full_url)
  6105. # ## Get the data
  6106. try:
  6107. f = urllib.request.urlopen(full_url)
  6108. except Exception:
  6109. # App.log.warning("Failed checking for latest version. Could not connect.")
  6110. self.log.warning("Failed checking for latest version. Could not connect.")
  6111. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6112. return
  6113. try:
  6114. data = json.load(f)
  6115. except Exception as e:
  6116. App.log.error("Could not parse information about latest version.")
  6117. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6118. self.log.debug("json.load(): %s" % str(e))
  6119. f.close()
  6120. return
  6121. f.close()
  6122. # ## Latest version?
  6123. if self.version >= data["version"]:
  6124. self.log.debug("FlatCAM is up to date!")
  6125. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6126. return
  6127. self.log.debug("Newer version available.")
  6128. self.message.emit(
  6129. _("Newer Version Available"),
  6130. '%s<br><br>><b>%s</b><br>%s' % (
  6131. _("There is a newer version of FlatCAM available for download:"),
  6132. str(data["name"]),
  6133. str(data["message"])
  6134. ),
  6135. _("info")
  6136. )
  6137. def on_plotcanvas_setup(self, container=None):
  6138. """
  6139. This is doing the setup for the plot area (canvas).
  6140. :param container: QT Widget where to install the canvas
  6141. :return: None
  6142. """
  6143. if container:
  6144. plot_container = container
  6145. else:
  6146. plot_container = self.ui.right_layout
  6147. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6148. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6149. self.is_legacy = True
  6150. self.defaults["global_graphic_engine"] = "2D"
  6151. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6152. else:
  6153. try:
  6154. self.plotcanvas = PlotCanvas(plot_container, self)
  6155. except Exception as er:
  6156. msg_txt = traceback.format_exc()
  6157. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6158. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6159. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6160. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6161. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6162. msg += msg_txt
  6163. self.inform.emit(msg)
  6164. return 'fail'
  6165. # So it can receive key presses
  6166. self.plotcanvas.native.setFocus()
  6167. if self.is_legacy is False:
  6168. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6169. # Set the mouse button for panning
  6170. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6171. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6172. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6173. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6174. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6175. # Keys over plot enabled
  6176. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6177. if self.defaults['global_cursor_type'] == 'small':
  6178. self.app_cursor = self.plotcanvas.new_cursor()
  6179. else:
  6180. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6181. if self.ui.grid_snap_btn.isChecked():
  6182. self.app_cursor.enabled = True
  6183. else:
  6184. self.app_cursor.enabled = False
  6185. if self.is_legacy is False:
  6186. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6187. else:
  6188. # will use the default Matplotlib axes
  6189. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6190. def on_zoom_fit(self):
  6191. """
  6192. Callback for zoom-fit request. This can be either from the corresponding
  6193. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6194. with axes limits from the geometry bounds of all objects.
  6195. :return: None
  6196. """
  6197. if self.is_legacy is False:
  6198. self.plotcanvas.fit_view()
  6199. else:
  6200. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6201. width = xmax - xmin
  6202. height = ymax - ymin
  6203. xmin -= 0.05 * width
  6204. xmax += 0.05 * width
  6205. ymin -= 0.05 * height
  6206. ymax += 0.05 * height
  6207. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6208. def on_zoom_in(self):
  6209. """
  6210. Callback for zoom-in request.
  6211. :return:
  6212. """
  6213. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6214. def on_zoom_out(self):
  6215. """
  6216. Callback for zoom-out request.
  6217. :return:
  6218. """
  6219. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6220. def disable_all_plots(self):
  6221. self.defaults.report_usage("disable_all_plots()")
  6222. self.disable_plots(self.collection.get_list())
  6223. self.inform.emit('[success] %s' % _("All plots disabled."))
  6224. def disable_other_plots(self):
  6225. self.defaults.report_usage("disable_other_plots()")
  6226. self.disable_plots(self.collection.get_non_selected())
  6227. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6228. def enable_all_plots(self):
  6229. self.defaults.report_usage("enable_all_plots()")
  6230. self.enable_plots(self.collection.get_list())
  6231. self.inform.emit('[success] %s' % _("All plots enabled."))
  6232. def enable_other_plots(self):
  6233. self.defaults.report_usage("enable_other_plots()")
  6234. self.enable_plots(self.collection.get_non_selected())
  6235. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6236. def on_enable_sel_plots(self):
  6237. self.log.debug("App.on_enable_sel_plot()")
  6238. object_list = self.collection.get_selected()
  6239. self.enable_plots(objects=object_list)
  6240. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6241. def on_disable_sel_plots(self):
  6242. self.log.debug("App.on_disable_sel_plot()")
  6243. # self.inform.emit(_("Disabling plots ..."))
  6244. object_list = self.collection.get_selected()
  6245. self.disable_plots(objects=object_list)
  6246. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6247. def enable_plots(self, objects):
  6248. """
  6249. Enable plots
  6250. :param objects: list of Objects to be enabled
  6251. :return:
  6252. """
  6253. self.log.debug("Enabling plots ...")
  6254. # self.inform.emit(_("Working ..."))
  6255. for obj in objects:
  6256. if obj.options['plot'] is False:
  6257. obj.options.set_change_callback(lambda x: None)
  6258. obj.options['plot'] = True
  6259. try:
  6260. # only the Gerber obj has on_plot_cb_click() method
  6261. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6262. # disable this cb while disconnected,
  6263. # in case the operation takes time the user is not allowed to change it
  6264. obj.ui.plot_cb.setDisabled(True)
  6265. except AttributeError:
  6266. pass
  6267. obj.set_form_item("plot")
  6268. try:
  6269. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6270. obj.ui.plot_cb.setDisabled(False)
  6271. except AttributeError:
  6272. pass
  6273. obj.options.set_change_callback(obj.on_options_change)
  6274. self.collection.update_view()
  6275. def worker_task(objs):
  6276. with self.proc_container.new(_("Enabling plots ...")):
  6277. for plot_obj in objs:
  6278. # obj.options['plot'] = True
  6279. if isinstance(plot_obj, CNCJobObject):
  6280. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6281. else:
  6282. plot_obj.plot(visible=True)
  6283. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6284. def disable_plots(self, objects):
  6285. """
  6286. Disables plots
  6287. :param objects: list of Objects to be disabled
  6288. :return:
  6289. """
  6290. self.log.debug("Disabling plots ...")
  6291. # self.inform.emit(_("Working ..."))
  6292. for obj in objects:
  6293. if obj.options['plot'] is True:
  6294. obj.options.set_change_callback(lambda x: None)
  6295. obj.options['plot'] = False
  6296. try:
  6297. # only the Gerber obj has on_plot_cb_click() method
  6298. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6299. obj.ui.plot_cb.setDisabled(True)
  6300. except AttributeError:
  6301. pass
  6302. obj.set_form_item("plot")
  6303. try:
  6304. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6305. obj.ui.plot_cb.setDisabled(False)
  6306. except AttributeError:
  6307. pass
  6308. obj.options.set_change_callback(obj.on_options_change)
  6309. try:
  6310. self.delete_selection_shape()
  6311. except Exception as e:
  6312. self.log.debug("App.disable_plots() --> %s" % str(e))
  6313. self.collection.update_view()
  6314. def worker_task(objs):
  6315. with self.proc_container.new(_("Disabling plots ...")):
  6316. for plot_obj in objs:
  6317. # obj.options['plot'] = True
  6318. if isinstance(plot_obj, CNCJobObject):
  6319. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6320. else:
  6321. plot_obj.plot(visible=False)
  6322. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6323. def toggle_plots(self, objects):
  6324. """
  6325. Toggle plots visibility
  6326. :param objects: list of Objects for which to be toggled the visibility
  6327. :return: None
  6328. """
  6329. # if no objects selected then do nothing
  6330. if not self.collection.get_selected():
  6331. return
  6332. self.log.debug("Toggling plots ...")
  6333. self.inform.emit(_("Working ..."))
  6334. for obj in objects:
  6335. if obj.options['plot'] is False:
  6336. obj.options['plot'] = True
  6337. else:
  6338. obj.options['plot'] = False
  6339. self.app_obj.plots_updated.emit()
  6340. def clear_plots(self):
  6341. """
  6342. Clear the plots
  6343. :return: None
  6344. """
  6345. objects = self.collection.get_list()
  6346. for obj in objects:
  6347. obj.clear(obj == objects[-1])
  6348. # Clear pool to free memory
  6349. self.clear_pool()
  6350. def on_set_color_action_triggered(self):
  6351. """
  6352. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6353. :return:
  6354. """
  6355. new_color = self.defaults['gerber_plot_fill']
  6356. clicked_action = self.sender()
  6357. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6358. act_name = clicked_action.text()
  6359. sel_obj_list = self.collection.get_selected()
  6360. if not sel_obj_list:
  6361. return
  6362. # a default value, I just chose this one
  6363. alpha_level = 'BF'
  6364. for sel_obj in sel_obj_list:
  6365. if sel_obj.kind == 'excellon':
  6366. alpha_level = str(hex(
  6367. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6368. elif sel_obj.kind == 'gerber':
  6369. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6370. elif sel_obj.kind == 'geometry':
  6371. alpha_level = 'FF'
  6372. else:
  6373. self.log.debug(
  6374. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6375. continue
  6376. sel_obj.alpha_level = alpha_level
  6377. if act_name == _('Red'):
  6378. new_color = '#FF0000' + alpha_level
  6379. if act_name == _('Blue'):
  6380. new_color = '#0000FF' + alpha_level
  6381. if act_name == _('Yellow'):
  6382. new_color = '#FFDF00' + alpha_level
  6383. if act_name == _('Green'):
  6384. new_color = '#00FF00' + alpha_level
  6385. if act_name == _('Purple'):
  6386. new_color = '#FF00FF' + alpha_level
  6387. if act_name == _('Brown'):
  6388. new_color = '#A52A2A' + alpha_level
  6389. if act_name == _('White'):
  6390. new_color = '#FFFFFF' + alpha_level
  6391. if act_name == _('Black'):
  6392. new_color = '#000000' + alpha_level
  6393. if act_name == _('Custom'):
  6394. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6395. c_dialog = QtWidgets.QColorDialog()
  6396. plot_fill_color = c_dialog.getColor(initial=new_color)
  6397. if plot_fill_color.isValid() is False:
  6398. return
  6399. new_color = str(plot_fill_color.name()) + alpha_level
  6400. if act_name == _("Default"):
  6401. for sel_obj in sel_obj_list:
  6402. if sel_obj.kind == 'excellon':
  6403. new_color = self.defaults['excellon_plot_fill']
  6404. new_line_color = self.defaults['excellon_plot_line']
  6405. elif sel_obj.kind == 'gerber':
  6406. new_color = self.defaults['gerber_plot_fill']
  6407. new_line_color = self.defaults['gerber_plot_line']
  6408. elif sel_obj.kind == 'geometry':
  6409. new_color = self.defaults['geometry_plot_line']
  6410. new_line_color = self.defaults['geometry_plot_line']
  6411. else:
  6412. self.log.debug(
  6413. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6414. continue
  6415. sel_obj.fill_color = new_color
  6416. sel_obj.outline_color = new_line_color
  6417. sel_obj.shapes.redraw(
  6418. update_colors=(new_color, new_line_color)
  6419. )
  6420. return
  6421. if act_name == _("Opacity"):
  6422. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6423. # '%s:' % _("Value"),
  6424. # min=0, max=255, step=1, value=191)
  6425. alpha_dialog = FCInputDialogSlider(
  6426. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6427. alpha_level, ok_button = alpha_dialog.get_results()
  6428. if ok_button:
  6429. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6430. for sel_obj in sel_obj_list:
  6431. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6432. sel_obj.shapes.redraw(
  6433. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6434. )
  6435. return
  6436. new_line_color = color_variant(new_color[:7], 0.7)
  6437. if act_name == _("White"):
  6438. new_line_color = color_variant("#dedede", 0.7)
  6439. for sel_obj in sel_obj_list:
  6440. sel_obj.fill_color = new_color
  6441. sel_obj.outline_color = new_line_color
  6442. sel_obj.shapes.redraw(
  6443. update_colors=(new_color, new_line_color)
  6444. )
  6445. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6446. group = self.collection.group_items["gerber"]
  6447. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6448. new_c = (new_line_color, new_color)
  6449. for sel_obj in sel_obj_list:
  6450. if sel_obj.kind == 'gerber':
  6451. item = sel_obj.item
  6452. item_index = self.collection.index(item.row(), 0, group_index)
  6453. idx = item_index.row()
  6454. self.defaults["gerber_color_list"][idx] = new_c
  6455. def generate_cnc_job(self, objects):
  6456. """
  6457. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6458. :param objects: Selected objects in the Project Tab
  6459. :return:
  6460. """
  6461. self.defaults.report_usage("generate_cnc_job()")
  6462. # for obj in objects:
  6463. # obj.generatecncjob()
  6464. for obj in objects:
  6465. obj.on_generatecnc_button_click()
  6466. def start_delayed_quit(self, delay, filename, should_quit=None):
  6467. """
  6468. :param delay: period of checking if project file size is more than zero; in seconds
  6469. :param filename: the name of the project file to be checked periodically for size more than zero
  6470. :param should_quit: if the task finished will be followed by an app quit; boolean
  6471. :return:
  6472. """
  6473. to_quit = should_quit
  6474. self.save_timer = QtCore.QTimer()
  6475. self.save_timer.setInterval(delay)
  6476. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6477. self.save_timer.start()
  6478. def check_project_file_size(self, filename, should_quit=None):
  6479. """
  6480. :param filename: the name of the project file to be checked periodically for size more than zero
  6481. :param should_quit: will quit the app if True; boolean
  6482. :return:
  6483. """
  6484. try:
  6485. if os.stat(filename).st_size > 0:
  6486. self.save_in_progress = False
  6487. self.save_timer.stop()
  6488. if should_quit:
  6489. self.app_quit.emit()
  6490. except Exception:
  6491. traceback.print_exc()
  6492. def save_project_auto(self):
  6493. """
  6494. Called periodically to save the project.
  6495. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6496. # progress.
  6497. :return:
  6498. """
  6499. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6500. self.on_file_saveproject()
  6501. def save_project_auto_update(self):
  6502. """
  6503. Update the auto save time interval value.
  6504. :return:
  6505. """
  6506. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6507. try:
  6508. if self.autosave_timer.isActive():
  6509. self.autosave_timer.stop()
  6510. except Exception:
  6511. pass
  6512. if self.defaults['global_autosave'] is True:
  6513. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6514. self.autosave_timer.start()
  6515. def on_options_app2project(self):
  6516. """
  6517. Callback for Options->Transfer Options->App=>Project. Copies options
  6518. from application defaults to project defaults.
  6519. :return: None
  6520. """
  6521. self.defaults.report_usage("on_options_app2project")
  6522. self.preferencesUiManager.defaults_read_form()
  6523. self.options.update(self.defaults)
  6524. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6525. """
  6526. Shows a message on the FlatCAM Shell
  6527. :param msg: Message to display.
  6528. :param show: Opens the shell.
  6529. :param error: Shows the message as an error.
  6530. :param warning: Shows the message as an warning.
  6531. :param success: Shows the message as an success.
  6532. :param selected: Indicate that something was selected on canvas
  6533. :return: None
  6534. """
  6535. end = '\n' if new_line is True else ''
  6536. if show:
  6537. self.ui.shell_dock.show()
  6538. try:
  6539. if error:
  6540. self.shell.append_error(msg + end)
  6541. elif warning:
  6542. self.shell.append_warning(msg + end)
  6543. elif success:
  6544. self.shell.append_success(msg + end)
  6545. elif selected:
  6546. self.shell.append_selected(msg + end)
  6547. else:
  6548. self.shell.append_output(msg + end)
  6549. except AttributeError:
  6550. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6551. def dec_format(self, val, dec=None):
  6552. """
  6553. Returns a formatted float value with a certain number of decimals
  6554. """
  6555. dec_nr = dec if dec is not None else self.decimals
  6556. return float('%.*f' % (dec_nr, val))
  6557. class ArgsThread(QtCore.QObject):
  6558. open_signal = pyqtSignal(list)
  6559. start = pyqtSignal()
  6560. stop = pyqtSignal()
  6561. if sys.platform == 'win32':
  6562. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6563. else:
  6564. address = ('/tmp/testipc', 'AF_UNIX')
  6565. def __init__(self):
  6566. super().__init__()
  6567. self.listener = None
  6568. self.thread_exit = False
  6569. self.start.connect(self.run)
  6570. self.stop.connect(self.close_listener)
  6571. def my_loop(self, address):
  6572. try:
  6573. self.listener = Listener(*address)
  6574. while self.thread_exit is False:
  6575. conn = self.listener.accept()
  6576. self.serve(conn)
  6577. except socket.error:
  6578. try:
  6579. conn = Client(*address)
  6580. conn.send(sys.argv)
  6581. conn.send('close')
  6582. # close the current instance only if there are args
  6583. if len(sys.argv) > 1:
  6584. try:
  6585. self.listener.close()
  6586. except Exception:
  6587. pass
  6588. sys.exit()
  6589. except ConnectionRefusedError:
  6590. if sys.platform == 'win32':
  6591. pass
  6592. else:
  6593. os.system('rm /tmp/testipc')
  6594. self.listener = Listener(*address)
  6595. while True:
  6596. conn = self.listener.accept()
  6597. self.serve(conn)
  6598. def serve(self, conn):
  6599. while self.thread_exit is False:
  6600. msg = conn.recv()
  6601. if msg == 'close':
  6602. break
  6603. self.open_signal.emit(msg)
  6604. conn.close()
  6605. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6606. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6607. @pyqtSlot()
  6608. def run(self):
  6609. self.my_loop(self.address)
  6610. @pyqtSlot()
  6611. def close_listener(self):
  6612. self.thread_exit = True
  6613. self.listener.close()
  6614. class MenuFileHandlers(QtCore.QObject):
  6615. def __init__(self, app):
  6616. super().__init__()
  6617. self.app = app
  6618. self.inform = self.app.inform
  6619. self.splash = self.app.splash
  6620. self.worker_task = self.app.worker_task
  6621. self.defaults = self.app.defaults
  6622. self.pagesize = {}
  6623. def on_fileopengerber(self, signal, name=None):
  6624. """
  6625. File menu callback for opening a Gerber.
  6626. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6627. :param name:
  6628. :return: None
  6629. """
  6630. self.app.log.debug("on_fileopengerber()")
  6631. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6632. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6633. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6634. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6635. "*.outline);;" \
  6636. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6637. "*.mil);;" \
  6638. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6639. "Allegro Files (*.art);;" \
  6640. "Mentor Files (*.pho *.gdo);;" \
  6641. "All Files (*.*)"
  6642. if name is None:
  6643. try:
  6644. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6645. directory=self.app.get_last_folder(),
  6646. filter=_filter_,
  6647. initialFilter=self.app.last_op_gerber_filter)
  6648. except TypeError:
  6649. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6650. filenames = [str(filename) for filename in filenames]
  6651. self.app.last_op_gerber_filter = _f
  6652. else:
  6653. filenames = [name]
  6654. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6655. "Canvas initialization finished in"),
  6656. '%.2f' % self.app.used_time,
  6657. _("Opening Gerber file.")),
  6658. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6659. color=QtGui.QColor("gray"))
  6660. if len(filenames) == 0:
  6661. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6662. else:
  6663. for filename in filenames:
  6664. if filename != '':
  6665. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6666. def on_fileopenexcellon(self, signal, name=None):
  6667. """
  6668. File menu callback for opening an Excellon file.
  6669. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6670. :param name:
  6671. :return: None
  6672. """
  6673. self.app.log.debug("on_fileopenexcellon()")
  6674. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6675. "All Files (*.*)"
  6676. if name is None:
  6677. try:
  6678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6679. directory=self.app.get_last_folder(),
  6680. filter=_filter_,
  6681. initialFilter=self.app.last_op_excellon_filter)
  6682. except TypeError:
  6683. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6684. filenames = [str(filename) for filename in filenames]
  6685. self.app.last_op_excellon_filter = _f
  6686. else:
  6687. filenames = [str(name)]
  6688. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6689. "Canvas initialization finished in"),
  6690. '%.2f' % self.app.used_time,
  6691. _("Opening Excellon file.")),
  6692. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6693. color=QtGui.QColor("gray"))
  6694. if len(filenames) == 0:
  6695. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6696. else:
  6697. for filename in filenames:
  6698. if filename != '':
  6699. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6700. def on_fileopengcode(self, signal, name=None):
  6701. """
  6702. File menu call back for opening gcode.
  6703. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6704. :param name:
  6705. :return:
  6706. """
  6707. self.app.log.debug("on_fileopengcode()")
  6708. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6709. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6710. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6711. "All Files (*.*)"
  6712. if name is None:
  6713. try:
  6714. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6715. directory=self.app.get_last_folder(),
  6716. filter=_filter_,
  6717. initialFilter=self.app.last_op_gcode_filter)
  6718. except TypeError:
  6719. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6720. filenames = [str(filename) for filename in filenames]
  6721. self.app.last_op_gcode_filter = _f
  6722. else:
  6723. filenames = [name]
  6724. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6725. "Canvas initialization finished in"),
  6726. '%.2f' % self.app.used_time,
  6727. _("Opening G-Code file.")),
  6728. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6729. color=QtGui.QColor("gray"))
  6730. if len(filenames) == 0:
  6731. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6732. else:
  6733. for filename in filenames:
  6734. if filename != '':
  6735. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6736. def on_file_openproject(self, signal):
  6737. """
  6738. File menu callback for opening a project.
  6739. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6740. :return: None
  6741. """
  6742. self.app.log.debug("on_file_openproject()")
  6743. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6744. try:
  6745. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6746. directory=self.app.get_last_folder(), filter=_filter_)
  6747. except TypeError:
  6748. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6749. filename = str(filename)
  6750. if filename == "":
  6751. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6752. else:
  6753. # self.worker_task.emit({'fcn': self.open_project,
  6754. # 'params': [filename]})
  6755. # The above was failing because open_project() is not
  6756. # thread safe. The new_project()
  6757. self.open_project(filename)
  6758. def on_fileopenhpgl2(self, signal, name=None):
  6759. """
  6760. File menu callback for opening a HPGL2.
  6761. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6762. :param name:
  6763. :return: None
  6764. """
  6765. self.app.log.debug("on_fileopenhpgl2()")
  6766. _filter_ = "HPGL2 Files (*.plt);;" \
  6767. "All Files (*.*)"
  6768. if name is None:
  6769. try:
  6770. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6771. directory=self.app.get_last_folder(),
  6772. filter=_filter_)
  6773. except TypeError:
  6774. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6775. filenames = [str(filename) for filename in filenames]
  6776. else:
  6777. filenames = [name]
  6778. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6779. "Canvas initialization finished in"),
  6780. '%.2f' % self.app.used_time,
  6781. _("Opening HPGL2 file.")),
  6782. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6783. color=QtGui.QColor("gray"))
  6784. if len(filenames) == 0:
  6785. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6786. else:
  6787. for filename in filenames:
  6788. if filename != '':
  6789. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6790. def on_file_openconfig(self, signal):
  6791. """
  6792. File menu callback for opening a config file.
  6793. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6794. :return: None
  6795. """
  6796. self.app.log.debug("on_file_openconfig()")
  6797. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6798. try:
  6799. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6800. directory=self.app.data_path, filter=_filter_)
  6801. except TypeError:
  6802. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6803. filter=_filter_)
  6804. if filename == "":
  6805. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6806. else:
  6807. self.open_config_file(filename)
  6808. def on_file_exportsvg(self):
  6809. """
  6810. Callback for menu item File->Export SVG.
  6811. :return: None
  6812. """
  6813. self.app.log.debug("on_file_exportsvg()")
  6814. obj = self.app.collection.get_active()
  6815. if obj is None:
  6816. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6817. msg = _("Please Select a Geometry object to export")
  6818. msgbox = QtWidgets.QMessageBox()
  6819. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6820. msgbox.setInformativeText(msg)
  6821. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6822. msgbox.setDefaultButton(bt_ok)
  6823. msgbox.exec_()
  6824. return
  6825. # Check for more compatible types and add as required
  6826. if (not isinstance(obj, GeometryObject)
  6827. and not isinstance(obj, GerberObject)
  6828. and not isinstance(obj, CNCJobObject)
  6829. and not isinstance(obj, ExcellonObject)):
  6830. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6831. msgbox = QtWidgets.QMessageBox()
  6832. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6833. msgbox.setInformativeText(msg)
  6834. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6835. msgbox.setDefaultButton(bt_ok)
  6836. msgbox.exec_()
  6837. return
  6838. name = obj.options["name"]
  6839. _filter = "SVG File (*.svg);;All Files (*.*)"
  6840. try:
  6841. filename, _f = FCFileSaveDialog.get_saved_filename(
  6842. caption=_("Export SVG"),
  6843. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6844. ext_filter=_filter)
  6845. except TypeError:
  6846. filename, _f = FCFileSaveDialog.get_saved_filename(
  6847. caption=_("Export SVG"),
  6848. ext_filter=_filter)
  6849. filename = str(filename)
  6850. if filename == "":
  6851. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6852. return
  6853. else:
  6854. self.export_svg(name, filename)
  6855. if self.defaults["global_open_style"] is False:
  6856. self.app.file_opened.emit("SVG", filename)
  6857. self.app.file_saved.emit("SVG", filename)
  6858. def on_file_exportpng(self):
  6859. self.app.log.debug("on_file_exportpng()")
  6860. date = str(datetime.today()).rpartition('.')[0]
  6861. date = ''.join(c for c in date if c not in ':-')
  6862. date = date.replace(' ', '_')
  6863. data = None
  6864. if self.app.is_legacy is False:
  6865. image = _screenshot(alpha=False)
  6866. data = np.asarray(image)
  6867. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6868. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6869. return
  6870. filter_ = "PNG File (*.png);;All Files (*.*)"
  6871. try:
  6872. filename, _f = FCFileSaveDialog.get_saved_filename(
  6873. caption=_("Export PNG Image"),
  6874. directory=self.app.get_last_save_folder() + '/png_' + date,
  6875. ext_filter=filter_)
  6876. except TypeError:
  6877. filename, _f = FCFileSaveDialog.get_saved_filename(
  6878. caption=_("Export PNG Image"),
  6879. ext_filter=filter_)
  6880. filename = str(filename)
  6881. if filename == "":
  6882. self.inform.emit(_("Cancelled."))
  6883. return
  6884. else:
  6885. if self.app.is_legacy is False:
  6886. write_png(filename, data)
  6887. else:
  6888. self.app.plotcanvas.figure.savefig(filename)
  6889. if self.defaults["global_open_style"] is False:
  6890. self.app.file_opened.emit("png", filename)
  6891. self.app.file_saved.emit("png", filename)
  6892. def on_file_savegerber(self):
  6893. """
  6894. Callback for menu item in Project context menu.
  6895. :return: None
  6896. """
  6897. self.app.log.debug("on_file_savegerber()")
  6898. obj = self.app.collection.get_active()
  6899. if obj is None:
  6900. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6901. return
  6902. # Check for more compatible types and add as required
  6903. if not isinstance(obj, GerberObject):
  6904. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6905. return
  6906. name = self.app.collection.get_active().options["name"]
  6907. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6908. try:
  6909. filename, _f = FCFileSaveDialog.get_saved_filename(
  6910. caption="Save Gerber source file",
  6911. directory=self.app.get_last_save_folder() + '/' + name,
  6912. ext_filter=_filter)
  6913. except TypeError:
  6914. filename, _f = FCFileSaveDialog.get_saved_filename(
  6915. caption=_("Save Gerber source file"),
  6916. ext_filter=_filter)
  6917. filename = str(filename)
  6918. if filename == "":
  6919. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6920. return
  6921. else:
  6922. self.save_source_file(name, filename)
  6923. if self.defaults["global_open_style"] is False:
  6924. self.app.file_opened.emit("Gerber", filename)
  6925. self.app.file_saved.emit("Gerber", filename)
  6926. def on_file_savescript(self):
  6927. """
  6928. Callback for menu item in Project context menu.
  6929. :return: None
  6930. """
  6931. self.app.log.debug("on_file_savescript()")
  6932. obj = self.app.collection.get_active()
  6933. if obj is None:
  6934. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6935. return
  6936. # Check for more compatible types and add as required
  6937. if not isinstance(obj, ScriptObject):
  6938. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6939. return
  6940. name = self.app.collection.get_active().options["name"]
  6941. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6942. try:
  6943. filename, _f = FCFileSaveDialog.get_saved_filename(
  6944. caption="Save Script source file",
  6945. directory=self.app.get_last_save_folder() + '/' + name,
  6946. ext_filter=_filter)
  6947. except TypeError:
  6948. filename, _f = FCFileSaveDialog.get_saved_filename(
  6949. caption=_("Save Script source file"),
  6950. ext_filter=_filter)
  6951. filename = str(filename)
  6952. if filename == "":
  6953. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6954. return
  6955. else:
  6956. self.save_source_file(name, filename)
  6957. if self.defaults["global_open_style"] is False:
  6958. self.app.file_opened.emit("Script", filename)
  6959. self.app.file_saved.emit("Script", filename)
  6960. def on_file_savedocument(self):
  6961. """
  6962. Callback for menu item in Project context menu.
  6963. :return: None
  6964. """
  6965. self.app.log.debug("on_file_savedocument()")
  6966. obj = self.app.collection.get_active()
  6967. if obj is None:
  6968. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6969. return
  6970. # Check for more compatible types and add as required
  6971. if not isinstance(obj, ScriptObject):
  6972. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6973. return
  6974. name = self.app.collection.get_active().options["name"]
  6975. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6976. try:
  6977. filename, _f = FCFileSaveDialog.get_saved_filename(
  6978. caption="Save Document source file",
  6979. directory=self.app.get_last_save_folder() + '/' + name,
  6980. ext_filter=_filter)
  6981. except TypeError:
  6982. filename, _f = FCFileSaveDialog.get_saved_filename(
  6983. caption=_("Save Document source file"),
  6984. ext_filter=_filter)
  6985. filename = str(filename)
  6986. if filename == "":
  6987. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6988. return
  6989. else:
  6990. self.save_source_file(name, filename)
  6991. if self.defaults["global_open_style"] is False:
  6992. self.app.file_opened.emit("Document", filename)
  6993. self.app.file_saved.emit("Document", filename)
  6994. def on_file_saveexcellon(self):
  6995. """
  6996. Callback for menu item in project context menu.
  6997. :return: None
  6998. """
  6999. self.app.log.debug("on_file_saveexcellon()")
  7000. obj = self.app.collection.get_active()
  7001. if obj is None:
  7002. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7003. return
  7004. # Check for more compatible types and add as required
  7005. if not isinstance(obj, ExcellonObject):
  7006. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7007. return
  7008. name = self.app.collection.get_active().options["name"]
  7009. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7010. try:
  7011. filename, _f = FCFileSaveDialog.get_saved_filename(
  7012. caption=_("Save Excellon source file"),
  7013. directory=self.app.get_last_save_folder() + '/' + name,
  7014. ext_filter=_filter)
  7015. except TypeError:
  7016. filename, _f = FCFileSaveDialog.get_saved_filename(
  7017. caption=_("Save Excellon source file"), ext_filter=_filter)
  7018. filename = str(filename)
  7019. if filename == "":
  7020. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7021. return
  7022. else:
  7023. self.save_source_file(name, filename)
  7024. if self.defaults["global_open_style"] is False:
  7025. self.app.file_opened.emit("Excellon", filename)
  7026. self.app.file_saved.emit("Excellon", filename)
  7027. def on_file_exportexcellon(self):
  7028. """
  7029. Callback for menu item File->Export->Excellon.
  7030. :return: None
  7031. """
  7032. self.app.log.debug("on_file_exportexcellon()")
  7033. obj = self.app.collection.get_active()
  7034. if obj is None:
  7035. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7036. return
  7037. # Check for more compatible types and add as required
  7038. if not isinstance(obj, ExcellonObject):
  7039. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7040. return
  7041. name = self.app.collection.get_active().options["name"]
  7042. _filter = self.defaults["excellon_save_filters"]
  7043. try:
  7044. filename, _f = FCFileSaveDialog.get_saved_filename(
  7045. caption=_("Export Excellon"),
  7046. directory=self.app.get_last_save_folder() + '/' + name,
  7047. ext_filter=_filter)
  7048. except TypeError:
  7049. filename, _f = FCFileSaveDialog.get_saved_filename(
  7050. caption=_("Export Excellon"),
  7051. ext_filter=_filter)
  7052. filename = str(filename)
  7053. if filename == "":
  7054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7055. return
  7056. else:
  7057. used_extension = filename.rpartition('.')[2]
  7058. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7059. self.export_excellon(name, filename)
  7060. if self.defaults["global_open_style"] is False:
  7061. self.app.file_opened.emit("Excellon", filename)
  7062. self.app.file_saved.emit("Excellon", filename)
  7063. def on_file_exportgerber(self):
  7064. """
  7065. Callback for menu item File->Export->Gerber.
  7066. :return: None
  7067. """
  7068. App.log.debug("on_file_exportgerber()")
  7069. obj = self.app.collection.get_active()
  7070. if obj is None:
  7071. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7072. return
  7073. # Check for more compatible types and add as required
  7074. if not isinstance(obj, GerberObject):
  7075. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7076. return
  7077. name = self.app.collection.get_active().options["name"]
  7078. _filter_ = self.defaults['gerber_save_filters']
  7079. try:
  7080. filename, _f = FCFileSaveDialog.get_saved_filename(
  7081. caption=_("Export Gerber"),
  7082. directory=self.app.get_last_save_folder() + '/' + name,
  7083. ext_filter=_filter_)
  7084. except TypeError:
  7085. filename, _f = FCFileSaveDialog.get_saved_filename(
  7086. caption=_("Export Gerber"),
  7087. ext_filter=_filter_)
  7088. filename = str(filename)
  7089. if filename == "":
  7090. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7091. return
  7092. else:
  7093. used_extension = filename.rpartition('.')[2]
  7094. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7095. self.export_gerber(name, filename)
  7096. if self.defaults["global_open_style"] is False:
  7097. self.app.file_opened.emit("Gerber", filename)
  7098. self.app.file_saved.emit("Gerber", filename)
  7099. def on_file_exportdxf(self):
  7100. """
  7101. Callback for menu item File->Export DXF.
  7102. :return: None
  7103. """
  7104. App.log.debug("on_file_exportdxf()")
  7105. obj = self.app.collection.get_active()
  7106. if obj is None:
  7107. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7108. msg = _("Please Select a Geometry object to export")
  7109. msgbox = QtWidgets.QMessageBox()
  7110. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7111. msgbox.setInformativeText(msg)
  7112. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7113. msgbox.setDefaultButton(bt_ok)
  7114. msgbox.exec_()
  7115. return
  7116. # Check for more compatible types and add as required
  7117. if not isinstance(obj, GeometryObject):
  7118. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7119. msgbox = QtWidgets.QMessageBox()
  7120. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7121. msgbox.setInformativeText(msg)
  7122. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7123. msgbox.setDefaultButton(bt_ok)
  7124. msgbox.exec_()
  7125. return
  7126. name = self.app.collection.get_active().options["name"]
  7127. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7128. try:
  7129. filename, _f = FCFileSaveDialog.get_saved_filename(
  7130. caption=_("Export DXF"),
  7131. directory=self.app.get_last_save_folder() + '/' + name,
  7132. ext_filter=_filter_)
  7133. except TypeError:
  7134. filename, _f = FCFileSaveDialog.get_saved_filename(
  7135. caption=_("Export DXF"),
  7136. ext_filter=_filter_)
  7137. filename = str(filename)
  7138. if filename == "":
  7139. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7140. return
  7141. else:
  7142. self.export_dxf(name, filename)
  7143. if self.defaults["global_open_style"] is False:
  7144. self.app.file_opened.emit("DXF", filename)
  7145. self.app.file_saved.emit("DXF", filename)
  7146. def on_file_importsvg(self, type_of_obj):
  7147. """
  7148. Callback for menu item File->Import SVG.
  7149. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7150. :type type_of_obj: str
  7151. :return: None
  7152. """
  7153. self.app.log.debug("on_file_importsvg()")
  7154. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7155. try:
  7156. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7157. directory=self.app.get_last_folder(),
  7158. filter=_filter_)
  7159. except TypeError:
  7160. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7161. filter=_filter_)
  7162. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7163. type_of_obj = "geometry"
  7164. filenames = [str(filename) for filename in filenames]
  7165. if len(filenames) == 0:
  7166. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7167. else:
  7168. for filename in filenames:
  7169. if filename != '':
  7170. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7171. def on_file_importdxf(self, type_of_obj):
  7172. """
  7173. Callback for menu item File->Import DXF.
  7174. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7175. :type type_of_obj: str
  7176. :return: None
  7177. """
  7178. self.app.log.debug("on_file_importdxf()")
  7179. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7180. try:
  7181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7182. directory=self.app.get_last_folder(),
  7183. filter=_filter_)
  7184. except TypeError:
  7185. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7186. filter=_filter_)
  7187. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7188. type_of_obj = "geometry"
  7189. filenames = [str(filename) for filename in filenames]
  7190. if len(filenames) == 0:
  7191. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7192. else:
  7193. for filename in filenames:
  7194. if filename != '':
  7195. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7196. def on_file_new_click(self):
  7197. """
  7198. Callback for menu item File -> New.
  7199. Executed on clicking the Menu -> File -> New Project
  7200. :return:
  7201. """
  7202. if self.app.collection.get_list() and self.app.should_we_save:
  7203. msgbox = QtWidgets.QMessageBox()
  7204. # msgbox.setText("<B>Save changes ...</B>")
  7205. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7206. "Creating a New project will delete them.\n"
  7207. "Do you want to Save the project?"))
  7208. msgbox.setWindowTitle(_("Save changes"))
  7209. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7210. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7211. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7212. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7213. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7214. msgbox.setDefaultButton(bt_yes)
  7215. msgbox.exec_()
  7216. response = msgbox.clickedButton()
  7217. if response == bt_yes:
  7218. self.on_file_saveprojectas()
  7219. elif response == bt_cancel:
  7220. return
  7221. elif response == bt_no:
  7222. self.on_file_new()
  7223. else:
  7224. self.on_file_new()
  7225. self.inform.emit('[success] %s...' % _("New Project created"))
  7226. def on_file_new(self, cli=None):
  7227. """
  7228. Returns the application to its startup state. This method is thread-safe.
  7229. :param cli: Boolean. If True this method was run from command line
  7230. :return: None
  7231. """
  7232. self.defaults.report_usage("on_file_new")
  7233. # Remove everything from memory
  7234. self.app.log.debug("on_file_new()")
  7235. # close any editor that might be open
  7236. if self.app.call_source != 'app':
  7237. self.app.editor2object(cleanup=True)
  7238. # ## EDITOR section
  7239. self.app.geo_editor = AppGeoEditor(self.app)
  7240. self.app.exc_editor = AppExcEditor(self.app)
  7241. self.app.grb_editor = AppGerberEditor(self.app)
  7242. # Clear pool
  7243. self.app.clear_pool()
  7244. for obj in self.app.collection.get_list():
  7245. # delete shapes left drawn from mark shape_collections, if any
  7246. if isinstance(obj, GerberObject):
  7247. try:
  7248. obj.mark_shapes_storage.clear()
  7249. obj.mark_shapes.clear(update=True)
  7250. obj.mark_shapes.enabled = False
  7251. except AttributeError:
  7252. pass
  7253. # also delete annotation shapes, if any
  7254. elif isinstance(obj, CNCJobObject):
  7255. try:
  7256. obj.text_col.enabled = False
  7257. del obj.text_col
  7258. obj.annotation.clear(update=True)
  7259. del obj.annotation
  7260. except AttributeError:
  7261. pass
  7262. # delete the exclusion areas
  7263. self.app.exc_areas.clear_shapes()
  7264. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7265. self.app.shell.init_tcl()
  7266. # delete any selection shape on canvas
  7267. self.app.delete_selection_shape()
  7268. # delete all FlatCAM objects
  7269. self.app.collection.delete_all()
  7270. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7271. self.app.setup_default_properties_tab()
  7272. # Clear project filename
  7273. self.app.project_filename = None
  7274. # Load the application defaults
  7275. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7276. # Re-fresh project options
  7277. self.app.on_options_app2project()
  7278. # Init FlatCAMTools
  7279. self.app.init_tools()
  7280. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7281. if cli is None:
  7282. # we need to go in reverse because once we remove a tab then the index changes
  7283. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7284. # and so on. Therefore the deletion should be done in reverse
  7285. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7286. for index in range(wdg_count, -1, -1):
  7287. try:
  7288. self.app.ui.plot_tab_area.closeTab(index)
  7289. except Exception as e:
  7290. log.debug("App.on_file_new() --> %s" % str(e))
  7291. # # And then add again the Plot Area
  7292. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7293. self.app.ui.plot_tab_area.protectTab(0)
  7294. # take the focus of the Notebook on Project Tab.
  7295. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7296. self.app.set_ui_title(name=_("New Project - Not saved"))
  7297. def on_filenewscript(self, silent=False):
  7298. """
  7299. Will create a new script file and open it in the Code Editor
  7300. :param silent: if True will not display status messages
  7301. :return: None
  7302. """
  7303. if silent is False:
  7304. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7305. # hide coordinates toolbars in the infobar while in DB
  7306. self.app.ui.coords_toolbar.hide()
  7307. self.app.ui.delta_coords_toolbar.hide()
  7308. self.app.app_obj.new_script_object()
  7309. def on_fileopenscript(self, name=None, silent=False):
  7310. """
  7311. Will open a Tcl script file into the Code Editor
  7312. :param silent: if True will not display status messages
  7313. :param name: name of a Tcl script file to open
  7314. :return: None
  7315. """
  7316. self.app.log.debug("on_fileopenscript()")
  7317. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7318. "All Files (*.*)"
  7319. if name:
  7320. filenames = [name]
  7321. else:
  7322. try:
  7323. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7324. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7325. except TypeError:
  7326. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7327. if len(filenames) == 0:
  7328. if silent is False:
  7329. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7330. else:
  7331. for filename in filenames:
  7332. if filename != '':
  7333. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7334. def on_fileopenscript_example(self, name=None, silent=False):
  7335. """
  7336. Will open a Tcl script file into the Code Editor
  7337. :param silent: if True will not display status messages
  7338. :param name: name of a Tcl script file to open
  7339. :return:
  7340. """
  7341. self.app.log.debug("on_fileopenscript_example()")
  7342. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7343. "All Files (*.*)"
  7344. # test if the app was frozen and choose the path for the configuration file
  7345. if getattr(sys, "frozen", False) is True:
  7346. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7347. else:
  7348. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7349. if name:
  7350. filenames = [name]
  7351. else:
  7352. try:
  7353. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7354. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7355. except TypeError:
  7356. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7357. if len(filenames) == 0:
  7358. if silent is False:
  7359. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7360. else:
  7361. for filename in filenames:
  7362. if filename != '':
  7363. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7364. def on_filerunscript(self, name=None, silent=False):
  7365. """
  7366. File menu callback for loading and running a TCL script.
  7367. :param silent: if True will not display status messages
  7368. :param name: name of a Tcl script file to be run by FlatCAM
  7369. :return: None
  7370. """
  7371. self.app.log.debug("on_file_runscript()")
  7372. if name:
  7373. filename = name
  7374. if self.app.cmd_line_headless != 1:
  7375. self.splash.showMessage('%s: %ssec\n%s' %
  7376. (_("Canvas initialization started.\n"
  7377. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7378. _("Executing ScriptObject file.")
  7379. ),
  7380. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7381. color=QtGui.QColor("gray"))
  7382. else:
  7383. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7384. "All Files (*.*)"
  7385. try:
  7386. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7387. directory=self.app.get_last_folder(),
  7388. filter=_filter_)
  7389. except TypeError:
  7390. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7391. # The Qt methods above will return a QString which can cause problems later.
  7392. # So far json.dump() will fail to serialize it.
  7393. filename = str(filename)
  7394. if filename == "":
  7395. if silent is False:
  7396. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7397. else:
  7398. if self.app.cmd_line_headless != 1:
  7399. if self.app.ui.shell_dock.isHidden():
  7400. self.app.ui.shell_dock.show()
  7401. try:
  7402. with open(filename, "r") as tcl_script:
  7403. cmd_line_shellfile_content = tcl_script.read()
  7404. if self.app.cmd_line_headless != 1:
  7405. self.app.shell.exec_command(cmd_line_shellfile_content)
  7406. else:
  7407. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7408. if silent is False:
  7409. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7410. except Exception as e:
  7411. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7412. sys.exit(2)
  7413. def on_file_saveproject(self, silent=False):
  7414. """
  7415. Callback for menu item File->Save Project. Saves the project to
  7416. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7417. if set to None. The project is saved by calling ``self.save_project()``.
  7418. :param silent: if True will not display status messages
  7419. :return: None
  7420. """
  7421. if self.app.project_filename is None:
  7422. self.on_file_saveprojectas()
  7423. else:
  7424. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7425. if self.defaults["global_open_style"] is False:
  7426. self.app.file_opened.emit("project", self.project_filename)
  7427. self.app.file_saved.emit("project", self.project_filename)
  7428. self.app.set_ui_title(name=self.app.project_filename)
  7429. self.app.should_we_save = False
  7430. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7431. """
  7432. Callback for menu item File->Save Project As... Opens a file
  7433. chooser and saves the project to the given file via
  7434. ``self.save_project()``.
  7435. :param make_copy if to be create a copy of the project; boolean
  7436. :param use_thread: if to be run in a separate thread; boolean
  7437. :param quit_action: if to be followed by quiting the application; boolean
  7438. :return: None
  7439. """
  7440. date = str(datetime.today()).rpartition('.')[0]
  7441. date = ''.join(c for c in date if c not in ':-')
  7442. date = date.replace(' ', '_')
  7443. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7444. try:
  7445. filename, _f = FCFileSaveDialog.get_saved_filename(
  7446. caption=_("Save Project As ..."),
  7447. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7448. proj=_("Project")),
  7449. ext_filter=filter_
  7450. )
  7451. except TypeError:
  7452. filename, _f = FCFileSaveDialog.get_saved_filename(
  7453. caption=_("Save Project As ..."),
  7454. ext_filter=filter_)
  7455. filename = str(filename)
  7456. if filename == '':
  7457. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7458. return
  7459. if use_thread is True:
  7460. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7461. else:
  7462. self.save_project(filename, quit_action)
  7463. # self.save_project(filename)
  7464. if self.defaults["global_open_style"] is False:
  7465. self.app.file_opened.emit("project", filename)
  7466. self.app.file_saved.emit("project", filename)
  7467. if not make_copy:
  7468. self.app.project_filename = filename
  7469. self.app.set_ui_title(name=self.app.project_filename)
  7470. self.app.should_we_save = False
  7471. def on_file_save_objects_pdf(self, use_thread=True):
  7472. date = str(datetime.today()).rpartition('.')[0]
  7473. date = ''.join(c for c in date if c not in ':-')
  7474. date = date.replace(' ', '_')
  7475. try:
  7476. obj_selection = self.app.collection.get_selected()
  7477. if len(obj_selection) == 1:
  7478. obj_name = str(obj_selection[0].options['name'])
  7479. else:
  7480. obj_name = _("FlatCAM objects print")
  7481. except AttributeError as err:
  7482. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7483. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7484. return
  7485. if not obj_selection:
  7486. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7487. return
  7488. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7489. try:
  7490. filename, _f = FCFileSaveDialog.get_saved_filename(
  7491. caption=_("Save Object as PDF ..."),
  7492. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7493. obj_name=obj_name,
  7494. date=date),
  7495. ext_filter=filter_
  7496. )
  7497. except TypeError:
  7498. filename, _f = FCFileSaveDialog.get_saved_filename(
  7499. caption=_("Save Object as PDF ..."),
  7500. ext_filter=filter_)
  7501. filename = str(filename)
  7502. if filename == '':
  7503. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7504. return
  7505. if use_thread is True:
  7506. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7507. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7508. else:
  7509. self.save_pdf(filename, obj_selection)
  7510. # self.save_project(filename)
  7511. if self.defaults["global_open_style"] is False:
  7512. self.app.file_opened.emit("pdf", filename)
  7513. self.app.file_saved.emit("pdf", filename)
  7514. def save_pdf(self, file_name, obj_selection):
  7515. p_size = self.defaults['global_workspaceT']
  7516. orientation = self.defaults['global_workspace_orientation']
  7517. color = 'black'
  7518. transparency_level = 1.0
  7519. self.pagesize.update(
  7520. {
  7521. 'Bounds': None,
  7522. 'A0': (841 * mm, 1189 * mm),
  7523. 'A1': (594 * mm, 841 * mm),
  7524. 'A2': (420 * mm, 594 * mm),
  7525. 'A3': (297 * mm, 420 * mm),
  7526. 'A4': (210 * mm, 297 * mm),
  7527. 'A5': (148 * mm, 210 * mm),
  7528. 'A6': (105 * mm, 148 * mm),
  7529. 'A7': (74 * mm, 105 * mm),
  7530. 'A8': (52 * mm, 74 * mm),
  7531. 'A9': (37 * mm, 52 * mm),
  7532. 'A10': (26 * mm, 37 * mm),
  7533. 'B0': (1000 * mm, 1414 * mm),
  7534. 'B1': (707 * mm, 1000 * mm),
  7535. 'B2': (500 * mm, 707 * mm),
  7536. 'B3': (353 * mm, 500 * mm),
  7537. 'B4': (250 * mm, 353 * mm),
  7538. 'B5': (176 * mm, 250 * mm),
  7539. 'B6': (125 * mm, 176 * mm),
  7540. 'B7': (88 * mm, 125 * mm),
  7541. 'B8': (62 * mm, 88 * mm),
  7542. 'B9': (44 * mm, 62 * mm),
  7543. 'B10': (31 * mm, 44 * mm),
  7544. 'C0': (917 * mm, 1297 * mm),
  7545. 'C1': (648 * mm, 917 * mm),
  7546. 'C2': (458 * mm, 648 * mm),
  7547. 'C3': (324 * mm, 458 * mm),
  7548. 'C4': (229 * mm, 324 * mm),
  7549. 'C5': (162 * mm, 229 * mm),
  7550. 'C6': (114 * mm, 162 * mm),
  7551. 'C7': (81 * mm, 114 * mm),
  7552. 'C8': (57 * mm, 81 * mm),
  7553. 'C9': (40 * mm, 57 * mm),
  7554. 'C10': (28 * mm, 40 * mm),
  7555. # American paper sizes
  7556. 'LETTER': (8.5 * inch, 11 * inch),
  7557. 'LEGAL': (8.5 * inch, 14 * inch),
  7558. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7559. # From https://en.wikipedia.org/wiki/Paper_size
  7560. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7561. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7562. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7563. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7564. 'LEDGER': (17 * inch, 11 * inch),
  7565. }
  7566. )
  7567. exported_svg = []
  7568. for obj in obj_selection:
  7569. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7570. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7571. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7572. color = obj.fill_color[:-2]
  7573. transparency_level = obj.fill_color[-2:]
  7574. elif obj.kind.lower() == 'geometry':
  7575. color = self.defaults["global_draw_color"]
  7576. # Change the attributes of the exported SVG
  7577. # We don't need stroke-width
  7578. # We set opacity to maximum
  7579. # We set the colour to WHITE
  7580. root = ET.fromstring(svg_obj)
  7581. for child in root:
  7582. child.set('fill', str(color))
  7583. child.set('opacity', str(transparency_level))
  7584. child.set('stroke', str(color))
  7585. exported_svg.append(ET.tostring(root))
  7586. xmin = Inf
  7587. ymin = Inf
  7588. xmax = -Inf
  7589. ymax = -Inf
  7590. for obj in obj_selection:
  7591. try:
  7592. gxmin, gymin, gxmax, gymax = obj.bounds()
  7593. xmin = min([xmin, gxmin])
  7594. ymin = min([ymin, gymin])
  7595. xmax = max([xmax, gxmax])
  7596. ymax = max([ymax, gymax])
  7597. except Exception as e:
  7598. self.app.log.warning(
  7599. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7600. # Determine bounding area for svg export
  7601. bounds = [xmin, ymin, xmax, ymax]
  7602. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7603. # This contain the measure units
  7604. uom = obj_selection[0].units.lower()
  7605. # Define a boundary around SVG of about 1.0mm (~39mils)
  7606. if uom in "mm":
  7607. boundary = 1.0
  7608. else:
  7609. boundary = 0.0393701
  7610. # Convert everything to strings for use in the xml doc
  7611. svgwidth = str(size[0] + (2 * boundary))
  7612. svgheight = str(size[1] + (2 * boundary))
  7613. minx = str(bounds[0] - boundary)
  7614. miny = str(bounds[1] + boundary + size[1])
  7615. # Add a SVG Header and footer to the svg output from shapely
  7616. # The transform flips the Y Axis so that everything renders
  7617. # properly within svg apps such as inkscape
  7618. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7619. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7620. svg_header += 'width="' + svgwidth + uom + '" '
  7621. svg_header += 'height="' + svgheight + uom + '" '
  7622. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7623. svg_header += '>'
  7624. svg_header += '<g transform="scale(1,-1)">'
  7625. svg_footer = '</g> </svg>'
  7626. svg_elem = str(svg_header)
  7627. for svg_item in exported_svg:
  7628. svg_elem += str(svg_item)
  7629. svg_elem += str(svg_footer)
  7630. # Parse the xml through a xml parser just to add line feeds
  7631. # and to make it look more pretty for the output
  7632. doc = parse_xml_string(svg_elem)
  7633. doc_final = doc.toprettyxml()
  7634. try:
  7635. if self.defaults['units'].upper() == 'IN':
  7636. unit = inch
  7637. else:
  7638. unit = mm
  7639. doc_final = StringIO(doc_final)
  7640. drawing = svg2rlg(doc_final)
  7641. if p_size == 'Bounds':
  7642. renderPDF.drawToFile(drawing, file_name)
  7643. else:
  7644. if orientation == 'p':
  7645. page_size = portrait(self.pagesize[p_size])
  7646. else:
  7647. page_size = landscape(self.pagesize[p_size])
  7648. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7649. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7650. renderPDF.draw(drawing, my_canvas, 0, 0)
  7651. my_canvas.save()
  7652. except Exception as e:
  7653. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7654. return 'fail'
  7655. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7656. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7657. """
  7658. Exports a Geometry Object to an SVG file.
  7659. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7660. :param filename: Path to the SVG file to save to.
  7661. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7662. :return:
  7663. """
  7664. if filename is None:
  7665. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7666. is not None else self.defaults["global_last_folder"]
  7667. self.app.log.debug("export_svg()")
  7668. try:
  7669. obj = self.app.collection.get_by_name(str(obj_name))
  7670. except Exception:
  7671. return 'fail'
  7672. with self.app.proc_container.new(_("Exporting SVG")):
  7673. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7674. # Determine bounding area for svg export
  7675. bounds = obj.bounds()
  7676. size = obj.size()
  7677. # Convert everything to strings for use in the xml doc
  7678. svgwidth = str(size[0])
  7679. svgheight = str(size[1])
  7680. minx = str(bounds[0])
  7681. miny = str(bounds[1] - size[1])
  7682. uom = obj.units.lower()
  7683. # Add a SVG Header and footer to the svg output from shapely
  7684. # The transform flips the Y Axis so that everything renders
  7685. # properly within svg apps such as inkscape
  7686. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7687. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7688. svg_header += 'width="' + svgwidth + uom + '" '
  7689. svg_header += 'height="' + svgheight + uom + '" '
  7690. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7691. svg_header += '<g transform="scale(1,-1)">'
  7692. svg_footer = '</g> </svg>'
  7693. svg_elem = svg_header + exported_svg + svg_footer
  7694. # Parse the xml through a xml parser just to add line feeds
  7695. # and to make it look more pretty for the output
  7696. svgcode = parse_xml_string(svg_elem)
  7697. svgcode = svgcode.toprettyxml()
  7698. try:
  7699. with open(filename, 'w') as fp:
  7700. fp.write(svgcode)
  7701. except PermissionError:
  7702. self.inform.emit('[WARNING] %s' %
  7703. _("Permission denied, saving not possible.\n"
  7704. "Most likely another app is holding the file open and not accessible."))
  7705. return 'fail'
  7706. if self.defaults["global_open_style"] is False:
  7707. self.app.file_opened.emit("SVG", filename)
  7708. self.app.file_saved.emit("SVG", filename)
  7709. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7710. def on_import_preferences(self):
  7711. """
  7712. Loads the application default settings from a saved file into
  7713. ``self.defaults`` dictionary.
  7714. :return: None
  7715. """
  7716. self.app.log.debug("App.on_import_preferences()")
  7717. # Show file chooser
  7718. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7719. try:
  7720. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7721. directory=self.app.data_path,
  7722. filter=filter_)
  7723. except TypeError:
  7724. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7725. filter=filter_)
  7726. filename = str(filename)
  7727. if filename == "":
  7728. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7729. return
  7730. # Load in the defaults from the chosen file
  7731. self.defaults.load(filename=filename, inform=self.inform)
  7732. self.app.preferencesUiManager.on_preferences_edited()
  7733. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7734. def on_export_preferences(self):
  7735. """
  7736. Save the defaults dictionary to a file.
  7737. :return: None
  7738. """
  7739. self.app.log.debug("on_export_preferences()")
  7740. # defaults_file_content = None
  7741. # Show file chooser
  7742. date = str(datetime.today()).rpartition('.')[0]
  7743. date = ''.join(c for c in date if c not in ':-')
  7744. date = date.replace(' ', '_')
  7745. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7746. try:
  7747. filename, _f = FCFileSaveDialog.get_saved_filename(
  7748. caption=_("Export FlatCAM Preferences"),
  7749. directory=self.app.data_path + '/preferences_' + date,
  7750. ext_filter=filter__
  7751. )
  7752. except TypeError:
  7753. filename, _f = FCFileSaveDialog.get_saved_filename(
  7754. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7755. filename = str(filename)
  7756. if filename == "":
  7757. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7758. return 'fail'
  7759. # Update options
  7760. self.app.preferencesUiManager.defaults_read_form()
  7761. self.defaults.propagate_defaults()
  7762. # Save update options
  7763. try:
  7764. self.defaults.write(filename=filename)
  7765. except Exception:
  7766. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7767. return
  7768. if self.defaults["global_open_style"] is False:
  7769. self.app.file_opened.emit("preferences", filename)
  7770. self.app.file_saved.emit("preferences", filename)
  7771. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7772. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7773. """
  7774. Exports a Excellon Object to an Excellon file.
  7775. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7776. :param filename: Path to the Excellon file to save to.
  7777. :param local_use:
  7778. :param use_thread: if to be run in a separate thread
  7779. :return:
  7780. """
  7781. if filename is None:
  7782. if self.defaults["global_last_save_folder"]:
  7783. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7784. else:
  7785. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7786. self.app.log.debug("export_excellon()")
  7787. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7788. self.defaults["excellon_exp_decimals"]
  7789. )
  7790. if local_use is None:
  7791. try:
  7792. obj = self.app.collection.get_by_name(str(obj_name))
  7793. except Exception:
  7794. return "Could not retrieve object: %s" % obj_name
  7795. else:
  7796. obj = local_use
  7797. if not isinstance(obj, ExcellonObject):
  7798. self.inform.emit('[ERROR_NOTCL] %s' %
  7799. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7800. return
  7801. # updated units
  7802. eunits = self.defaults["excellon_exp_units"]
  7803. ewhole = self.defaults["excellon_exp_integer"]
  7804. efract = self.defaults["excellon_exp_decimals"]
  7805. ezeros = self.defaults["excellon_exp_zeros"]
  7806. eformat = self.defaults["excellon_exp_format"]
  7807. slot_type = self.defaults["excellon_exp_slot_type"]
  7808. fc_units = self.defaults['units'].upper()
  7809. if fc_units == 'MM':
  7810. factor = 1 if eunits == 'METRIC' else 0.03937
  7811. else:
  7812. factor = 25.4 if eunits == 'METRIC' else 1
  7813. def make_excellon():
  7814. try:
  7815. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7816. header = 'M48\n'
  7817. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7818. (str(self.app.version), str(self.app.version_date))
  7819. header += ';Filename: %s' % str(obj_name) + '\n'
  7820. header += ';Created on : %s' % time_str + '\n'
  7821. if eformat == 'dec':
  7822. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7823. header += eunits + '\n'
  7824. for tool in obj.tools:
  7825. if eunits == 'METRIC':
  7826. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7827. tool=str(tool),
  7828. dec=2)
  7829. else:
  7830. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7831. tool=str(tool),
  7832. dec=4)
  7833. else:
  7834. if ezeros == 'LZ':
  7835. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7836. form='ndec', e_zeros='LZ', factor=factor,
  7837. slot_type=slot_type)
  7838. header += '%s,%s\n' % (eunits, 'LZ')
  7839. header += format_exc
  7840. for tool in obj.tools:
  7841. if eunits == 'METRIC':
  7842. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7843. float(obj.tools[tool]['tooldia']) * factor,
  7844. tool=str(tool),
  7845. dec=2)
  7846. else:
  7847. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7848. float(obj.tools[tool]['tooldia']) * factor,
  7849. tool=str(tool),
  7850. dec=4)
  7851. else:
  7852. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7853. form='ndec', e_zeros='TZ', factor=factor,
  7854. slot_type=slot_type)
  7855. header += '%s,%s\n' % (eunits, 'TZ')
  7856. header += format_exc
  7857. for tool in obj.tools:
  7858. if eunits == 'METRIC':
  7859. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7860. float(obj.tools[tool]['tooldia']) * factor,
  7861. tool=str(tool),
  7862. dec=2)
  7863. else:
  7864. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7865. float(obj.tools[tool]['tooldia']) * factor,
  7866. tool=str(tool),
  7867. dec=4)
  7868. header += '%\n'
  7869. footer = 'M30\n'
  7870. exported_excellon = header
  7871. exported_excellon += excellon_code
  7872. exported_excellon += footer
  7873. if local_use is None:
  7874. try:
  7875. with open(filename, 'w') as fp:
  7876. fp.write(exported_excellon)
  7877. except PermissionError:
  7878. self.inform.emit('[WARNING] %s' %
  7879. _("Permission denied, saving not possible.\n"
  7880. "Most likely another app is holding the file open and not accessible."))
  7881. return 'fail'
  7882. if self.defaults["global_open_style"] is False:
  7883. self.app.file_opened.emit("Excellon", filename)
  7884. self.app.file_saved.emit("Excellon", filename)
  7885. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7886. else:
  7887. return exported_excellon
  7888. except Exception as e:
  7889. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7890. return 'fail'
  7891. if use_thread is True:
  7892. with self.app.proc_container.new(_("Exporting Excellon")):
  7893. def job_thread_exc(app_obj):
  7894. ret = make_excellon()
  7895. if ret == 'fail':
  7896. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7897. return
  7898. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7899. else:
  7900. eret = make_excellon()
  7901. if eret == 'fail':
  7902. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7903. return 'fail'
  7904. if local_use is not None:
  7905. return eret
  7906. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7907. """
  7908. Exports a Gerber Object to an Gerber file.
  7909. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7910. :param filename: Path to the Gerber file to save to.
  7911. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7912. When not None, the value will be the actual Gerber object for which to create
  7913. the Gerber code
  7914. :param use_thread: if to be run in a separate thread
  7915. :return:
  7916. """
  7917. if filename is None:
  7918. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7919. is not None else self.defaults["global_last_folder"]
  7920. self.app.log.debug("export_gerber()")
  7921. if local_use is None:
  7922. try:
  7923. obj = self.app.collection.get_by_name(str(obj_name))
  7924. except Exception:
  7925. return 'fail'
  7926. else:
  7927. obj = local_use
  7928. # updated units
  7929. gunits = self.defaults["gerber_exp_units"]
  7930. gwhole = self.defaults["gerber_exp_integer"]
  7931. gfract = self.defaults["gerber_exp_decimals"]
  7932. gzeros = self.defaults["gerber_exp_zeros"]
  7933. fc_units = self.defaults['units'].upper()
  7934. if fc_units == 'MM':
  7935. factor = 1 if gunits == 'MM' else 0.03937
  7936. else:
  7937. factor = 25.4 if gunits == 'MM' else 1
  7938. def make_gerber():
  7939. try:
  7940. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7941. header = 'G04*\n'
  7942. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7943. (str(self.app.version), str(self.app.version_date))
  7944. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7945. header += 'G04 Created on : %s*' % time_str + '\n'
  7946. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7947. header += "%MO{units}*%\n".format(units=gunits)
  7948. for apid in obj.apertures:
  7949. if obj.apertures[apid]['type'] == 'C':
  7950. header += "%ADD{apid}{type},{size}*%\n".format(
  7951. apid=str(apid),
  7952. type='C',
  7953. size=(factor * obj.apertures[apid]['size'])
  7954. )
  7955. elif obj.apertures[apid]['type'] == 'R':
  7956. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7957. apid=str(apid),
  7958. type='R',
  7959. width=(factor * obj.apertures[apid]['width']),
  7960. height=(factor * obj.apertures[apid]['height'])
  7961. )
  7962. elif obj.apertures[apid]['type'] == 'O':
  7963. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7964. apid=str(apid),
  7965. type='O',
  7966. width=(factor * obj.apertures[apid]['width']),
  7967. height=(factor * obj.apertures[apid]['height'])
  7968. )
  7969. header += '\n'
  7970. # obsolete units but some software may need it
  7971. if gunits == 'IN':
  7972. header += 'G70*\n'
  7973. else:
  7974. header += 'G71*\n'
  7975. # Absolute Mode
  7976. header += 'G90*\n'
  7977. header += 'G01*\n'
  7978. # positive polarity
  7979. header += '%LPD*%\n'
  7980. footer = 'M02*\n'
  7981. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7982. exported_gerber = header
  7983. exported_gerber += gerber_code
  7984. exported_gerber += footer
  7985. if local_use is None:
  7986. try:
  7987. with open(filename, 'w') as fp:
  7988. fp.write(exported_gerber)
  7989. except PermissionError:
  7990. self.inform.emit('[WARNING] %s' %
  7991. _("Permission denied, saving not possible.\n"
  7992. "Most likely another app is holding the file open and not accessible."))
  7993. return 'fail'
  7994. if self.defaults["global_open_style"] is False:
  7995. self.app.file_opened.emit("Gerber", filename)
  7996. self.app.file_saved.emit("Gerber", filename)
  7997. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7998. else:
  7999. return exported_gerber
  8000. except Exception as e:
  8001. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8002. return 'fail'
  8003. if use_thread is True:
  8004. with self.app.proc_container.new(_("Exporting Gerber")):
  8005. def job_thread_grb(app_obj):
  8006. ret = make_gerber()
  8007. if ret == 'fail':
  8008. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8009. return
  8010. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8011. else:
  8012. gret = make_gerber()
  8013. if gret == 'fail':
  8014. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8015. return 'fail'
  8016. if local_use is not None:
  8017. return gret
  8018. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8019. """
  8020. Exports a Geometry Object to an DXF file.
  8021. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8022. :param filename: Path to the DXF file to save to.
  8023. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8024. When not None, the value will be the actual Geometry object for which to create
  8025. the Geometry/DXF code
  8026. :param use_thread: if to be run in a separate thread
  8027. :return:
  8028. """
  8029. if filename is None:
  8030. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8031. is not None else self.defaults["global_last_folder"]
  8032. self.app.log.debug("export_dxf()")
  8033. if local_use is None:
  8034. try:
  8035. obj = self.app.collection.get_by_name(str(obj_name))
  8036. except Exception:
  8037. return 'fail'
  8038. else:
  8039. obj = local_use
  8040. def make_dxf():
  8041. try:
  8042. dxf_code = obj.export_dxf()
  8043. if local_use is None:
  8044. try:
  8045. dxf_code.saveas(filename)
  8046. except PermissionError:
  8047. self.inform.emit('[WARNING] %s' %
  8048. _("Permission denied, saving not possible.\n"
  8049. "Most likely another app is holding the file open and not accessible."))
  8050. return 'fail'
  8051. if self.defaults["global_open_style"] is False:
  8052. self.app.file_opened.emit("DXF", filename)
  8053. self.app.file_saved.emit("DXF", filename)
  8054. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8055. else:
  8056. return dxf_code
  8057. except Exception as e:
  8058. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8059. return 'fail'
  8060. if use_thread is True:
  8061. with self.app.proc_container.new(_("Exporting DXF")):
  8062. def job_thread_exc(app_obj):
  8063. ret_dxf_val = make_dxf()
  8064. if ret_dxf_val == 'fail':
  8065. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8066. return
  8067. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8068. else:
  8069. ret = make_dxf()
  8070. if ret == 'fail':
  8071. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8072. return
  8073. if local_use is not None:
  8074. return ret
  8075. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8076. """
  8077. Adds a new Geometry Object to the projects and populates
  8078. it with shapes extracted from the SVG file.
  8079. :param plot: If True then the resulting object will be plotted on canvas
  8080. :param filename: Path to the SVG file.
  8081. :param geo_type: Type of FlatCAM object that will be created from SVG
  8082. :param outname: The name given to the resulting FlatCAM object
  8083. :return:
  8084. """
  8085. self.app.log.debug("App.import_svg()")
  8086. obj_type = ""
  8087. if geo_type is None or geo_type == "geometry":
  8088. obj_type = "geometry"
  8089. elif geo_type == "gerber":
  8090. obj_type = "gerber"
  8091. else:
  8092. self.inform.emit('[ERROR_NOTCL] %s' %
  8093. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8094. return
  8095. units = self.defaults['units'].upper()
  8096. def obj_init(geo_obj, app_obj):
  8097. geo_obj.import_svg(filename, obj_type, units=units)
  8098. geo_obj.multigeo = True
  8099. with open(filename) as f:
  8100. file_content = f.read()
  8101. geo_obj.source_file = file_content
  8102. # appGUI feedback
  8103. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8104. with self.app.proc_container.new(_("Importing SVG")):
  8105. # Object name
  8106. name = outname or filename.split('/')[-1].split('\\')[-1]
  8107. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8108. if ret == 'fail':
  8109. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8110. return 'fail'
  8111. # Register recent file
  8112. self.app.file_opened.emit("svg", filename)
  8113. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8114. """
  8115. Adds a new Geometry Object to the projects and populates
  8116. it with shapes extracted from the DXF file.
  8117. :param filename: Path to the DXF file.
  8118. :param geo_type: Type of FlatCAM object that will be created from DXF
  8119. :param outname: Name for the imported Geometry
  8120. :param plot: If True then the resulting object will be plotted on canvas
  8121. :return:
  8122. """
  8123. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8124. obj_type = ""
  8125. if geo_type is None or geo_type == "geometry":
  8126. obj_type = "geometry"
  8127. elif geo_type == "gerber":
  8128. obj_type = geo_type
  8129. else:
  8130. self.inform.emit('[ERROR_NOTCL] %s' %
  8131. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8132. return
  8133. units = self.defaults['units'].upper()
  8134. def obj_init(geo_obj, app_obj):
  8135. if obj_type == "geometry":
  8136. geo_obj.import_dxf_as_geo(filename, units=units)
  8137. elif obj_type == "gerber":
  8138. geo_obj.import_dxf_as_gerber(filename, units=units)
  8139. else:
  8140. return "fail"
  8141. geo_obj.multigeo = True
  8142. with open(filename) as f:
  8143. file_content = f.read()
  8144. geo_obj.source_file = file_content
  8145. # appGUI feedback
  8146. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8147. with self.app.proc_container.new(_("Importing DXF")):
  8148. # Object name
  8149. name = outname or filename.split('/')[-1].split('\\')[-1]
  8150. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8151. if ret == 'fail':
  8152. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8153. return 'fail'
  8154. # Register recent file
  8155. self.app.file_opened.emit("dxf", filename)
  8156. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8157. """
  8158. Opens a Gerber file, parses it and creates a new object for
  8159. it in the program. Thread-safe.
  8160. :param outname: Name of the resulting object. None causes the
  8161. name to be that of the file. Str.
  8162. :param filename: Gerber file filename
  8163. :type filename: str
  8164. :param plot: boolean, to plot or not the resulting object
  8165. :param from_tcl: True if run from Tcl Shell
  8166. :return: None
  8167. """
  8168. # How the object should be initialized
  8169. def obj_init(gerber_obj, app_obj):
  8170. assert isinstance(gerber_obj, GerberObject), \
  8171. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8172. # Opening the file happens here
  8173. try:
  8174. gerber_obj.parse_file(filename)
  8175. except IOError:
  8176. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8177. return "fail"
  8178. except ParseError as err:
  8179. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8180. app_obj.log.error(str(err))
  8181. return "fail"
  8182. except Exception as e:
  8183. log.debug("App.open_gerber() --> %s" % str(e))
  8184. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8185. msg += traceback.format_exc()
  8186. app_obj.inform.emit(msg)
  8187. return "fail"
  8188. if gerber_obj.is_empty():
  8189. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8190. _("Object is not Gerber file or empty. Aborting object creation."))
  8191. return "fail"
  8192. self.app.log.debug("open_gerber()")
  8193. with self.app.proc_container.new(_("Opening Gerber")):
  8194. # Object name
  8195. name = outname or filename.split('/')[-1].split('\\')[-1]
  8196. # # ## Object creation # ##
  8197. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8198. if ret_val == 'fail':
  8199. if from_tcl:
  8200. filename = self.defaults['global_tcl_path'] + '/' + name
  8201. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8202. if ret_val == 'fail':
  8203. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8204. return 'fail'
  8205. # Register recent file
  8206. self.app.file_opened.emit("gerber", filename)
  8207. # appGUI feedback
  8208. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8209. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8210. """
  8211. Opens an Excellon file, parses it and creates a new object for
  8212. it in the program. Thread-safe.
  8213. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8214. :param filename: Excellon file filename
  8215. :type filename: str
  8216. :param plot: boolean, to plot or not the resulting object
  8217. :param from_tcl: True if run from Tcl Shell
  8218. :return: None
  8219. """
  8220. self.app.log.debug("open_excellon()")
  8221. # How the object should be initialized
  8222. def obj_init(excellon_obj, app_obj):
  8223. try:
  8224. ret = excellon_obj.parse_file(filename=filename)
  8225. if ret == "fail":
  8226. app_obj.log.debug("Excellon parsing failed.")
  8227. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8228. return "fail"
  8229. except IOError:
  8230. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8231. app_obj.log.debug("Could not open Excellon object.")
  8232. return "fail"
  8233. except Exception:
  8234. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8235. msg += traceback.format_exc()
  8236. app_obj.inform.emit(msg)
  8237. return "fail"
  8238. ret = excellon_obj.create_geometry()
  8239. if ret == 'fail':
  8240. app_obj.log.debug("Could not create geometry for Excellon object.")
  8241. return "fail"
  8242. for tool in excellon_obj.tools:
  8243. if excellon_obj.tools[tool]['solid_geometry']:
  8244. return
  8245. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8246. return "fail"
  8247. with self.app.proc_container.new(_("Opening Excellon.")):
  8248. # Object name
  8249. name = outname or filename.split('/')[-1].split('\\')[-1]
  8250. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8251. if ret_val == 'fail':
  8252. if from_tcl:
  8253. filename = self.defaults['global_tcl_path'] + '/' + name
  8254. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8255. if ret_val == 'fail':
  8256. self.inform.emit('[ERROR_NOTCL] %s' %
  8257. _('Open Excellon file failed. Probable not an Excellon file.'))
  8258. return
  8259. # Register recent file
  8260. self.app.file_opened.emit("excellon", filename)
  8261. # appGUI feedback
  8262. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8263. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8264. """
  8265. Opens a G-gcode file, parses it and creates a new object for
  8266. it in the program. Thread-safe.
  8267. :param filename: G-code file filename
  8268. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8269. :param force_parsing:
  8270. :param plot: If True plot the object on canvas
  8271. :param from_tcl: True if run from Tcl Shell
  8272. :return: None
  8273. """
  8274. self.app.log.debug("open_gcode()")
  8275. # How the object should be initialized
  8276. def obj_init(job_obj, app_obj_):
  8277. """
  8278. :param job_obj: the resulting object
  8279. :type app_obj_: App
  8280. """
  8281. assert isinstance(app_obj_, App), \
  8282. "Initializer expected App, got %s" % type(app_obj_)
  8283. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8284. try:
  8285. f = open(filename)
  8286. gcode = f.read()
  8287. f.close()
  8288. except IOError:
  8289. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8290. return "fail"
  8291. job_obj.gcode = gcode
  8292. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8293. if gcode_ret == "fail":
  8294. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8295. return "fail"
  8296. job_obj.create_geometry()
  8297. with self.app.proc_container.new(_("Opening G-Code.")):
  8298. # Object name
  8299. name = outname or filename.split('/')[-1].split('\\')[-1]
  8300. # New object creation and file processing
  8301. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8302. if ret_val == 'fail':
  8303. if from_tcl:
  8304. filename = self.defaults['global_tcl_path'] + '/' + name
  8305. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8306. if ret_val == 'fail':
  8307. self.inform.emit('[ERROR_NOTCL] %s' %
  8308. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8309. "Try to load it from File menu.\n "
  8310. "Attempting to create a FlatCAM CNCJob Object from "
  8311. "G-Code file failed during processing"))
  8312. return "fail"
  8313. # Register recent file
  8314. self.app.file_opened.emit("cncjob", filename)
  8315. # appGUI feedback
  8316. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8317. def open_hpgl2(self, filename, outname=None):
  8318. """
  8319. Opens a HPGL2 file, parses it and creates a new object for
  8320. it in the program. Thread-safe.
  8321. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8322. :param filename: HPGL2 file filename
  8323. :return: None
  8324. """
  8325. filename = filename
  8326. # How the object should be initialized
  8327. def obj_init(geo_obj, app_obj):
  8328. assert isinstance(geo_obj, GeometryObject), \
  8329. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8330. # Opening the file happens here
  8331. obj = HPGL2(self)
  8332. try:
  8333. HPGL2.parse_file(obj, filename)
  8334. except IOError:
  8335. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8336. return "fail"
  8337. except ParseError as err:
  8338. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8339. app_obj.log.error(str(err))
  8340. return "fail"
  8341. except Exception as e:
  8342. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8343. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8344. msg += traceback.format_exc()
  8345. app_obj.inform.emit(msg)
  8346. return "fail"
  8347. geo_obj.multigeo = True
  8348. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8349. geo_obj.tools = deepcopy(obj.tools)
  8350. geo_obj.source_file = deepcopy(obj.source_file)
  8351. del obj
  8352. if not geo_obj.solid_geometry:
  8353. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8354. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8355. return "fail"
  8356. self.app.log.debug("open_hpgl2()")
  8357. with self.app.proc_container.new(_("Opening HPGL2")):
  8358. # Object name
  8359. name = outname or filename.split('/')[-1].split('\\')[-1]
  8360. # # ## Object creation # ##
  8361. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8362. if ret == 'fail':
  8363. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8364. return 'fail'
  8365. # Register recent file
  8366. self.app.file_opened.emit("geometry", filename)
  8367. # appGUI feedback
  8368. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8369. def open_script(self, filename, outname=None, silent=False):
  8370. """
  8371. Opens a Script file, parses it and creates a new object for
  8372. it in the program. Thread-safe.
  8373. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8374. :param filename: Script file filename
  8375. :param silent: If True there will be no messages printed to StatusBar
  8376. :return: None
  8377. """
  8378. def obj_init(script_obj, app_obj):
  8379. assert isinstance(script_obj, ScriptObject), \
  8380. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8381. if silent is False:
  8382. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8383. try:
  8384. script_obj.parse_file(filename)
  8385. except IOError:
  8386. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8387. return "fail"
  8388. except ParseError as err:
  8389. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8390. app_obj.log.error(str(err))
  8391. return "fail"
  8392. except Exception as e:
  8393. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8394. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8395. msg += traceback.format_exc()
  8396. app_obj.inform.emit(msg)
  8397. return "fail"
  8398. self.app.log.debug("open_script()")
  8399. with self.app.proc_container.new(_("Opening TCL Script...")):
  8400. # Object name
  8401. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8402. # Object creation
  8403. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8404. if ret_val == 'fail':
  8405. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8406. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8407. if ret_val == 'fail':
  8408. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8409. return 'fail'
  8410. # Register recent file
  8411. self.app.file_opened.emit("script", filename)
  8412. # appGUI feedback
  8413. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8414. def open_config_file(self, filename, run_from_arg=None):
  8415. """
  8416. Loads a config file from the specified file.
  8417. :param filename: Name of the file from which to load.
  8418. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8419. :return: None
  8420. """
  8421. self.app.log.debug("Opening config file: " + filename)
  8422. if run_from_arg:
  8423. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8424. "Canvas initialization finished in"),
  8425. '%.2f' % self.app.used_time,
  8426. _("Opening FlatCAM Config file.")),
  8427. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8428. color=QtGui.QColor("gray"))
  8429. # # add the tab if it was closed
  8430. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8431. # # first clear previous text in text editor (if any)
  8432. # self.ui.text_editor_tab.code_editor.clear()
  8433. #
  8434. # # Switch plot_area to CNCJob tab
  8435. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8436. # close the Code editor if already open
  8437. if self.app.toggle_codeeditor:
  8438. self.app.on_toggle_code_editor()
  8439. self.app.on_toggle_code_editor()
  8440. try:
  8441. if filename:
  8442. f = QtCore.QFile(filename)
  8443. if f.open(QtCore.QIODevice.ReadOnly):
  8444. stream = QtCore.QTextStream(f)
  8445. code_edited = stream.readAll()
  8446. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8447. f.close()
  8448. except IOError:
  8449. self.app.log.error("Failed to open config file: %s" % filename)
  8450. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8451. return
  8452. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8453. """
  8454. Loads a project from the specified file.
  8455. 1) Loads and parses file
  8456. 2) Registers the file as recently opened.
  8457. 3) Calls on_file_new()
  8458. 4) Updates options
  8459. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8460. 6) Calls plot_all() if plot=True
  8461. :param filename: Name of the file from which to load.
  8462. :param run_from_arg: True if run for arguments
  8463. :param plot: If True plot all objects in the project
  8464. :param cli: Run from command line
  8465. :param from_tcl: True if run from Tcl Sehll
  8466. :return: None
  8467. """
  8468. self.app.log.debug("Opening project: " + filename)
  8469. # block autosaving while a project is loaded
  8470. self.app.block_autosave = True
  8471. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8472. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8473. if cli is None:
  8474. self.app.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8475. if run_from_arg:
  8476. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8477. "Canvas initialization finished in"),
  8478. '%.2f' % self.app.used_time,
  8479. _("Opening FlatCAM Project file.")),
  8480. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8481. color=QtGui.QColor("gray"))
  8482. # Open and parse an uncompressed Project file
  8483. try:
  8484. f = open(filename, 'r')
  8485. except IOError:
  8486. if from_tcl:
  8487. name = filename.split('/')[-1].split('\\')[-1]
  8488. filename = self.defaults['global_tcl_path'] + '/' + name
  8489. try:
  8490. f = open(filename, 'r')
  8491. except IOError:
  8492. self.app.log.error("Failed to open project file: %s" % filename)
  8493. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8494. return
  8495. else:
  8496. self.app.log.error("Failed to open project file: %s" % filename)
  8497. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8498. return
  8499. try:
  8500. d = json.load(f, object_hook=dict2obj)
  8501. except Exception as e:
  8502. self.app.log.error(
  8503. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8504. (filename, str(e)))
  8505. f.close()
  8506. # Open and parse a compressed Project file
  8507. try:
  8508. with lzma.open(filename) as f:
  8509. file_content = f.read().decode('utf-8')
  8510. d = json.loads(file_content, object_hook=dict2obj)
  8511. except Exception as e:
  8512. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8513. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8514. return
  8515. # Clear the current project
  8516. # # NOT THREAD SAFE # ##
  8517. if run_from_arg is True:
  8518. pass
  8519. elif cli is True:
  8520. self.app.delete_selection_shape()
  8521. else:
  8522. self.on_file_new()
  8523. # Project options
  8524. self.app.options.update(d['options'])
  8525. self.app.project_filename = filename
  8526. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8527. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8528. if cli is None:
  8529. self.app.set_screen_units(self.app.options["units"])
  8530. # Re create objects
  8531. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8532. for obj in d['objs']:
  8533. def obj_init(obj_inst, app_inst):
  8534. try:
  8535. obj_inst.from_dict(obj)
  8536. except Exception as erro:
  8537. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8538. return 'fail'
  8539. self.app.log.debug(
  8540. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8541. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8542. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8543. if cli is None:
  8544. self.app.set_ui_title(name="{} {}: {}".format(
  8545. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8546. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8547. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8548. self.app.should_we_save = False
  8549. self.app.file_opened.emit("project", filename)
  8550. # restore autosaving after a project was loaded
  8551. self.app.block_autosave = False
  8552. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8553. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8554. if cli is None:
  8555. self.app.set_ui_title(name=self.app.project_filename)
  8556. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8557. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8558. """
  8559. Saves the current project to the specified file.
  8560. :param filename: Name of the file in which to save.
  8561. :type filename: str
  8562. :param quit_action: if the project saving will be followed by an app quit; boolean
  8563. :param silent: if True will not display status messages
  8564. :param from_tcl True is run from Tcl Shell
  8565. :return: None
  8566. """
  8567. self.app.log.debug("save_project()")
  8568. self.app.save_in_progress = True
  8569. if from_tcl:
  8570. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8571. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8572. # Capture the latest changes
  8573. # Current object
  8574. try:
  8575. current_object = self.app.collection.get_active()
  8576. if current_object:
  8577. current_object.read_form()
  8578. except Exception as e:
  8579. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8580. # Serialize the whole project
  8581. d = {
  8582. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8583. "options": self.app.options,
  8584. "version": self.app.version
  8585. }
  8586. if self.defaults["global_save_compressed"] is True:
  8587. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8588. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8589. # # Write
  8590. f.write(g)
  8591. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8592. else:
  8593. # Open file
  8594. try:
  8595. f = open(filename, 'w')
  8596. except IOError:
  8597. self.app.log.error("Failed to open file for saving: %s", filename)
  8598. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8599. return
  8600. # Write
  8601. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8602. f.close()
  8603. # verification of the saved project
  8604. # Open and parse
  8605. try:
  8606. saved_f = open(filename, 'r')
  8607. except IOError:
  8608. if silent is False:
  8609. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8610. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8611. return
  8612. try:
  8613. saved_d = json.load(saved_f, object_hook=dict2obj)
  8614. except Exception:
  8615. if silent is False:
  8616. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8617. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8618. f.close()
  8619. return
  8620. saved_f.close()
  8621. if silent is False:
  8622. if 'version' in saved_d:
  8623. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8624. else:
  8625. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8626. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8627. tb_settings = QSettings("Open Source", "FlatCAM")
  8628. lock_state = self.app.ui.lock_action.isChecked()
  8629. tb_settings.setValue('toolbar_lock', lock_state)
  8630. # This will write the setting to the platform specific storage.
  8631. del tb_settings
  8632. # if quit:
  8633. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8634. # t.start()
  8635. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8636. def save_source_file(self, obj_name, filename):
  8637. """
  8638. Exports a FlatCAM Object to an Gerber/Excellon file.
  8639. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8640. :param filename: Path to the Gerber file to save to.
  8641. :return:
  8642. """
  8643. if filename is None:
  8644. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8645. is not None else self.defaults["global_last_folder"]
  8646. self.app.log.debug("save source file()")
  8647. obj = self.app.collection.get_by_name(obj_name)
  8648. file_string = StringIO(obj.source_file)
  8649. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8650. if file_string.getvalue() == '':
  8651. self.inform.emit('[ERROR_NOTCL] %s' %
  8652. _("Save cancelled because source file is empty. Try to export the file."))
  8653. return 'fail'
  8654. try:
  8655. with open(filename, 'w') as file:
  8656. file.writelines('G04*\n')
  8657. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8658. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8659. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8660. file.writelines('G04 Created on : %s*\n' % time_string)
  8661. for line in file_string:
  8662. file.writelines(line)
  8663. except PermissionError:
  8664. self.inform.emit('[WARNING] %s' %
  8665. _("Permission denied, saving not possible.\n"
  8666. "Most likely another app is holding the file open and not accessible."))
  8667. return 'fail'
  8668. def on_file_savedefaults(self):
  8669. """
  8670. Callback for menu item File->Save Defaults. Saves application default options
  8671. ``self.defaults`` to current_defaults.FlatConfig.
  8672. :return: None
  8673. """
  8674. self.app.preferencesUiManager.save_defaults()
  8675. # end of file