app_Main.py 472 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520
  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
  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, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. self.defaults["root_folder_path"] = self.app_home
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### SYS TRAY ##################################################
  598. # ###########################################################################################################
  599. if self.defaults["global_systray_icon"]:
  600. self.parent_w = QtWidgets.QWidget()
  601. if self.cmd_line_headless == 1:
  602. self.trayIcon = FlatCAMSystemTray(app=self,
  603. icon=QtGui.QIcon(self.resource_location +
  604. '/flatcam_icon32_green.png'),
  605. headless=True,
  606. parent=self.parent_w)
  607. else:
  608. self.trayIcon = FlatCAMSystemTray(app=self,
  609. icon=QtGui.QIcon(self.resource_location +
  610. '/flatcam_icon32_green.png'),
  611. parent=self.parent_w)
  612. # ###########################################################################################################
  613. # ############################################### Worker SETUP ##############################################
  614. # ###########################################################################################################
  615. if self.defaults["global_worker_number"]:
  616. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  617. else:
  618. self.workers = WorkerStack(workers_number=2)
  619. self.worker_task.connect(self.workers.add_task)
  620. self.log.debug("Finished creating Workers crew.")
  621. # ###########################################################################################################
  622. # ############################################# Activity Monitor ###########################################
  623. # ###########################################################################################################
  624. # self.activity_view = FlatCAMActivityView(app=self)
  625. # self.ui.infobar.addWidget(self.activity_view)
  626. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  627. # ###########################################################################################################
  628. # ############################################# Signal handling #############################################
  629. # ###########################################################################################################
  630. # ########################################## Custom signals ################################################
  631. # signal for displaying messages in status bar
  632. self.inform[str].connect(self.info)
  633. self.inform[str, bool].connect(self.info)
  634. # signal for displaying messages in the shell
  635. self.inform_shell[str].connect(self.info_shell)
  636. self.inform_shell[str, bool].connect(self.info_shell)
  637. # signal to be called when the app is quiting
  638. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  639. self.message.connect(lambda: message_dialog(parent=self.ui))
  640. # self.progress.connect(self.set_progress_bar)
  641. # signals emitted when file state change
  642. self.file_opened.connect(self.register_recent)
  643. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  644. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  645. # when the defaults dictionary values change
  646. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  647. # ########################################## Standard signals ###############################################
  648. # ### Menu
  649. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  650. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  651. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  652. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  653. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  654. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  655. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  656. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  657. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  658. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  659. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  660. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  661. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  662. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  663. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  664. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  665. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  666. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  667. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  668. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  669. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  670. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  671. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  672. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  673. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  674. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  675. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  676. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  677. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  678. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  679. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  680. self.ui.menufile_exit.triggered.connect(self.final_save)
  681. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  682. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  683. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  684. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  685. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  686. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  687. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  688. self.ui.menueditdelete.triggered.connect(self.on_delete)
  689. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  690. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  691. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  692. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  693. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  694. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  695. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  696. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  697. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  698. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  699. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  700. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  701. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  702. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  703. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  704. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  705. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  706. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  707. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  708. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  709. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  710. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  711. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  712. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  713. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  714. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  715. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  716. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  717. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  718. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  719. self.ui.menuview_replot.triggered.connect(self.plot_all)
  720. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  721. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  722. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  723. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  724. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  725. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  726. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  727. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  728. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  729. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  730. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  731. self.ui.menuhelp_about.triggered.connect(self.on_about)
  732. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  733. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  734. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  735. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  736. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  737. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  738. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  739. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  740. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  741. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  742. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  743. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  744. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  745. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  746. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  747. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  748. # ToolBar signals
  749. self.connect_toolbar_signals(ui=self.ui)
  750. # Context Menu
  751. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  752. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  753. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  754. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  755. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  756. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  757. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  758. self.ui.clearplot.triggered.connect(self.clear_plots)
  759. self.ui.replot.triggered.connect(self.plot_all)
  760. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  761. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  762. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  763. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  764. self.ui.popmenu_move.triggered.connect(self.obj_move)
  765. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  766. # Project Context Menu -> Color Setting
  767. for act in self.ui.menuprojectcolor.actions():
  768. act.triggered.connect(self.on_set_color_action_triggered)
  769. # Notebook tab clicking
  770. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  771. # ###########################################################################################################
  772. # #################################### GUI PREFERENCES SIGNALS ##############################################
  773. # ###########################################################################################################
  774. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  775. lambda: self.on_toggle_units(no_pref=False))
  776. # ##################################### Workspace Setting Signals ###########################################
  777. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  778. self.on_workspace_modified)
  779. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  780. self.on_workspace_modified
  781. )
  782. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  783. # ###########################################################################################################
  784. # ######################################## GUI SETTINGS SIGNALS #############################################
  785. # ###########################################################################################################
  786. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  787. # ######################################## Tools related signals ############################################
  788. # portability changed signal
  789. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  790. # Object list
  791. self.object_status_changed.connect(self.collection.on_collection_updated)
  792. # when there are arguments at application startup this get launched
  793. self.args_at_startup[list].connect(self.on_startup_args)
  794. # ###########################################################################################################
  795. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  796. # ###########################################################################################################
  797. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  798. lambda: self.restore_extensions(ext_type='excellon'))
  799. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  800. lambda: self.restore_extensions(ext_type='gcode'))
  801. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  802. lambda: self.restore_extensions(ext_type='gerber'))
  803. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  804. lambda: self.delete_all_extensions(ext_type='excellon'))
  805. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  806. lambda: self.delete_all_extensions(ext_type='gcode'))
  807. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  808. lambda: self.delete_all_extensions(ext_type='gerber'))
  809. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  810. lambda: self.add_extension(ext_type='excellon'))
  811. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  812. lambda: self.add_extension(ext_type='gcode'))
  813. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  814. lambda: self.add_extension(ext_type='gerber'))
  815. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  816. lambda: self.del_extension(ext_type='excellon'))
  817. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  818. lambda: self.del_extension(ext_type='gcode'))
  819. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  820. lambda: self.del_extension(ext_type='gerber'))
  821. # connect the 'Apply' buttons from the Preferences/File Associations
  822. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  823. lambda: self.on_register_files(obj_type='excellon'))
  824. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  825. lambda: self.on_register_files(obj_type='gcode'))
  826. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  827. lambda: self.on_register_files(obj_type='gerber'))
  828. # ###########################################################################################################
  829. # ########################################### KEYWORDS SIGNALS ##############################################
  830. # ###########################################################################################################
  831. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  832. lambda: self.restore_extensions(ext_type='keyword'))
  833. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  834. lambda: self.delete_all_extensions(ext_type='keyword'))
  835. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  836. lambda: self.add_extension(ext_type='keyword'))
  837. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  838. lambda: self.del_extension(ext_type='keyword'))
  839. # ###########################################################################################################
  840. # ########################################### GUI SIGNALS ###################################################
  841. # ###########################################################################################################
  842. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  843. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  844. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  845. # ###########################################################################################################
  846. # ####################################### VARIOUS SIGNALS ###################################################
  847. # ###########################################################################################################
  848. # connect the abort_all_tasks related slots to the related signals
  849. self.proc_container.idle_flag.connect(self.app_is_idle)
  850. # signal emitted when a tab is closed in the Plot Area
  851. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  852. # signal to close the application
  853. self.close_app_signal.connect(self.kill_app)
  854. # ################################# FINISHED CONNECTING SIGNALS #############################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. self.log.debug("Finished connecting Signals.")
  859. # ###########################################################################################################
  860. # ########################################## Other setups ###################################################
  861. # ###########################################################################################################
  862. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  863. # depending on from where those tools are called different actions can be done
  864. self.call_source = 'app'
  865. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  866. self.tool_tab_locked = False
  867. # decide if to show or hide the Notebook side of the screen at startup
  868. if self.defaults["global_project_at_startup"] is True:
  869. self.ui.splitter.setSizes([1, 1])
  870. else:
  871. self.ui.splitter.setSizes([0, 1])
  872. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  873. self.setup_default_properties_tab()
  874. # ###########################################################################################################
  875. # ####################################### Auto-complete KEYWORDS ############################################
  876. # ###########################################################################################################
  877. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  878. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  879. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  880. 'export_exc',
  881. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  882. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  883. 'interiors', 'isolate', 'join_excellon',
  884. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  885. 'mirror', 'ncc',
  886. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  887. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  888. 'options', 'origin',
  889. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  890. 'save', 'save_project',
  891. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  892. 'skew', 'subtract_poly', 'subtract_rectangle',
  893. 'version', 'write_gcode'
  894. ]
  895. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  896. 'Paste_1',
  897. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  898. 'Toolchange_manual', 'True', 'Users',
  899. 'all', 'auto', 'axis',
  900. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  901. 'contour', 'default',
  902. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  903. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  904. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  905. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  906. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  907. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  908. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  909. 'spacing_columns',
  910. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  911. 'toolchange_xy', 'toolchangez', 'travelz',
  912. 'tooldia', 'use_threads', 'value',
  913. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  914. ]
  915. self.tcl_keywords = [
  916. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  917. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  918. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  919. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  920. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  921. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  922. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  923. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  924. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  925. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  926. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  927. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  928. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  929. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  930. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  931. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  932. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  933. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  934. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  935. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  936. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  937. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  938. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  939. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  940. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  941. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  942. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  943. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  944. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  945. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  946. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  947. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  948. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  949. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  950. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  951. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  952. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  953. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  954. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  955. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  956. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  957. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  958. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  959. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  960. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  961. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  962. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  963. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  964. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  965. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  966. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  967. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  968. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  969. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  970. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  971. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  972. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  973. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  974. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  975. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  976. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  977. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  978. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  979. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  980. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  981. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  982. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  983. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  984. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  985. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  986. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  987. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  988. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  989. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  990. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  991. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  992. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  993. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  994. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  995. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  996. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  997. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  998. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  999. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1000. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1001. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1002. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1003. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1004. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1005. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1006. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1007. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1008. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1009. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1010. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1011. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1012. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1013. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1014. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1015. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1016. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1017. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1018. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1019. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1020. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1021. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1022. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1023. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1024. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1025. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1026. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1027. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1028. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1029. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1030. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1031. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1032. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1033. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1034. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1035. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1036. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1037. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1038. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1039. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1040. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1041. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1042. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1043. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1044. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1045. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1046. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1047. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1048. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1049. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1050. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1051. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1052. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1053. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1054. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1055. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1056. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1057. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1058. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1059. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1060. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1061. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1062. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1063. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1064. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1065. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1066. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1067. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1068. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1069. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1070. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1071. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1072. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1073. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1074. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1075. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1076. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1077. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1078. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1079. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1080. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1081. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1082. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1083. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1084. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1085. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1086. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1087. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1088. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1089. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1090. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1091. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1092. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1093. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1094. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1095. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1096. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1097. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1098. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1099. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1100. ]
  1101. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1102. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1103. # ###########################################################################################################
  1104. # ########################################## Tools and Plugins ##############################################
  1105. # ###########################################################################################################
  1106. self.shell = None
  1107. self.dblsidedtool = None
  1108. self.distance_tool = None
  1109. self.distance_min_tool = None
  1110. self.panelize_tool = None
  1111. self.film_tool = None
  1112. self.paste_tool = None
  1113. self.calculator_tool = None
  1114. self.rules_tool = None
  1115. self.sub_tool = None
  1116. self.move_tool = None
  1117. self.cutout_tool = None
  1118. self.ncclear_tool = None
  1119. self.paint_tool = None
  1120. self.isolation_tool = None
  1121. self.drilling_tool = None
  1122. self.optimal_tool = None
  1123. self.transform_tool = None
  1124. self.properties_tool = None
  1125. self.pdf_tool = None
  1126. self.image_tool = None
  1127. self.pcb_wizard_tool = None
  1128. self.cal_exc_tool = None
  1129. self.qrcode_tool = None
  1130. self.copper_thieving_tool = None
  1131. self.fiducial_tool = None
  1132. self.edrills_tool = None
  1133. self.align_objects_tool = None
  1134. self.punch_tool = None
  1135. self.invert_tool = None
  1136. self.corners_tool = None
  1137. self.etch_tool = None
  1138. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1139. try:
  1140. self.install_tools()
  1141. except AttributeError as e:
  1142. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1143. # ###########################################################################################################
  1144. # ############################################ SETUP RECENT ITEMS ###########################################
  1145. # ###########################################################################################################
  1146. self.setup_recent_items()
  1147. # ###########################################################################################################
  1148. # ######################################### BookMarks Manager ###############################################
  1149. # ###########################################################################################################
  1150. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1151. self.install_bookmarks()
  1152. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1153. # ###########################################################################################################
  1154. # ########################################### Tools Database ################################################
  1155. # ###########################################################################################################
  1156. self.tools_db_tab = None
  1157. # ### System Font Parsing ###
  1158. # self.f_parse = ParseFont(self)
  1159. # self.parse_system_fonts()
  1160. # ###########################################################################################################
  1161. # ############################################## Shell SETUP ################################################
  1162. # ###########################################################################################################
  1163. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1164. if self.defaults["global_shell_at_startup"]:
  1165. self.ui.shell_dock.show()
  1166. else:
  1167. self.ui.shell_dock.hide()
  1168. # ###########################################################################################################
  1169. # ######################################### Check for updates ###############################################
  1170. # ###########################################################################################################
  1171. # Separate thread (Not worker)
  1172. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1173. if (self.beta is False or self.beta is None) and \
  1174. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1175. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1176. # self.thr2 = QtCore.QThread()
  1177. self.worker_task.emit({'fcn': self.version_check,
  1178. 'params': []})
  1179. # self.thr2.start(QtCore.QThread.LowPriority)
  1180. # ###########################################################################################################
  1181. # ##################################### Register files with FlatCAM; #######################################
  1182. # ################################### It works only for Windows for now ####################################
  1183. # ###########################################################################################################
  1184. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1185. self.on_register_files()
  1186. # ###########################################################################################################
  1187. # ######################################## Variables for global usage #######################################
  1188. # ###########################################################################################################
  1189. # hold the App units
  1190. self.units = 'MM'
  1191. # coordinates for relative position display
  1192. self.rel_point1 = (0, 0)
  1193. self.rel_point2 = (0, 0)
  1194. # variable to store coordinates
  1195. self.pos = (0, 0)
  1196. self.pos_canvas = (0, 0)
  1197. self.pos_jump = (0, 0)
  1198. # variable to store mouse coordinates
  1199. self.mouse = [0, 0]
  1200. # variable to store the delta positions on cavnas
  1201. self.dx = 0
  1202. self.dy = 0
  1203. # decide if we have a double click or single click
  1204. self.doubleclick = False
  1205. # store here the is_dragging value
  1206. self.event_is_dragging = False
  1207. # variable to store if a command is active (then the var is not None) and which one it is
  1208. self.command_active = None
  1209. # variable to store the status of moving selection action
  1210. # None value means that it's not an selection action
  1211. # True value = a selection from left to right
  1212. # False value = a selection from right to left
  1213. self.selection_type = None
  1214. # List to store the objects that are currently loaded in FlatCAM
  1215. # This list is updated on each object creation or object delete
  1216. self.all_objects_list = []
  1217. self.objects_under_the_click_list = []
  1218. # List to store the objects that are selected
  1219. self.sel_objects_list = []
  1220. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1221. self.key_modifiers = None
  1222. # Variable to store the status of the code editor
  1223. self.toggle_codeeditor = False
  1224. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1225. self.click_noproject = False
  1226. self.cursor = None
  1227. # Variable to store the GCODE that was edited
  1228. self.gcode_edited = ""
  1229. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  1230. self.old_state_of_tools_toolbar = False
  1231. self.text_editor_tab = None
  1232. # reference for the self.ui.code_editor
  1233. self.reference_code_editor = None
  1234. self.script_code = ''
  1235. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1236. self.tools_db_changed_flag = False
  1237. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1238. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1239. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1240. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1241. 'tsm']
  1242. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1243. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1244. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1245. 'sbp', 'tap', 'xpi']
  1246. self.svg_list = ['svg']
  1247. self.dxf_list = ['dxf']
  1248. self.pdf_list = ['pdf']
  1249. self.prj_list = ['flatprj']
  1250. self.conf_list = ['flatconfig']
  1251. # last used filters
  1252. self.last_op_gerber_filter = None
  1253. self.last_op_excellon_filter = None
  1254. self.last_op_gcode_filter = None
  1255. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1256. # flag for polygons not cleared
  1257. self.poly_not_cleared = False
  1258. # VisPy visuals
  1259. self.isHovering = False
  1260. self.notHovering = True
  1261. # Window geometry
  1262. self.x_pos = None
  1263. self.y_pos = None
  1264. self.width = None
  1265. self.height = None
  1266. # when True, the app has to return from any thread
  1267. self.abort_flag = False
  1268. # set the value used in the Windows Title
  1269. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1270. # this holds a widget that is installed in the Plot Area when View Source option is used
  1271. self.source_editor_tab = None
  1272. self.pagesize = {}
  1273. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1274. # VisPy visuals
  1275. if self.is_legacy is False:
  1276. try:
  1277. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1278. except AttributeError:
  1279. self.tool_shapes = None
  1280. else:
  1281. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1282. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1283. # used in the delayed shutdown self.start_delayed_quit() method
  1284. self.save_timer = None
  1285. # ###########################################################################################################
  1286. # ################################## ADDING FlatCAM EDITORS section #########################################
  1287. # ###########################################################################################################
  1288. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1289. # at the first launch of the App , the editors will not be functional.
  1290. try:
  1291. self.geo_editor = AppGeoEditor(self)
  1292. except Exception as es:
  1293. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1294. try:
  1295. self.exc_editor = AppExcEditor(self)
  1296. except Exception as es:
  1297. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1298. try:
  1299. self.grb_editor = AppGerberEditor(self)
  1300. except Exception as es:
  1301. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1302. try:
  1303. self.gcode_editor = AppGCodeEditor(self)
  1304. except Exception as es:
  1305. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1306. self.log.debug("Finished adding FlatCAM Editor's.")
  1307. self.set_ui_title(name=_("New Project - Not saved"))
  1308. current_platform = platform.architecture()[0]
  1309. if current_platform != '64bit':
  1310. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1311. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1312. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1314. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1315. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1316. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1317. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1318. # ###########################################################################################################
  1319. # ########################################### EXCLUSION AREAS ###############################################
  1320. # ###########################################################################################################
  1321. self.exc_areas = ExclusionAreas(app=self)
  1322. # ###########################################################################################################
  1323. # ##################################### Finished the CONSTRUCTOR ############################################
  1324. # ###########################################################################################################
  1325. App.log.debug("END of constructor. Releasing control.")
  1326. # ###########################################################################################################
  1327. # ########################################## SHOW GUI #######################################################
  1328. # ###########################################################################################################
  1329. # if the app is not started as headless, show it
  1330. if self.cmd_line_headless != 1:
  1331. if show_splash:
  1332. # finish the splash
  1333. self.splash.finish(self.ui)
  1334. mgui_settings = QSettings("Open Source", "FlatCAM")
  1335. if mgui_settings.contains("maximized_gui"):
  1336. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1337. if maximized_ui is True:
  1338. self.ui.showMaximized()
  1339. else:
  1340. self.ui.show()
  1341. else:
  1342. self.ui.show()
  1343. if self.defaults["global_systray_icon"]:
  1344. self.trayIcon.show()
  1345. else:
  1346. log.warning("******************* RUNNING HEADLESS *******************")
  1347. # ###########################################################################################################
  1348. # ######################################## START-UP ARGUMENTS ###############################################
  1349. # ###########################################################################################################
  1350. # test if the program was started with a script as parameter
  1351. if self.cmd_line_shellvar:
  1352. try:
  1353. cnt = 0
  1354. command_tcl = 0
  1355. for i in self.cmd_line_shellvar.split(','):
  1356. if i is not None:
  1357. # noinspection PyBroadException
  1358. try:
  1359. command_tcl = eval(i)
  1360. except Exception:
  1361. command_tcl = i
  1362. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1363. cnt += 1
  1364. # if there are Windows paths then replace the path separator with a Unix like one
  1365. if sys.platform == 'win32':
  1366. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1367. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1368. except Exception as ext:
  1369. print("ERROR: ", ext)
  1370. sys.exit(2)
  1371. if self.cmd_line_shellfile:
  1372. if self.cmd_line_headless != 1:
  1373. if self.ui.shell_dock.isHidden():
  1374. self.ui.shell_dock.show()
  1375. try:
  1376. with open(self.cmd_line_shellfile, "r") as myfile:
  1377. # if show_splash:
  1378. # self.splash.showMessage('%s: %ssec\n%s' % (
  1379. # _("Canvas initialization started.\n"
  1380. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1381. # _("Executing Tcl Script ...")),
  1382. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1383. # color=QtGui.QColor("gray"))
  1384. cmd_line_shellfile_text = myfile.read()
  1385. if self.cmd_line_headless != 1:
  1386. self.shell.exec_command(cmd_line_shellfile_text)
  1387. else:
  1388. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1389. except Exception as ext:
  1390. print("ERROR: ", ext)
  1391. sys.exit(2)
  1392. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1393. # the path/file_name must be enclosed in quotes if it contain spaces
  1394. if App.args:
  1395. self.args_at_startup.emit(App.args)
  1396. if self.defaults.old_defaults_found is True:
  1397. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1398. "Please reboot the application to update."))
  1399. self.defaults.old_defaults_found = False
  1400. # ######################################### INIT FINISHED #######################################################
  1401. # #################################################################################################################
  1402. # #################################################################################################################
  1403. # #################################################################################################################
  1404. # #################################################################################################################
  1405. # #################################################################################################################
  1406. @staticmethod
  1407. def copy_and_overwrite(from_path, to_path):
  1408. """
  1409. From here:
  1410. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1411. :param from_path: source path
  1412. :param to_path: destination path
  1413. :return: None
  1414. """
  1415. if os.path.exists(to_path):
  1416. shutil.rmtree(to_path)
  1417. try:
  1418. shutil.copytree(from_path, to_path)
  1419. except FileNotFoundError:
  1420. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1421. shutil.copytree(from_new_path, to_path)
  1422. def on_startup_args(self, args, silent=False):
  1423. """
  1424. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1425. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1426. :param args: a list containing the application args at startup
  1427. :return: None
  1428. """
  1429. if args is not None:
  1430. args_to_process = args
  1431. else:
  1432. args_to_process = App.args
  1433. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1434. for argument in args_to_process:
  1435. if '.FlatPrj'.lower() in argument.lower():
  1436. try:
  1437. project_name = str(argument)
  1438. if project_name == "":
  1439. if silent is False:
  1440. self.inform.emit(_("Cancelled."))
  1441. else:
  1442. # self.open_project(project_name)
  1443. run_from_arg = True
  1444. # self.worker_task.emit({'fcn': self.open_project,
  1445. # 'params': [project_name, run_from_arg]})
  1446. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1447. except Exception as e:
  1448. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1449. elif '.FlatConfig'.lower() in argument.lower():
  1450. try:
  1451. file_name = str(argument)
  1452. if file_name == "":
  1453. if silent is False:
  1454. self.inform.emit(_("Open Config file failed."))
  1455. else:
  1456. run_from_arg = True
  1457. # self.worker_task.emit({'fcn': self.open_config_file,
  1458. # 'params': [file_name, run_from_arg]})
  1459. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1460. except Exception as e:
  1461. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1462. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1463. try:
  1464. file_name = str(argument)
  1465. if file_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Open Script file failed."))
  1468. else:
  1469. if silent is False:
  1470. self.on_fileopenscript(name=file_name)
  1471. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1472. self.on_filerunscript(name=file_name)
  1473. except Exception as e:
  1474. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1475. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1476. log.debug("App.on_startup_args() --> Quit event.")
  1477. sys.exit()
  1478. elif 'save'.lower() in argument.lower():
  1479. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1480. self.preferencesUiManager.save_defaults()
  1481. else:
  1482. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1483. proc_arg = argument.lower()
  1484. for ext in exc_list:
  1485. proc_ext = ext.replace(' ', '')
  1486. proc_ext = '.%s' % proc_ext
  1487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1488. file_name = str(argument)
  1489. if file_name == "":
  1490. if silent is False:
  1491. self.inform.emit(_("Open Excellon file failed."))
  1492. else:
  1493. self.on_fileopenexcellon(name=file_name, signal=None)
  1494. return
  1495. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1496. for ext in gco_list:
  1497. proc_ext = ext.replace(' ', '')
  1498. proc_ext = '.%s' % proc_ext
  1499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1500. file_name = str(argument)
  1501. if file_name == "":
  1502. if silent is False:
  1503. self.inform.emit(_("Open GCode file failed."))
  1504. else:
  1505. self.on_fileopengcode(name=file_name, signal=None)
  1506. return
  1507. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1508. for ext in grb_list:
  1509. proc_ext = ext.replace(' ', '')
  1510. proc_ext = '.%s' % proc_ext
  1511. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1512. file_name = str(argument)
  1513. if file_name == "":
  1514. if silent is False:
  1515. self.inform.emit(_("Open Gerber file failed."))
  1516. else:
  1517. self.on_fileopengerber(name=file_name, signal=None)
  1518. return
  1519. # if it reached here without already returning then the app was registered with a file that it does not
  1520. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1521. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1522. # for arg in args_to_process:
  1523. # if 'FlatCAM.exe' in arg:
  1524. # continue
  1525. # else:
  1526. # sys.exit(2)
  1527. def set_ui_title(self, name):
  1528. """
  1529. Sets the title of the main window.
  1530. :param name: String that store the project path and project name
  1531. :return: None
  1532. """
  1533. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1534. (self.version,
  1535. ('BETA' if self.beta else ''),
  1536. platform.architecture()[0],
  1537. self.engine,
  1538. name)
  1539. )
  1540. def on_app_restart(self):
  1541. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1542. # be left in the SySTray
  1543. try:
  1544. self.trayIcon.hide()
  1545. except Exception:
  1546. pass
  1547. fcTranslate.restart_program(app=self)
  1548. def clear_pool(self):
  1549. """
  1550. Clear the multiprocessing pool and calls garbage collector.
  1551. :return: None
  1552. """
  1553. self.pool.close()
  1554. self.pool = Pool()
  1555. self.pool_recreated.emit(self.pool)
  1556. gc.collect()
  1557. def install_tools(self):
  1558. """
  1559. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1560. Instantiation of the Tools classes.
  1561. The order that the tools are installed is important as they can depend on each other install position.
  1562. :return: None
  1563. """
  1564. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1565. self.shell = FCShell(app=self, version=self.version)
  1566. self.distance_tool = Distance(self)
  1567. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1568. before=self.ui.menueditorigin,
  1569. separator=False)
  1570. self.distance_min_tool = DistanceMin(self)
  1571. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1572. pos=self.ui.menuedit,
  1573. before=self.ui.menueditorigin,
  1574. separator=True)
  1575. self.dblsidedtool = DblSidedTool(self)
  1576. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1577. self.cal_exc_tool = ToolCalibration(self)
  1578. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1579. before=self.dblsidedtool.menuAction,
  1580. separator=False)
  1581. self.align_objects_tool = AlignObjects(self)
  1582. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1583. self.edrills_tool = ToolExtractDrills(self)
  1584. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1585. self.panelize_tool = Panelize(self)
  1586. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1587. self.film_tool = Film(self)
  1588. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1589. self.paste_tool = SolderPaste(self)
  1590. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1591. self.calculator_tool = ToolCalculator(self)
  1592. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1593. self.sub_tool = ToolSub(self)
  1594. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1595. pos=self.ui.menutool, separator=True)
  1596. self.rules_tool = RulesCheck(self)
  1597. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1598. pos=self.ui.menutool, separator=False)
  1599. self.optimal_tool = ToolOptimal(self)
  1600. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1601. pos=self.ui.menutool, separator=True)
  1602. self.move_tool = ToolMove(self)
  1603. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1604. before=self.ui.menueditorigin, separator=True)
  1605. self.cutout_tool = CutOut(self)
  1606. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1607. before=self.sub_tool.menuAction)
  1608. self.ncclear_tool = NonCopperClear(self)
  1609. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1610. before=self.sub_tool.menuAction, separator=True)
  1611. self.paint_tool = ToolPaint(self)
  1612. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1613. before=self.sub_tool.menuAction, separator=True)
  1614. self.isolation_tool = ToolIsolation(self)
  1615. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1616. before=self.sub_tool.menuAction, separator=True)
  1617. self.drilling_tool = ToolDrilling(self)
  1618. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1619. before=self.sub_tool.menuAction, separator=True)
  1620. self.copper_thieving_tool = ToolCopperThieving(self)
  1621. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1622. pos=self.ui.menutool)
  1623. self.fiducial_tool = ToolFiducials(self)
  1624. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1625. pos=self.ui.menutool)
  1626. self.qrcode_tool = QRCode(self)
  1627. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1628. pos=self.ui.menutool)
  1629. self.punch_tool = ToolPunchGerber(self)
  1630. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1631. self.invert_tool = ToolInvertGerber(self)
  1632. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1633. self.corners_tool = ToolCorners(self)
  1634. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1635. self.etch_tool = ToolEtchCompensation(self)
  1636. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1637. self.transform_tool = ToolTransform(self)
  1638. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1639. pos=self.ui.menuoptions, separator=True)
  1640. self.properties_tool = Properties(self)
  1641. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1642. pos=self.ui.menuoptions)
  1643. self.pdf_tool = ToolPDF(self)
  1644. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1645. pos=self.ui.menufileimport,
  1646. separator=True)
  1647. self.image_tool = ToolImage(self)
  1648. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1649. pos=self.ui.menufileimport,
  1650. separator=True)
  1651. self.pcb_wizard_tool = PcbWizard(self)
  1652. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1653. pos=self.ui.menufileimport)
  1654. self.log.debug("Tools are installed.")
  1655. def remove_tools(self):
  1656. """
  1657. Will remove all the actions in the Tool menu.
  1658. :return: None
  1659. """
  1660. for act in self.ui.menutool.actions():
  1661. self.ui.menutool.removeAction(act)
  1662. def init_tools(self):
  1663. """
  1664. Initialize the Tool tab in the notebook side of the central widget.
  1665. Remove the actions in the Tools menu.
  1666. Instantiate again the FlatCAM tools (plugins).
  1667. All this is required when changing the layout: standard, compact etc.
  1668. :return: None
  1669. """
  1670. log.debug("init_tools()")
  1671. # delete the data currently in the Tools Tab and the Tab itself
  1672. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1673. if widget is not None:
  1674. widget.deleteLater()
  1675. self.ui.notebook.removeTab(2)
  1676. # rebuild the Tools Tab
  1677. self.ui.tool_tab = QtWidgets.QWidget()
  1678. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1679. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1680. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1681. self.ui.tool_scroll_area = VerticalScrollArea()
  1682. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1683. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1684. # first remove all of them
  1685. self.remove_tools()
  1686. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1687. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1688. '&Command Line\tS')
  1689. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1690. # third install all of them
  1691. try:
  1692. self.install_tools()
  1693. except AttributeError:
  1694. pass
  1695. self.log.debug("Tools are initialized.")
  1696. # def parse_system_fonts(self):
  1697. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1698. # 'params': []})
  1699. def connect_tools_signals_to_toolbar(self, ui):
  1700. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1701. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1702. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1703. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1704. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1705. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1706. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1707. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1708. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1709. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1710. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1711. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1712. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1713. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1714. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1715. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1716. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1717. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1718. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1719. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1720. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1721. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1722. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1723. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1724. def connect_toolbar_signals(self, ui):
  1725. """
  1726. Reconnect the signals to the actions in the toolbar.
  1727. This has to be done each time after the FlatCAM tools are removed/installed.
  1728. :return: None
  1729. """
  1730. # Toolbar
  1731. # File Toolbar Signals
  1732. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1733. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1734. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1735. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1736. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1737. # View Toolbar Signals
  1738. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1739. ui.replot_btn.triggered.connect(self.plot_all)
  1740. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1741. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1742. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1743. # Edit Toolbar Signals
  1744. ui.editgeo_btn.triggered.connect(self.object2editor)
  1745. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1746. ui.copy_btn.triggered.connect(self.on_copy_command)
  1747. ui.delete_btn.triggered.connect(self.on_delete)
  1748. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1749. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1750. ui.origin_btn.triggered.connect(self.on_set_origin)
  1751. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1752. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1753. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1754. # Scripting Toolbar Signals
  1755. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1756. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1757. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1758. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1759. # Tools Toolbar Signals
  1760. try:
  1761. self.connect_tools_signals_to_toolbar(ui=ui)
  1762. except Exception as err:
  1763. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1764. def object2editor(self):
  1765. """
  1766. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1767. :return: None
  1768. """
  1769. self.defaults.report_usage("object2editor()")
  1770. # disable the objects menu as it may interfere with the appEditors
  1771. self.ui.menuobjects.setDisabled(True)
  1772. edited_object = self.collection.get_active()
  1773. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1774. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1775. pass
  1776. else:
  1777. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1778. return
  1779. if isinstance(edited_object, GeometryObject):
  1780. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1781. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1782. # we set the notebook to hidden
  1783. # self.ui.splitter.setSizes([0, 1])
  1784. if edited_object.multigeo is True:
  1785. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1786. if len(sel_rows) > 1:
  1787. self.inform.emit('[WARNING_NOTCL] %s' %
  1788. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1789. "is not possible.\n"
  1790. "Edit only one geometry at a time."))
  1791. if not sel_rows:
  1792. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1793. return
  1794. # determine the tool dia of the selected tool
  1795. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1796. # now find the key in the edited_object.tools that has this tooldia
  1797. multi_tool = 1
  1798. for tool in edited_object.tools:
  1799. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1800. multi_tool = tool
  1801. break
  1802. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1803. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1804. else:
  1805. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1806. self.geo_editor.edit_fcgeometry(edited_object)
  1807. # set call source to the Editor we go into
  1808. self.call_source = 'geo_editor'
  1809. elif isinstance(edited_object, ExcellonObject):
  1810. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1811. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1812. if self.ui.splitter.sizes()[0] == 0:
  1813. self.ui.splitter.setSizes([1, 1])
  1814. self.exc_editor.edit_fcexcellon(edited_object)
  1815. # set call source to the Editor we go into
  1816. self.call_source = 'exc_editor'
  1817. elif isinstance(edited_object, GerberObject):
  1818. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1819. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1820. if self.ui.splitter.sizes()[0] == 0:
  1821. self.ui.splitter.setSizes([1, 1])
  1822. self.grb_editor.edit_fcgerber(edited_object)
  1823. # set call source to the Editor we go into
  1824. self.call_source = 'grb_editor'
  1825. # reset the following variables so the UI is built again after edit
  1826. edited_object.ui_build = False
  1827. elif isinstance(edited_object, CNCJobObject):
  1828. if self.ui.splitter.sizes()[0] == 0:
  1829. self.ui.splitter.setSizes([1, 1])
  1830. # set call source to the Editor we go into
  1831. self.call_source = 'gcode_editor'
  1832. self.gcode_editor.edit_fcgcode(edited_object)
  1833. # make sure that we can't select another object while in Editor Mode:
  1834. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1835. self.ui.project_frame.setDisabled(True)
  1836. # delete any selection shape that might be active as they are not relevant in Editor
  1837. self.delete_selection_shape()
  1838. # hide the Tools Toolbar
  1839. tools_tb = self.ui.toolbartools
  1840. if tools_tb.isVisible():
  1841. self.old_state_of_tools_toolbar = True
  1842. tools_tb.hide()
  1843. else:
  1844. self.old_state_of_tools_toolbar = False
  1845. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1846. self.ui.plot_tab_area.protectTab(0)
  1847. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1848. self.should_we_save = True
  1849. def editor2object(self, cleanup=None):
  1850. """
  1851. Transfers the Geometry or Excellon from it's editor to the current object.
  1852. :return: None
  1853. """
  1854. self.defaults.report_usage("editor2object()")
  1855. # re-enable the objects menu that was disabled on entry in Editor mode
  1856. self.ui.menuobjects.setDisabled(False)
  1857. # do not update a geometry or excellon object unless it comes out of an editor
  1858. if self.call_source != 'app':
  1859. edited_obj = self.collection.get_active()
  1860. if cleanup is None:
  1861. msgbox = QtWidgets.QMessageBox()
  1862. msgbox.setText(_("Do you want to save the edited object?"))
  1863. msgbox.setWindowTitle(_("Close Editor"))
  1864. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1865. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1866. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1867. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1868. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1869. msgbox.setDefaultButton(bt_yes)
  1870. msgbox.exec_()
  1871. response = msgbox.clickedButton()
  1872. if response == bt_yes:
  1873. # show the Tools Toolbar
  1874. tools_tb = self.ui.toolbartools
  1875. if self.old_state_of_tools_toolbar is True:
  1876. tools_tb.show()
  1877. # clean the Tools Tab
  1878. self.ui.tool_scroll_area.takeWidget()
  1879. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1880. self.ui.notebook.setTabText(2, _("Tool"))
  1881. if edited_obj.kind == 'geometry':
  1882. obj_type = "Geometry"
  1883. self.geo_editor.update_fcgeometry(edited_obj)
  1884. # self.geo_editor.update_options(edited_obj)
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the appGUI
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. # update the geo object options so it is including the bounding box values
  1889. try:
  1890. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1891. edited_obj.options['xmin'] = xmin
  1892. edited_obj.options['ymin'] = ymin
  1893. edited_obj.options['xmax'] = xmax
  1894. edited_obj.options['ymax'] = ymax
  1895. except AttributeError as e:
  1896. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1897. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1898. edited_obj.build_ui()
  1899. edited_obj.plot()
  1900. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1901. elif edited_obj.kind == 'gerber':
  1902. obj_type = "Gerber"
  1903. self.grb_editor.update_fcgerber()
  1904. # self.grb_editor.update_options(edited_obj)
  1905. # delete the old object (the source object) if it was an empty one
  1906. try:
  1907. if len(edited_obj.solid_geometry) == 0:
  1908. old_name = edited_obj.options['name']
  1909. self.collection.delete_by_name(old_name)
  1910. except TypeError:
  1911. # if the solid_geometry is a single Polygon the len() will not work
  1912. # in any case, falling here means that we have something in the solid_geometry, even if only
  1913. # a single Polygon, therefore we pass this
  1914. pass
  1915. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1916. # restore GUI to the Selected TAB
  1917. # Remove anything else in the GUI
  1918. self.ui.properties_scroll_area.takeWidget()
  1919. elif edited_obj.kind == 'excellon':
  1920. obj_type = "Excellon"
  1921. self.exc_editor.update_fcexcellon(edited_obj)
  1922. # self.exc_editor.update_options(edited_obj)
  1923. # restore GUI to the Selected TAB
  1924. # Remove anything else in the GUI
  1925. self.ui.tool_scroll_area.takeWidget()
  1926. # delete the old object (the source object) if it was an empty one
  1927. # find if we have drills:
  1928. has_drills = None
  1929. for tt in edited_obj.tools:
  1930. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1931. has_drills = True
  1932. break
  1933. # find if we have slots:
  1934. has_slots = None
  1935. for tt in edited_obj.tools:
  1936. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1937. has_slots = True
  1938. break
  1939. if has_drills is None and has_slots is None:
  1940. old_name = edited_obj.options['name']
  1941. self.collection.delete_by_name(name=old_name)
  1942. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1943. elif edited_obj.kind == 'cncjob':
  1944. obj_type = "CNCJob"
  1945. self.gcode_editor.update_fcgcode(edited_obj)
  1946. # self.exc_editor.update_options(edited_obj)
  1947. # restore GUI to the Selected TAB
  1948. # Remove anything else in the GUI
  1949. self.ui.tool_scroll_area.takeWidget()
  1950. edited_obj.build_ui()
  1951. # close the open tab
  1952. for idx in range(self.ui.plot_tab_area.count()):
  1953. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1954. self.ui.plot_tab_area.closeTab(idx)
  1955. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1956. else:
  1957. self.inform.emit('[WARNING_NOTCL] %s' %
  1958. _("Select a Gerber, Geometry, Excellon or CNCJobObject to update."))
  1959. return
  1960. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1961. elif response == bt_no:
  1962. # show the Tools Toolbar
  1963. tools_tb = self.ui.toolbartools
  1964. if self.old_state_of_tools_toolbar is True:
  1965. tools_tb.show()
  1966. # clean the Tools Tab
  1967. self.ui.tool_scroll_area.takeWidget()
  1968. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1969. self.ui.notebook.setTabText(2, _("Tool"))
  1970. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1971. if edited_obj.kind == 'geometry':
  1972. self.geo_editor.deactivate()
  1973. edited_obj.build_ui()
  1974. edited_obj.plot()
  1975. elif edited_obj.kind == 'gerber':
  1976. self.grb_editor.deactivate_grb_editor()
  1977. edited_obj.build_ui()
  1978. elif edited_obj.kind == 'excellon':
  1979. self.exc_editor.deactivate()
  1980. edited_obj.build_ui()
  1981. elif edited_obj.kind == 'cncjob':
  1982. self.gcode_editor.deactivate()
  1983. edited_obj.build_ui()
  1984. # close the open tab
  1985. for idx in range(self.ui.plot_tab_area.count()):
  1986. try:
  1987. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1988. self.ui.plot_tab_area.closeTab(idx)
  1989. except AttributeError:
  1990. continue
  1991. else:
  1992. self.inform.emit('[WARNING_NOTCL] %s' %
  1993. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1994. return
  1995. elif response == bt_cancel:
  1996. return
  1997. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1998. # edited_obj.build_ui()
  1999. # Switch notebook to Properties page
  2000. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2001. else:
  2002. # show the Tools Toolbar
  2003. tools_tb = self.ui.toolbartools
  2004. if self.old_state_of_tools_toolbar is True:
  2005. tools_tb.show()
  2006. if isinstance(edited_obj, GeometryObject):
  2007. self.geo_editor.deactivate()
  2008. elif isinstance(edited_obj, GerberObject):
  2009. self.grb_editor.deactivate_grb_editor()
  2010. elif isinstance(edited_obj, ExcellonObject):
  2011. self.exc_editor.deactivate()
  2012. else:
  2013. self.inform.emit('[WARNING_NOTCL] %s' %
  2014. _("Select a Gerber, Geometry or Excellon Object to update."))
  2015. return
  2016. # if notebook is hidden we show it
  2017. if self.ui.splitter.sizes()[0] == 0:
  2018. self.ui.splitter.setSizes([1, 1])
  2019. # restore the call_source to app
  2020. self.call_source = 'app'
  2021. # edited_obj.plot()
  2022. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2023. self.ui.plot_tab_area.protectTab(0)
  2024. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2025. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2026. self.ui.project_frame.setDisabled(False)
  2027. def get_last_folder(self):
  2028. """
  2029. Get the folder path from where the last file was opened.
  2030. :return: String, last opened folder path
  2031. """
  2032. return self.defaults["global_last_folder"]
  2033. def get_last_save_folder(self):
  2034. """
  2035. Get the folder path from where the last file was saved.
  2036. :return: String, last saved folder path
  2037. """
  2038. loc = self.defaults["global_last_save_folder"]
  2039. if loc is None:
  2040. loc = self.defaults["global_last_folder"]
  2041. if loc is None:
  2042. loc = os.path.dirname(__file__)
  2043. return loc
  2044. @QtCore.pyqtSlot(str)
  2045. @QtCore.pyqtSlot(str, bool)
  2046. def info(self, msg, shell_echo=True):
  2047. """
  2048. Informs the user. Normally on the status bar, optionally
  2049. also on the shell.
  2050. :param msg: Text to write.
  2051. :type msg: str
  2052. :param shell_echo: Control if to display the message msg in the Shell
  2053. :type shell_echo: bool
  2054. :return: None
  2055. """
  2056. # Type of message in brackets at the beginning of the message.
  2057. match = re.search(r"\[(.*)\](.*)", msg)
  2058. if match:
  2059. level = match.group(1)
  2060. msg_ = match.group(2)
  2061. self.ui.fcinfo.set_status(str(msg_), level=level)
  2062. if shell_echo is True:
  2063. if level.lower() == "error":
  2064. self.shell_message(msg, error=True, show=True)
  2065. elif level.lower() == "warning":
  2066. self.shell_message(msg, warning=True, show=True)
  2067. elif level.lower() == "error_notcl":
  2068. self.shell_message(msg, error=True, show=False)
  2069. elif level.lower() == "warning_notcl":
  2070. self.shell_message(msg, warning=True, show=False)
  2071. elif level.lower() == "success":
  2072. self.shell_message(msg, success=True, show=False)
  2073. elif level.lower() == "selected":
  2074. self.shell_message(msg, selected=True, show=False)
  2075. else:
  2076. self.shell_message(msg, show=False)
  2077. else:
  2078. self.ui.fcinfo.set_status(str(msg), level="info")
  2079. # make sure that if the message is to clear the infobar with a space
  2080. # is not printed over and over on the shell
  2081. if msg != '' and shell_echo is True:
  2082. self.shell_message(msg)
  2083. def info_shell(self, msg, new_line=True):
  2084. self.shell_message(msg=msg, new_line=new_line)
  2085. def on_import_preferences(self):
  2086. """
  2087. Loads the application default settings from a saved file into
  2088. ``self.defaults`` dictionary.
  2089. :return: None
  2090. """
  2091. self.defaults.report_usage("on_import_preferences")
  2092. App.log.debug("App.on_import_preferences()")
  2093. # Show file chooser
  2094. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2095. try:
  2096. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2097. directory=self.data_path,
  2098. filter=filter_)
  2099. except TypeError:
  2100. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2101. filter=filter_)
  2102. filename = str(filename)
  2103. if filename == "":
  2104. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2105. return
  2106. # Load in the defaults from the chosen file
  2107. self.defaults.load(filename=filename, inform=self.inform)
  2108. self.preferencesUiManager.on_preferences_edited()
  2109. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2110. def on_export_preferences(self):
  2111. """
  2112. Save the defaults dictionary to a file.
  2113. :return: None
  2114. """
  2115. self.defaults.report_usage("on_export_preferences")
  2116. App.log.debug("on_export_preferences()")
  2117. # defaults_file_content = None
  2118. # Show file chooser
  2119. date = str(datetime.today()).rpartition('.')[0]
  2120. date = ''.join(c for c in date if c not in ':-')
  2121. date = date.replace(' ', '_')
  2122. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2123. try:
  2124. filename, _f = FCFileSaveDialog.get_saved_filename(
  2125. caption=_("Export FlatCAM Preferences"),
  2126. directory=self.data_path + '/preferences_' + date,
  2127. ext_filter=filter__
  2128. )
  2129. except TypeError:
  2130. filename, _f = FCFileSaveDialog.get_saved_filename(
  2131. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2132. filename = str(filename)
  2133. if filename == "":
  2134. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2135. return
  2136. # Update options
  2137. self.preferencesUiManager.defaults_read_form()
  2138. self.defaults.propagate_defaults()
  2139. # Save update options
  2140. try:
  2141. self.defaults.write(filename=filename)
  2142. except Exception:
  2143. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2144. return
  2145. if self.defaults["global_open_style"] is False:
  2146. self.file_opened.emit("preferences", filename)
  2147. self.file_saved.emit("preferences", filename)
  2148. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2149. def save_to_file(self, content_to_save, txt_content):
  2150. """
  2151. Save something to a file.
  2152. :return: None
  2153. """
  2154. self.defaults.report_usage("save_to_file")
  2155. App.log.debug("save_to_file()")
  2156. self.date = str(datetime.today()).rpartition('.')[0]
  2157. self.date = ''.join(c for c in self.date if c not in ':-')
  2158. self.date = self.date.replace(' ', '_')
  2159. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2160. path_to_save = self.defaults["global_last_save_folder"] if \
  2161. self.defaults["global_last_save_folder"] is not None else self.data_path
  2162. try:
  2163. filename, _f = FCFileSaveDialog.get_saved_filename(
  2164. caption=_("Save to file"),
  2165. directory=path_to_save + '/file_' + self.date,
  2166. ext_filter=filter__
  2167. )
  2168. except TypeError:
  2169. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2170. filename = str(filename)
  2171. if filename == "":
  2172. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2173. return
  2174. else:
  2175. try:
  2176. with open(filename, 'w') as f:
  2177. ___ = f.read()
  2178. except PermissionError:
  2179. self.inform.emit('[WARNING] %s' %
  2180. _("Permission denied, saving not possible.\n"
  2181. "Most likely another app is holding the file open and not accessible."))
  2182. return
  2183. except IOError:
  2184. App.log.debug('Creating a new file ...')
  2185. f = open(filename, 'w')
  2186. f.close()
  2187. except Exception:
  2188. e = sys.exc_info()[0]
  2189. App.log.error("Could not load the file.")
  2190. App.log.error(str(e))
  2191. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2192. return
  2193. # Save content
  2194. if filename.rpartition('.')[2].lower() == 'html':
  2195. file_content = content_to_save
  2196. else:
  2197. file_content = txt_content
  2198. try:
  2199. with open(filename, "w") as f:
  2200. f.write(file_content)
  2201. except Exception:
  2202. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2203. return
  2204. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2205. def register_recent(self, kind, filename):
  2206. """
  2207. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2208. dictionary.
  2209. :param kind: type of file that was opened
  2210. :param filename: the path and file name for the file that was opened
  2211. :return:
  2212. """
  2213. self.log.debug("register_recent()")
  2214. self.log.debug(" %s" % kind)
  2215. self.log.debug(" %s" % filename)
  2216. record = {'kind': str(kind), 'filename': str(filename)}
  2217. if record in self.recent:
  2218. return
  2219. if record in self.recent_projects:
  2220. return
  2221. if record['kind'] == 'project':
  2222. self.recent_projects.insert(0, record)
  2223. else:
  2224. self.recent.insert(0, record)
  2225. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2226. self.recent.pop()
  2227. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2228. self.recent_projects.pop()
  2229. try:
  2230. f = open(self.data_path + '/recent.json', 'w')
  2231. except IOError:
  2232. App.log.error("Failed to open recent items file for writing.")
  2233. self.inform.emit('[ERROR_NOTCL] %s' %
  2234. _('Failed to open recent files file for writing.'))
  2235. return
  2236. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2237. f.close()
  2238. try:
  2239. fp = open(self.data_path + '/recent_projects.json', 'w')
  2240. except IOError:
  2241. App.log.error("Failed to open recent items file for writing.")
  2242. self.inform.emit('[ERROR_NOTCL] %s' %
  2243. _('Failed to open recent projects file for writing.'))
  2244. return
  2245. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2246. fp.close()
  2247. # Re-build the recent items menu
  2248. self.setup_recent_items()
  2249. def on_about(self):
  2250. """
  2251. Displays the "about" dialog found in the Menu --> Help.
  2252. :return: None
  2253. """
  2254. self.defaults.report_usage("on_about")
  2255. version = self.version
  2256. version_date = self.version_date
  2257. beta = self.beta
  2258. class AboutDialog(QtWidgets.QDialog):
  2259. def __init__(self, app, parent=None):
  2260. QtWidgets.QDialog.__init__(self, parent)
  2261. self.app = app
  2262. # Icon and title
  2263. self.setWindowIcon(parent.app_icon)
  2264. self.setWindowTitle(_("About FlatCAM"))
  2265. self.resize(600, 200)
  2266. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2267. # self.setStyleSheet(
  2268. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2269. # "background-attachment: fixed"
  2270. # )
  2271. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2272. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2273. # palette = QtGui.QPalette()
  2274. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2275. # self.setPalette(palette)
  2276. logo = QtWidgets.QLabel()
  2277. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2278. title = QtWidgets.QLabel(
  2279. "<font size=8><B>FlatCAM</B></font><BR>"
  2280. "{title}<BR>"
  2281. "<BR>"
  2282. "<BR>"
  2283. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2284. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2285. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2286. "<B>{issue}</B></a><BR>".format(
  2287. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2288. devel=_("Development"),
  2289. down=_("DOWNLOAD"),
  2290. issue=_("Issue tracker"))
  2291. )
  2292. title.setOpenExternalLinks(True)
  2293. closebtn = QtWidgets.QPushButton(_("Close"))
  2294. tab_widget = QtWidgets.QTabWidget()
  2295. description_label = QtWidgets.QLabel(
  2296. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2297. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2298. version=version,
  2299. beta=('BETA' if beta else ''),
  2300. date=version_date,
  2301. arch=platform.architecture()[0])
  2302. )
  2303. description_label.setOpenExternalLinks(True)
  2304. lic_lbl_header = QtWidgets.QLabel(
  2305. '%s:<br>%s<br>' % (
  2306. _('Licensed under the MIT license'),
  2307. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2308. "http://www.opensource.org/licenses/mit-license.php</a>"
  2309. )
  2310. )
  2311. lic_lbl_header.setOpenExternalLinks(True)
  2312. lic_lbl_body = QtWidgets.QLabel(
  2313. _(
  2314. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2315. 'of this software and associated documentation files (the "Software"), to deal\n'
  2316. 'in the Software without restriction, including without limitation the rights\n'
  2317. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2318. 'copies of the Software, and to permit persons to whom the Software is\n'
  2319. 'furnished to do so, subject to the following conditions:\n\n'
  2320. 'The above copyright notice and this permission notice shall be included in\n'
  2321. 'all copies or substantial portions of the Software.\n\n'
  2322. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2323. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2324. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2325. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2326. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2327. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2328. 'THE SOFTWARE.'
  2329. )
  2330. )
  2331. attributions_label = QtWidgets.QLabel(
  2332. _(
  2333. 'Some of the icons used are from the following sources:<br>'
  2334. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2335. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2336. 'title="Flaticon">www.flaticon.com</a></div>'
  2337. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2338. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2339. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2340. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2341. 'title="Flaticon">www.flaticon.com</a></div>'
  2342. )
  2343. )
  2344. attributions_label.setOpenExternalLinks(True)
  2345. # layouts
  2346. layout1 = QtWidgets.QVBoxLayout()
  2347. layout1_1 = QtWidgets.QHBoxLayout()
  2348. layout1_2 = QtWidgets.QHBoxLayout()
  2349. layout2 = QtWidgets.QHBoxLayout()
  2350. layout3 = QtWidgets.QHBoxLayout()
  2351. self.setLayout(layout1)
  2352. layout1.addLayout(layout1_1)
  2353. layout1.addLayout(layout1_2)
  2354. layout1.addLayout(layout2)
  2355. layout1.addLayout(layout3)
  2356. layout1_1.addStretch()
  2357. layout1_1.addWidget(description_label)
  2358. layout1_2.addWidget(tab_widget)
  2359. self.splash_tab = QtWidgets.QWidget()
  2360. self.splash_tab.setObjectName("splash_about")
  2361. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2362. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2363. tab_widget.addTab(self.splash_tab, _("Splash"))
  2364. self.programmmers_tab = QtWidgets.QWidget()
  2365. self.programmmers_tab.setObjectName("programmers_about")
  2366. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2367. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2368. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2369. self.translators_tab = QtWidgets.QWidget()
  2370. self.translators_tab.setObjectName("translators_about")
  2371. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2372. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2373. tab_widget.addTab(self.translators_tab, _("Translators"))
  2374. self.license_tab = QtWidgets.QWidget()
  2375. self.license_tab.setObjectName("license_about")
  2376. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2377. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2378. tab_widget.addTab(self.license_tab, _("License"))
  2379. self.attributions_tab = QtWidgets.QWidget()
  2380. self.attributions_tab.setObjectName("attributions_about")
  2381. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2382. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2383. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2384. self.splash_tab_layout.addWidget(logo, stretch=0)
  2385. self.splash_tab_layout.addWidget(title, stretch=1)
  2386. pal = QtGui.QPalette()
  2387. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2388. self.prog_grid_lay = QtWidgets.QGridLayout()
  2389. self.prog_grid_lay.setHorizontalSpacing(20)
  2390. self.prog_grid_lay.setColumnStretch(0, 0)
  2391. self.prog_grid_lay.setColumnStretch(2, 1)
  2392. prog_widget = QtWidgets.QWidget()
  2393. prog_widget.setLayout(self.prog_grid_lay)
  2394. prog_scroll = QtWidgets.QScrollArea()
  2395. prog_scroll.setWidget(prog_widget)
  2396. prog_scroll.setWidgetResizable(True)
  2397. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2398. prog_scroll.setPalette(pal)
  2399. self.programmmers_tab_layout.addWidget(prog_scroll)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2402. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2403. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2404. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2405. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2406. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2407. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2408. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2409. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2410. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2411. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2412. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2413. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2414. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2415. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2416. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2417. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2418. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2419. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2420. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2421. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2422. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2423. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2424. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2425. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2426. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2427. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2428. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2429. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2430. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2431. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2432. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2433. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2434. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2435. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2436. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2437. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2438. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2439. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2440. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2441. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2442. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2443. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2444. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2445. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2446. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2447. self.translator_grid_lay = QtWidgets.QGridLayout()
  2448. self.translator_grid_lay.setColumnStretch(0, 0)
  2449. self.translator_grid_lay.setColumnStretch(1, 0)
  2450. self.translator_grid_lay.setColumnStretch(2, 1)
  2451. self.translator_grid_lay.setColumnStretch(3, 0)
  2452. # trans_widget = QtWidgets.QWidget()
  2453. # trans_widget.setLayout(self.translator_grid_lay)
  2454. # self.translators_tab_layout.addWidget(trans_widget)
  2455. # self.translators_tab_layout.addStretch()
  2456. trans_widget = QtWidgets.QWidget()
  2457. trans_widget.setLayout(self.translator_grid_lay)
  2458. trans_scroll = QtWidgets.QScrollArea()
  2459. trans_scroll.setWidget(trans_widget)
  2460. trans_scroll.setWidgetResizable(True)
  2461. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2462. trans_scroll.setPalette(pal)
  2463. self.translators_tab_layout.addWidget(trans_scroll)
  2464. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2465. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2466. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2467. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2468. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2469. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2470. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2471. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2472. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2473. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2474. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2475. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2476. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2477. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2478. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2479. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2480. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2481. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2482. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2483. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2484. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2485. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2486. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2487. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2488. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2489. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2490. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2491. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2492. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2493. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2494. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2495. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2496. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2497. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2498. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2499. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2500. self.translator_grid_lay.setColumnStretch(0, 0)
  2501. self.translators_tab_layout.addStretch()
  2502. self.license_tab_layout.addWidget(lic_lbl_header)
  2503. self.license_tab_layout.addWidget(lic_lbl_body)
  2504. self.license_tab_layout.addStretch()
  2505. self.attributions_tab_layout.addWidget(attributions_label)
  2506. self.attributions_tab_layout.addStretch()
  2507. layout3.addStretch()
  2508. layout3.addWidget(closebtn)
  2509. closebtn.clicked.connect(self.accept)
  2510. AboutDialog(app=self, parent=self.ui).exec_()
  2511. def on_readme(self):
  2512. """
  2513. Displays the "about" dialog found in the Menu --> Help.
  2514. :return: None
  2515. """
  2516. class ReadmeDialog(QtWidgets.QDialog):
  2517. def __init__(self, app, parent=None):
  2518. QtWidgets.QDialog.__init__(self, parent)
  2519. self.app = app
  2520. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2521. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2522. "<b>click</b></a>"
  2523. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2524. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2525. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2526. # Icon and title
  2527. self.setWindowIcon(parent.app_icon)
  2528. self.setWindowTitle(_("Important Information's"))
  2529. self.resize(750, 375)
  2530. logo = QtWidgets.QLabel()
  2531. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2532. # content = QtWidgets.QLabel(
  2533. # "%s<br>"
  2534. # "%s<br><br>"
  2535. # "%s,<br>"
  2536. # "%s<br>"
  2537. # "<ul>"
  2538. # "<li> &nbsp;%s %s</li>"
  2539. # "<li> &nbsp;%s %s</li>"
  2540. # "</ul>"
  2541. # "%s %s.<br>"
  2542. # "%s"
  2543. # "<ul>"
  2544. # "<li> &nbsp;%s &#128077;</li>"
  2545. # "<li> &nbsp;%s &#128513;</li>"
  2546. # "</ul>" %
  2547. # (
  2548. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2549. # _("Yet it cannot evolve without <b>contributions</b>."),
  2550. # _("If you want to see this application grow and become better and better"),
  2551. # _("you can <b>contribute</b> to the development yourself by:"),
  2552. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2553. # new_features_link,
  2554. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2555. # bugs_link,
  2556. # _("If you like or use this program you can make a donation"),
  2557. # donation_link,
  2558. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2559. # _("it will be welcomed with joy"),
  2560. # _("it will give me a reason to continue")
  2561. # )
  2562. # )
  2563. content = QtWidgets.QLabel(
  2564. "%s<br>"
  2565. "%s<br><br>"
  2566. "%s,<br>"
  2567. "%s<br>"
  2568. "<ul>"
  2569. "<li> &nbsp;%s %s</li>"
  2570. "<li> &nbsp;%s %s</li>"
  2571. "</ul>" %
  2572. (
  2573. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2574. _("Yet it cannot evolve without <b>contributions</b>."),
  2575. _("If you want to see this application grow and become better and better"),
  2576. _("you can <b>contribute</b> to the development yourself by:"),
  2577. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2578. new_features_link,
  2579. _("Bug Reports by providing the steps required to reproduce the bug"),
  2580. bugs_link
  2581. )
  2582. )
  2583. content.setOpenExternalLinks(True)
  2584. # palette
  2585. pal = QtGui.QPalette()
  2586. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2587. # layouts
  2588. main_layout = QtWidgets.QVBoxLayout()
  2589. self.setLayout(main_layout)
  2590. tab_layout = QtWidgets.QHBoxLayout()
  2591. buttons_hlay = QtWidgets.QHBoxLayout()
  2592. main_layout.addLayout(tab_layout)
  2593. main_layout.addLayout(buttons_hlay)
  2594. tab_widget = QtWidgets.QTabWidget()
  2595. tab_layout.addWidget(tab_widget)
  2596. closebtn = QtWidgets.QPushButton(_("Close"))
  2597. buttons_hlay.addStretch()
  2598. buttons_hlay.addWidget(closebtn)
  2599. # CONTRIBUTE section
  2600. self.intro_tab = QtWidgets.QWidget()
  2601. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2602. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2603. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2604. self.grid_lay = QtWidgets.QGridLayout()
  2605. self.grid_lay.setHorizontalSpacing(20)
  2606. self.grid_lay.setColumnStretch(0, 0)
  2607. self.grid_lay.setColumnStretch(1, 1)
  2608. intro_wdg = QtWidgets.QWidget()
  2609. intro_wdg.setLayout(self.grid_lay)
  2610. intro_scroll_area = QtWidgets.QScrollArea()
  2611. intro_scroll_area.setWidget(intro_wdg)
  2612. intro_scroll_area.setWidgetResizable(True)
  2613. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2614. intro_scroll_area.setPalette(pal)
  2615. self.grid_lay.addWidget(logo, 0, 0)
  2616. self.grid_lay.addWidget(content, 0, 1)
  2617. self.intro_tab_layout.addWidget(intro_scroll_area)
  2618. # LINKS EXCHANGE section
  2619. self.links_tab = QtWidgets.QWidget()
  2620. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2621. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2622. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2623. self.links_lay = QtWidgets.QHBoxLayout()
  2624. links_wdg = QtWidgets.QWidget()
  2625. links_wdg.setLayout(self.links_lay)
  2626. links_scroll_area = QtWidgets.QScrollArea()
  2627. links_scroll_area.setWidget(links_wdg)
  2628. links_scroll_area.setWidgetResizable(True)
  2629. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2630. links_scroll_area.setPalette(pal)
  2631. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2632. self.links_tab_layout.addWidget(links_scroll_area)
  2633. # HOW TO section
  2634. self.howto_tab = QtWidgets.QWidget()
  2635. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2636. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2637. tab_widget.addTab(self.howto_tab, _("How To's"))
  2638. self.howto_lay = QtWidgets.QHBoxLayout()
  2639. howto_wdg = QtWidgets.QWidget()
  2640. howto_wdg.setLayout(self.howto_lay)
  2641. howto_scroll_area = QtWidgets.QScrollArea()
  2642. howto_scroll_area.setWidget(howto_wdg)
  2643. howto_scroll_area.setWidgetResizable(True)
  2644. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2645. howto_scroll_area.setPalette(pal)
  2646. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2647. self.howto_tab_layout.addWidget(howto_scroll_area)
  2648. # BUTTONS section
  2649. closebtn.clicked.connect(self.accept)
  2650. ReadmeDialog(app=self, parent=self.ui).exec_()
  2651. def install_bookmarks(self, book_dict=None):
  2652. """
  2653. Install the bookmarks actions in the Help menu -> Bookmarks
  2654. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2655. :return: None
  2656. """
  2657. if book_dict is None:
  2658. self.defaults["global_bookmarks"].update(
  2659. {
  2660. '1': ['FlatCAM', "http://flatcam.org"],
  2661. '2': ['Backup Site', ""]
  2662. }
  2663. )
  2664. else:
  2665. self.defaults["global_bookmarks"].clear()
  2666. self.defaults["global_bookmarks"].update(book_dict)
  2667. # first try to disconnect if somehow they get connected from elsewhere
  2668. for act in self.ui.menuhelp_bookmarks.actions():
  2669. try:
  2670. act.triggered.disconnect()
  2671. except TypeError:
  2672. pass
  2673. # clear all actions except the last one who is the Bookmark manager
  2674. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2675. pass
  2676. else:
  2677. self.ui.menuhelp_bookmarks.removeAction(act)
  2678. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2679. if self.defaults["global_bookmarks"]:
  2680. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2681. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2682. # the JSON is first making the keys as strings (therefore I have to use strings too
  2683. # or do the conversion :(
  2684. # )
  2685. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2686. # the '10' entry jsut after '1' therefore ordering as strings
  2687. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2688. key=lambda x: int(x[0]))
  2689. for entry, bookmark in sorted_bookmarks:
  2690. title = bookmark[0]
  2691. weblink = bookmark[1]
  2692. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2693. act.setText(title)
  2694. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2695. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2696. if title == 'Backup Site' and weblink == "":
  2697. act.triggered.connect(self.on_backup_site)
  2698. else:
  2699. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2700. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2701. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2702. def on_bookmarks_manager(self):
  2703. """
  2704. Adds the bookmark manager in a Tab in Plot Area
  2705. :return:
  2706. """
  2707. for idx in range(self.ui.plot_tab_area.count()):
  2708. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2709. # there can be only one instance of Bookmark Manager at one time
  2710. return
  2711. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2712. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2713. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2714. # add the tab if it was closed
  2715. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2716. # delete the absolute and relative position and messages in the infobar
  2717. # self.ui.position_label.setText("")
  2718. # self.ui.rel_position_label.setText("")
  2719. # hide coordinates toolbars in the infobar while in DB
  2720. self.ui.coords_toolbar.hide()
  2721. self.ui.delta_coords_toolbar.hide()
  2722. # Switch plot_area to preferences page
  2723. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2724. def on_backup_site(self):
  2725. msgbox = QtWidgets.QMessageBox()
  2726. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2727. "1. FlatCAM.org website is down\n"
  2728. "2. Someone forked FlatCAM project and wants to point\n"
  2729. "to his own website\n\n"
  2730. "If you can't get any informations about FlatCAM beta\n"
  2731. "use the YouTube channel link from the Help menu."))
  2732. msgbox.setWindowTitle(_("Alternative website"))
  2733. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2734. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2735. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2736. msgbox.setDefaultButton(bt_yes)
  2737. msgbox.exec_()
  2738. # response = msgbox.clickedButton()
  2739. def on_file_savedefaults(self):
  2740. """
  2741. Callback for menu item File->Save Defaults. Saves application default options
  2742. ``self.defaults`` to current_defaults.FlatConfig.
  2743. :return: None
  2744. """
  2745. self.preferencesUiManager.save_defaults()
  2746. def final_save(self):
  2747. """
  2748. Callback for doing a preferences save to file whenever the application is about to quit.
  2749. If the project has changes, it will ask the user to save the project.
  2750. :return: None
  2751. """
  2752. if self.save_in_progress:
  2753. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2754. return
  2755. if self.should_we_save and self.collection.get_list():
  2756. msgbox = QtWidgets.QMessageBox()
  2757. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2758. "\n"
  2759. "Do you want to Save the project?"))
  2760. msgbox.setWindowTitle(_("Save changes"))
  2761. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2762. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2763. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2764. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2765. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2766. msgbox.setDefaultButton(bt_yes)
  2767. msgbox.exec_()
  2768. response = msgbox.clickedButton()
  2769. if response == bt_yes:
  2770. try:
  2771. self.trayIcon.hide()
  2772. except Exception:
  2773. pass
  2774. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2775. elif response == bt_no:
  2776. try:
  2777. self.trayIcon.hide()
  2778. except Exception:
  2779. pass
  2780. self.quit_application()
  2781. elif response == bt_cancel:
  2782. return
  2783. else:
  2784. try:
  2785. self.trayIcon.hide()
  2786. except Exception:
  2787. pass
  2788. self.quit_application()
  2789. def quit_application(self):
  2790. """
  2791. Called (as a pyslot or not) when the application is quit.
  2792. :return: None
  2793. """
  2794. # close editors before quiting the app, if they are open
  2795. if self.geo_editor.editor_active is True:
  2796. self.geo_editor.deactivate()
  2797. try:
  2798. self.geo_editor.disconnect()
  2799. except TypeError:
  2800. pass
  2801. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2802. if self.exc_editor.editor_active is True:
  2803. self.exc_editor.deactivate()
  2804. try:
  2805. self.grb_editor.disconnect()
  2806. except TypeError:
  2807. pass
  2808. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2809. if self.grb_editor.editor_active is True:
  2810. self.grb_editor.deactivate_grb_editor()
  2811. try:
  2812. self.exc_editor.disconnect()
  2813. except TypeError:
  2814. pass
  2815. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2816. # disconnect the mouse events
  2817. if self.is_legacy:
  2818. self.plotcanvas.graph_event_disconnect(self.mm)
  2819. self.plotcanvas.graph_event_disconnect(self.mp)
  2820. self.plotcanvas.graph_event_disconnect(self.mr)
  2821. self.plotcanvas.graph_event_disconnect(self.mdc)
  2822. self.plotcanvas.graph_event_disconnect(self.kp)
  2823. else:
  2824. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2825. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2826. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2827. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2828. self.on_mouse_double_click_over_plot)
  2829. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2830. self.preferencesUiManager.save_defaults(silent=True)
  2831. log.debug("App.quit_application() --> App Defaults saved.")
  2832. if self.cmd_line_headless != 1:
  2833. # save app state to file
  2834. stgs = QSettings("Open Source", "FlatCAM")
  2835. stgs.setValue('saved_gui_state', self.ui.saveState())
  2836. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2837. stgs.setValue(
  2838. 'language',
  2839. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2840. )
  2841. stgs.setValue(
  2842. 'notebook_font_size',
  2843. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2844. )
  2845. stgs.setValue(
  2846. 'axis_font_size',
  2847. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2848. )
  2849. stgs.setValue(
  2850. 'textbox_font_size',
  2851. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2852. )
  2853. stgs.setValue(
  2854. 'hud_font_size',
  2855. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2856. )
  2857. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2858. stgs.setValue(
  2859. 'machinist',
  2860. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2861. )
  2862. # This will write the setting to the platform specific storage.
  2863. del stgs
  2864. log.debug("App.quit_application() --> App UI state saved.")
  2865. # try to quit the Socket opened by ArgsThread class
  2866. try:
  2867. # self.new_launch.thread_exit = True
  2868. # self.new_launch.listener.close()
  2869. self.new_launch.stop.emit()
  2870. except Exception as err:
  2871. log.debug("App.quit_application() --> %s" % str(err))
  2872. # try to quit the QThread that run ArgsThread class
  2873. try:
  2874. # del self.new_launch
  2875. self.listen_th.quit()
  2876. except Exception as e:
  2877. log.debug("App.quit_application() --> %s" % str(e))
  2878. # terminate workers
  2879. # self.workers.__del__()
  2880. self.clear_pool()
  2881. # quit app by signalling for self.kill_app() method
  2882. # self.close_app_signal.emit()
  2883. QtWidgets.qApp.quit()
  2884. sys.exit(0)
  2885. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2886. # we use the following command
  2887. # minor_v = sys.version_info.minor
  2888. # if minor_v < 8:
  2889. # # make sure that the app closes
  2890. # sys.exit(0)
  2891. # else:
  2892. # os._exit(0) # fix to work with Python 3.8
  2893. @staticmethod
  2894. def kill_app():
  2895. QtWidgets.qApp.quit()
  2896. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2897. # we use the following command
  2898. sys.exit(0)
  2899. def on_portable_checked(self, state):
  2900. """
  2901. Callback called when the checkbox in Preferences GUI is checked.
  2902. It will set the application as portable by creating the preferences and recent files in the
  2903. 'config' folder found in the FlatCAM installation folder.
  2904. :param state: boolean, the state of the checkbox when clicked/checked
  2905. :return:
  2906. """
  2907. line_no = 0
  2908. data = None
  2909. if sys.platform != 'win32':
  2910. # this won't work in Linux or MacOS
  2911. return
  2912. # test if the app was frozen and choose the path for the configuration file
  2913. if getattr(sys, "frozen", False) is True:
  2914. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2915. else:
  2916. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2917. config_file = current_data_path + '\\configuration.txt'
  2918. try:
  2919. with open(config_file, 'r') as f:
  2920. try:
  2921. data = f.readlines()
  2922. except Exception as e:
  2923. log.debug('App.__init__() -->%s' % str(e))
  2924. return
  2925. except FileNotFoundError:
  2926. pass
  2927. for line in data:
  2928. line = line.strip('\n')
  2929. param = str(line).rpartition('=')
  2930. if param[0] == 'portable':
  2931. break
  2932. line_no += 1
  2933. if state:
  2934. data[line_no] = 'portable=True\n'
  2935. # create the new defauults files
  2936. # create current_defaults.FlatConfig file if there is none
  2937. try:
  2938. f = open(current_data_path + '/current_defaults.FlatConfig')
  2939. f.close()
  2940. except IOError:
  2941. App.log.debug('Creating empty current_defaults.FlatConfig')
  2942. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2943. json.dump({}, f)
  2944. f.close()
  2945. # create factory_defaults.FlatConfig file if there is none
  2946. try:
  2947. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2948. f.close()
  2949. except IOError:
  2950. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2951. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2952. json.dump({}, f)
  2953. f.close()
  2954. try:
  2955. f = open(current_data_path + '/recent.json')
  2956. f.close()
  2957. except IOError:
  2958. App.log.debug('Creating empty recent.json')
  2959. f = open(current_data_path + '/recent.json', 'w')
  2960. json.dump([], f)
  2961. f.close()
  2962. try:
  2963. fp = open(current_data_path + '/recent_projects.json')
  2964. fp.close()
  2965. except IOError:
  2966. App.log.debug('Creating empty recent_projects.json')
  2967. fp = open(current_data_path + '/recent_projects.json', 'w')
  2968. json.dump([], fp)
  2969. fp.close()
  2970. # save the current defaults to the new defaults file
  2971. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2972. else:
  2973. data[line_no] = 'portable=False\n'
  2974. with open(config_file, 'w') as f:
  2975. f.writelines(data)
  2976. def on_register_files(self, obj_type=None):
  2977. """
  2978. Called whenever there is a need to register file extensions with FlatCAM.
  2979. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2980. :param obj_type: the type of object to be register for.
  2981. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2982. :return: None
  2983. """
  2984. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2985. new_reg_path = 'Software\\Classes\\'
  2986. # find if the current user is admin
  2987. try:
  2988. is_admin = os.getuid() == 0
  2989. except AttributeError:
  2990. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2991. if is_admin is True:
  2992. root_path = winreg.HKEY_LOCAL_MACHINE
  2993. else:
  2994. root_path = winreg.HKEY_CURRENT_USER
  2995. # create the keys
  2996. def set_reg(name, root_pth, new_reg_path, value):
  2997. try:
  2998. winreg.CreateKey(root_pth, new_reg_path)
  2999. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3000. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3001. return True
  3002. except WindowsError:
  3003. return False
  3004. # delete key in registry
  3005. def delete_reg(root_pth, reg_path, key_to_del):
  3006. key_to_del_path = reg_path + key_to_del
  3007. try:
  3008. winreg.DeleteKey(root_pth, key_to_del_path)
  3009. return True
  3010. except WindowsError:
  3011. return False
  3012. if obj_type is None or obj_type == 'excellon':
  3013. exc_list = \
  3014. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3015. exc_list = [x for x in exc_list if x != '']
  3016. # register all keys in the Preferences window
  3017. for ext in exc_list:
  3018. new_k = new_reg_path + '.%s' % ext
  3019. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3020. # and unregister those that are no longer in the Preferences windows but are in the file
  3021. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3022. if ext not in exc_list:
  3023. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3024. # now write the updated extensions to the self.defaults
  3025. # new_ext = ''
  3026. # for ext in exc_list:
  3027. # new_ext = new_ext + ext + ', '
  3028. # self.defaults["fa_excellon"] = new_ext
  3029. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3030. if obj_type is None or obj_type == 'gcode':
  3031. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3032. gco_list = [x for x in gco_list if x != '']
  3033. # register all keys in the Preferences window
  3034. for ext in gco_list:
  3035. new_k = new_reg_path + '.%s' % ext
  3036. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3037. # and unregister those that are no longer in the Preferences windows but are in the file
  3038. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3039. if ext not in gco_list:
  3040. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3041. # now write the updated extensions to the self.defaults
  3042. # new_ext = ''
  3043. # for ext in gco_list:
  3044. # new_ext = new_ext + ext + ', '
  3045. # self.defaults["fa_gcode"] = new_ext
  3046. self.inform.emit('[success] %s' %
  3047. _("Selected GCode file extensions registered with FlatCAM."))
  3048. if obj_type is None or obj_type == 'gerber':
  3049. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3050. grb_list = [x for x in grb_list if x != '']
  3051. # register all keys in the Preferences window
  3052. for ext in grb_list:
  3053. new_k = new_reg_path + '.%s' % ext
  3054. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3055. # and unregister those that are no longer in the Preferences windows but are in the file
  3056. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3057. if ext not in grb_list:
  3058. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3059. # now write the updated extensions to the self.defaults
  3060. # new_ext = ''
  3061. # for ext in grb_list:
  3062. # new_ext = new_ext + ext + ', '
  3063. # self.defaults["fa_gerber"] = new_ext
  3064. self.inform.emit('[success] %s' %
  3065. _("Selected Gerber file extensions registered with FlatCAM."))
  3066. def add_extension(self, ext_type):
  3067. """
  3068. Add a file extension to the list for a specific object
  3069. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3070. :return:
  3071. """
  3072. if ext_type == 'excellon':
  3073. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3074. if new_ext == '':
  3075. return
  3076. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3077. if new_ext in old_val:
  3078. return
  3079. old_val.append(new_ext)
  3080. old_val.sort()
  3081. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3082. if ext_type == 'gcode':
  3083. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3084. if new_ext == '':
  3085. return
  3086. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3087. if new_ext in old_val:
  3088. return
  3089. old_val.append(new_ext)
  3090. old_val.sort()
  3091. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3092. if ext_type == 'gerber':
  3093. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3094. if new_ext == '':
  3095. return
  3096. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3097. if new_ext in old_val:
  3098. return
  3099. old_val.append(new_ext)
  3100. old_val.sort()
  3101. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3102. if ext_type == 'keyword':
  3103. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3104. if new_kw == '':
  3105. return
  3106. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3107. if new_kw in old_val:
  3108. return
  3109. old_val.append(new_kw)
  3110. old_val.sort()
  3111. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3112. # update the self.myKeywords so the model is updated
  3113. self.autocomplete_kw_list = \
  3114. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3115. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3116. self.shell._edit.set_model_data(self.myKeywords)
  3117. def del_extension(self, ext_type):
  3118. """
  3119. Remove a file extension from the list for a specific object
  3120. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3121. :return:
  3122. """
  3123. if ext_type == 'excellon':
  3124. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3125. if new_ext == '':
  3126. return
  3127. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3128. if new_ext not in old_val:
  3129. return
  3130. old_val.remove(new_ext)
  3131. old_val.sort()
  3132. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3133. if ext_type == 'gcode':
  3134. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3135. if new_ext == '':
  3136. return
  3137. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3138. if new_ext not in old_val:
  3139. return
  3140. old_val.remove(new_ext)
  3141. old_val.sort()
  3142. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3143. if ext_type == 'gerber':
  3144. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3145. if new_ext == '':
  3146. return
  3147. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3148. if new_ext not in old_val:
  3149. return
  3150. old_val.remove(new_ext)
  3151. old_val.sort()
  3152. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3153. if ext_type == 'keyword':
  3154. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3155. if new_kw == '':
  3156. return
  3157. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3158. if new_kw not in old_val:
  3159. return
  3160. old_val.remove(new_kw)
  3161. old_val.sort()
  3162. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3163. # update the self.myKeywords so the model is updated
  3164. self.autocomplete_kw_list = \
  3165. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3166. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3167. self.shell._edit.set_model_data(self.myKeywords)
  3168. def restore_extensions(self, ext_type):
  3169. """
  3170. Restore all file extensions associations with FlatCAM, for a specific object
  3171. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3172. :return:
  3173. """
  3174. if ext_type == 'excellon':
  3175. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3176. # for the ability to open Excellon files with .txt extension
  3177. new_exc_list = deepcopy(self.exc_list)
  3178. try:
  3179. new_exc_list.remove('txt')
  3180. except ValueError:
  3181. pass
  3182. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3183. if ext_type == 'gcode':
  3184. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3185. if ext_type == 'gerber':
  3186. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3187. if ext_type == 'keyword':
  3188. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3189. # update the self.myKeywords so the model is updated
  3190. self.autocomplete_kw_list = self.default_keywords
  3191. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3192. self.shell._edit.set_model_data(self.myKeywords)
  3193. def delete_all_extensions(self, ext_type):
  3194. """
  3195. Delete all file extensions associations with FlatCAM, for a specific object
  3196. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3197. :return:
  3198. """
  3199. if ext_type == 'excellon':
  3200. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3201. if ext_type == 'gcode':
  3202. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3203. if ext_type == 'gerber':
  3204. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3205. if ext_type == 'keyword':
  3206. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3207. # update the self.myKeywords so the model is updated
  3208. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3209. self.shell._edit.set_model_data(self.myKeywords)
  3210. def on_edit_join(self, name=None):
  3211. """
  3212. Callback for Edit->Join. Joins the selected geometry objects into
  3213. a new one.
  3214. :return: None
  3215. """
  3216. self.defaults.report_usage("on_edit_join()")
  3217. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3218. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3219. geo_type_set = set()
  3220. objs = self.collection.get_selected()
  3221. if len(objs) < 2:
  3222. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3223. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3224. return 'fail'
  3225. for obj in objs:
  3226. geo_type_set.add(obj.multigeo)
  3227. # if len(geo_type_list) == 1 means that all list elements are the same
  3228. if len(geo_type_set) != 1:
  3229. self.inform.emit('[ERROR] %s' %
  3230. _("Failed join. The Geometry objects are of different types.\n"
  3231. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3232. "convert from one to another and retry joining \n"
  3233. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3234. "the result may not be what was expected. \n"
  3235. "Check the generated GCODE."))
  3236. return
  3237. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3238. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3239. if True in geo_type_set:
  3240. def initialize(geo_obj, app):
  3241. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3242. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3243. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3244. for v in geo_obj.tools.values():
  3245. v['data']['name'] = obj_name_multi
  3246. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3247. else:
  3248. def initialize(geo_obj, app):
  3249. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3250. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3251. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3252. for v in geo_obj.tools.values():
  3253. v['data']['name'] = obj_name_single
  3254. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3255. self.should_we_save = True
  3256. def on_edit_join_exc(self):
  3257. """
  3258. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3259. a new Excellon.
  3260. :return: None
  3261. """
  3262. self.defaults.report_usage("on_edit_join_exc()")
  3263. objs = self.collection.get_selected()
  3264. for obj in objs:
  3265. if not isinstance(obj, ExcellonObject):
  3266. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3267. return
  3268. if len(objs) < 2:
  3269. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3270. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3271. return 'fail'
  3272. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3273. def initialize(exc_obj, app):
  3274. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3275. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3276. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3277. self.should_we_save = True
  3278. def on_edit_join_grb(self):
  3279. """
  3280. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3281. a new Gerber object.
  3282. :return: None
  3283. """
  3284. self.defaults.report_usage("on_edit_join_grb()")
  3285. objs = self.collection.get_selected()
  3286. for obj in objs:
  3287. if not isinstance(obj, GerberObject):
  3288. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3289. return
  3290. if len(objs) < 2:
  3291. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3292. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3293. return 'fail'
  3294. def initialize(grb_obj, app):
  3295. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3296. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3297. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3298. self.should_we_save = True
  3299. def on_convert_singlegeo_to_multigeo(self):
  3300. """
  3301. Called for converting a Geometry object from single-geo to multi-geo.
  3302. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3303. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3304. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3305. the solid-geometry of that tool.
  3306. :return: None
  3307. """
  3308. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3309. obj = self.collection.get_active()
  3310. if obj is None:
  3311. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3312. return
  3313. if not isinstance(obj, GeometryObject):
  3314. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3315. return
  3316. obj.multigeo = True
  3317. for tooluid, dict_value in obj.tools.items():
  3318. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3319. if not isinstance(obj.solid_geometry, list):
  3320. obj.solid_geometry = [obj.solid_geometry]
  3321. # obj.solid_geometry[:] = []
  3322. obj.plot()
  3323. self.should_we_save = True
  3324. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3325. def on_convert_multigeo_to_singlegeo(self):
  3326. """
  3327. Called for converting a Geometry object from multi-geo to single-geo.
  3328. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3329. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3330. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3331. the solid-geometry of that tool.
  3332. :return: None
  3333. """
  3334. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3335. obj = self.collection.get_active()
  3336. if obj is None:
  3337. self.inform.emit('[ERROR_NOTCL] %s' %
  3338. _("Failed. Select a Geometry Object and try again."))
  3339. return
  3340. if not isinstance(obj, GeometryObject):
  3341. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3342. (_("Expected a GeometryObject, got"), type(obj)))
  3343. return
  3344. obj.multigeo = False
  3345. total_solid_geometry = []
  3346. for tooluid, dict_value in obj.tools.items():
  3347. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3348. # clear the original geometry
  3349. dict_value['solid_geometry'][:] = []
  3350. obj.solid_geometry = deepcopy(total_solid_geometry)
  3351. obj.plot()
  3352. self.should_we_save = True
  3353. self.inform.emit('[success] %s' %
  3354. _("A Geometry object was converted to SingleGeo type."))
  3355. def on_defaults_dict_change(self, field):
  3356. """
  3357. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3358. Edit -> Preferences tab window.
  3359. :param field: the key of the self.defaults dictionary that was changed.
  3360. :return: None
  3361. """
  3362. self.preferencesUiManager.defaults_write_form_field(field=field)
  3363. if field == "units":
  3364. self.set_screen_units(self.defaults['units'])
  3365. def set_screen_units(self, units):
  3366. """
  3367. Set the FlatCAM units on the status bar.
  3368. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3369. :return: None
  3370. """
  3371. self.ui.units_label.setText("[" + units.lower() + "]")
  3372. def on_toggle_units_click(self):
  3373. try:
  3374. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3375. except (TypeError, AttributeError):
  3376. pass
  3377. if self.defaults["units"] == 'MM':
  3378. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3379. else:
  3380. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3381. self.on_toggle_units(no_pref=True)
  3382. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3383. lambda: self.on_toggle_units(no_pref=False))
  3384. def scale_defaults(self, sfactor, dimensions):
  3385. for dim in dimensions:
  3386. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3387. 'tools_painttooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3388. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3389. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3390. if not self.defaults[dim] or self.defaults[dim] == '':
  3391. continue
  3392. if isinstance(self.defaults[dim], str):
  3393. try:
  3394. tools_diameters = eval(self.defaults[dim])
  3395. except Exception as e:
  3396. log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3397. continue
  3398. elif isinstance(self.defaults[dim], (float, int)):
  3399. tools_diameters = [self.defaults[dim]]
  3400. else:
  3401. tools_diameters = list(self.defaults[dim])
  3402. if isinstance(tools_diameters, (tuple, list)):
  3403. pass
  3404. elif isinstance(tools_diameters, (int, float)):
  3405. tools_diameters = [self.defaults[dim]]
  3406. else:
  3407. continue
  3408. td_len = len(tools_diameters)
  3409. conv_list = []
  3410. for t in range(td_len):
  3411. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3412. self.defaults[dim] = conv_list
  3413. elif dim in ['global_gridx', 'global_gridy']:
  3414. # format the number of decimals to the one specified in self.decimals
  3415. try:
  3416. val = float(self.defaults[dim]) * sfactor
  3417. except Exception as e:
  3418. log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3419. continue
  3420. self.defaults[dim] = self.dec_format(val, self.decimals)
  3421. else:
  3422. # the number of decimals for the rest is kept unchanged
  3423. if self.defaults[dim]:
  3424. try:
  3425. val = float(self.defaults[dim]) * sfactor
  3426. except Exception as e:
  3427. log.debug(
  3428. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3429. )
  3430. continue
  3431. self.defaults[dim] = self.dec_format(val, self.decimals)
  3432. def on_toggle_units(self, no_pref=False):
  3433. """
  3434. Callback for the Units radio-button change in the Preferences tab.
  3435. Changes the application's default units adn for the project too.
  3436. If changing the project's units, the change propagates to all of
  3437. the objects in the project.
  3438. :return: None
  3439. """
  3440. self.defaults.report_usage("on_toggle_units")
  3441. if self.toggle_units_ignore:
  3442. return
  3443. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3444. # If option is the same, then ignore
  3445. if new_units == self.defaults["units"].upper():
  3446. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3447. return
  3448. # Keys in self.defaults for which to scale their values
  3449. dimensions = [
  3450. # Global
  3451. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3452. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3453. # Gerber Object
  3454. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3455. # Gerber Editor
  3456. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3457. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3458. # Excellon Object
  3459. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3460. # Excellon Editor
  3461. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3462. "excellon_editor_slot_length",
  3463. # Geometry Object
  3464. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3465. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3466. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3467. "geometry_extracut_length", "geometry_z_pdepth",
  3468. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3469. # CNCJob Object
  3470. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3471. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3472. # Isolation Tool
  3473. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3474. # Drilling Tool
  3475. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3476. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3477. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3478. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3479. # NCC Tool
  3480. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3481. "tools_ncc_newdia",
  3482. # Cutout Tool
  3483. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3484. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3485. # Paint Tool
  3486. "tools_painttooldia", 'tools_paintoffset', "tools_paintcutz", "tools_painttipdia", "tools_paintnewdia",
  3487. # 2Sided Tool
  3488. "tools_2sided_drilldia",
  3489. # Film Tool
  3490. "tools_film_boundary", "tools_film_scale_stroke",
  3491. # Panel Tool
  3492. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3493. "tools_panelize_constrainy",
  3494. # Calculators Tool
  3495. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3496. # Transform Tool
  3497. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3498. "tools_transform_buffer_dis",
  3499. # SolderPaste Tool
  3500. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3501. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3502. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3503. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3504. # Corner Markers Tool
  3505. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3506. # Check Rules Tool
  3507. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3508. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3509. # QRCode Tool
  3510. "tools_qrcode_border_size",
  3511. # Copper Thieving Tool
  3512. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3513. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3514. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3515. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3516. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3517. "tools_copper_thieving_mask_clearance",
  3518. # Fiducials Tool
  3519. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3520. # Calibration Tool
  3521. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3522. # Drills Extraction Tool
  3523. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3524. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3525. # Punch Gerber Tool
  3526. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3527. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3528. # Invert Gerber Tool
  3529. "tools_invert_margin",
  3530. ]
  3531. # The scaling factor depending on choice of units.
  3532. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3533. # Changing project units. Warn user.
  3534. msgbox = QtWidgets.QMessageBox()
  3535. msgbox.setWindowTitle(_("Toggle Units"))
  3536. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3537. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3538. msgbox.setText(_("Changing the units of the project\n"
  3539. "will scale all objects.\n\n"
  3540. "Do you want to continue?"))
  3541. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3542. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3543. msgbox.setDefaultButton(bt_ok)
  3544. msgbox.exec_()
  3545. response = msgbox.clickedButton()
  3546. if response == bt_ok:
  3547. if no_pref is False:
  3548. self.preferencesUiManager.defaults_read_form()
  3549. self.scale_defaults(factor, dimensions)
  3550. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3551. self.defaults["units"] = new_units
  3552. # update the defaults from form, some may assume that the conversion is enough and it's not
  3553. self.on_options_app2project()
  3554. # update the objects
  3555. for obj in self.collection.get_list():
  3556. obj.convert_units(new_units)
  3557. # make that the properties stored in the object are also updated
  3558. self.app_obj.object_changed.emit(obj)
  3559. # rebuild the object UI
  3560. obj.build_ui()
  3561. # change this only if the workspace is active
  3562. if self.defaults['global_workspace'] is True:
  3563. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3564. # adjust the grid values on the main toolbar
  3565. val_x = float(self.defaults['global_gridx']) * factor
  3566. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3567. current = self.collection.get_active()
  3568. if current is not None:
  3569. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3570. if not isinstance(current, GeometryObject):
  3571. current.to_form()
  3572. # replot all objects
  3573. self.plot_all()
  3574. # set the status labels to reflect the current FlatCAM units
  3575. self.set_screen_units(new_units)
  3576. # signal to the app that we changed the object properties and it should save the project
  3577. self.should_we_save = True
  3578. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3579. else:
  3580. # Undo toggling
  3581. self.toggle_units_ignore = True
  3582. if self.defaults['units'].upper() == 'MM':
  3583. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3584. else:
  3585. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3586. self.toggle_units_ignore = False
  3587. # store the grid values so they are not changed in the next step
  3588. val_x = float(self.defaults['global_gridx'])
  3589. val_y = float(self.defaults['global_gridy'])
  3590. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3591. self.preferencesUiManager.defaults_read_form()
  3592. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3593. # in self.defaults from the GUI elements but
  3594. # I don't want it for the grid values, so I update them here
  3595. self.defaults['global_gridx'] = val_x
  3596. self.defaults['global_gridy'] = val_y
  3597. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3598. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3599. def on_deselect_all(self):
  3600. self.collection.set_all_inactive()
  3601. self.delete_selection_shape()
  3602. def on_workspace_modified(self):
  3603. # self.save_defaults(silent=True)
  3604. self.plotcanvas.delete_workspace()
  3605. self.preferencesUiManager.defaults_read_form()
  3606. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3607. def on_workspace(self):
  3608. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3609. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3610. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3611. else:
  3612. self.plotcanvas.delete_workspace()
  3613. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3614. self.preferencesUiManager.defaults_read_form()
  3615. # self.save_defaults(silent=True)
  3616. def on_workspace_toggle(self):
  3617. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3618. try:
  3619. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3620. except TypeError:
  3621. pass
  3622. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3623. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3624. self.on_workspace()
  3625. def on_cursor_type(self, val):
  3626. """
  3627. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3628. :return: None
  3629. """
  3630. self.app_cursor.enabled = False
  3631. if val == 'small':
  3632. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3633. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3634. self.app_cursor = self.plotcanvas.new_cursor()
  3635. else:
  3636. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3637. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3638. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3639. if self.ui.grid_snap_btn.isChecked():
  3640. self.app_cursor.enabled = True
  3641. else:
  3642. self.app_cursor.enabled = False
  3643. def on_tool_add_keypress(self):
  3644. # ## Current application units in Upper Case
  3645. self.units = self.defaults['units'].upper()
  3646. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3647. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3648. if notebook_widget_name == 'properties_tab':
  3649. if self.collection.get_active().kind == 'geometry':
  3650. # Tool add works for Geometry only if Advanced is True in Preferences
  3651. if self.defaults["global_app_level"] == 'a':
  3652. tool_add_popup = FCInputDialog(title="New Tool ...",
  3653. text='Enter a Tool Diameter:',
  3654. min=0.0000, max=99.9999, decimals=4)
  3655. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3656. val, ok = tool_add_popup.get_value()
  3657. if ok:
  3658. if float(val) == 0:
  3659. self.inform.emit('[WARNING_NOTCL] %s' %
  3660. _("Please enter a tool diameter with non-zero value, in Float format."))
  3661. return
  3662. self.collection.get_active().on_tool_add(dia=float(val))
  3663. else:
  3664. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3665. else:
  3666. msgbox = QtWidgets.QMessageBox()
  3667. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3668. "Go to Preferences -> General - Show Advanced Options."))
  3669. msgbox.setWindowTitle("Tool adding ...")
  3670. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3671. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3672. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3673. msgbox.setDefaultButton(bt_ok)
  3674. msgbox.exec_()
  3675. # work only if the notebook tab on focus is the Tools_Tab
  3676. if notebook_widget_name == 'tool_tab':
  3677. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3678. # and only if the tool is NCC Tool
  3679. if tool_widget == self.ncclear_tool.toolName:
  3680. self.ncclear_tool.on_add_tool_by_key()
  3681. # and only if the tool is Paint Area Tool
  3682. elif tool_widget == self.paint_tool.toolName:
  3683. self.paint_tool.on_add_tool_by_key()
  3684. # and only if the tool is Solder Paste Dispensing Tool
  3685. elif tool_widget == self.paste_tool.toolName:
  3686. self.paste_tool.on_add_tool_by_key()
  3687. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3688. # See description below.
  3689. def on_delete_keypress(self):
  3690. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3691. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3692. if notebook_widget_name == 'properties_tab':
  3693. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3694. self.collection.get_active().on_tool_delete()
  3695. # work only if the notebook tab on focus is the Tools_Tab
  3696. elif notebook_widget_name == 'tool_tab':
  3697. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3698. # and only if the tool is NCC Tool
  3699. if tool_widget == self.ncclear_tool.toolName:
  3700. self.ncclear_tool.on_tool_delete()
  3701. # and only if the tool is Paint Tool
  3702. elif tool_widget == self.paint_tool.toolName:
  3703. self.paint_tool.on_tool_delete()
  3704. # and only if the tool is Solder Paste Dispensing Tool
  3705. elif tool_widget == self.paste_tool.toolName:
  3706. self.paste_tool.on_tool_delete()
  3707. # and only if the tool is Isolation Tool
  3708. elif tool_widget == self.isolation_tool.toolName:
  3709. self.isolation_tool.on_tool_delete()
  3710. else:
  3711. self.on_delete()
  3712. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3713. # some screens you have to be careful where you hover with your mouse.
  3714. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3715. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3716. # Complicated, I know :)
  3717. def on_delete(self, force_deletion=False):
  3718. """
  3719. Delete the currently selected FlatCAMObjs.
  3720. :param force_deletion: used by Tcl command
  3721. :return: None
  3722. """
  3723. self.defaults.report_usage("on_delete()")
  3724. response = None
  3725. bt_ok = None
  3726. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3727. # a geometry object before we update it.
  3728. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3729. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3730. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3731. msgbox = QtWidgets.QMessageBox()
  3732. msgbox.setWindowTitle(_("Delete objects"))
  3733. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3734. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3735. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3736. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3737. "the selected objects?"))
  3738. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3739. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3740. msgbox.setDefaultButton(bt_ok)
  3741. msgbox.exec_()
  3742. response = msgbox.clickedButton()
  3743. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3744. response = bt_ok
  3745. if response == bt_ok:
  3746. if self.collection.get_active():
  3747. self.log.debug("App.on_delete()")
  3748. for obj_active in self.collection.get_selected():
  3749. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3750. if obj_active.kind == 'gerber':
  3751. obj_active.mark_shapes_storage.clear()
  3752. obj_active.mark_shapes.clear(update=True)
  3753. obj_active.mark_shapes.enabled = False
  3754. elif obj_active.kind == 'cncjob':
  3755. try:
  3756. obj_active.text_col.enabled = False
  3757. del obj_active.text_col
  3758. obj_active.annotation.clear(update=True)
  3759. del obj_active.annotation
  3760. obj_active.probing_shapes.clear(update=True)
  3761. except AttributeError as e:
  3762. log.debug(
  3763. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3764. )
  3765. while self.collection.get_selected():
  3766. self.delete_first_selected()
  3767. # make sure that the selection shape is deleted, too
  3768. self.delete_selection_shape()
  3769. # if there are no longer objects delete also the exclusion areas shapes
  3770. if not self.collection.get_list():
  3771. self.exc_areas.clear_shapes()
  3772. self.inform.emit('%s...' % _("Object(s) deleted"))
  3773. else:
  3774. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3775. else:
  3776. self.inform.emit(_("Save the work in Editor and try again ..."))
  3777. def delete_first_selected(self):
  3778. # Keep this for later
  3779. try:
  3780. sel_obj = self.collection.get_active()
  3781. name = sel_obj.options["name"]
  3782. isPlotted = sel_obj.options["plot"]
  3783. except AttributeError:
  3784. self.log.debug("Nothing selected for deletion")
  3785. return
  3786. if self.is_legacy is True:
  3787. # Remove plot only if the object was plotted otherwise delaxes will fail
  3788. if isPlotted:
  3789. try:
  3790. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3791. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3792. except Exception as e:
  3793. log.debug("App.delete_first_selected() --> %s" % str(e))
  3794. self.plotcanvas.auto_adjust_axes()
  3795. # Remove from dictionary
  3796. self.collection.delete_active()
  3797. # Clear form
  3798. self.setup_default_properties_tab()
  3799. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3800. def on_set_origin(self):
  3801. """
  3802. Set the origin to the left mouse click position
  3803. :return: None
  3804. """
  3805. # display the message for the user
  3806. # and ask him to click on the desired position
  3807. self.defaults.report_usage("on_set_origin()")
  3808. def origin_replot():
  3809. def worker_task():
  3810. with self.proc_container.new('%s...' % _("Plotting")):
  3811. for obj in self.collection.get_list():
  3812. obj.plot()
  3813. self.plotcanvas.fit_view()
  3814. if self.is_legacy:
  3815. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3816. else:
  3817. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3818. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3819. self.inform.emit(_('Click to set the origin ...'))
  3820. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3821. # first disconnect it as it may have been used by something else
  3822. try:
  3823. self.replot_signal.disconnect()
  3824. except TypeError:
  3825. pass
  3826. self.replot_signal[list].connect(origin_replot)
  3827. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3828. """
  3829. :param event:
  3830. :param location:
  3831. :param noplot:
  3832. :param use_thread:
  3833. :return:
  3834. """
  3835. noplot_sig = noplot
  3836. def worker_task():
  3837. with self.proc_container.new(_("Setting Origin...")):
  3838. obj_list = self.collection.get_list()
  3839. for obj in obj_list:
  3840. obj.offset((x, y))
  3841. self.app_obj.object_changed.emit(obj)
  3842. # Update the object bounding box options
  3843. a, b, c, d = obj.bounds()
  3844. obj.options['xmin'] = a
  3845. obj.options['ymin'] = b
  3846. obj.options['xmax'] = c
  3847. obj.options['ymax'] = d
  3848. self.inform.emit('[success] %s...' % _('Origin set'))
  3849. for obj in obj_list:
  3850. out_name = obj.options["name"]
  3851. if obj.kind == 'gerber':
  3852. obj.source_file = self.export_gerber(
  3853. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3854. elif obj.kind == 'excellon':
  3855. obj.source_file = self.export_excellon(
  3856. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3857. if noplot_sig is False:
  3858. self.replot_signal.emit([])
  3859. if location is not None:
  3860. if len(location) != 2:
  3861. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3862. return 'fail'
  3863. x, y = location
  3864. if use_thread is True:
  3865. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3866. else:
  3867. worker_task()
  3868. self.should_we_save = True
  3869. return
  3870. if event is not None and event.button == 1:
  3871. if self.is_legacy is False:
  3872. event_pos = event.pos
  3873. else:
  3874. event_pos = (event.xdata, event.ydata)
  3875. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3876. if self.grid_status():
  3877. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3878. else:
  3879. pos = pos_canvas
  3880. x = 0 - pos[0]
  3881. y = 0 - pos[1]
  3882. if use_thread is True:
  3883. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3884. else:
  3885. worker_task()
  3886. self.should_we_save = True
  3887. def on_move2origin(self, use_thread=True):
  3888. """
  3889. Move selected objects to origin.
  3890. :param use_thread: Control if to use threaded operation. Boolean.
  3891. :return:
  3892. """
  3893. def worker_task():
  3894. with self.proc_container.new(_("Moving to Origin...")):
  3895. obj_list = self.collection.get_selected()
  3896. if not obj_list:
  3897. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3898. return
  3899. xminlist = []
  3900. yminlist = []
  3901. # first get a bounding box to fit all
  3902. for obj in obj_list:
  3903. xmin, ymin, xmax, ymax = obj.bounds()
  3904. xminlist.append(xmin)
  3905. yminlist.append(ymin)
  3906. # get the minimum x,y for all objects selected
  3907. x = min(xminlist)
  3908. y = min(yminlist)
  3909. for obj in obj_list:
  3910. obj.offset((-x, -y))
  3911. self.app_obj.object_changed.emit(obj)
  3912. # Update the object bounding box options
  3913. a, b, c, d = obj.bounds()
  3914. obj.options['xmin'] = a
  3915. obj.options['ymin'] = b
  3916. obj.options['xmax'] = c
  3917. obj.options['ymax'] = d
  3918. for obj in obj_list:
  3919. obj.plot()
  3920. for obj in obj_list:
  3921. out_name = obj.options["name"]
  3922. if obj.kind == 'gerber':
  3923. obj.source_file = self.export_gerber(
  3924. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3925. elif obj.kind == 'excellon':
  3926. obj.source_file = self.export_excellon(
  3927. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3928. self.inform.emit('[success] %s...' % _('Origin set'))
  3929. if use_thread is True:
  3930. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3931. else:
  3932. worker_task()
  3933. self.should_we_save = True
  3934. def on_jump_to(self, custom_location=None, fit_center=True):
  3935. """
  3936. Jump to a location by setting the mouse cursor location.
  3937. :param custom_location: Jump to a specified point. (x, y) tuple.
  3938. :param fit_center: If to fit view. Boolean.
  3939. :return:
  3940. """
  3941. self.defaults.report_usage("on_jump_to()")
  3942. if not custom_location:
  3943. dia_box_location = None
  3944. try:
  3945. dia_box_location = eval(self.clipboard.text())
  3946. except Exception:
  3947. pass
  3948. if type(dia_box_location) == tuple:
  3949. dia_box_location = str(dia_box_location)
  3950. else:
  3951. dia_box_location = None
  3952. # dia_box = Dialog_box(title=_("Jump to ..."),
  3953. # label=_("Enter the coordinates in format X,Y:"),
  3954. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3955. # initial_text=dia_box_location)
  3956. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3957. label=_("Enter the coordinates in format X,Y:"),
  3958. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3959. initial_text=dia_box_location,
  3960. reference=self.defaults['global_jump_ref'])
  3961. if dia_box.ok is True:
  3962. try:
  3963. location = eval(dia_box.location)
  3964. if not isinstance(location, tuple):
  3965. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3966. return
  3967. if dia_box.reference == 'rel':
  3968. rel_x = self.mouse[0] + location[0]
  3969. rel_y = self.mouse[1] + location[1]
  3970. location = (rel_x, rel_y)
  3971. self.defaults['global_jump_ref'] = dia_box.reference
  3972. except Exception:
  3973. return
  3974. else:
  3975. return
  3976. else:
  3977. location = custom_location
  3978. self.jump_signal.emit(location)
  3979. if fit_center:
  3980. self.plotcanvas.fit_center(loc=location)
  3981. cursor = QtGui.QCursor()
  3982. if self.is_legacy is False:
  3983. # I don't know where those differences come from but they are constant for the current
  3984. # execution of the application and they are multiples of a value around 0.0263mm.
  3985. # In a random way sometimes they are more sometimes they are less
  3986. # if units == 'MM':
  3987. # cal_factor = 0.0263
  3988. # else:
  3989. # cal_factor = 0.0263 / 25.4
  3990. cal_location = (location[0], location[1])
  3991. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3992. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3993. j_pos = (
  3994. int(canvas_origin.x() + round(jump_loc[0])),
  3995. int(canvas_origin.y() + round(jump_loc[1]))
  3996. )
  3997. cursor.setPos(j_pos[0], j_pos[1])
  3998. else:
  3999. # find the canvas origin which is in the top left corner
  4000. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4001. # determine the coordinates for the lowest left point of the canvas
  4002. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4003. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4004. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4005. # canvas) and the point (width, height) is in the top-right location
  4006. loc = self.plotcanvas.axes.transData.transform_point(location)
  4007. j_pos = (
  4008. int(x0 + loc[0]),
  4009. int(y0 - loc[1])
  4010. )
  4011. cursor.setPos(j_pos[0], j_pos[1])
  4012. self.plotcanvas.mouse = [location[0], location[1]]
  4013. if self.defaults["global_cursor_color_enabled"] is True:
  4014. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4015. else:
  4016. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4017. if self.grid_status():
  4018. # Update cursor
  4019. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4020. symbol='++', edge_color=self.cursor_color_3D,
  4021. edge_width=self.defaults["global_cursor_width"],
  4022. size=self.defaults["global_cursor_size"])
  4023. # Set the relative position label
  4024. dx = location[0] - float(self.rel_point1[0])
  4025. dy = location[1] - float(self.rel_point1[1])
  4026. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4027. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4028. # Set the position label
  4029. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4030. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4031. units = self.defaults["units"].lower()
  4032. self.plotcanvas.text_hud.text = \
  4033. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4034. dx, units, dy, units, location[0], units, location[1], units)
  4035. self.inform.emit('[success] %s' % _("Done."))
  4036. return location
  4037. def on_locate(self, obj, fit_center=True):
  4038. """
  4039. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4040. :param obj: The object on which to locate certain points
  4041. :param fit_center: If to fit view. Boolean.
  4042. :return: A point location. (x, y) tuple.
  4043. """
  4044. self.defaults.report_usage("on_locate()")
  4045. if obj is None:
  4046. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4047. return 'fail'
  4048. class DialogBoxChoice(QtWidgets.QDialog):
  4049. def __init__(self, title=None, icon=None, choice='bl'):
  4050. """
  4051. :param title: string with the window title
  4052. """
  4053. super(DialogBoxChoice, self).__init__()
  4054. self.ok = False
  4055. self.setWindowIcon(icon)
  4056. self.setWindowTitle(str(title))
  4057. self.form = QtWidgets.QFormLayout(self)
  4058. self.ref_radio = RadioSet([
  4059. {"label": _("Bottom-Left"), "value": "bl"},
  4060. {"label": _("Top-Left"), "value": "tl"},
  4061. {"label": _("Bottom-Right"), "value": "br"},
  4062. {"label": _("Top-Right"), "value": "tr"},
  4063. {"label": _("Center"), "value": "c"}
  4064. ], orientation='vertical', stretch=False)
  4065. self.ref_radio.set_value(choice)
  4066. self.form.addRow(self.ref_radio)
  4067. self.button_box = QtWidgets.QDialogButtonBox(
  4068. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4069. Qt.Horizontal, parent=self)
  4070. self.form.addRow(self.button_box)
  4071. self.button_box.accepted.connect(self.accept)
  4072. self.button_box.rejected.connect(self.reject)
  4073. if self.exec_() == QtWidgets.QDialog.Accepted:
  4074. self.ok = True
  4075. self.location_point = self.ref_radio.get_value()
  4076. else:
  4077. self.ok = False
  4078. self.location_point = None
  4079. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4080. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4081. choice=self.defaults['global_locate_pt'])
  4082. if dia_box.ok is True:
  4083. try:
  4084. location_point = dia_box.location_point
  4085. self.defaults['global_locate_pt'] = dia_box.location_point
  4086. except Exception:
  4087. return
  4088. else:
  4089. return
  4090. loc_b = obj.bounds()
  4091. if location_point == 'bl':
  4092. location = (loc_b[0], loc_b[1])
  4093. elif location_point == 'tl':
  4094. location = (loc_b[0], loc_b[3])
  4095. elif location_point == 'br':
  4096. location = (loc_b[2], loc_b[1])
  4097. elif location_point == 'tr':
  4098. location = (loc_b[2], loc_b[3])
  4099. else:
  4100. # center
  4101. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4102. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4103. location = (cx, cy)
  4104. self.locate_signal.emit(location, location_point)
  4105. if fit_center:
  4106. self.plotcanvas.fit_center(loc=location)
  4107. cursor = QtGui.QCursor()
  4108. if self.is_legacy is False:
  4109. # I don't know where those differences come from but they are constant for the current
  4110. # execution of the application and they are multiples of a value around 0.0263mm.
  4111. # In a random way sometimes they are more sometimes they are less
  4112. # if units == 'MM':
  4113. # cal_factor = 0.0263
  4114. # else:
  4115. # cal_factor = 0.0263 / 25.4
  4116. cal_location = (location[0], location[1])
  4117. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4118. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4119. j_pos = (
  4120. int(canvas_origin.x() + round(jump_loc[0])),
  4121. int(canvas_origin.y() + round(jump_loc[1]))
  4122. )
  4123. cursor.setPos(j_pos[0], j_pos[1])
  4124. else:
  4125. # find the canvas origin which is in the top left corner
  4126. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4127. # determine the coordinates for the lowest left point of the canvas
  4128. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4129. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4130. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4131. # canvas) and the point (width, height) is in the top-right location
  4132. loc = self.plotcanvas.axes.transData.transform_point(location)
  4133. j_pos = (
  4134. int(x0 + loc[0]),
  4135. int(y0 - loc[1])
  4136. )
  4137. cursor.setPos(j_pos[0], j_pos[1])
  4138. self.plotcanvas.mouse = [location[0], location[1]]
  4139. if self.defaults["global_cursor_color_enabled"] is True:
  4140. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4141. else:
  4142. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4143. if self.grid_status():
  4144. # Update cursor
  4145. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4146. symbol='++', edge_color=self.cursor_color_3D,
  4147. edge_width=self.defaults["global_cursor_width"],
  4148. size=self.defaults["global_cursor_size"])
  4149. # Set the relative position label
  4150. self.dx = location[0] - float(self.rel_point1[0])
  4151. self.dy = location[1] - float(self.rel_point1[1])
  4152. # Set the position label
  4153. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4154. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4155. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4156. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4157. units = self.defaults["units"].lower()
  4158. self.plotcanvas.text_hud.text = \
  4159. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4160. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4161. self.inform.emit('[success] %s' % _("Done."))
  4162. return location
  4163. def on_copy_command(self):
  4164. """
  4165. Will copy a selection of objects, creating new objects.
  4166. :return:
  4167. """
  4168. self.defaults.report_usage("on_copy_command()")
  4169. def initialize(obj_init, app):
  4170. """
  4171. :param obj_init: the new object
  4172. :type obj_init: class
  4173. :param app: An instance of the App class
  4174. :type app: App
  4175. :return: None
  4176. :rtype:
  4177. """
  4178. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4179. try:
  4180. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4181. except AttributeError:
  4182. pass
  4183. try:
  4184. obj_init.apertures = deepcopy(obj.apertures)
  4185. except AttributeError:
  4186. pass
  4187. try:
  4188. if obj.tools:
  4189. obj_init.tools = deepcopy(obj.tools)
  4190. except Exception as err:
  4191. log.debug("App.on_copy_command() --> %s" % str(err))
  4192. try:
  4193. obj_init.source_file = deepcopy(obj.source_file)
  4194. except (AttributeError, TypeError):
  4195. pass
  4196. def initialize_excellon(obj_init, app):
  4197. obj_init.source_file = deepcopy(obj.source_file)
  4198. obj_init.tools = deepcopy(obj.tools)
  4199. # drills are offset, so they need to be deep copied
  4200. obj_init.drills = deepcopy(obj.drills)
  4201. # slots are offset, so they need to be deep copied
  4202. obj_init.slots = deepcopy(obj.slots)
  4203. obj_init.create_geometry()
  4204. def initialize_script(obj_init, app_obj):
  4205. obj_init.source_file = deepcopy(obj.source_file)
  4206. def initialize_document(obj_init, app_obj):
  4207. obj_init.source_file = deepcopy(obj.source_file)
  4208. for obj in self.collection.get_selected():
  4209. obj_name = obj.options["name"]
  4210. try:
  4211. if isinstance(obj, ExcellonObject):
  4212. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4213. elif isinstance(obj, GerberObject):
  4214. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4215. elif isinstance(obj, GeometryObject):
  4216. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4217. elif isinstance(obj, ScriptObject):
  4218. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4219. elif isinstance(obj, DocumentObject):
  4220. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4221. except Exception as e:
  4222. return "Operation failed: %s" % str(e)
  4223. def on_copy_object2(self, custom_name):
  4224. def initialize_geometry(obj_init, app):
  4225. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4226. try:
  4227. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4228. except AttributeError:
  4229. pass
  4230. try:
  4231. obj_init.apertures = deepcopy(obj.apertures)
  4232. except AttributeError:
  4233. pass
  4234. try:
  4235. if obj.tools:
  4236. obj_init.tools = deepcopy(obj.tools)
  4237. except Exception as ee:
  4238. log.debug("on_copy_object2() --> %s" % str(ee))
  4239. def initialize_gerber(obj_init, app):
  4240. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4241. obj_init.apertures = deepcopy(obj.apertures)
  4242. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4243. def initialize_excellon(obj_init, app):
  4244. obj_init.tools = deepcopy(obj.tools)
  4245. # drills are offset, so they need to be deep copied
  4246. obj_init.drills = deepcopy(obj.drills)
  4247. # slots are offset, so they need to be deep copied
  4248. obj_init.slots = deepcopy(obj.slots)
  4249. obj_init.create_geometry()
  4250. for obj in self.collection.get_selected():
  4251. obj_name = obj.options["name"]
  4252. try:
  4253. if isinstance(obj, ExcellonObject):
  4254. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4255. elif isinstance(obj, GerberObject):
  4256. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4257. elif isinstance(obj, GeometryObject):
  4258. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4259. except Exception as er:
  4260. return "Operation failed: %s" % str(er)
  4261. def on_rename_object(self, text):
  4262. """
  4263. Will rename an object.
  4264. :param text: New name for the object.
  4265. :return:
  4266. """
  4267. self.defaults.report_usage("on_rename_object()")
  4268. named_obj = self.collection.get_active()
  4269. for obj in named_obj:
  4270. if obj is list:
  4271. self.on_rename_object(text)
  4272. else:
  4273. try:
  4274. obj.options['name'] = text
  4275. except Exception as e:
  4276. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4277. def convert_any2geo(self):
  4278. """
  4279. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4280. :return:
  4281. """
  4282. self.defaults.report_usage("convert_any2geo()")
  4283. def initialize(obj_init, app):
  4284. obj_init.solid_geometry = obj.solid_geometry
  4285. try:
  4286. obj_init.follow_geometry = obj.follow_geometry
  4287. except AttributeError:
  4288. pass
  4289. try:
  4290. obj_init.apertures = obj.apertures
  4291. except AttributeError:
  4292. pass
  4293. try:
  4294. if obj.tools:
  4295. obj_init.tools = obj.tools
  4296. except AttributeError:
  4297. pass
  4298. def initialize_excellon(obj_init, app):
  4299. # objs = self.collection.get_selected()
  4300. # GeometryObject.merge(objs, obj)
  4301. solid_geo = []
  4302. for tool in obj.tools:
  4303. for geo in obj.tools[tool]['solid_geometry']:
  4304. solid_geo.append(geo)
  4305. obj_init.solid_geometry = deepcopy(solid_geo)
  4306. if not self.collection.get_selected():
  4307. log.warning("App.convert_any2geo --> No object selected")
  4308. self.inform.emit('[WARNING_NOTCL] %s' %
  4309. _("No object is selected. Select an object and try again."))
  4310. return
  4311. for obj in self.collection.get_selected():
  4312. obj_name = obj.options["name"]
  4313. try:
  4314. if obj.kind == 'excellon':
  4315. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4316. else:
  4317. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4318. except Exception as e:
  4319. return "Operation failed: %s" % str(e)
  4320. def convert_any2gerber(self):
  4321. """
  4322. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4323. :return:
  4324. """
  4325. def initialize_geometry(obj_init, app):
  4326. apertures = {}
  4327. apid = 0
  4328. apertures[str(apid)] = {}
  4329. apertures[str(apid)]['geometry'] = []
  4330. for obj_orig in obj.solid_geometry:
  4331. new_elem = {}
  4332. new_elem['solid'] = obj_orig
  4333. try:
  4334. new_elem['follow'] = obj_orig.exterior
  4335. except AttributeError:
  4336. pass
  4337. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4338. apertures[str(apid)]['size'] = 0.0
  4339. apertures[str(apid)]['type'] = 'C'
  4340. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4341. obj_init.apertures = deepcopy(apertures)
  4342. def initialize_excellon(obj_init, app):
  4343. apertures = {}
  4344. apid = 10
  4345. for tool in obj.tools:
  4346. apertures[str(apid)] = {}
  4347. apertures[str(apid)]['geometry'] = []
  4348. for geo in obj.tools[tool]['solid_geometry']:
  4349. new_el = {}
  4350. new_el['solid'] = geo
  4351. new_el['follow'] = geo.exterior
  4352. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4353. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4354. apertures[str(apid)]['type'] = 'C'
  4355. apid += 1
  4356. # create solid_geometry
  4357. solid_geometry = []
  4358. for apid in apertures:
  4359. for geo_el in apertures[apid]['geometry']:
  4360. solid_geometry.append(geo_el['solid'])
  4361. solid_geometry = MultiPolygon(solid_geometry)
  4362. solid_geometry = solid_geometry.buffer(0.0000001)
  4363. obj_init.solid_geometry = deepcopy(solid_geometry)
  4364. obj_init.apertures = deepcopy(apertures)
  4365. # clear the working objects (perhaps not necessary due of Python GC)
  4366. apertures.clear()
  4367. if not self.collection.get_selected():
  4368. log.warning("App.convert_any2gerber --> No object selected")
  4369. self.inform.emit('[WARNING_NOTCL] %s' %
  4370. _("No object is selected. Select an object and try again."))
  4371. return
  4372. for obj in self.collection.get_selected():
  4373. obj_name = obj.options["name"]
  4374. try:
  4375. if obj.kind == 'excellon':
  4376. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4377. elif obj.kind == 'geometry':
  4378. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4379. else:
  4380. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4381. except Exception as e:
  4382. return "Operation failed: %s" % str(e)
  4383. def convert_any2excellon(self):
  4384. """
  4385. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4386. :return:
  4387. """
  4388. def initialize_geometry(obj_init, app):
  4389. tools = {}
  4390. tooluid = 1
  4391. obj_init.solid_geometry = []
  4392. for geo in obj.solid_geometry:
  4393. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4394. continue
  4395. minx, miny, maxx, maxy = geo.bounds
  4396. new_dia = min([maxx-minx, maxy-miny])
  4397. new_drill = geo.centroid
  4398. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4399. current_tooldias = []
  4400. if tools:
  4401. for tool in tools:
  4402. if tools[tool] and 'tooldia' in tools[tool]:
  4403. current_tooldias.append(tools[tool]['tooldia'])
  4404. if new_dia in current_tooldias:
  4405. for tool in tools:
  4406. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4407. new_dia)):
  4408. tools[tool]['drills'].append(new_drill)
  4409. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4410. else:
  4411. tools[tooluid] = {}
  4412. tools[tooluid]['tooldia'] = new_dia
  4413. tools[tooluid]['drills'] = [new_drill]
  4414. tools[tooluid]['slots'] = []
  4415. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4416. tooluid += 1
  4417. try:
  4418. obj_init.solid_geometry.append(new_drill_geo)
  4419. except (TypeError, AttributeError):
  4420. obj_init.solid_geometry = [new_drill_geo]
  4421. obj_init.tools = deepcopy(tools)
  4422. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4423. def initialize_gerber(obj_init, app):
  4424. tools = {}
  4425. tooluid = 1
  4426. obj_init.solid_geometry = []
  4427. for apid in obj.apertures:
  4428. if 'geometry' in obj.apertures[apid]:
  4429. for geo_dict in obj.apertures[apid]['geometry']:
  4430. if 'follow' in geo_dict:
  4431. if isinstance(geo_dict['follow'], Point):
  4432. geo = geo_dict['solid']
  4433. minx, miny, maxx, maxy = geo.bounds
  4434. new_dia = min([maxx - minx, maxy - miny])
  4435. new_drill = geo.centroid
  4436. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4437. current_tooldias = []
  4438. if tools:
  4439. for tool in tools:
  4440. if tools[tool] and 'tooldia' in tools[tool]:
  4441. current_tooldias.append(
  4442. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4443. )
  4444. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4445. for tool in tools:
  4446. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4447. '%.*f' % (self.decimals, new_dia)):
  4448. if new_drill not in tools[tool]['drills']:
  4449. tools[tool]['drills'].append(new_drill)
  4450. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4451. else:
  4452. tools[tooluid] = {}
  4453. tools[tooluid]['tooldia'] = new_dia
  4454. tools[tooluid]['drills'] = [new_drill]
  4455. tools[tooluid]['slots'] = []
  4456. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4457. tooluid += 1
  4458. try:
  4459. obj_init.solid_geometry.append(new_drill_geo)
  4460. except (TypeError, AttributeError):
  4461. obj_init.solid_geometry = [new_drill_geo]
  4462. elif isinstance(geo_dict['follow'], LineString):
  4463. geo_coords = list(geo_dict['follow'].coords)
  4464. # slots can have only a start and stop point and no intermediate points
  4465. if len(geo_coords) != 2:
  4466. continue
  4467. geo = geo_dict['solid']
  4468. try:
  4469. new_dia = obj.apertures[apid]['size']
  4470. except Exception:
  4471. continue
  4472. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4473. new_slot_geo = geo
  4474. current_tooldias = []
  4475. if tools:
  4476. for tool in tools:
  4477. if tools[tool] and 'tooldia' in tools[tool]:
  4478. current_tooldias.append(
  4479. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4480. )
  4481. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4482. for tool in tools:
  4483. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4484. '%.*f' % (self.decimals, new_dia)):
  4485. if new_slot not in tools[tool]['slots']:
  4486. tools[tool]['slots'].append(new_slot)
  4487. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4488. else:
  4489. tools[tooluid] = {}
  4490. tools[tooluid]['tooldia'] = new_dia
  4491. tools[tooluid]['drills'] = []
  4492. tools[tooluid]['slots'] = [new_slot]
  4493. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4494. tooluid += 1
  4495. try:
  4496. obj_init.solid_geometry.append(new_slot_geo)
  4497. except (TypeError, AttributeError):
  4498. obj_init.solid_geometry = [new_slot_geo]
  4499. obj_init.tools = deepcopy(tools)
  4500. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4501. if not self.collection.get_selected():
  4502. log.warning("App.convert_any2excellon--> No object selected")
  4503. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4504. return
  4505. for obj in self.collection.get_selected():
  4506. obj_name = obj.options["name"]
  4507. try:
  4508. if obj.kind == 'gerber':
  4509. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4510. elif obj.kind == 'geometry':
  4511. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4512. else:
  4513. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4514. except Exception as e:
  4515. return "Operation failed: %s" % str(e)
  4516. def abort_all_tasks(self):
  4517. """
  4518. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4519. on the first possible occasion.
  4520. :return:
  4521. """
  4522. if self.abort_flag is False:
  4523. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4524. self.abort_flag = True
  4525. self.cleanup.emit()
  4526. def app_is_idle(self):
  4527. if self.abort_flag:
  4528. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4529. self.abort_flag = False
  4530. def on_selectall(self):
  4531. """
  4532. Will draw a selection box shape around the selected objects.
  4533. :return:
  4534. """
  4535. self.defaults.report_usage("on_selectall()")
  4536. # delete the possible selection box around a possible selected object
  4537. self.delete_selection_shape()
  4538. for name in self.collection.get_names():
  4539. self.collection.set_active(name)
  4540. curr_sel_obj = self.collection.get_by_name(name)
  4541. # create the selection box around the selected object
  4542. if self.defaults['global_selection_shape'] is True:
  4543. self.draw_selection_shape(curr_sel_obj)
  4544. def on_toggle_preferences(self):
  4545. pref_open = False
  4546. for idx in range(self.ui.plot_tab_area.count()):
  4547. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4548. pref_open = True
  4549. if pref_open:
  4550. for idx in range(self.ui.plot_tab_area.count()):
  4551. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4552. self.ui.plot_tab_area.removeTab(idx)
  4553. break
  4554. self.ui.pref_status_label.setStyleSheet("")
  4555. else:
  4556. self.on_preferences()
  4557. def on_preferences(self):
  4558. """
  4559. Adds the Preferences in a Tab in Plot Area
  4560. :return:
  4561. """
  4562. # add the tab if it was closed
  4563. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4564. # delete the absolute and relative position and messages in the infobar
  4565. # self.ui.position_label.setText("")
  4566. # self.ui.rel_position_label.setText("")
  4567. # hide coordinates toolbars in the infobar while in DB
  4568. self.ui.coords_toolbar.hide()
  4569. self.ui.delta_coords_toolbar.hide()
  4570. # Switch plot_area to preferences page
  4571. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4572. # self.ui.show()
  4573. self.ui.pref_status_label.setStyleSheet("""
  4574. QLabel
  4575. {
  4576. color: black;
  4577. background-color: lightseagreen;
  4578. }
  4579. """
  4580. )
  4581. # detect changes in the preferences
  4582. for idx in range(self.ui.pref_tab_area.count()):
  4583. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4584. try:
  4585. try:
  4586. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4587. except (TypeError, AttributeError):
  4588. pass
  4589. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4590. except AttributeError:
  4591. pass
  4592. try:
  4593. try:
  4594. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4595. except (TypeError, AttributeError):
  4596. pass
  4597. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4598. except AttributeError:
  4599. pass
  4600. try:
  4601. try:
  4602. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4603. except (TypeError, AttributeError):
  4604. pass
  4605. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4606. except AttributeError:
  4607. pass
  4608. try:
  4609. try:
  4610. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4611. except (TypeError, AttributeError):
  4612. pass
  4613. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4614. except AttributeError:
  4615. pass
  4616. try:
  4617. try:
  4618. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4619. except (TypeError, AttributeError):
  4620. pass
  4621. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4622. except AttributeError:
  4623. pass
  4624. def on_tools_database(self, source='app'):
  4625. """
  4626. Adds the Tools Database in a Tab in Plot Area.
  4627. :return:
  4628. """
  4629. for idx in range(self.ui.plot_tab_area.count()):
  4630. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4631. # there can be only one instance of Tools Database at one time
  4632. return
  4633. if source == 'app':
  4634. self.tools_db_tab = ToolsDB2(
  4635. app=self,
  4636. parent=self.ui,
  4637. callback_on_edited=self.on_tools_db_edited,
  4638. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4639. )
  4640. elif source == 'ncc':
  4641. self.tools_db_tab = ToolsDB2(
  4642. app=self,
  4643. parent=self.ui,
  4644. callback_on_edited=self.on_tools_db_edited,
  4645. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4646. )
  4647. elif source == 'paint':
  4648. self.tools_db_tab = ToolsDB2(
  4649. app=self,
  4650. parent=self.ui,
  4651. callback_on_edited=self.on_tools_db_edited,
  4652. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4653. )
  4654. elif source == 'iso':
  4655. self.tools_db_tab = ToolsDB2(
  4656. app=self,
  4657. parent=self.ui,
  4658. callback_on_edited=self.on_tools_db_edited,
  4659. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4660. )
  4661. elif source == 'cutout':
  4662. self.tools_db_tab = ToolsDB2(
  4663. app=self,
  4664. parent=self.ui,
  4665. callback_on_edited=self.on_tools_db_edited,
  4666. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4667. )
  4668. # add the tab if it was closed
  4669. try:
  4670. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4671. self.tools_db_tab.setObjectName("database_tab")
  4672. except Exception as e:
  4673. log.debug("App.on_tools_database() --> %s" % str(e))
  4674. return
  4675. # delete the absolute and relative position and messages in the infobar
  4676. # self.ui.position_label.setText("")
  4677. # self.ui.rel_position_label.setText("")
  4678. # hide coordinates toolbars in the infobar while in DB
  4679. self.ui.coords_toolbar.hide()
  4680. self.ui.delta_coords_toolbar.hide()
  4681. # Switch plot_area to preferences page
  4682. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4683. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4684. self.tools_db_tab.ui_connect()
  4685. def on_tools_db_edited(self):
  4686. """
  4687. Executed whenever a tool is edited in Tools Database.
  4688. Will color the text of the Tools Database tab to Red color.
  4689. :return:
  4690. """
  4691. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4692. for idx in range(self.ui.plot_tab_area.count()):
  4693. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4694. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4695. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4696. self.tools_db_changed_flag = True
  4697. def on_geometry_tool_add_from_db_executed(self, tool):
  4698. """
  4699. Here add the tool from DB in the selected geometry object.
  4700. :return:
  4701. """
  4702. tool_from_db = deepcopy(tool)
  4703. obj = self.collection.get_active()
  4704. if obj.kind == 'geometry':
  4705. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4706. # close the tab and delete it
  4707. for idx in range(self.ui.plot_tab_area.count()):
  4708. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4709. wdg = self.ui.plot_tab_area.widget(idx)
  4710. wdg.deleteLater()
  4711. self.ui.plot_tab_area.removeTab(idx)
  4712. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4713. elif obj.kind == 'gerber':
  4714. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4715. # close the tab and delete it
  4716. for idx in range(self.ui.plot_tab_area.count()):
  4717. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4718. wdg = self.ui.plot_tab_area.widget(idx)
  4719. wdg.deleteLater()
  4720. self.ui.plot_tab_area.removeTab(idx)
  4721. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4722. else:
  4723. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4724. def on_plot_area_tab_closed(self, tab_obj_name):
  4725. """
  4726. Executed whenever a QTab is closed in the Plot Area.
  4727. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4728. :return:
  4729. """
  4730. if tab_obj_name == "preferences_tab":
  4731. self.preferencesUiManager.on_close_preferences_tab()
  4732. elif tab_obj_name == "database_tab":
  4733. # disconnect the signals from the table widget in tab
  4734. self.tools_db_tab.ui_disconnect()
  4735. if self.tools_db_changed_flag is True:
  4736. msgbox = QtWidgets.QMessageBox()
  4737. msgbox.setText(_("One or more Tools are edited.\n"
  4738. "Do you want to update the Tools Database?"))
  4739. msgbox.setWindowTitle(_("Save Tools Database"))
  4740. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4741. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4742. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4743. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4744. msgbox.setDefaultButton(bt_yes)
  4745. msgbox.exec_()
  4746. response = msgbox.clickedButton()
  4747. if response == bt_yes:
  4748. self.tools_db_tab.on_save_tools_db()
  4749. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4750. else:
  4751. self.tools_db_changed_flag = False
  4752. self.inform.emit('')
  4753. return
  4754. self.tools_db_tab.deleteLater()
  4755. elif tab_obj_name == "text_editor_tab":
  4756. self.toggle_codeeditor = False
  4757. elif tab_obj_name == "bookmarks_tab":
  4758. self.book_dialog_tab.rebuild_actions()
  4759. self.book_dialog_tab.deleteLater()
  4760. else:
  4761. pass
  4762. # restore the coords toolbars
  4763. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4764. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4765. def on_flipy(self):
  4766. """
  4767. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4768. :return:
  4769. """
  4770. self.defaults.report_usage("on_flipy()")
  4771. obj_list = self.collection.get_selected()
  4772. xminlist = []
  4773. yminlist = []
  4774. xmaxlist = []
  4775. ymaxlist = []
  4776. if not obj_list:
  4777. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4778. else:
  4779. try:
  4780. # first get a bounding box to fit all
  4781. for obj in obj_list:
  4782. xmin, ymin, xmax, ymax = obj.bounds()
  4783. xminlist.append(xmin)
  4784. yminlist.append(ymin)
  4785. xmaxlist.append(xmax)
  4786. ymaxlist.append(ymax)
  4787. # get the minimum x,y and maximum x,y for all objects selected
  4788. xminimal = min(xminlist)
  4789. yminimal = min(yminlist)
  4790. xmaximal = max(xmaxlist)
  4791. ymaximal = max(ymaxlist)
  4792. px = 0.5 * (xminimal + xmaximal)
  4793. py = 0.5 * (yminimal + ymaximal)
  4794. # execute mirroring
  4795. for obj in obj_list:
  4796. obj.mirror('X', [px, py])
  4797. obj.plot()
  4798. self.app_obj.object_changed.emit(obj)
  4799. self.inform.emit('[success] %s' %
  4800. _("Flip on Y axis done."))
  4801. except Exception as e:
  4802. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4803. return
  4804. def on_flipx(self):
  4805. """
  4806. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4807. :return:
  4808. """
  4809. self.defaults.report_usage("on_flipx()")
  4810. obj_list = self.collection.get_selected()
  4811. xminlist = []
  4812. yminlist = []
  4813. xmaxlist = []
  4814. ymaxlist = []
  4815. if not obj_list:
  4816. self.inform.emit('[WARNING_NOTCL] %s' %
  4817. _("No object selected to Flip on X axis."))
  4818. else:
  4819. try:
  4820. # first get a bounding box to fit all
  4821. for obj in obj_list:
  4822. xmin, ymin, xmax, ymax = obj.bounds()
  4823. xminlist.append(xmin)
  4824. yminlist.append(ymin)
  4825. xmaxlist.append(xmax)
  4826. ymaxlist.append(ymax)
  4827. # get the minimum x,y and maximum x,y for all objects selected
  4828. xminimal = min(xminlist)
  4829. yminimal = min(yminlist)
  4830. xmaximal = max(xmaxlist)
  4831. ymaximal = max(ymaxlist)
  4832. px = 0.5 * (xminimal + xmaximal)
  4833. py = 0.5 * (yminimal + ymaximal)
  4834. # execute mirroring
  4835. for obj in obj_list:
  4836. obj.mirror('Y', [px, py])
  4837. obj.plot()
  4838. self.app_obj.object_changed.emit(obj)
  4839. self.inform.emit('[success] %s' %
  4840. _("Flip on X axis done."))
  4841. except Exception as e:
  4842. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4843. return
  4844. def on_rotate(self, silent=False, preset=None):
  4845. """
  4846. Executed when Options -> Rotate Selection menu entry is clicked.
  4847. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4848. :param preset: A value to be used as predefined angle for rotation.
  4849. :return:
  4850. """
  4851. self.defaults.report_usage("on_rotate()")
  4852. obj_list = self.collection.get_selected()
  4853. xminlist = []
  4854. yminlist = []
  4855. xmaxlist = []
  4856. ymaxlist = []
  4857. if not obj_list:
  4858. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4859. else:
  4860. if silent is False:
  4861. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4862. min=-360, max=360, decimals=4,
  4863. init_val=float(self.defaults['tools_transform_rotate']))
  4864. num, ok = rotatebox.get_value()
  4865. else:
  4866. num = preset
  4867. ok = True
  4868. if ok:
  4869. try:
  4870. # first get a bounding box to fit all
  4871. for obj in obj_list:
  4872. xmin, ymin, xmax, ymax = obj.bounds()
  4873. xminlist.append(xmin)
  4874. yminlist.append(ymin)
  4875. xmaxlist.append(xmax)
  4876. ymaxlist.append(ymax)
  4877. # get the minimum x,y and maximum x,y for all objects selected
  4878. xminimal = min(xminlist)
  4879. yminimal = min(yminlist)
  4880. xmaximal = max(xmaxlist)
  4881. ymaximal = max(ymaxlist)
  4882. px = 0.5 * (xminimal + xmaximal)
  4883. py = 0.5 * (yminimal + ymaximal)
  4884. for sel_obj in obj_list:
  4885. sel_obj.rotate(-float(num), point=(px, py))
  4886. sel_obj.plot()
  4887. self.app_obj.object_changed.emit(sel_obj)
  4888. self.inform.emit('[success] %s' % _("Rotation done."))
  4889. except Exception as e:
  4890. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4891. return
  4892. def on_skewx(self):
  4893. """
  4894. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4895. :return:
  4896. """
  4897. self.defaults.report_usage("on_skewx()")
  4898. obj_list = self.collection.get_selected()
  4899. xminlist = []
  4900. yminlist = []
  4901. if not obj_list:
  4902. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4903. else:
  4904. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4905. min=-360, max=360, decimals=4,
  4906. init_val=float(self.defaults['tools_transform_skew_x']))
  4907. num, ok = skewxbox.get_value()
  4908. if ok:
  4909. # first get a bounding box to fit all
  4910. for obj in obj_list:
  4911. xmin, ymin, xmax, ymax = obj.bounds()
  4912. xminlist.append(xmin)
  4913. yminlist.append(ymin)
  4914. # get the minimum x,y and maximum x,y for all objects selected
  4915. xminimal = min(xminlist)
  4916. yminimal = min(yminlist)
  4917. for obj in obj_list:
  4918. obj.skew(num, 0, point=(xminimal, yminimal))
  4919. obj.plot()
  4920. self.app_obj.object_changed.emit(obj)
  4921. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4922. def on_skewy(self):
  4923. """
  4924. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4925. :return:
  4926. """
  4927. self.defaults.report_usage("on_skewy()")
  4928. obj_list = self.collection.get_selected()
  4929. xminlist = []
  4930. yminlist = []
  4931. if not obj_list:
  4932. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4933. else:
  4934. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4935. min=-360, max=360, decimals=4,
  4936. init_val=float(self.defaults['tools_transform_skew_y']))
  4937. num, ok = skewybox.get_value()
  4938. if ok:
  4939. # first get a bounding box to fit all
  4940. for obj in obj_list:
  4941. xmin, ymin, xmax, ymax = obj.bounds()
  4942. xminlist.append(xmin)
  4943. yminlist.append(ymin)
  4944. # get the minimum x,y and maximum x,y for all objects selected
  4945. xminimal = min(xminlist)
  4946. yminimal = min(yminlist)
  4947. for obj in obj_list:
  4948. obj.skew(0, num, point=(xminimal, yminimal))
  4949. obj.plot()
  4950. self.app_obj.object_changed.emit(obj)
  4951. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4952. def on_plots_updated(self):
  4953. """
  4954. Callback used to report when the plots have changed.
  4955. Adjust axes and zooms to fit.
  4956. :return: None
  4957. """
  4958. if self.is_legacy is False:
  4959. self.plotcanvas.update()
  4960. else:
  4961. self.plotcanvas.auto_adjust_axes()
  4962. self.on_zoom_fit()
  4963. self.collection.update_view()
  4964. # self.inform.emit(_("Plots updated ..."))
  4965. def on_toolbar_replot(self):
  4966. """
  4967. Callback for toolbar button. Re-plots all objects.
  4968. :return: None
  4969. """
  4970. self.log.debug("on_toolbar_replot()")
  4971. try:
  4972. obj = self.collection.get_active()
  4973. if obj:
  4974. obj.read_form()
  4975. else:
  4976. self.on_zoom_fit()
  4977. except AttributeError as e:
  4978. log.debug("on_toolbar_replot() -> %s" % str(e))
  4979. pass
  4980. self.plot_all()
  4981. def grid_status(self):
  4982. return True if self.ui.grid_snap_btn.isChecked() else False
  4983. def populate_cmenu_grids(self):
  4984. units = self.defaults['units'].lower()
  4985. # for act in self.ui.cmenu_gridmenu.actions():
  4986. # act.triggered.disconnect()
  4987. self.ui.cmenu_gridmenu.clear()
  4988. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4989. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4990. _("Grid On/Off"))
  4991. grid_toggle.setCheckable(True)
  4992. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4993. self.ui.cmenu_gridmenu.addSeparator()
  4994. for grid in sorted_list:
  4995. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4996. "%s" % str(grid))
  4997. action.triggered.connect(self.set_grid)
  4998. self.ui.cmenu_gridmenu.addSeparator()
  4999. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5000. _("Add"))
  5001. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5002. _("Delete"))
  5003. grid_add.triggered.connect(self.on_grid_add)
  5004. grid_delete.triggered.connect(self.on_grid_delete)
  5005. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5006. def set_grid(self):
  5007. menu_action = self.sender()
  5008. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5009. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5010. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5011. def on_grid_add(self):
  5012. # ## Current application units in lower Case
  5013. units = self.defaults['units'].lower()
  5014. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5015. text=_('Enter a Grid Value:'),
  5016. min=0.0000, max=99.9999, decimals=4)
  5017. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5018. val, ok = grid_add_popup.get_value()
  5019. if ok:
  5020. if float(val) == 0:
  5021. self.inform.emit('[WARNING_NOTCL] %s' %
  5022. _("Please enter a grid value with non-zero value, in Float format."))
  5023. return
  5024. else:
  5025. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5026. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5027. self.inform.emit('[success] %s...' % _("New Grid added"))
  5028. else:
  5029. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5030. else:
  5031. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5032. def on_grid_delete(self):
  5033. # ## Current application units in lower Case
  5034. units = self.defaults['units'].lower()
  5035. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5036. text='Enter a Grid Value:',
  5037. min=0.0000, max=99.9999, decimals=4)
  5038. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5039. val, ok = grid_del_popup.get_value()
  5040. if ok:
  5041. if float(val) == 0:
  5042. self.inform.emit('[WARNING_NOTCL] %s' %
  5043. _("Please enter a grid value with non-zero value, in Float format."))
  5044. return
  5045. else:
  5046. try:
  5047. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5048. except ValueError:
  5049. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5050. return
  5051. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5052. else:
  5053. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5054. def on_shortcut_list(self):
  5055. self.defaults.report_usage("on_shortcut_list()")
  5056. # add the tab if it was closed
  5057. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5058. # delete the absolute and relative position and messages in the infobar
  5059. # self.ui.position_label.setText("")
  5060. # self.ui.rel_position_label.setText("")
  5061. # hide coordinates toolbars in the infobar while in DB
  5062. self.ui.coords_toolbar.hide()
  5063. self.ui.delta_coords_toolbar.hide()
  5064. # Switch plot_area to preferences page
  5065. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5066. # self.ui.show()
  5067. def on_select_tab(self, name):
  5068. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5069. if self.ui.splitter.sizes()[0] == 0:
  5070. self.ui.splitter.setSizes([1, 1])
  5071. else:
  5072. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5073. self.ui.splitter.setSizes([0, 1])
  5074. if name == 'project':
  5075. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5076. elif name == 'selected':
  5077. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5078. elif name == 'tool':
  5079. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5080. def on_copy_name(self):
  5081. self.defaults.report_usage("on_copy_name()")
  5082. obj = self.collection.get_active()
  5083. try:
  5084. name = obj.options["name"]
  5085. except AttributeError:
  5086. log.debug("on_copy_name() --> No object selected to copy it's name")
  5087. self.inform.emit('[WARNING_NOTCL] %s' %
  5088. _(" No object selected to copy it's name"))
  5089. return
  5090. self.clipboard.setText(name)
  5091. self.inform.emit(_("Name copied on clipboard ..."))
  5092. def on_mouse_click_over_plot(self, event):
  5093. """
  5094. Default actions are:
  5095. :param event: Contains information about the event, like which button
  5096. was clicked, the pixel coordinates and the axes coordinates.
  5097. :return: None
  5098. """
  5099. self.pos = []
  5100. if self.is_legacy is False:
  5101. event_pos = event.pos
  5102. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5103. # # Set the mouse button for panning
  5104. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5105. else:
  5106. event_pos = (event.xdata, event.ydata)
  5107. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5108. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5109. # So it can receive key presses
  5110. self.plotcanvas.native.setFocus()
  5111. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5112. if self.grid_status():
  5113. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5114. else:
  5115. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5116. try:
  5117. if event.button == 1:
  5118. # Reset here the relative coordinates so there is a new reference on the click position
  5119. if self.rel_point1 is None:
  5120. self.rel_point1 = self.pos
  5121. else:
  5122. self.rel_point2 = copy(self.rel_point1)
  5123. self.rel_point1 = self.pos
  5124. self.on_mouse_move_over_plot(event, origin_click=True)
  5125. except Exception as e:
  5126. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5127. def on_mouse_double_click_over_plot(self, event):
  5128. if event.button == 1:
  5129. self.doubleclick = True
  5130. def on_mouse_move_over_plot(self, event, origin_click=None):
  5131. """
  5132. Callback for the mouse motion event over the plot.
  5133. :param event: Contains information about the event.
  5134. :param origin_click
  5135. :return: None
  5136. """
  5137. if self.is_legacy is False:
  5138. event_pos = event.pos
  5139. if self.defaults["global_pan_button"] == '2':
  5140. pan_button = 2
  5141. else:
  5142. pan_button = 3
  5143. self.event_is_dragging = event.is_dragging
  5144. else:
  5145. event_pos = (event.xdata, event.ydata)
  5146. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5147. if self.defaults["global_pan_button"] == '2':
  5148. pan_button = 3
  5149. else:
  5150. pan_button = 2
  5151. self.event_is_dragging = self.plotcanvas.is_dragging
  5152. # So it can receive key presses but not when the Tcl Shell is active
  5153. if not self.ui.shell_dock.isVisible():
  5154. if not self.plotcanvas.native.hasFocus():
  5155. self.plotcanvas.native.setFocus()
  5156. self.pos_jump = event_pos
  5157. self.ui.popMenu.mouse_is_panning = False
  5158. if origin_click is None:
  5159. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5160. if event.button == pan_button and self.event_is_dragging == 1:
  5161. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5162. if self.ui.popMenu.popup_active:
  5163. self.ui.popMenu.popup_active = False
  5164. return
  5165. self.ui.popMenu.mouse_is_panning = True
  5166. return
  5167. if self.rel_point1 is not None:
  5168. try: # May fail in case mouse not within axes
  5169. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5170. if pos_canvas[0] is None or pos_canvas[1] is None:
  5171. return
  5172. if self.grid_status():
  5173. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5174. # Update cursor
  5175. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5176. symbol='++', edge_color=self.cursor_color_3D,
  5177. edge_width=self.defaults["global_cursor_width"],
  5178. size=self.defaults["global_cursor_size"])
  5179. else:
  5180. pos = (pos_canvas[0], pos_canvas[1])
  5181. self.dx = pos[0] - float(self.rel_point1[0])
  5182. self.dy = pos[1] - float(self.rel_point1[1])
  5183. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5184. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5185. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5186. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5187. units = self.defaults["units"].lower()
  5188. self.plotcanvas.text_hud.text = \
  5189. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5190. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5191. self.mouse = [pos[0], pos[1]]
  5192. if self.defaults['global_selection_shape'] is False:
  5193. self.selection_type = None
  5194. return
  5195. # if the mouse is moved and the LMB is clicked then the action is a selection
  5196. if self.event_is_dragging == 1 and event.button == 1:
  5197. self.delete_selection_shape()
  5198. if self.dx < 0:
  5199. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5200. face_color=self.defaults['global_alt_sel_fill'])
  5201. self.selection_type = False
  5202. elif self.dx >= 0:
  5203. self.draw_moving_selection_shape(self.pos, pos)
  5204. self.selection_type = True
  5205. else:
  5206. self.selection_type = None
  5207. else:
  5208. self.selection_type = None
  5209. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5210. if self.defaults['global_hover']:
  5211. for obj in self.collection.get_list():
  5212. try:
  5213. # select the object(s) only if it is enabled (plotted)
  5214. if obj.options['plot']:
  5215. if obj not in self.collection.get_selected():
  5216. poly_obj = Polygon(
  5217. [(obj.options['xmin'], obj.options['ymin']),
  5218. (obj.options['xmax'], obj.options['ymin']),
  5219. (obj.options['xmax'], obj.options['ymax']),
  5220. (obj.options['xmin'], obj.options['ymax'])]
  5221. )
  5222. if Point(pos).within(poly_obj):
  5223. if obj.isHovering is False:
  5224. obj.isHovering = True
  5225. obj.notHovering = True
  5226. # create the selection box around the selected object
  5227. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5228. else:
  5229. if obj.notHovering is True:
  5230. obj.notHovering = False
  5231. obj.isHovering = False
  5232. self.delete_hover_shape()
  5233. except Exception:
  5234. # the Exception here will happen if we try to select on screen and we have an
  5235. # newly (and empty) just created Geometry or Excellon object that do not have the
  5236. # xmin, xmax, ymin, ymax options.
  5237. # In this case poly_obj creation (see above) will fail
  5238. pass
  5239. except Exception as e:
  5240. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5241. self.ui.position_label.setText("")
  5242. self.ui.rel_position_label.setText("")
  5243. self.mouse = None
  5244. def on_mouse_click_release_over_plot(self, event):
  5245. """
  5246. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5247. and has been registered in ''self.__init__()''.
  5248. :param event: contains information about the event.
  5249. :return:
  5250. """
  5251. if self.is_legacy is False:
  5252. event_pos = event.pos
  5253. right_button = 2
  5254. else:
  5255. event_pos = (event.xdata, event.ydata)
  5256. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5257. right_button = 3
  5258. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5259. if self.grid_status():
  5260. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5261. else:
  5262. pos = (pos_canvas[0], pos_canvas[1])
  5263. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5264. # canvas menu
  5265. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5266. self.ui.popMenu.mouse_is_panning = False
  5267. self.cursor = QtGui.QCursor()
  5268. self.populate_cmenu_grids()
  5269. self.ui.popMenu.popup(self.cursor.pos())
  5270. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5271. # selection and then select a type of selection ("enclosing" or "touching")
  5272. if event.button == 1: # left click
  5273. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5274. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5275. if modifiers == QtCore.Qt.ShiftModifier:
  5276. # do not auto open the Project Tab
  5277. self.click_noproject = True
  5278. self.clipboard.setText(
  5279. self.defaults["global_point_clipboard_format"] %
  5280. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5281. )
  5282. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5283. return
  5284. if self.doubleclick is True:
  5285. self.doubleclick = False
  5286. if self.collection.get_selected():
  5287. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5288. if self.ui.splitter.sizes()[0] == 0:
  5289. self.ui.splitter.setSizes([1, 1])
  5290. try:
  5291. # delete the selection shape(S) as it may be in the way
  5292. self.delete_selection_shape()
  5293. self.delete_hover_shape()
  5294. except Exception as e:
  5295. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5296. return
  5297. else:
  5298. # WORKAROUND for LEGACY MODE
  5299. if self.is_legacy is True:
  5300. # if there is no move on canvas then we have no dragging selection
  5301. if self.dx == 0 or self.dy == 0:
  5302. self.selection_type = None
  5303. if self.selection_type is not None:
  5304. try:
  5305. self.selection_area_handler(self.pos, pos, self.selection_type)
  5306. self.selection_type = None
  5307. except Exception as e:
  5308. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5309. return
  5310. else:
  5311. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5312. if key_modifier == QtCore.Qt.ShiftModifier:
  5313. mod_key = 'Shift'
  5314. elif key_modifier == QtCore.Qt.ControlModifier:
  5315. mod_key = 'Control'
  5316. else:
  5317. mod_key = None
  5318. try:
  5319. if self.command_active is None:
  5320. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5321. # deselect, and if it's not selected then it will be selected
  5322. # If there is no active command (self.command_active is None) then we check if we clicked
  5323. # on a object by checking the bounding limits against mouse click position
  5324. if mod_key == self.defaults["global_mselect_key"]:
  5325. self.select_objects(key='multisel')
  5326. else:
  5327. # If there is no active command (self.command_active is None) then we check if
  5328. # we clicked on a object by checking the bounding limits against mouse click position
  5329. self.select_objects()
  5330. self.delete_hover_shape()
  5331. except Exception as e:
  5332. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5333. return
  5334. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5335. """
  5336. :param start_pos: mouse position when the selection LMB click was done
  5337. :param end_pos: mouse position when the left mouse button is released
  5338. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5339. :return:
  5340. """
  5341. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5342. # delete previous selection shape
  5343. self.delete_selection_shape()
  5344. # make all objects inactive
  5345. self.collection.set_all_inactive()
  5346. for obj in self.collection.get_list():
  5347. try:
  5348. # select the object(s) only if it is enabled (plotted)
  5349. if obj.options['plot']:
  5350. # it's a line without area
  5351. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5352. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5353. # it's a geometry with area
  5354. else:
  5355. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5356. (obj.options['xmax'], obj.options['ymin']),
  5357. (obj.options['xmax'], obj.options['ymax']),
  5358. (obj.options['xmin'], obj.options['ymax'])])
  5359. if poly_obj.is_empty or not poly_obj.is_valid:
  5360. continue
  5361. if sel_type is True:
  5362. if poly_obj.within(poly_selection):
  5363. # create the selection box around the selected object
  5364. if self.defaults['global_selection_shape'] is True:
  5365. self.draw_selection_shape(obj)
  5366. self.collection.set_active(obj.options['name'])
  5367. else:
  5368. if poly_selection.intersects(poly_obj):
  5369. # create the selection box around the selected object
  5370. if self.defaults['global_selection_shape'] is True:
  5371. self.draw_selection_shape(obj)
  5372. self.collection.set_active(obj.options['name'])
  5373. obj.selection_shape_drawn = True
  5374. except Exception as e:
  5375. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5376. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5377. # In this case poly_obj creation (see above) will fail
  5378. log.debug("App.selection_area_handler() --> %s" % str(e))
  5379. def select_objects(self, key=None):
  5380. """
  5381. Will select objects clicked on canvas
  5382. :param key: for future use in cumulative selection
  5383. :return:
  5384. """
  5385. # list where we store the overlapped objects under our mouse left click position
  5386. if key is None:
  5387. self.objects_under_the_click_list = []
  5388. # Populate the list with the overlapped objects on the click position
  5389. curr_x, curr_y = self.pos
  5390. for obj in self.all_objects_list:
  5391. # ScriptObject and DocumentObject objects can't be selected
  5392. if obj.kind == 'script' or obj.kind == 'document':
  5393. continue
  5394. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5395. continue
  5396. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5397. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5398. if obj.options['name'] not in self.objects_under_the_click_list:
  5399. if obj.options['plot']:
  5400. # add objects to the objects_under_the_click list only if the object is plotted
  5401. # (active and not disabled)
  5402. self.objects_under_the_click_list.append(obj.options['name'])
  5403. try:
  5404. if self.objects_under_the_click_list:
  5405. curr_sel_obj = self.collection.get_active()
  5406. # case when there is only an object under the click and we toggle it
  5407. if len(self.objects_under_the_click_list) == 1:
  5408. if curr_sel_obj is None:
  5409. self.collection.set_active(self.objects_under_the_click_list[0])
  5410. curr_sel_obj = self.collection.get_active()
  5411. # create the selection box around the selected object
  5412. if self.defaults['global_selection_shape'] is True:
  5413. self.draw_selection_shape(curr_sel_obj)
  5414. curr_sel_obj.selection_shape_drawn = True
  5415. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5416. self.collection.on_objects_selection(False)
  5417. self.delete_selection_shape()
  5418. curr_sel_obj.selection_shape_drawn = False
  5419. self.collection.set_active(self.objects_under_the_click_list[0])
  5420. curr_sel_obj = self.collection.get_active()
  5421. # create the selection box around the selected object
  5422. if self.defaults['global_selection_shape'] is True:
  5423. self.draw_selection_shape(curr_sel_obj)
  5424. curr_sel_obj.selection_shape_drawn = True
  5425. self.selected_message(curr_sel_obj=curr_sel_obj)
  5426. elif curr_sel_obj.selection_shape_drawn is False:
  5427. if self.defaults['global_selection_shape'] is True:
  5428. self.draw_selection_shape(curr_sel_obj)
  5429. curr_sel_obj.selection_shape_drawn = True
  5430. else:
  5431. self.collection.on_objects_selection(False)
  5432. self.delete_selection_shape()
  5433. if self.call_source != 'app':
  5434. self.call_source = 'app'
  5435. self.selected_message(curr_sel_obj=curr_sel_obj)
  5436. else:
  5437. # If there is no selected object
  5438. # make active the first element of the overlapped objects list
  5439. if self.collection.get_active() is None:
  5440. self.collection.set_active(self.objects_under_the_click_list[0])
  5441. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5442. name_sel_obj = self.collection.get_active().options['name']
  5443. # In case that there is a selected object but it is not in the overlapped object list
  5444. # make that object inactive and activate the first element in the overlapped object list
  5445. if name_sel_obj not in self.objects_under_the_click_list:
  5446. self.collection.set_inactive(name_sel_obj)
  5447. name_sel_obj = self.objects_under_the_click_list[0]
  5448. self.collection.set_active(name_sel_obj)
  5449. else:
  5450. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5451. self.collection.set_all_inactive()
  5452. self.collection.set_active(
  5453. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5454. curr_sel_obj = self.collection.get_active()
  5455. # delete the possible selection box around a possible selected object
  5456. self.delete_selection_shape()
  5457. curr_sel_obj.selection_shape_drawn = False
  5458. # create the selection box around the selected object
  5459. if self.defaults['global_selection_shape'] is True:
  5460. self.draw_selection_shape(curr_sel_obj)
  5461. curr_sel_obj.selection_shape_drawn = True
  5462. self.selected_message(curr_sel_obj=curr_sel_obj)
  5463. else:
  5464. # deselect everything
  5465. self.collection.on_objects_selection(False)
  5466. # delete the possible selection box around a possible selected object
  5467. self.delete_selection_shape()
  5468. for o in self.collection.get_list():
  5469. o.selection_shape_drawn = False
  5470. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5471. # only when working on App
  5472. if self.call_source == 'app':
  5473. if self.click_noproject is False:
  5474. # if the Tool Tab is in focus don't change focus to Project Tab
  5475. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5476. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5477. else:
  5478. # restore auto open the Project Tab
  5479. self.click_noproject = False
  5480. # delete any text in the status bar, implicitly the last object name that was selected
  5481. # self.inform.emit("")
  5482. else:
  5483. self.call_source = 'app'
  5484. except Exception as e:
  5485. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5486. def selected_message(self, curr_sel_obj):
  5487. if curr_sel_obj:
  5488. if curr_sel_obj.kind == 'gerber':
  5489. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5490. color='green',
  5491. name=str(curr_sel_obj.options['name']),
  5492. tx=_("selected"))
  5493. )
  5494. elif curr_sel_obj.kind == 'excellon':
  5495. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5496. color='brown',
  5497. name=str(curr_sel_obj.options['name']),
  5498. tx=_("selected"))
  5499. )
  5500. elif curr_sel_obj.kind == 'cncjob':
  5501. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5502. color='blue',
  5503. name=str(curr_sel_obj.options['name']),
  5504. tx=_("selected"))
  5505. )
  5506. elif curr_sel_obj.kind == 'geometry':
  5507. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5508. color='red',
  5509. name=str(curr_sel_obj.options['name']),
  5510. tx=_("selected"))
  5511. )
  5512. def delete_hover_shape(self):
  5513. self.hover_shapes.clear()
  5514. self.hover_shapes.redraw()
  5515. def draw_hover_shape(self, sel_obj, color=None):
  5516. """
  5517. :param sel_obj: The object for which the hover shape must be drawn
  5518. :param color: The color of the hover shape
  5519. :return: None
  5520. """
  5521. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5522. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5523. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5524. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5525. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5526. if self.defaults['units'].upper() == 'MM':
  5527. hover_rect = hover_rect.buffer(-0.1)
  5528. hover_rect = hover_rect.buffer(0.2)
  5529. else:
  5530. hover_rect = hover_rect.buffer(-0.00393)
  5531. hover_rect = hover_rect.buffer(0.00787)
  5532. # if color:
  5533. # face = Color(color)
  5534. # face.alpha = 0.2
  5535. # outline = Color(color, alpha=0.8)
  5536. # else:
  5537. # face = Color(self.defaults['global_sel_fill'])
  5538. # face.alpha = 0.2
  5539. # outline = self.defaults['global_sel_line']
  5540. if color:
  5541. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5542. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5543. else:
  5544. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5545. outline = self.defaults['global_sel_line']
  5546. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5547. if self.is_legacy is True:
  5548. self.hover_shapes.redraw()
  5549. def delete_selection_shape(self):
  5550. self.move_tool.sel_shapes.clear()
  5551. self.move_tool.sel_shapes.redraw()
  5552. def draw_selection_shape(self, sel_obj, color=None):
  5553. """
  5554. Will draw a selection shape around the selected object.
  5555. :param sel_obj: The object for which the selection shape must be drawn
  5556. :param color: The color for the selection shape.
  5557. :return: None
  5558. """
  5559. if sel_obj is None:
  5560. return
  5561. # it's a line without area
  5562. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5563. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5564. # it's a geometry with area
  5565. else:
  5566. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5567. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5568. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5569. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5570. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5571. b_sel_rect = None
  5572. try:
  5573. if self.defaults['units'].upper() == 'MM':
  5574. b_sel_rect = sel_rect.buffer(-0.1)
  5575. b_sel_rect = b_sel_rect.buffer(0.2)
  5576. else:
  5577. b_sel_rect = sel_rect.buffer(-0.00393)
  5578. b_sel_rect = b_sel_rect.buffer(0.00787)
  5579. except Exception:
  5580. pass
  5581. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5582. b_sel_rect = sel_rect
  5583. if color:
  5584. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5585. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5586. else:
  5587. if self.is_legacy is False:
  5588. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5589. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5590. else:
  5591. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5592. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5593. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5594. color=outline,
  5595. face_color=face,
  5596. update=True,
  5597. layer=0,
  5598. tolerance=None))
  5599. if self.is_legacy is True:
  5600. self.move_tool.sel_shapes.redraw()
  5601. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5602. """
  5603. Will draw a selection shape when dragging mouse on canvas.
  5604. :param old_coords: Old coordinates
  5605. :param coords: New coordinates
  5606. :param kwargs: Keyword arguments
  5607. :return:
  5608. """
  5609. if 'color' in kwargs:
  5610. color = kwargs['color']
  5611. else:
  5612. color = self.defaults['global_sel_line']
  5613. if 'face_color' in kwargs:
  5614. face_color = kwargs['face_color']
  5615. else:
  5616. face_color = self.defaults['global_sel_fill']
  5617. if 'face_alpha' in kwargs:
  5618. face_alpha = kwargs['face_alpha']
  5619. else:
  5620. face_alpha = 0.3
  5621. x0, y0 = old_coords
  5622. x1, y1 = coords
  5623. pt1 = (x0, y0)
  5624. pt2 = (x1, y0)
  5625. pt3 = (x1, y1)
  5626. pt4 = (x0, y1)
  5627. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5628. # color_t = Color(face_color)
  5629. # color_t.alpha = face_alpha
  5630. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5631. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5632. layer=0, tolerance=None)
  5633. if self.is_legacy is True:
  5634. self.move_tool.sel_shapes.redraw()
  5635. def on_file_new_click(self):
  5636. """
  5637. Callback for menu item File -> New.
  5638. Executed on clicking the Menu -> File -> New Project
  5639. :return:
  5640. """
  5641. if self.collection.get_list() and self.should_we_save:
  5642. msgbox = QtWidgets.QMessageBox()
  5643. # msgbox.setText("<B>Save changes ...</B>")
  5644. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5645. "Creating a New project will delete them.\n"
  5646. "Do you want to Save the project?"))
  5647. msgbox.setWindowTitle(_("Save changes"))
  5648. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5649. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5650. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5651. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5652. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5653. msgbox.setDefaultButton(bt_yes)
  5654. msgbox.exec_()
  5655. response = msgbox.clickedButton()
  5656. if response == bt_yes:
  5657. self.on_file_saveprojectas()
  5658. elif response == bt_cancel:
  5659. return
  5660. elif response == bt_no:
  5661. self.on_file_new()
  5662. else:
  5663. self.on_file_new()
  5664. self.inform.emit('[success] %s...' % _("New Project created"))
  5665. def on_file_new(self, cli=None):
  5666. """
  5667. Returns the application to its startup state. This method is thread-safe.
  5668. :param cli: Boolean. If True this method was run from command line
  5669. :return: None
  5670. """
  5671. self.defaults.report_usage("on_file_new")
  5672. # Remove everything from memory
  5673. App.log.debug("on_file_new()")
  5674. # close any editor that might be open
  5675. if self.call_source != 'app':
  5676. self.editor2object(cleanup=True)
  5677. # ## EDITOR section
  5678. self.geo_editor = AppGeoEditor(self)
  5679. self.exc_editor = AppExcEditor(self)
  5680. self.grb_editor = AppGerberEditor(self)
  5681. # Clear pool
  5682. self.clear_pool()
  5683. for obj in self.collection.get_list():
  5684. # delete shapes left drawn from mark shape_collections, if any
  5685. if isinstance(obj, GerberObject):
  5686. try:
  5687. obj.mark_shapes_storage.clear()
  5688. obj.mark_shapes.clear(update=True)
  5689. obj.mark_shapes.enabled = False
  5690. except AttributeError:
  5691. pass
  5692. # also delete annotation shapes, if any
  5693. elif isinstance(obj, CNCJobObject):
  5694. try:
  5695. obj.text_col.enabled = False
  5696. del obj.text_col
  5697. obj.annotation.clear(update=True)
  5698. del obj.annotation
  5699. except AttributeError:
  5700. pass
  5701. # delete the exclusion areas
  5702. self.exc_areas.clear_shapes()
  5703. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5704. self.shell.init_tcl()
  5705. # delete any selection shape on canvas
  5706. self.delete_selection_shape()
  5707. # delete all FlatCAM objects
  5708. self.collection.delete_all()
  5709. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5710. self.setup_default_properties_tab()
  5711. # Clear project filename
  5712. self.project_filename = None
  5713. # Load the application defaults
  5714. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  5715. # Re-fresh project options
  5716. self.on_options_app2project()
  5717. # Init FlatCAMTools
  5718. self.init_tools()
  5719. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5720. if cli is None:
  5721. # we need to go in reverse because once we remove a tab then the index changes
  5722. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5723. # and so on. Therefore the deletion should be done in reverse
  5724. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5725. for index in range(wdg_count, -1, -1):
  5726. try:
  5727. self.ui.plot_tab_area.closeTab(index)
  5728. except Exception as e:
  5729. log.debug("App.on_file_new() --> %s" % str(e))
  5730. # # And then add again the Plot Area
  5731. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, _("Plot Area"))
  5732. self.ui.plot_tab_area.protectTab(0)
  5733. # take the focus of the Notebook on Project Tab.
  5734. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5735. self.set_ui_title(name=_("New Project - Not saved"))
  5736. def obj_properties(self):
  5737. """
  5738. Will launch the object Properties Tool
  5739. :return:
  5740. """
  5741. self.defaults.report_usage("obj_properties()")
  5742. self.properties_tool.run(toggle=False)
  5743. def on_project_context_save(self):
  5744. """
  5745. Wrapper, will save the object function of it's type
  5746. :return:
  5747. """
  5748. sel_objects = self.collection.get_selected()
  5749. len_objects = len(sel_objects)
  5750. cnt = 0
  5751. if len_objects > 1:
  5752. for o in sel_objects:
  5753. if o.kind == 'cncjob':
  5754. cnt += 1
  5755. if len_objects == cnt:
  5756. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5757. _filter_ = self.defaults['cncjob_save_filters'] + \
  5758. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5759. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5760. try:
  5761. filename, _f = FCFileSaveDialog.get_saved_filename(
  5762. caption=_("Export Code ..."),
  5763. directory=dir_file_to_save,
  5764. ext_filter=_filter_
  5765. )
  5766. except TypeError:
  5767. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5768. ext_filter=_filter_)
  5769. filename = filename.rpartition('/')[0]
  5770. for ob in sel_objects:
  5771. ob.read_form()
  5772. fname = '%s/%s' % (filename, ob.options['name'])
  5773. ob.export_gcode_handler(fname, is_gcode=True)
  5774. return
  5775. obj = self.collection.get_active()
  5776. if type(obj) == GeometryObject:
  5777. self.on_file_exportdxf()
  5778. elif type(obj) == ExcellonObject:
  5779. self.on_file_saveexcellon()
  5780. elif type(obj) == CNCJobObject:
  5781. obj.on_exportgcode_button_click()
  5782. elif type(obj) == GerberObject:
  5783. self.on_file_savegerber()
  5784. elif type(obj) == ScriptObject:
  5785. self.on_file_savescript()
  5786. elif type(obj) == DocumentObject:
  5787. self.on_file_savedocument()
  5788. def obj_move(self):
  5789. """
  5790. Callback for the Move menu entry in various Context Menu's.
  5791. :return:
  5792. """
  5793. self.defaults.report_usage("obj_move()")
  5794. self.move_tool.run(toggle=False)
  5795. def on_fileopengerber(self, signal, name=None):
  5796. """
  5797. File menu callback for opening a Gerber.
  5798. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5799. :param name:
  5800. :return: None
  5801. """
  5802. self.defaults.report_usage("on_fileopengerber")
  5803. App.log.debug("on_fileopengerber()")
  5804. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5805. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5806. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5807. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5808. "*.outline);;" \
  5809. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5810. "*.mil);;" \
  5811. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5812. "Allegro Files (*.art);;" \
  5813. "Mentor Files (*.pho *.gdo);;" \
  5814. "All Files (*.*)"
  5815. if name is None:
  5816. try:
  5817. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5818. directory=self.get_last_folder(),
  5819. filter=_filter_,
  5820. initialFilter=self.last_op_gerber_filter)
  5821. except TypeError:
  5822. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5823. filenames = [str(filename) for filename in filenames]
  5824. self.last_op_gerber_filter = _f
  5825. else:
  5826. filenames = [name]
  5827. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5828. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5829. _("Opening Gerber file.")),
  5830. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5831. color=QtGui.QColor("gray"))
  5832. if len(filenames) == 0:
  5833. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5834. else:
  5835. for filename in filenames:
  5836. if filename != '':
  5837. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5838. def on_fileopenexcellon(self, signal, name=None):
  5839. """
  5840. File menu callback for opening an Excellon file.
  5841. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5842. :param name:
  5843. :return: None
  5844. """
  5845. self.defaults.report_usage("on_fileopenexcellon")
  5846. App.log.debug("on_fileopenexcellon()")
  5847. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5848. "All Files (*.*)"
  5849. if name is None:
  5850. try:
  5851. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5852. directory=self.get_last_folder(),
  5853. filter=_filter_,
  5854. initialFilter=self.last_op_excellon_filter)
  5855. except TypeError:
  5856. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5857. filenames = [str(filename) for filename in filenames]
  5858. self.last_op_excellon_filter = _f
  5859. else:
  5860. filenames = [str(name)]
  5861. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5862. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5863. _("Opening Excellon file.")),
  5864. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5865. color=QtGui.QColor("gray"))
  5866. if len(filenames) == 0:
  5867. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5868. else:
  5869. for filename in filenames:
  5870. if filename != '':
  5871. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5872. def on_fileopengcode(self, signal, name=None):
  5873. """
  5874. File menu call back for opening gcode.
  5875. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5876. :param name:
  5877. :return:
  5878. """
  5879. self.defaults.report_usage("on_fileopengcode")
  5880. App.log.debug("on_fileopengcode()")
  5881. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5882. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5883. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5884. "All Files (*.*)"
  5885. if name is None:
  5886. try:
  5887. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5888. directory=self.get_last_folder(),
  5889. filter=_filter_,
  5890. initialFilter=self.last_op_gcode_filter)
  5891. except TypeError:
  5892. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5893. filenames = [str(filename) for filename in filenames]
  5894. self.last_op_gcode_filter = _f
  5895. else:
  5896. filenames = [name]
  5897. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5898. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5899. _("Opening G-Code file.")),
  5900. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5901. color=QtGui.QColor("gray"))
  5902. if len(filenames) == 0:
  5903. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5904. else:
  5905. for filename in filenames:
  5906. if filename != '':
  5907. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5908. def on_file_openproject(self, signal):
  5909. """
  5910. File menu callback for opening a project.
  5911. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5912. :return: None
  5913. """
  5914. self.defaults.report_usage("on_file_openproject")
  5915. App.log.debug("on_file_openproject()")
  5916. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5917. try:
  5918. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5919. directory=self.get_last_folder(), filter=_filter_)
  5920. except TypeError:
  5921. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5922. # The Qt methods above will return a QString which can cause problems later.
  5923. # So far json.dump() will fail to serialize it.
  5924. # TODO: Improve the serialization methods and remove this fix.
  5925. filename = str(filename)
  5926. if filename == "":
  5927. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5928. else:
  5929. # self.worker_task.emit({'fcn': self.open_project,
  5930. # 'params': [filename]})
  5931. # The above was failing because open_project() is not
  5932. # thread safe. The new_project()
  5933. self.open_project(filename)
  5934. def on_fileopenhpgl2(self, signal, name=None):
  5935. """
  5936. File menu callback for opening a HPGL2.
  5937. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5938. :param name:
  5939. :return: None
  5940. """
  5941. self.defaults.report_usage("on_fileopenhpgl2")
  5942. App.log.debug("on_fileopenhpgl2()")
  5943. _filter_ = "HPGL2 Files (*.plt);;" \
  5944. "All Files (*.*)"
  5945. if name is None:
  5946. try:
  5947. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5948. directory=self.get_last_folder(),
  5949. filter=_filter_)
  5950. except TypeError:
  5951. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5952. filenames = [str(filename) for filename in filenames]
  5953. else:
  5954. filenames = [name]
  5955. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5956. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5957. _("Opening HPGL2 file.")),
  5958. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5959. color=QtGui.QColor("gray"))
  5960. if len(filenames) == 0:
  5961. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5962. else:
  5963. for filename in filenames:
  5964. if filename != '':
  5965. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5966. def on_file_openconfig(self, signal):
  5967. """
  5968. File menu callback for opening a config file.
  5969. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5970. :return: None
  5971. """
  5972. self.defaults.report_usage("on_file_openconfig")
  5973. App.log.debug("on_file_openconfig()")
  5974. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5975. try:
  5976. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5977. directory=self.data_path, filter=_filter_)
  5978. except TypeError:
  5979. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5980. filter=_filter_)
  5981. if filename == "":
  5982. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5983. else:
  5984. self.open_config_file(filename)
  5985. def on_file_exportsvg(self):
  5986. """
  5987. Callback for menu item File->Export SVG.
  5988. :return: None
  5989. """
  5990. self.defaults.report_usage("on_file_exportsvg")
  5991. App.log.debug("on_file_exportsvg()")
  5992. obj = self.collection.get_active()
  5993. if obj is None:
  5994. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5995. msg = _("Please Select a Geometry object to export")
  5996. msgbox = QtWidgets.QMessageBox()
  5997. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5998. msgbox.setInformativeText(msg)
  5999. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6000. msgbox.setDefaultButton(bt_ok)
  6001. msgbox.exec_()
  6002. return
  6003. # Check for more compatible types and add as required
  6004. if (not isinstance(obj, GeometryObject)
  6005. and not isinstance(obj, GerberObject)
  6006. and not isinstance(obj, CNCJobObject)
  6007. and not isinstance(obj, ExcellonObject)):
  6008. msg = '[ERROR_NOTCL] %s' % \
  6009. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6010. msgbox = QtWidgets.QMessageBox()
  6011. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6012. msgbox.setInformativeText(msg)
  6013. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6014. msgbox.setDefaultButton(bt_ok)
  6015. msgbox.exec_()
  6016. return
  6017. name = obj.options["name"]
  6018. _filter = "SVG File (*.svg);;All Files (*.*)"
  6019. try:
  6020. filename, _f = FCFileSaveDialog.get_saved_filename(
  6021. caption=_("Export SVG"),
  6022. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6023. ext_filter=_filter)
  6024. except TypeError:
  6025. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  6026. filename = str(filename)
  6027. if filename == "":
  6028. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6029. return
  6030. else:
  6031. self.export_svg(name, filename)
  6032. if self.defaults["global_open_style"] is False:
  6033. self.file_opened.emit("SVG", filename)
  6034. self.file_saved.emit("SVG", filename)
  6035. def on_file_exportpng(self):
  6036. self.defaults.report_usage("on_file_exportpng")
  6037. App.log.debug("on_file_exportpng()")
  6038. self.date = str(datetime.today()).rpartition('.')[0]
  6039. self.date = ''.join(c for c in self.date if c not in ':-')
  6040. self.date = self.date.replace(' ', '_')
  6041. data = None
  6042. if self.is_legacy is False:
  6043. image = _screenshot(alpha=False)
  6044. data = np.asarray(image)
  6045. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6046. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6047. return
  6048. filter_ = "PNG File (*.png);;All Files (*.*)"
  6049. try:
  6050. filename, _f = FCFileSaveDialog.get_saved_filename(
  6051. caption=_("Export PNG Image"),
  6052. directory=self.get_last_save_folder() + '/png_' + self.date,
  6053. ext_filter=filter_)
  6054. except TypeError:
  6055. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6056. filename = str(filename)
  6057. if filename == "":
  6058. self.inform.emit(_("Cancelled."))
  6059. return
  6060. else:
  6061. if self.is_legacy is False:
  6062. write_png(filename, data)
  6063. else:
  6064. self.plotcanvas.figure.savefig(filename)
  6065. if self.defaults["global_open_style"] is False:
  6066. self.file_opened.emit("png", filename)
  6067. self.file_saved.emit("png", filename)
  6068. def on_file_savegerber(self):
  6069. """
  6070. Callback for menu item in Project context menu.
  6071. :return: None
  6072. """
  6073. self.defaults.report_usage("on_file_savegerber")
  6074. App.log.debug("on_file_savegerber()")
  6075. obj = self.collection.get_active()
  6076. if obj is None:
  6077. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6078. return
  6079. # Check for more compatible types and add as required
  6080. if not isinstance(obj, GerberObject):
  6081. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6082. return
  6083. name = self.collection.get_active().options["name"]
  6084. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6085. try:
  6086. filename, _f = FCFileSaveDialog.get_saved_filename(
  6087. caption="Save Gerber source file",
  6088. directory=self.get_last_save_folder() + '/' + name,
  6089. ext_filter=_filter)
  6090. except TypeError:
  6091. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6092. filename = str(filename)
  6093. if filename == "":
  6094. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6095. return
  6096. else:
  6097. self.save_source_file(name, filename)
  6098. if self.defaults["global_open_style"] is False:
  6099. self.file_opened.emit("Gerber", filename)
  6100. self.file_saved.emit("Gerber", filename)
  6101. def on_file_savescript(self):
  6102. """
  6103. Callback for menu item in Project context menu.
  6104. :return: None
  6105. """
  6106. self.defaults.report_usage("on_file_savescript")
  6107. App.log.debug("on_file_savescript()")
  6108. obj = self.collection.get_active()
  6109. if obj is None:
  6110. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6111. return
  6112. # Check for more compatible types and add as required
  6113. if not isinstance(obj, ScriptObject):
  6114. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6115. return
  6116. name = self.collection.get_active().options["name"]
  6117. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6118. try:
  6119. filename, _f = FCFileSaveDialog.get_saved_filename(
  6120. caption="Save Script source file",
  6121. directory=self.get_last_save_folder() + '/' + name,
  6122. ext_filter=_filter)
  6123. except TypeError:
  6124. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6125. filename = str(filename)
  6126. if filename == "":
  6127. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6128. return
  6129. else:
  6130. self.save_source_file(name, filename)
  6131. if self.defaults["global_open_style"] is False:
  6132. self.file_opened.emit("Script", filename)
  6133. self.file_saved.emit("Script", filename)
  6134. def on_file_savedocument(self):
  6135. """
  6136. Callback for menu item in Project context menu.
  6137. :return: None
  6138. """
  6139. self.defaults.report_usage("on_file_savedocument")
  6140. App.log.debug("on_file_savedocument()")
  6141. obj = self.collection.get_active()
  6142. if obj is None:
  6143. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6144. return
  6145. # Check for more compatible types and add as required
  6146. if not isinstance(obj, ScriptObject):
  6147. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6148. return
  6149. name = self.collection.get_active().options["name"]
  6150. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6151. try:
  6152. filename, _f = FCFileSaveDialog.get_saved_filename(
  6153. caption="Save Document source file",
  6154. directory=self.get_last_save_folder() + '/' + name,
  6155. ext_filter=_filter)
  6156. except TypeError:
  6157. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6158. ext_filter=_filter)
  6159. filename = str(filename)
  6160. if filename == "":
  6161. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6162. return
  6163. else:
  6164. self.save_source_file(name, filename)
  6165. if self.defaults["global_open_style"] is False:
  6166. self.file_opened.emit("Document", filename)
  6167. self.file_saved.emit("Document", filename)
  6168. def on_file_saveexcellon(self):
  6169. """
  6170. Callback for menu item in project context menu.
  6171. :return: None
  6172. """
  6173. self.defaults.report_usage("on_file_saveexcellon")
  6174. App.log.debug("on_file_saveexcellon()")
  6175. obj = self.collection.get_active()
  6176. if obj is None:
  6177. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6178. return
  6179. # Check for more compatible types and add as required
  6180. if not isinstance(obj, ExcellonObject):
  6181. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6182. return
  6183. name = self.collection.get_active().options["name"]
  6184. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6185. try:
  6186. filename, _f = FCFileSaveDialog.get_saved_filename(
  6187. caption=_("Save Excellon source file"),
  6188. directory=self.get_last_save_folder() + '/' + name,
  6189. ext_filter=_filter)
  6190. except TypeError:
  6191. filename, _f = FCFileSaveDialog.get_saved_filename(
  6192. caption=_("Save Excellon source file"), ext_filter=_filter)
  6193. filename = str(filename)
  6194. if filename == "":
  6195. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6196. return
  6197. else:
  6198. self.save_source_file(name, filename)
  6199. if self.defaults["global_open_style"] is False:
  6200. self.file_opened.emit("Excellon", filename)
  6201. self.file_saved.emit("Excellon", filename)
  6202. def on_file_exportexcellon(self):
  6203. """
  6204. Callback for menu item File->Export->Excellon.
  6205. :return: None
  6206. """
  6207. self.defaults.report_usage("on_file_exportexcellon")
  6208. App.log.debug("on_file_exportexcellon()")
  6209. obj = self.collection.get_active()
  6210. if obj is None:
  6211. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6212. return
  6213. # Check for more compatible types and add as required
  6214. if not isinstance(obj, ExcellonObject):
  6215. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6216. return
  6217. name = self.collection.get_active().options["name"]
  6218. _filter = self.defaults["excellon_save_filters"]
  6219. try:
  6220. filename, _f = FCFileSaveDialog.get_saved_filename(
  6221. caption=_("Export Excellon"),
  6222. directory=self.get_last_save_folder() + '/' + name,
  6223. ext_filter=_filter)
  6224. except TypeError:
  6225. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6226. filename = str(filename)
  6227. if filename == "":
  6228. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6229. return
  6230. else:
  6231. used_extension = filename.rpartition('.')[2]
  6232. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6233. self.export_excellon(name, filename)
  6234. if self.defaults["global_open_style"] is False:
  6235. self.file_opened.emit("Excellon", filename)
  6236. self.file_saved.emit("Excellon", filename)
  6237. def on_file_exportgerber(self):
  6238. """
  6239. Callback for menu item File->Export->Gerber.
  6240. :return: None
  6241. """
  6242. self.defaults.report_usage("on_file_exportgerber")
  6243. App.log.debug("on_file_exportgerber()")
  6244. obj = self.collection.get_active()
  6245. if obj is None:
  6246. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6247. return
  6248. # Check for more compatible types and add as required
  6249. if not isinstance(obj, GerberObject):
  6250. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6251. return
  6252. name = self.collection.get_active().options["name"]
  6253. _filter_ = self.defaults['gerber_save_filters']
  6254. try:
  6255. filename, _f = FCFileSaveDialog.get_saved_filename(
  6256. caption=_("Export Gerber"),
  6257. directory=self.get_last_save_folder() + '/' + name,
  6258. ext_filter=_filter_)
  6259. except TypeError:
  6260. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6261. filename = str(filename)
  6262. if filename == "":
  6263. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6264. return
  6265. else:
  6266. used_extension = filename.rpartition('.')[2]
  6267. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6268. self.export_gerber(name, filename)
  6269. if self.defaults["global_open_style"] is False:
  6270. self.file_opened.emit("Gerber", filename)
  6271. self.file_saved.emit("Gerber", filename)
  6272. def on_file_exportdxf(self):
  6273. """
  6274. Callback for menu item File->Export DXF.
  6275. :return: None
  6276. """
  6277. self.defaults.report_usage("on_file_exportdxf")
  6278. App.log.debug("on_file_exportdxf()")
  6279. obj = self.collection.get_active()
  6280. if obj is None:
  6281. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6282. msg = _("Please Select a Geometry object to export")
  6283. msgbox = QtWidgets.QMessageBox()
  6284. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6285. msgbox.setInformativeText(msg)
  6286. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6287. msgbox.setDefaultButton(bt_ok)
  6288. msgbox.exec_()
  6289. return
  6290. # Check for more compatible types and add as required
  6291. if not isinstance(obj, GeometryObject):
  6292. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6293. msgbox = QtWidgets.QMessageBox()
  6294. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6295. msgbox.setInformativeText(msg)
  6296. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6297. msgbox.setDefaultButton(bt_ok)
  6298. msgbox.exec_()
  6299. return
  6300. name = self.collection.get_active().options["name"]
  6301. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6302. try:
  6303. filename, _f = FCFileSaveDialog.get_saved_filename(
  6304. caption=_("Export DXF"),
  6305. directory=self.get_last_save_folder() + '/' + name,
  6306. ext_filter=_filter_)
  6307. except TypeError:
  6308. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6309. filename = str(filename)
  6310. if filename == "":
  6311. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6312. return
  6313. else:
  6314. self.export_dxf(name, filename)
  6315. if self.defaults["global_open_style"] is False:
  6316. self.file_opened.emit("DXF", filename)
  6317. self.file_saved.emit("DXF", filename)
  6318. def on_file_importsvg(self, type_of_obj):
  6319. """
  6320. Callback for menu item File->Import SVG.
  6321. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6322. :type type_of_obj: str
  6323. :return: None
  6324. """
  6325. self.defaults.report_usage("on_file_importsvg")
  6326. App.log.debug("on_file_importsvg()")
  6327. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6328. try:
  6329. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6330. directory=self.get_last_folder(), filter=_filter_)
  6331. except TypeError:
  6332. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6333. filter=_filter_)
  6334. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6335. type_of_obj = "geometry"
  6336. filenames = [str(filename) for filename in filenames]
  6337. if len(filenames) == 0:
  6338. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6339. else:
  6340. for filename in filenames:
  6341. if filename != '':
  6342. self.worker_task.emit({'fcn': self.import_svg,
  6343. 'params': [filename, type_of_obj]})
  6344. def on_file_importdxf(self, type_of_obj):
  6345. """
  6346. Callback for menu item File->Import DXF.
  6347. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6348. :type type_of_obj: str
  6349. :return: None
  6350. """
  6351. self.defaults.report_usage("on_file_importdxf")
  6352. App.log.debug("on_file_importdxf()")
  6353. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6354. try:
  6355. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6356. directory=self.get_last_folder(),
  6357. filter=_filter_)
  6358. except TypeError:
  6359. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6360. filter=_filter_)
  6361. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6362. type_of_obj = "geometry"
  6363. filenames = [str(filename) for filename in filenames]
  6364. if len(filenames) == 0:
  6365. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6366. else:
  6367. for filename in filenames:
  6368. if filename != '':
  6369. self.worker_task.emit({'fcn': self.import_dxf,
  6370. 'params': [filename, type_of_obj]})
  6371. # ###############################################################################################################
  6372. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6373. # ###############################################################################################################
  6374. def init_code_editor(self, name):
  6375. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6376. # add the tab if it was closed
  6377. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6378. self.text_editor_tab.setObjectName('text_editor_tab')
  6379. # delete the absolute and relative position and messages in the infobar
  6380. # self.ui.position_label.setText("")
  6381. # self.ui.rel_position_label.setText("")
  6382. # hide coordinates toolbars in the infobar while in DB
  6383. self.ui.coords_toolbar.hide()
  6384. self.ui.delta_coords_toolbar.hide()
  6385. self.toggle_codeeditor = True
  6386. self.text_editor_tab.code_editor.completer_enable = False
  6387. self.text_editor_tab.buttonRun.hide()
  6388. # make sure to keep a reference to the code editor
  6389. self.reference_code_editor = self.text_editor_tab.code_editor
  6390. # Switch plot_area to CNCJob tab
  6391. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6392. def on_view_source(self):
  6393. """
  6394. Called when the user wants to see the source file of the selected object
  6395. :return:
  6396. """
  6397. try:
  6398. obj = self.collection.get_active()
  6399. except Exception as e:
  6400. log.debug("App.on_view_source() --> %s" % str(e))
  6401. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6402. return 'fail'
  6403. if obj is None:
  6404. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6405. return 'fail'
  6406. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6407. self.proc_container.view.set_busy(_("Loading..."))
  6408. flt = "All Files (*.*)"
  6409. if obj.kind == 'gerber':
  6410. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6411. elif obj.kind == 'excellon':
  6412. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6413. elif obj.kind == 'cncjob':
  6414. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6415. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6416. # add the tab if it was closed
  6417. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6418. self.source_editor_tab.setObjectName('source_editor_tab')
  6419. # delete the absolute and relative position and messages in the infobar
  6420. # self.ui.position_label.setText("")
  6421. # self.ui.rel_position_label.setText("")
  6422. # hide coordinates toolbars in the infobar while in DB
  6423. self.ui.coords_toolbar.hide()
  6424. self.ui.delta_coords_toolbar.hide()
  6425. self.source_editor_tab.code_editor.completer_enable = False
  6426. self.source_editor_tab.buttonRun.hide()
  6427. # Switch plot_area to CNCJob tab
  6428. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6429. try:
  6430. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6431. except TypeError:
  6432. pass
  6433. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6434. try:
  6435. self.source_editor_tab.buttonSave.clicked.disconnect()
  6436. except TypeError:
  6437. pass
  6438. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6439. # then append the text from GCode to the text editor
  6440. if obj.kind == 'cncjob':
  6441. try:
  6442. file = obj.export_gcode(to_file=True)
  6443. if file == 'fail':
  6444. return 'fail'
  6445. except AttributeError:
  6446. self.inform.emit('[WARNING_NOTCL] %s' %
  6447. _("There is no selected object for which to see it's source file code."))
  6448. return 'fail'
  6449. else:
  6450. try:
  6451. file = StringIO(obj.source_file)
  6452. except (AttributeError, TypeError):
  6453. self.inform.emit('[WARNING_NOTCL] %s' %
  6454. _("There is no selected object for which to see it's source file code."))
  6455. return 'fail'
  6456. self.source_editor_tab.t_frame.hide()
  6457. try:
  6458. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6459. except Exception as e:
  6460. log.debug('App.on_view_source() -->%s' % str(e))
  6461. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6462. return
  6463. self.source_editor_tab.t_frame.show()
  6464. self.proc_container.view.set_idle()
  6465. # self.ui.show()
  6466. def on_toggle_code_editor(self):
  6467. self.defaults.report_usage("on_toggle_code_editor()")
  6468. if self.toggle_codeeditor is False:
  6469. self.init_code_editor(name=_("Code Editor"))
  6470. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6471. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6472. self.text_editor_tab.buttonSave.clicked.disconnect()
  6473. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6474. else:
  6475. for idx in range(self.ui.plot_tab_area.count()):
  6476. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6477. self.ui.plot_tab_area.closeTab(idx)
  6478. break
  6479. self.toggle_codeeditor = False
  6480. def on_code_editor_close(self):
  6481. self.toggle_codeeditor = False
  6482. def goto_text_line(self):
  6483. """
  6484. Will scroll a text to the specified text line.
  6485. :return: None
  6486. """
  6487. dia_box = Dialog_box(title=_("Go to Line ..."),
  6488. label=_("Line:"),
  6489. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6490. initial_text='')
  6491. try:
  6492. line = int(dia_box.location) - 1
  6493. except (ValueError, TypeError):
  6494. line = 0
  6495. if dia_box.ok:
  6496. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6497. # at the top of the window
  6498. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6499. # get the document() of the AppTextEditor
  6500. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6501. # create a Text Cursor based on the searched line
  6502. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6503. # set cursor of the code editor with the cursor at the searcehd line
  6504. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6505. def on_filenewscript(self, silent=False):
  6506. """
  6507. Will create a new script file and open it in the Code Editor
  6508. :param silent: if True will not display status messages
  6509. :return: None
  6510. """
  6511. if silent is False:
  6512. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6513. # delete the absolute and relative position and messages in the infobar
  6514. # self.ui.position_label.setText("")
  6515. # self.ui.rel_position_label.setText("")
  6516. # hide coordinates toolbars in the infobar while in DB
  6517. self.ui.coords_toolbar.hide()
  6518. self.ui.delta_coords_toolbar.hide()
  6519. self.app_obj.new_script_object()
  6520. # script_text = script_obj.source_file
  6521. #
  6522. # self.proc_container.view.set_busy(_("Loading..."))
  6523. # script_obj.script_editor_tab.t_frame.hide()
  6524. #
  6525. # script_obj.script_editor_tab.t_frame.show()
  6526. # self.proc_container.view.set_idle()
  6527. def on_fileopenscript(self, name=None, silent=False):
  6528. """
  6529. Will open a Tcl script file into the Code Editor
  6530. :param silent: if True will not display status messages
  6531. :param name: name of a Tcl script file to open
  6532. :return: None
  6533. """
  6534. self.defaults.report_usage("on_fileopenscript")
  6535. App.log.debug("on_fileopenscript()")
  6536. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6537. "All Files (*.*)"
  6538. if name:
  6539. filenames = [name]
  6540. else:
  6541. try:
  6542. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6543. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6544. except TypeError:
  6545. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6546. if len(filenames) == 0:
  6547. if silent is False:
  6548. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6549. else:
  6550. for filename in filenames:
  6551. if filename != '':
  6552. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6553. def on_fileopenscript_example(self, name=None, silent=False):
  6554. """
  6555. Will open a Tcl script file into the Code Editor
  6556. :param silent: if True will not display status messages
  6557. :param name: name of a Tcl script file to open
  6558. :return:
  6559. """
  6560. self.defaults.report_usage("on_fileopenscript_example")
  6561. log.debug("on_fileopenscript_example()")
  6562. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6563. "All Files (*.*)"
  6564. # test if the app was frozen and choose the path for the configuration file
  6565. if getattr(sys, "frozen", False) is True:
  6566. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6567. else:
  6568. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6569. if name:
  6570. filenames = [name]
  6571. else:
  6572. try:
  6573. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6574. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6575. except TypeError:
  6576. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6577. if len(filenames) == 0:
  6578. if silent is False:
  6579. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6580. else:
  6581. for filename in filenames:
  6582. if filename != '':
  6583. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6584. def on_filerunscript(self, name=None, silent=False):
  6585. """
  6586. File menu callback for loading and running a TCL script.
  6587. :param silent: if True will not display status messages
  6588. :param name: name of a Tcl script file to be run by FlatCAM
  6589. :return: None
  6590. """
  6591. self.defaults.report_usage("on_filerunscript")
  6592. App.log.debug("on_file_runscript()")
  6593. if name:
  6594. filename = name
  6595. if self.cmd_line_headless != 1:
  6596. self.splash.showMessage('%s: %ssec\n%s' %
  6597. (_("Canvas initialization started.\n"
  6598. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6599. _("Executing ScriptObject file.")
  6600. ),
  6601. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6602. color=QtGui.QColor("gray"))
  6603. else:
  6604. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6605. "All Files (*.*)"
  6606. try:
  6607. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6608. directory=self.get_last_folder(), filter=_filter_)
  6609. except TypeError:
  6610. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6611. # The Qt methods above will return a QString which can cause problems later.
  6612. # So far json.dump() will fail to serialize it.
  6613. filename = str(filename)
  6614. if filename == "":
  6615. if silent is False:
  6616. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6617. else:
  6618. if self.cmd_line_headless != 1:
  6619. if self.ui.shell_dock.isHidden():
  6620. self.ui.shell_dock.show()
  6621. try:
  6622. with open(filename, "r") as tcl_script:
  6623. cmd_line_shellfile_content = tcl_script.read()
  6624. if self.cmd_line_headless != 1:
  6625. self.shell.exec_command(cmd_line_shellfile_content)
  6626. else:
  6627. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6628. if silent is False:
  6629. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6630. except Exception as e:
  6631. log.debug("App.on_filerunscript() -> %s" % str(e))
  6632. sys.exit(2)
  6633. def on_file_saveproject(self, silent=False):
  6634. """
  6635. Callback for menu item File->Save Project. Saves the project to
  6636. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6637. if set to None. The project is saved by calling ``self.save_project()``.
  6638. :param silent: if True will not display status messages
  6639. :return: None
  6640. """
  6641. self.defaults.report_usage("on_file_saveproject")
  6642. if self.project_filename is None:
  6643. self.on_file_saveprojectas()
  6644. else:
  6645. self.worker_task.emit({'fcn': self.save_project,
  6646. 'params': [self.project_filename, silent]})
  6647. if self.defaults["global_open_style"] is False:
  6648. self.file_opened.emit("project", self.project_filename)
  6649. self.file_saved.emit("project", self.project_filename)
  6650. self.set_ui_title(name=self.project_filename)
  6651. self.should_we_save = False
  6652. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6653. """
  6654. Callback for menu item File->Save Project As... Opens a file
  6655. chooser and saves the project to the given file via
  6656. ``self.save_project()``.
  6657. :param make_copy if to be create a copy of the project; boolean
  6658. :param use_thread: if to be run in a separate thread; boolean
  6659. :param quit_action: if to be followed by quiting the application; boolean
  6660. :return: None
  6661. """
  6662. self.defaults.report_usage("on_file_saveprojectas")
  6663. self.date = str(datetime.today()).rpartition('.')[0]
  6664. self.date = ''.join(c for c in self.date if c not in ':-')
  6665. self.date = self.date.replace(' ', '_')
  6666. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6667. try:
  6668. filename, _f = FCFileSaveDialog.get_saved_filename(
  6669. caption=_("Save Project As ..."),
  6670. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6671. proj=_("Project")),
  6672. ext_filter=filter_
  6673. )
  6674. except TypeError:
  6675. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6676. filename = str(filename)
  6677. if filename == '':
  6678. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6679. return
  6680. if use_thread is True:
  6681. self.worker_task.emit({'fcn': self.save_project,
  6682. 'params': [filename, quit_action]})
  6683. else:
  6684. self.save_project(filename, quit_action)
  6685. # self.save_project(filename)
  6686. if self.defaults["global_open_style"] is False:
  6687. self.file_opened.emit("project", filename)
  6688. self.file_saved.emit("project", filename)
  6689. if not make_copy:
  6690. self.project_filename = filename
  6691. self.set_ui_title(name=self.project_filename)
  6692. self.should_we_save = False
  6693. def on_file_save_objects_pdf(self, use_thread=True):
  6694. self.date = str(datetime.today()).rpartition('.')[0]
  6695. self.date = ''.join(c for c in self.date if c not in ':-')
  6696. self.date = self.date.replace(' ', '_')
  6697. try:
  6698. obj_selection = self.collection.get_selected()
  6699. if len(obj_selection) == 1:
  6700. obj_name = str(obj_selection[0].options['name'])
  6701. else:
  6702. obj_name = _("FlatCAM objects print")
  6703. except AttributeError as err:
  6704. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6705. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6706. return
  6707. if not obj_selection:
  6708. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6709. return
  6710. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6711. try:
  6712. filename, _f = FCFileSaveDialog.get_saved_filename(
  6713. caption=_("Save Object as PDF ..."),
  6714. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6715. obj_name=obj_name,
  6716. date=self.date),
  6717. ext_filter=filter_
  6718. )
  6719. except TypeError:
  6720. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6721. filename = str(filename)
  6722. if filename == '':
  6723. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6724. return
  6725. if use_thread is True:
  6726. self.proc_container.new(_("Printing PDF ... Please wait."))
  6727. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6728. else:
  6729. self.save_pdf(filename, obj_selection)
  6730. # self.save_project(filename)
  6731. if self.defaults["global_open_style"] is False:
  6732. self.file_opened.emit("pdf", filename)
  6733. self.file_saved.emit("pdf", filename)
  6734. def save_pdf(self, file_name, obj_selection):
  6735. p_size = self.defaults['global_workspaceT']
  6736. orientation = self.defaults['global_workspace_orientation']
  6737. color = 'black'
  6738. transparency_level = 1.0
  6739. self.pagesize = {}
  6740. self.pagesize.update(
  6741. {
  6742. 'Bounds': None,
  6743. 'A0': (841 * mm, 1189 * mm),
  6744. 'A1': (594 * mm, 841 * mm),
  6745. 'A2': (420 * mm, 594 * mm),
  6746. 'A3': (297 * mm, 420 * mm),
  6747. 'A4': (210 * mm, 297 * mm),
  6748. 'A5': (148 * mm, 210 * mm),
  6749. 'A6': (105 * mm, 148 * mm),
  6750. 'A7': (74 * mm, 105 * mm),
  6751. 'A8': (52 * mm, 74 * mm),
  6752. 'A9': (37 * mm, 52 * mm),
  6753. 'A10': (26 * mm, 37 * mm),
  6754. 'B0': (1000 * mm, 1414 * mm),
  6755. 'B1': (707 * mm, 1000 * mm),
  6756. 'B2': (500 * mm, 707 * mm),
  6757. 'B3': (353 * mm, 500 * mm),
  6758. 'B4': (250 * mm, 353 * mm),
  6759. 'B5': (176 * mm, 250 * mm),
  6760. 'B6': (125 * mm, 176 * mm),
  6761. 'B7': (88 * mm, 125 * mm),
  6762. 'B8': (62 * mm, 88 * mm),
  6763. 'B9': (44 * mm, 62 * mm),
  6764. 'B10': (31 * mm, 44 * mm),
  6765. 'C0': (917 * mm, 1297 * mm),
  6766. 'C1': (648 * mm, 917 * mm),
  6767. 'C2': (458 * mm, 648 * mm),
  6768. 'C3': (324 * mm, 458 * mm),
  6769. 'C4': (229 * mm, 324 * mm),
  6770. 'C5': (162 * mm, 229 * mm),
  6771. 'C6': (114 * mm, 162 * mm),
  6772. 'C7': (81 * mm, 114 * mm),
  6773. 'C8': (57 * mm, 81 * mm),
  6774. 'C9': (40 * mm, 57 * mm),
  6775. 'C10': (28 * mm, 40 * mm),
  6776. # American paper sizes
  6777. 'LETTER': (8.5 * inch, 11 * inch),
  6778. 'LEGAL': (8.5 * inch, 14 * inch),
  6779. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6780. # From https://en.wikipedia.org/wiki/Paper_size
  6781. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6782. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6783. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6784. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6785. 'LEDGER': (17 * inch, 11 * inch),
  6786. }
  6787. )
  6788. exported_svg = []
  6789. for obj in obj_selection:
  6790. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6791. scale_factor_x=None, scale_factor_y=None,
  6792. skew_factor_x=None, skew_factor_y=None,
  6793. mirror=None)
  6794. if obj.kind.lower() == 'gerber':
  6795. # color = self.defaults["gerber_plot_fill"][:-2]
  6796. color = obj.fill_color[:-2]
  6797. elif obj.kind.lower() == 'excellon':
  6798. color = '#C40000'
  6799. elif obj.kind.lower() == 'geometry':
  6800. color = self.defaults["global_draw_color"]
  6801. # Change the attributes of the exported SVG
  6802. # We don't need stroke-width
  6803. # We set opacity to maximum
  6804. # We set the colour to WHITE
  6805. root = ET.fromstring(svg_obj)
  6806. for child in root:
  6807. child.set('fill', str(color))
  6808. child.set('opacity', str(transparency_level))
  6809. child.set('stroke', str(color))
  6810. exported_svg.append(ET.tostring(root))
  6811. xmin = Inf
  6812. ymin = Inf
  6813. xmax = -Inf
  6814. ymax = -Inf
  6815. for obj in obj_selection:
  6816. try:
  6817. gxmin, gymin, gxmax, gymax = obj.bounds()
  6818. xmin = min([xmin, gxmin])
  6819. ymin = min([ymin, gymin])
  6820. xmax = max([xmax, gxmax])
  6821. ymax = max([ymax, gymax])
  6822. except Exception as e:
  6823. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6824. # Determine bounding area for svg export
  6825. bounds = [xmin, ymin, xmax, ymax]
  6826. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6827. # This contain the measure units
  6828. uom = obj_selection[0].units.lower()
  6829. # Define a boundary around SVG of about 1.0mm (~39mils)
  6830. if uom in "mm":
  6831. boundary = 1.0
  6832. else:
  6833. boundary = 0.0393701
  6834. # Convert everything to strings for use in the xml doc
  6835. svgwidth = str(size[0] + (2 * boundary))
  6836. svgheight = str(size[1] + (2 * boundary))
  6837. minx = str(bounds[0] - boundary)
  6838. miny = str(bounds[1] + boundary + size[1])
  6839. # Add a SVG Header and footer to the svg output from shapely
  6840. # The transform flips the Y Axis so that everything renders
  6841. # properly within svg apps such as inkscape
  6842. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6843. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6844. svg_header += 'width="' + svgwidth + uom + '" '
  6845. svg_header += 'height="' + svgheight + uom + '" '
  6846. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6847. svg_header += '>'
  6848. svg_header += '<g transform="scale(1,-1)">'
  6849. svg_footer = '</g> </svg>'
  6850. svg_elem = str(svg_header)
  6851. for svg_item in exported_svg:
  6852. svg_elem += str(svg_item)
  6853. svg_elem += str(svg_footer)
  6854. # Parse the xml through a xml parser just to add line feeds
  6855. # and to make it look more pretty for the output
  6856. doc = parse_xml_string(svg_elem)
  6857. doc_final = doc.toprettyxml()
  6858. try:
  6859. if self.defaults['units'].upper() == 'IN':
  6860. unit = inch
  6861. else:
  6862. unit = mm
  6863. doc_final = StringIO(doc_final)
  6864. drawing = svg2rlg(doc_final)
  6865. if p_size == 'Bounds':
  6866. renderPDF.drawToFile(drawing, file_name)
  6867. else:
  6868. if orientation == 'p':
  6869. page_size = portrait(self.pagesize[p_size])
  6870. else:
  6871. page_size = landscape(self.pagesize[p_size])
  6872. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6873. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6874. renderPDF.draw(drawing, my_canvas, 0, 0)
  6875. my_canvas.save()
  6876. except Exception as e:
  6877. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6878. return 'fail'
  6879. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6880. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6881. """
  6882. Exports a Geometry Object to an SVG file.
  6883. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6884. :param filename: Path to the SVG file to save to.
  6885. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6886. :return:
  6887. """
  6888. self.defaults.report_usage("export_svg()")
  6889. if filename is None:
  6890. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6891. is not None else self.defaults["global_last_folder"]
  6892. self.log.debug("export_svg()")
  6893. try:
  6894. obj = self.collection.get_by_name(str(obj_name))
  6895. except Exception:
  6896. # TODO: The return behavior has not been established... should raise exception?
  6897. return "Could not retrieve object: %s" % obj_name
  6898. with self.proc_container.new(_("Exporting SVG")) as proc:
  6899. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6900. # Determine bounding area for svg export
  6901. bounds = obj.bounds()
  6902. size = obj.size()
  6903. # Convert everything to strings for use in the xml doc
  6904. svgwidth = str(size[0])
  6905. svgheight = str(size[1])
  6906. minx = str(bounds[0])
  6907. miny = str(bounds[1] - size[1])
  6908. uom = obj.units.lower()
  6909. # Add a SVG Header and footer to the svg output from shapely
  6910. # The transform flips the Y Axis so that everything renders
  6911. # properly within svg apps such as inkscape
  6912. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6913. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6914. svg_header += 'width="' + svgwidth + uom + '" '
  6915. svg_header += 'height="' + svgheight + uom + '" '
  6916. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6917. svg_header += '<g transform="scale(1,-1)">'
  6918. svg_footer = '</g> </svg>'
  6919. svg_elem = svg_header + exported_svg + svg_footer
  6920. # Parse the xml through a xml parser just to add line feeds
  6921. # and to make it look more pretty for the output
  6922. svgcode = parse_xml_string(svg_elem)
  6923. svgcode = svgcode.toprettyxml()
  6924. try:
  6925. with open(filename, 'w') as fp:
  6926. fp.write(svgcode)
  6927. except PermissionError:
  6928. self.inform.emit('[WARNING] %s' %
  6929. _("Permission denied, saving not possible.\n"
  6930. "Most likely another app is holding the file open and not accessible."))
  6931. return 'fail'
  6932. if self.defaults["global_open_style"] is False:
  6933. self.file_opened.emit("SVG", filename)
  6934. self.file_saved.emit("SVG", filename)
  6935. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6936. def save_source_file(self, obj_name, filename, use_thread=True):
  6937. """
  6938. Exports a FlatCAM Object to an Gerber/Excellon file.
  6939. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6940. :param filename: Path to the Gerber file to save to.
  6941. :param use_thread: if to be run in a separate thread
  6942. :return:
  6943. """
  6944. self.defaults.report_usage("save source file()")
  6945. if filename is None:
  6946. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6947. is not None else self.defaults["global_last_folder"]
  6948. self.log.debug("save source file()")
  6949. obj = self.collection.get_by_name(obj_name)
  6950. file_string = StringIO(obj.source_file)
  6951. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6952. if file_string.getvalue() == '':
  6953. self.inform.emit('[ERROR_NOTCL] %s' %
  6954. _("Save cancelled because source file is empty. Try to export the file."))
  6955. return 'fail'
  6956. try:
  6957. with open(filename, 'w') as file:
  6958. file.writelines('G04*\n')
  6959. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6960. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6961. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6962. file.writelines('G04 Created on : %s*\n' % time_string)
  6963. for line in file_string:
  6964. file.writelines(line)
  6965. except PermissionError:
  6966. self.inform.emit('[WARNING] %s' %
  6967. _("Permission denied, saving not possible.\n"
  6968. "Most likely another app is holding the file open and not accessible."))
  6969. return 'fail'
  6970. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6971. """
  6972. Exports a Excellon Object to an Excellon file.
  6973. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6974. :param filename: Path to the Excellon file to save to.
  6975. :param local_use:
  6976. :param use_thread: if to be run in a separate thread
  6977. :return:
  6978. """
  6979. self.defaults.report_usage("export_excellon()")
  6980. if filename is None:
  6981. if self.defaults["global_last_save_folder"]:
  6982. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6983. else:
  6984. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6985. self.log.debug("export_excellon()")
  6986. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6987. self.defaults["excellon_exp_decimals"]
  6988. )
  6989. if local_use is None:
  6990. try:
  6991. obj = self.collection.get_by_name(str(obj_name))
  6992. except Exception:
  6993. return "Could not retrieve object: %s" % obj_name
  6994. else:
  6995. obj = local_use
  6996. if not isinstance(obj, ExcellonObject):
  6997. self.inform.emit('[ERROR_NOTCL] %s' %
  6998. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6999. return
  7000. # updated units
  7001. eunits = self.defaults["excellon_exp_units"]
  7002. ewhole = self.defaults["excellon_exp_integer"]
  7003. efract = self.defaults["excellon_exp_decimals"]
  7004. ezeros = self.defaults["excellon_exp_zeros"]
  7005. eformat = self.defaults["excellon_exp_format"]
  7006. slot_type = self.defaults["excellon_exp_slot_type"]
  7007. fc_units = self.defaults['units'].upper()
  7008. if fc_units == 'MM':
  7009. factor = 1 if eunits == 'METRIC' else 0.03937
  7010. else:
  7011. factor = 25.4 if eunits == 'METRIC' else 1
  7012. def make_excellon():
  7013. try:
  7014. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7015. header = 'M48\n'
  7016. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7017. (str(self.version), str(self.version_date))
  7018. header += ';Filename: %s' % str(obj_name) + '\n'
  7019. header += ';Created on : %s' % time_str + '\n'
  7020. if eformat == 'dec':
  7021. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7022. header += eunits + '\n'
  7023. for tool in obj.tools:
  7024. if eunits == 'METRIC':
  7025. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7026. tool=str(tool),
  7027. dec=2)
  7028. else:
  7029. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7030. tool=str(tool),
  7031. dec=4)
  7032. else:
  7033. if ezeros == 'LZ':
  7034. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7035. form='ndec', e_zeros='LZ', factor=factor,
  7036. slot_type=slot_type)
  7037. header += '%s,%s\n' % (eunits, 'LZ')
  7038. header += format_exc
  7039. for tool in obj.tools:
  7040. if eunits == 'METRIC':
  7041. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7042. float(obj.tools[tool]['tooldia']) * factor,
  7043. tool=str(tool),
  7044. dec=2)
  7045. else:
  7046. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7047. float(obj.tools[tool]['tooldia']) * factor,
  7048. tool=str(tool),
  7049. dec=4)
  7050. else:
  7051. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7052. form='ndec', e_zeros='TZ', factor=factor,
  7053. slot_type=slot_type)
  7054. header += '%s,%s\n' % (eunits, 'TZ')
  7055. header += format_exc
  7056. for tool in obj.tools:
  7057. if eunits == 'METRIC':
  7058. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7059. float(obj.tools[tool]['tooldia']) * factor,
  7060. tool=str(tool),
  7061. dec=2)
  7062. else:
  7063. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7064. float(obj.tools[tool]['tooldia']) * factor,
  7065. tool=str(tool),
  7066. dec=4)
  7067. header += '%\n'
  7068. footer = 'M30\n'
  7069. exported_excellon = header
  7070. exported_excellon += excellon_code
  7071. exported_excellon += footer
  7072. if local_use is None:
  7073. try:
  7074. with open(filename, 'w') as fp:
  7075. fp.write(exported_excellon)
  7076. except PermissionError:
  7077. self.inform.emit('[WARNING] %s' %
  7078. _("Permission denied, saving not possible.\n"
  7079. "Most likely another app is holding the file open and not accessible."))
  7080. return 'fail'
  7081. if self.defaults["global_open_style"] is False:
  7082. self.file_opened.emit("Excellon", filename)
  7083. self.file_saved.emit("Excellon", filename)
  7084. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7085. else:
  7086. return exported_excellon
  7087. except Exception as e:
  7088. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7089. return 'fail'
  7090. if use_thread is True:
  7091. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7092. def job_thread_exc(app_obj):
  7093. ret = make_excellon()
  7094. if ret == 'fail':
  7095. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7096. return
  7097. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7098. else:
  7099. eret = make_excellon()
  7100. if eret == 'fail':
  7101. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7102. return 'fail'
  7103. if local_use is not None:
  7104. return eret
  7105. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7106. """
  7107. Exports a Gerber Object to an Gerber file.
  7108. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7109. :param filename: Path to the Gerber file to save to.
  7110. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7111. When not None, the value will be the actual Gerber object for which to create
  7112. the Gerber code
  7113. :param use_thread: if to be run in a separate thread
  7114. :return:
  7115. """
  7116. self.defaults.report_usage("export_gerber()")
  7117. if filename is None:
  7118. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7119. is not None else self.defaults["global_last_folder"]
  7120. self.log.debug("export_gerber()")
  7121. if local_use is None:
  7122. try:
  7123. obj = self.collection.get_by_name(str(obj_name))
  7124. except Exception:
  7125. return 'fail'
  7126. else:
  7127. obj = local_use
  7128. # updated units
  7129. gunits = self.defaults["gerber_exp_units"]
  7130. gwhole = self.defaults["gerber_exp_integer"]
  7131. gfract = self.defaults["gerber_exp_decimals"]
  7132. gzeros = self.defaults["gerber_exp_zeros"]
  7133. fc_units = self.defaults['units'].upper()
  7134. if fc_units == 'MM':
  7135. factor = 1 if gunits == 'MM' else 0.03937
  7136. else:
  7137. factor = 25.4 if gunits == 'MM' else 1
  7138. def make_gerber():
  7139. try:
  7140. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7141. header = 'G04*\n'
  7142. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7143. (str(self.version), str(self.version_date))
  7144. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7145. header += 'G04 Created on : %s*' % time_str + '\n'
  7146. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7147. header += "%MO{units}*%\n".format(units=gunits)
  7148. for apid in obj.apertures:
  7149. if obj.apertures[apid]['type'] == 'C':
  7150. header += "%ADD{apid}{type},{size}*%\n".format(
  7151. apid=str(apid),
  7152. type='C',
  7153. size=(factor * obj.apertures[apid]['size'])
  7154. )
  7155. elif obj.apertures[apid]['type'] == 'R':
  7156. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7157. apid=str(apid),
  7158. type='R',
  7159. width=(factor * obj.apertures[apid]['width']),
  7160. height=(factor * obj.apertures[apid]['height'])
  7161. )
  7162. elif obj.apertures[apid]['type'] == 'O':
  7163. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7164. apid=str(apid),
  7165. type='O',
  7166. width=(factor * obj.apertures[apid]['width']),
  7167. height=(factor * obj.apertures[apid]['height'])
  7168. )
  7169. header += '\n'
  7170. # obsolete units but some software may need it
  7171. if gunits == 'IN':
  7172. header += 'G70*\n'
  7173. else:
  7174. header += 'G71*\n'
  7175. # Absolute Mode
  7176. header += 'G90*\n'
  7177. header += 'G01*\n'
  7178. # positive polarity
  7179. header += '%LPD*%\n'
  7180. footer = 'M02*\n'
  7181. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7182. exported_gerber = header
  7183. exported_gerber += gerber_code
  7184. exported_gerber += footer
  7185. if local_use is None:
  7186. try:
  7187. with open(filename, 'w') as fp:
  7188. fp.write(exported_gerber)
  7189. except PermissionError:
  7190. self.inform.emit('[WARNING] %s' %
  7191. _("Permission denied, saving not possible.\n"
  7192. "Most likely another app is holding the file open and not accessible."))
  7193. return 'fail'
  7194. if self.defaults["global_open_style"] is False:
  7195. self.file_opened.emit("Gerber", filename)
  7196. self.file_saved.emit("Gerber", filename)
  7197. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7198. else:
  7199. return exported_gerber
  7200. except Exception as e:
  7201. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7202. return 'fail'
  7203. if use_thread is True:
  7204. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7205. def job_thread_grb(app_obj):
  7206. ret = make_gerber()
  7207. if ret == 'fail':
  7208. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7209. return
  7210. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7211. else:
  7212. gret = make_gerber()
  7213. if gret == 'fail':
  7214. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7215. return 'fail'
  7216. if local_use is not None:
  7217. return gret
  7218. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7219. """
  7220. Exports a Geometry Object to an DXF file.
  7221. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7222. :param filename: Path to the DXF file to save to.
  7223. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7224. When not None, the value will be the actual Geometry object for which to create
  7225. the Geometry/DXF code
  7226. :param use_thread: if to be run in a separate thread
  7227. :return:
  7228. """
  7229. self.defaults.report_usage("export_dxf()")
  7230. if filename is None:
  7231. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7232. is not None else self.defaults["global_last_folder"]
  7233. self.log.debug("export_dxf()")
  7234. if local_use is None:
  7235. try:
  7236. obj = self.collection.get_by_name(str(obj_name))
  7237. except Exception:
  7238. return 'fail'
  7239. else:
  7240. obj = local_use
  7241. def make_dxf():
  7242. try:
  7243. dxf_code = obj.export_dxf()
  7244. if local_use is None:
  7245. try:
  7246. dxf_code.saveas(filename)
  7247. except PermissionError:
  7248. self.inform.emit('[WARNING] %s' %
  7249. _("Permission denied, saving not possible.\n"
  7250. "Most likely another app is holding the file open and not accessible."))
  7251. return 'fail'
  7252. if self.defaults["global_open_style"] is False:
  7253. self.file_opened.emit("DXF", filename)
  7254. self.file_saved.emit("DXF", filename)
  7255. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7256. else:
  7257. return dxf_code
  7258. except Exception as e:
  7259. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7260. return 'fail'
  7261. if use_thread is True:
  7262. with self.proc_container.new(_("Exporting DXF")) as proc:
  7263. def job_thread_exc(app_obj):
  7264. ret_dxf_val = make_dxf()
  7265. if ret_dxf_val == 'fail':
  7266. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7267. return
  7268. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7269. else:
  7270. ret = make_dxf()
  7271. if ret == 'fail':
  7272. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7273. return
  7274. if local_use is not None:
  7275. return ret
  7276. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7277. """
  7278. Adds a new Geometry Object to the projects and populates
  7279. it with shapes extracted from the SVG file.
  7280. :param plot: If True then the resulting object will be plotted on canvas
  7281. :param filename: Path to the SVG file.
  7282. :param geo_type: Type of FlatCAM object that will be created from SVG
  7283. :param outname: The name given to the resulting FlatCAM object
  7284. :return:
  7285. """
  7286. self.defaults.report_usage("import_svg()")
  7287. log.debug("App.import_svg()")
  7288. obj_type = ""
  7289. if geo_type is None or geo_type == "geometry":
  7290. obj_type = "geometry"
  7291. elif geo_type == "gerber":
  7292. obj_type = "gerber"
  7293. else:
  7294. self.inform.emit('[ERROR_NOTCL] %s' %
  7295. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7296. return
  7297. units = self.defaults['units'].upper()
  7298. def obj_init(geo_obj, app_obj):
  7299. geo_obj.import_svg(filename, obj_type, units=units)
  7300. geo_obj.multigeo = True
  7301. with open(filename) as f:
  7302. file_content = f.read()
  7303. geo_obj.source_file = file_content
  7304. with self.proc_container.new(_("Importing SVG")) as proc:
  7305. # Object name
  7306. name = outname or filename.split('/')[-1].split('\\')[-1]
  7307. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7308. if ret == 'fail':
  7309. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7310. return 'fail'
  7311. # Register recent file
  7312. self.file_opened.emit("svg", filename)
  7313. # appGUI feedback
  7314. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7315. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7316. """
  7317. Adds a new Geometry Object to the projects and populates
  7318. it with shapes extracted from the DXF file.
  7319. :param filename: Path to the DXF file.
  7320. :param geo_type: Type of FlatCAM object that will be created from DXF
  7321. :param outname: Name for the imported Geometry
  7322. :param plot: If True then the resulting object will be plotted on canvas
  7323. :return:
  7324. """
  7325. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7326. obj_type = ""
  7327. if geo_type is None or geo_type == "geometry":
  7328. obj_type = "geometry"
  7329. elif geo_type == "gerber":
  7330. obj_type = geo_type
  7331. else:
  7332. self.inform.emit('[ERROR_NOTCL] %s' %
  7333. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7334. return
  7335. units = self.defaults['units'].upper()
  7336. def obj_init(geo_obj, app_obj):
  7337. if obj_type == "geometry":
  7338. geo_obj.import_dxf_as_geo(filename, units=units)
  7339. elif obj_type == "gerber":
  7340. geo_obj.import_dxf_as_gerber(filename, units=units)
  7341. else:
  7342. return "fail"
  7343. geo_obj.multigeo = True
  7344. with open(filename) as f:
  7345. file_content = f.read()
  7346. geo_obj.source_file = file_content
  7347. with self.proc_container.new(_("Importing DXF")):
  7348. # Object name
  7349. name = outname or filename.split('/')[-1].split('\\')[-1]
  7350. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7351. if ret == 'fail':
  7352. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7353. return 'fail'
  7354. # Register recent file
  7355. self.file_opened.emit("dxf", filename)
  7356. # appGUI feedback
  7357. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7358. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7359. """
  7360. Opens a Gerber file, parses it and creates a new object for
  7361. it in the program. Thread-safe.
  7362. :param outname: Name of the resulting object. None causes the
  7363. name to be that of the file. Str.
  7364. :param filename: Gerber file filename
  7365. :type filename: str
  7366. :param plot: boolean, to plot or not the resulting object
  7367. :param from_tcl: True if run from Tcl Shell
  7368. :return: None
  7369. """
  7370. # How the object should be initialized
  7371. def obj_init(gerber_obj, app_obj):
  7372. assert isinstance(gerber_obj, GerberObject), \
  7373. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7374. # Opening the file happens here
  7375. try:
  7376. gerber_obj.parse_file(filename)
  7377. except IOError:
  7378. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7379. return "fail"
  7380. except ParseError as err:
  7381. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7382. app_obj.log.error(str(err))
  7383. return "fail"
  7384. except Exception as e:
  7385. log.debug("App.open_gerber() --> %s" % str(e))
  7386. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7387. msg += traceback.format_exc()
  7388. app_obj.inform.emit(msg)
  7389. return "fail"
  7390. if gerber_obj.is_empty():
  7391. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7392. _("Object is not Gerber file or empty. Aborting object creation."))
  7393. return "fail"
  7394. App.log.debug("open_gerber()")
  7395. with self.proc_container.new(_("Opening Gerber")):
  7396. # Object name
  7397. name = outname or filename.split('/')[-1].split('\\')[-1]
  7398. # # ## Object creation # ##
  7399. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7400. if ret_val == 'fail':
  7401. if from_tcl:
  7402. filename = self.defaults['global_tcl_path'] + '/' + name
  7403. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7404. if ret_val == 'fail':
  7405. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7406. return 'fail'
  7407. # Register recent file
  7408. self.file_opened.emit("gerber", filename)
  7409. # appGUI feedback
  7410. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7411. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7412. """
  7413. Opens an Excellon file, parses it and creates a new object for
  7414. it in the program. Thread-safe.
  7415. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7416. :param filename: Excellon file filename
  7417. :type filename: str
  7418. :param plot: boolean, to plot or not the resulting object
  7419. :param from_tcl: True if run from Tcl Shell
  7420. :return: None
  7421. """
  7422. App.log.debug("open_excellon()")
  7423. # How the object should be initialized
  7424. def obj_init(excellon_obj, app_obj):
  7425. try:
  7426. ret = excellon_obj.parse_file(filename=filename)
  7427. if ret == "fail":
  7428. log.debug("Excellon parsing failed.")
  7429. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7430. return "fail"
  7431. except IOError:
  7432. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7433. log.debug("Could not open Excellon object.")
  7434. return "fail"
  7435. except Exception:
  7436. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7437. msg += traceback.format_exc()
  7438. app_obj.inform.emit(msg)
  7439. return "fail"
  7440. ret = excellon_obj.create_geometry()
  7441. if ret == 'fail':
  7442. log.debug("Could not create geometry for Excellon object.")
  7443. return "fail"
  7444. for tool in excellon_obj.tools:
  7445. if excellon_obj.tools[tool]['solid_geometry']:
  7446. return
  7447. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7448. return "fail"
  7449. with self.proc_container.new(_("Opening Excellon.")):
  7450. # Object name
  7451. name = outname or filename.split('/')[-1].split('\\')[-1]
  7452. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7453. if ret_val == 'fail':
  7454. if from_tcl:
  7455. filename = self.defaults['global_tcl_path'] + '/' + name
  7456. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7457. if ret_val == 'fail':
  7458. self.inform.emit('[ERROR_NOTCL] %s' %
  7459. _('Open Excellon file failed. Probable not an Excellon file.'))
  7460. return
  7461. # Register recent file
  7462. self.file_opened.emit("excellon", filename)
  7463. # appGUI feedback
  7464. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7465. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7466. """
  7467. Opens a G-gcode file, parses it and creates a new object for
  7468. it in the program. Thread-safe.
  7469. :param filename: G-code file filename
  7470. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7471. :param force_parsing:
  7472. :param plot: If True plot the object on canvas
  7473. :param from_tcl: True if run from Tcl Shell
  7474. :return: None
  7475. """
  7476. App.log.debug("open_gcode()")
  7477. # How the object should be initialized
  7478. def obj_init(job_obj, app_obj_):
  7479. """
  7480. :param job_obj: the resulting object
  7481. :type app_obj_: App
  7482. """
  7483. assert isinstance(app_obj_, App), \
  7484. "Initializer expected App, got %s" % type(app_obj_)
  7485. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7486. try:
  7487. f = open(filename)
  7488. gcode = f.read()
  7489. f.close()
  7490. except IOError:
  7491. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7492. return "fail"
  7493. job_obj.gcode = gcode
  7494. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7495. if gcode_ret == "fail":
  7496. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7497. return "fail"
  7498. job_obj.create_geometry()
  7499. with self.proc_container.new(_("Opening G-Code.")):
  7500. # Object name
  7501. name = outname or filename.split('/')[-1].split('\\')[-1]
  7502. # New object creation and file processing
  7503. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7504. if ret_val == 'fail':
  7505. if from_tcl:
  7506. filename = self.defaults['global_tcl_path'] + '/' + name
  7507. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7508. if ret_val == 'fail':
  7509. self.inform.emit('[ERROR_NOTCL] %s' %
  7510. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7511. "Try to load it from File menu.\n "
  7512. "Attempting to create a FlatCAM CNCJob Object from "
  7513. "G-Code file failed during processing"))
  7514. return "fail"
  7515. # Register recent file
  7516. self.file_opened.emit("cncjob", filename)
  7517. # appGUI feedback
  7518. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7519. def open_hpgl2(self, filename, outname=None):
  7520. """
  7521. Opens a HPGL2 file, parses it and creates a new object for
  7522. it in the program. Thread-safe.
  7523. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7524. :param filename: HPGL2 file filename
  7525. :return: None
  7526. """
  7527. filename = filename
  7528. # How the object should be initialized
  7529. def obj_init(geo_obj, app_obj):
  7530. assert isinstance(geo_obj, GeometryObject), \
  7531. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7532. # Opening the file happens here
  7533. obj = HPGL2(self)
  7534. try:
  7535. HPGL2.parse_file(obj, filename)
  7536. except IOError:
  7537. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7538. return "fail"
  7539. except ParseError as err:
  7540. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7541. app_obj.log.error(str(err))
  7542. return "fail"
  7543. except Exception as e:
  7544. log.debug("App.open_hpgl2() --> %s" % str(e))
  7545. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7546. msg += traceback.format_exc()
  7547. app_obj.inform.emit(msg)
  7548. return "fail"
  7549. geo_obj.multigeo = True
  7550. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7551. geo_obj.tools = deepcopy(obj.tools)
  7552. geo_obj.source_file = deepcopy(obj.source_file)
  7553. del obj
  7554. if not geo_obj.solid_geometry:
  7555. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7556. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7557. return "fail"
  7558. App.log.debug("open_hpgl2()")
  7559. with self.proc_container.new(_("Opening HPGL2")):
  7560. # Object name
  7561. name = outname or filename.split('/')[-1].split('\\')[-1]
  7562. # # ## Object creation # ##
  7563. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7564. if ret == 'fail':
  7565. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7566. return 'fail'
  7567. # Register recent file
  7568. self.file_opened.emit("geometry", filename)
  7569. # appGUI feedback
  7570. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7571. def open_script(self, filename, outname=None, silent=False):
  7572. """
  7573. Opens a Script file, parses it and creates a new object for
  7574. it in the program. Thread-safe.
  7575. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7576. :param filename: Script file filename
  7577. :param silent: If True there will be no messages printed to StatusBar
  7578. :return: None
  7579. """
  7580. def obj_init(script_obj, app_obj):
  7581. assert isinstance(script_obj, ScriptObject), \
  7582. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7583. if silent is False:
  7584. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7585. try:
  7586. script_obj.parse_file(filename)
  7587. except IOError:
  7588. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7589. return "fail"
  7590. except ParseError as err:
  7591. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7592. app_obj.log.error(str(err))
  7593. return "fail"
  7594. except Exception as e:
  7595. log.debug("App.open_script() -> %s" % str(e))
  7596. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7597. msg += traceback.format_exc()
  7598. app_obj.inform.emit(msg)
  7599. return "fail"
  7600. App.log.debug("open_script()")
  7601. with self.proc_container.new(_("Opening TCL Script...")):
  7602. # Object name
  7603. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7604. # Object creation
  7605. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7606. if ret_val == 'fail':
  7607. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7608. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7609. if ret_val == 'fail':
  7610. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7611. return 'fail'
  7612. # Register recent file
  7613. self.file_opened.emit("script", filename)
  7614. # appGUI feedback
  7615. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7616. def open_config_file(self, filename, run_from_arg=None):
  7617. """
  7618. Loads a config file from the specified file.
  7619. :param filename: Name of the file from which to load.
  7620. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7621. :return: None
  7622. """
  7623. App.log.debug("Opening config file: " + filename)
  7624. if run_from_arg:
  7625. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7626. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7627. _("Opening FlatCAM Config file.")),
  7628. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7629. color=QtGui.QColor("gray"))
  7630. # # add the tab if it was closed
  7631. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7632. # # first clear previous text in text editor (if any)
  7633. # self.ui.text_editor_tab.code_editor.clear()
  7634. #
  7635. # # Switch plot_area to CNCJob tab
  7636. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7637. # close the Code editor if already open
  7638. if self.toggle_codeeditor:
  7639. self.on_toggle_code_editor()
  7640. self.on_toggle_code_editor()
  7641. try:
  7642. if filename:
  7643. f = QtCore.QFile(filename)
  7644. if f.open(QtCore.QIODevice.ReadOnly):
  7645. stream = QtCore.QTextStream(f)
  7646. code_edited = stream.readAll()
  7647. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7648. f.close()
  7649. except IOError:
  7650. App.log.error("Failed to open config file: %s" % filename)
  7651. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7652. (_("Failed to open config file"), filename))
  7653. return
  7654. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7655. """
  7656. Loads a project from the specified file.
  7657. 1) Loads and parses file
  7658. 2) Registers the file as recently opened.
  7659. 3) Calls on_file_new()
  7660. 4) Updates options
  7661. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7662. 6) Calls plot_all() if plot=True
  7663. :param filename: Name of the file from which to load.
  7664. :param run_from_arg: True if run for arguments
  7665. :param plot: If True plot all objects in the project
  7666. :param cli: Run from command line
  7667. :param from_tcl: True if run from Tcl Sehll
  7668. :return: None
  7669. """
  7670. App.log.debug("Opening project: " + filename)
  7671. # block autosaving while a project is loaded
  7672. self.block_autosave = True
  7673. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7674. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7675. if cli is None:
  7676. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7677. if run_from_arg:
  7678. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7679. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7680. _("Opening FlatCAM Project file.")),
  7681. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7682. color=QtGui.QColor("gray"))
  7683. # Open and parse an uncompressed Project file
  7684. try:
  7685. f = open(filename, 'r')
  7686. except IOError:
  7687. if from_tcl:
  7688. name = filename.split('/')[-1].split('\\')[-1]
  7689. filename = self.defaults['global_tcl_path'] + '/' + name
  7690. try:
  7691. f = open(filename, 'r')
  7692. except IOError:
  7693. log.error("Failed to open project file: %s" % filename)
  7694. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7695. return
  7696. else:
  7697. log.error("Failed to open project file: %s" % filename)
  7698. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7699. return
  7700. try:
  7701. d = json.load(f, object_hook=dict2obj)
  7702. except Exception as e:
  7703. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7704. (filename, str(e)))
  7705. f.close()
  7706. # Open and parse a compressed Project file
  7707. try:
  7708. with lzma.open(filename) as f:
  7709. file_content = f.read().decode('utf-8')
  7710. d = json.loads(file_content, object_hook=dict2obj)
  7711. except Exception as e:
  7712. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7713. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7714. return
  7715. # Clear the current project
  7716. # # NOT THREAD SAFE # ##
  7717. if run_from_arg is True:
  7718. pass
  7719. elif cli is True:
  7720. self.delete_selection_shape()
  7721. else:
  7722. self.on_file_new()
  7723. # Project options
  7724. self.options.update(d['options'])
  7725. self.project_filename = filename
  7726. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7727. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7728. if cli is None:
  7729. self.set_screen_units(self.options["units"])
  7730. # Re create objects
  7731. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7732. for obj in d['objs']:
  7733. def obj_init(obj_inst, app_inst):
  7734. try:
  7735. obj_inst.from_dict(obj)
  7736. except Exception as e:
  7737. print('App.open_project() --> ' + str(e))
  7738. return 'fail'
  7739. App.log.debug("Recreating from opened project an %s object: %s" %
  7740. (obj['kind'].capitalize(), obj['options']['name']))
  7741. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7742. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7743. if cli is None:
  7744. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7745. obj['kind'].upper(),
  7746. obj['options']['name']
  7747. )
  7748. )
  7749. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7750. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7751. self.should_we_save = False
  7752. self.file_opened.emit("project", filename)
  7753. # restore autosaving after a project was loaded
  7754. self.block_autosave = False
  7755. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7756. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7757. if cli is None:
  7758. self.set_ui_title(name=self.project_filename)
  7759. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7760. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7761. """
  7762. Re-generates all plots from all objects.
  7763. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7764. :param muted: if True don't print messages
  7765. :param use_thread: if True will use threading for plotting the objects
  7766. :return: None
  7767. """
  7768. self.log.debug("Plot_all()")
  7769. if muted is not True:
  7770. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7771. for plot_obj in self.collection.get_list():
  7772. def worker_task(obj):
  7773. with self.proc_container.new("Plotting"):
  7774. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7775. if fit_view is True:
  7776. self.app_obj.object_plotted.emit(obj)
  7777. if use_thread is True:
  7778. # Send to worker
  7779. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7780. else:
  7781. worker_task(plot_obj)
  7782. def register_folder(self, filename):
  7783. """
  7784. Register the last folder used by the app to open something
  7785. :param filename: the last folder is extracted from the filename
  7786. :return: None
  7787. """
  7788. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7789. def register_save_folder(self, filename):
  7790. """
  7791. Register the last folder used by the app to save something
  7792. :param filename: the last folder is extracted from the filename
  7793. :return: None
  7794. """
  7795. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7796. # def set_progress_bar(self, percentage, text=""):
  7797. # """
  7798. # Set a progress bar to a value (percentage)
  7799. #
  7800. # :param percentage: Value set to the progressbar
  7801. # :param text: Not used
  7802. # :return: None
  7803. # """
  7804. # self.ui.progress_bar.setValue(int(percentage))
  7805. def setup_recent_items(self):
  7806. """
  7807. Setup a dictionary with the recent files accessed, organized by type
  7808. :return:
  7809. """
  7810. icons = {
  7811. "gerber": self.resource_location + "/flatcam_icon16.png",
  7812. "excellon": self.resource_location + "/drill16.png",
  7813. 'geometry': self.resource_location + "/geometry16.png",
  7814. "cncjob": self.resource_location + "/cnc16.png",
  7815. "script": self.resource_location + "/script_new24.png",
  7816. "document": self.resource_location + "/notes16_1.png",
  7817. "project": self.resource_location + "/project16.png",
  7818. "svg": self.resource_location + "/geometry16.png",
  7819. "dxf": self.resource_location + "/dxf16.png",
  7820. "pdf": self.resource_location + "/pdf32.png",
  7821. "image": self.resource_location + "/image16.png"
  7822. }
  7823. try:
  7824. image_opener = self.image_tool.import_image
  7825. except AttributeError:
  7826. image_opener = None
  7827. openers = {
  7828. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7829. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7830. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7831. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7832. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7833. "document": None,
  7834. 'project': self.open_project,
  7835. 'svg': self.import_svg,
  7836. 'dxf': self.import_dxf,
  7837. 'image': image_opener,
  7838. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7839. }
  7840. # Open recent file for files
  7841. try:
  7842. f = open(self.data_path + '/recent.json')
  7843. except IOError:
  7844. App.log.error("Failed to load recent item list.")
  7845. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7846. return
  7847. try:
  7848. self.recent = json.load(f)
  7849. except json.errors.JSONDecodeError:
  7850. App.log.error("Failed to parse recent item list.")
  7851. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7852. f.close()
  7853. return
  7854. f.close()
  7855. # Open recent file for projects
  7856. try:
  7857. fp = open(self.data_path + '/recent_projects.json')
  7858. except IOError:
  7859. App.log.error("Failed to load recent project item list.")
  7860. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7861. return
  7862. try:
  7863. self.recent_projects = json.load(fp)
  7864. except json.errors.JSONDecodeError:
  7865. App.log.error("Failed to parse recent project item list.")
  7866. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7867. fp.close()
  7868. return
  7869. fp.close()
  7870. # Closure needed to create callbacks in a loop.
  7871. # Otherwise late binding occurs.
  7872. def make_callback(func, fname):
  7873. def opener():
  7874. func(fname)
  7875. return opener
  7876. def reset_recent_files():
  7877. # Reset menu
  7878. self.ui.recent.clear()
  7879. self.recent = []
  7880. try:
  7881. ff = open(self.data_path + '/recent.json', 'w')
  7882. except IOError:
  7883. App.log.error("Failed to open recent items file for writing.")
  7884. return
  7885. json.dump(self.recent, ff)
  7886. def reset_recent_projects():
  7887. # Reset menu
  7888. self.ui.recent_projects.clear()
  7889. self.recent_projects = []
  7890. try:
  7891. frp = open(self.data_path + '/recent_projects.json', 'w')
  7892. except IOError:
  7893. App.log.error("Failed to open recent projects items file for writing.")
  7894. return
  7895. json.dump(self.recent, frp)
  7896. # Reset menu
  7897. self.ui.recent.clear()
  7898. self.ui.recent_projects.clear()
  7899. # Create menu items for projects
  7900. for recent in self.recent_projects:
  7901. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7902. if recent['kind'] == 'project':
  7903. try:
  7904. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7905. # Attach callback
  7906. o = make_callback(openers[recent["kind"]], recent['filename'])
  7907. action.triggered.connect(o)
  7908. self.ui.recent_projects.addAction(action)
  7909. except KeyError:
  7910. App.log.error("Unsupported file type: %s" % recent["kind"])
  7911. # Last action in Recent Files menu is one that Clear the content
  7912. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7913. (_("Clear Recent projects")), self)
  7914. clear_action_proj.triggered.connect(reset_recent_projects)
  7915. self.ui.recent_projects.addSeparator()
  7916. self.ui.recent_projects.addAction(clear_action_proj)
  7917. # Create menu items for files
  7918. for recent in self.recent:
  7919. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7920. if recent['kind'] != 'project':
  7921. try:
  7922. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7923. # Attach callback
  7924. o = make_callback(openers[recent["kind"]], recent['filename'])
  7925. action.triggered.connect(o)
  7926. self.ui.recent.addAction(action)
  7927. except KeyError:
  7928. App.log.error("Unsupported file type: %s" % recent["kind"])
  7929. # Last action in Recent Files menu is one that Clear the content
  7930. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7931. (_("Clear Recent files")), self)
  7932. clear_action.triggered.connect(reset_recent_files)
  7933. self.ui.recent.addSeparator()
  7934. self.ui.recent.addAction(clear_action)
  7935. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7936. # self.ui.menufilerecent.set_submenu(recent_menu)
  7937. # recent_menu.show_all()
  7938. # self.ui.recent.show()
  7939. self.log.debug("Recent items list has been populated.")
  7940. def on_properties_tab_click(self, index):
  7941. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  7942. self.setup_default_properties_tab()
  7943. def setup_default_properties_tab(self):
  7944. """
  7945. Default text for the Properties tab when is not taken by the Object UI.
  7946. :return:
  7947. """
  7948. # label = QtWidgets.QLabel("Choose an item from Project")
  7949. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7950. # sel_title = QtWidgets.QTextEdit()
  7951. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7952. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7953. #
  7954. # f_settings = QSettings("Open Source", "FlatCAM")
  7955. # if f_settings.contains("notebook_font_size"):
  7956. # fsize = f_settings.value('notebook_font_size', type=int)
  7957. # else:
  7958. # fsize = 12
  7959. #
  7960. # tsize = fsize + int(fsize / 2)
  7961. #
  7962. # selected_text = ''
  7963. #
  7964. # sel_title.setText(selected_text)
  7965. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7966. # Tree Widget
  7967. d_properties_tw = FCTree(columns=2)
  7968. d_properties_tw.setObjectName("default_properties")
  7969. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7970. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  7971. root = d_properties_tw.invisibleRootItem()
  7972. font = QtGui.QFont()
  7973. font.setBold(True)
  7974. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  7975. # main Items categories
  7976. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  7977. d_properties_tw.addChild(parent=general_cat,
  7978. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  7979. d_properties_tw.addChild(parent=general_cat,
  7980. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  7981. d_properties_tw.addChild(parent=general_cat,
  7982. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  7983. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  7984. d_properties_tw.addChild(parent=grid_cat,
  7985. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  7986. column1=True)
  7987. d_properties_tw.addChild(parent=grid_cat,
  7988. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  7989. column1=True)
  7990. d_properties_tw.addChild(parent=grid_cat,
  7991. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  7992. column1=True)
  7993. d_properties_tw.addChild(parent=grid_cat,
  7994. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  7995. column1=True)
  7996. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  7997. d_properties_tw.addChild(parent=canvas_cat,
  7998. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  7999. column1=True)
  8000. d_properties_tw.addChild(parent=canvas_cat,
  8001. title=['%s:' % _("Workspace active"),
  8002. '%s' % str(self.defaults['global_workspace'])],
  8003. column1=True)
  8004. d_properties_tw.addChild(parent=canvas_cat,
  8005. title=['%s:' % _("Workspace size"),
  8006. '%s' % str(self.defaults['global_workspaceT'])],
  8007. column1=True)
  8008. d_properties_tw.addChild(parent=canvas_cat,
  8009. title=['%s:' % _("Workspace orientation"),
  8010. '%s' % _("Portrait") if self.defaults[
  8011. 'global_workspace_orientation'] == 'p' else
  8012. _("Landscape")],
  8013. column1=True)
  8014. d_properties_tw.addChild(parent=canvas_cat,
  8015. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  8016. column1=True)
  8017. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  8018. def setup_obj_classes(self):
  8019. """
  8020. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8021. class.
  8022. :return: None
  8023. """
  8024. FlatCAMObj.app = self
  8025. ObjectCollection.app = self
  8026. Gerber.app = self
  8027. Excellon.app = self
  8028. Geometry.app = self
  8029. CNCjob.app = self
  8030. FCProcess.app = self
  8031. FCProcessContainer.app = self
  8032. OptionsGroupUI.app = self
  8033. def version_check(self):
  8034. """
  8035. Checks for the latest version of the program. Alerts the
  8036. user if theirs is outdated. This method is meant to be run
  8037. in a separate thread.
  8038. :return: None
  8039. """
  8040. self.log.debug("version_check()")
  8041. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8042. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8043. App.version_url,
  8044. str(self.defaults['global_serial']),
  8045. str(self.version),
  8046. str(self.os),
  8047. urllib.parse.urlencode(self.defaults["global_stats"])
  8048. )
  8049. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8050. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8051. # urllib.parse.urlencode(self.defaults["global_stats"])
  8052. else:
  8053. # no_stats dict; just so it won't break things on website
  8054. no_ststs_dict = {}
  8055. no_ststs_dict["global_ststs"] = {}
  8056. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  8057. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8058. App.log.debug("Checking for updates @ %s" % full_url)
  8059. # ## Get the data
  8060. try:
  8061. f = urllib.request.urlopen(full_url)
  8062. except Exception:
  8063. # App.log.warning("Failed checking for latest version. Could not connect.")
  8064. self.log.warning("Failed checking for latest version. Could not connect.")
  8065. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8066. return
  8067. try:
  8068. data = json.load(f)
  8069. except Exception as e:
  8070. App.log.error("Could not parse information about latest version.")
  8071. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8072. App.log.debug("json.load(): %s" % str(e))
  8073. f.close()
  8074. return
  8075. f.close()
  8076. # ## Latest version?
  8077. if self.version >= data["version"]:
  8078. App.log.debug("FlatCAM is up to date!")
  8079. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8080. return
  8081. App.log.debug("Newer version available.")
  8082. self.message.emit(
  8083. _("Newer Version Available"),
  8084. '%s<br><br>><b>%s</b><br>%s' % (
  8085. _("There is a newer version of FlatCAM available for download:"),
  8086. str(data["name"]),
  8087. str(data["message"])
  8088. ),
  8089. _("info")
  8090. )
  8091. def on_plotcanvas_setup(self, container=None):
  8092. """
  8093. This is doing the setup for the plot area (canvas).
  8094. :param container: QT Widget where to install the canvas
  8095. :return: None
  8096. """
  8097. if container:
  8098. plot_container = container
  8099. else:
  8100. plot_container = self.ui.right_layout
  8101. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8102. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8103. self.is_legacy = True
  8104. self.defaults["global_graphic_engine"] = "2D"
  8105. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8106. else:
  8107. try:
  8108. self.plotcanvas = PlotCanvas(plot_container, self)
  8109. except Exception as er:
  8110. msg_txt = traceback.format_exc()
  8111. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8112. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8113. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8114. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8115. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8116. msg += msg_txt
  8117. self.inform.emit(msg)
  8118. return 'fail'
  8119. # So it can receive key presses
  8120. self.plotcanvas.native.setFocus()
  8121. if self.is_legacy is False:
  8122. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8123. # Set the mouse button for panning
  8124. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8125. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8126. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8127. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8128. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8129. # Keys over plot enabled
  8130. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8131. if self.defaults['global_cursor_type'] == 'small':
  8132. self.app_cursor = self.plotcanvas.new_cursor()
  8133. else:
  8134. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8135. if self.ui.grid_snap_btn.isChecked():
  8136. self.app_cursor.enabled = True
  8137. else:
  8138. self.app_cursor.enabled = False
  8139. if self.is_legacy is False:
  8140. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8141. else:
  8142. # will use the default Matplotlib axes
  8143. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8144. def on_zoom_fit(self):
  8145. """
  8146. Callback for zoom-fit request. This can be either from the corresponding
  8147. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8148. with axes limits from the geometry bounds of all objects.
  8149. :return: None
  8150. """
  8151. if self.is_legacy is False:
  8152. self.plotcanvas.fit_view()
  8153. else:
  8154. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8155. width = xmax - xmin
  8156. height = ymax - ymin
  8157. xmin -= 0.05 * width
  8158. xmax += 0.05 * width
  8159. ymin -= 0.05 * height
  8160. ymax += 0.05 * height
  8161. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8162. def on_zoom_in(self):
  8163. """
  8164. Callback for zoom-in request.
  8165. :return:
  8166. """
  8167. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8168. def on_zoom_out(self):
  8169. """
  8170. Callback for zoom-out request.
  8171. :return:
  8172. """
  8173. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8174. def disable_all_plots(self):
  8175. self.defaults.report_usage("disable_all_plots()")
  8176. self.disable_plots(self.collection.get_list())
  8177. self.inform.emit('[success] %s' %
  8178. _("All plots disabled."))
  8179. def disable_other_plots(self):
  8180. self.defaults.report_usage("disable_other_plots()")
  8181. self.disable_plots(self.collection.get_non_selected())
  8182. self.inform.emit('[success] %s' %
  8183. _("All non selected plots disabled."))
  8184. def enable_all_plots(self):
  8185. self.defaults.report_usage("enable_all_plots()")
  8186. self.enable_plots(self.collection.get_list())
  8187. self.inform.emit('[success] %s' %
  8188. _("All plots enabled."))
  8189. def on_enable_sel_plots(self):
  8190. log.debug("App.on_enable_sel_plot()")
  8191. object_list = self.collection.get_selected()
  8192. self.enable_plots(objects=object_list)
  8193. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8194. def on_disable_sel_plots(self):
  8195. log.debug("App.on_disable_sel_plot()")
  8196. # self.inform.emit(_("Disabling plots ..."))
  8197. object_list = self.collection.get_selected()
  8198. self.disable_plots(objects=object_list)
  8199. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8200. def enable_plots(self, objects):
  8201. """
  8202. Enable plots
  8203. :param objects: list of Objects to be enabled
  8204. :return:
  8205. """
  8206. log.debug("Enabling plots ...")
  8207. # self.inform.emit(_("Working ..."))
  8208. for obj in objects:
  8209. if obj.options['plot'] is False:
  8210. obj.options.set_change_callback(lambda x: None)
  8211. obj.options['plot'] = True
  8212. try:
  8213. # only the Gerber obj has on_plot_cb_click() method
  8214. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8215. # disable this cb while disconnected,
  8216. # in case the operation takes time the user is not allowed to change it
  8217. obj.ui.plot_cb.setDisabled(True)
  8218. except AttributeError:
  8219. pass
  8220. obj.set_form_item("plot")
  8221. try:
  8222. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8223. obj.ui.plot_cb.setDisabled(False)
  8224. except AttributeError:
  8225. pass
  8226. obj.options.set_change_callback(obj.on_options_change)
  8227. def worker_task(objs):
  8228. with self.proc_container.new(_("Enabling plots ...")):
  8229. for plot_obj in objs:
  8230. # obj.options['plot'] = True
  8231. if isinstance(plot_obj, CNCJobObject):
  8232. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8233. else:
  8234. plot_obj.plot(visible=True)
  8235. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8236. def disable_plots(self, objects):
  8237. """
  8238. Disables plots
  8239. :param objects: list of Objects to be disabled
  8240. :return:
  8241. """
  8242. # if no objects selected then do nothing
  8243. if not self.collection.get_selected():
  8244. return
  8245. log.debug("Disabling plots ...")
  8246. # self.inform.emit(_("Working ..."))
  8247. for obj in objects:
  8248. if obj.options['plot'] is True:
  8249. obj.options.set_change_callback(lambda x: None)
  8250. obj.options['plot'] = False
  8251. try:
  8252. # only the Gerber obj has on_plot_cb_click() method
  8253. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8254. obj.ui.plot_cb.setDisabled(True)
  8255. except AttributeError:
  8256. pass
  8257. obj.set_form_item("plot")
  8258. try:
  8259. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8260. obj.ui.plot_cb.setDisabled(False)
  8261. except AttributeError:
  8262. pass
  8263. obj.options.set_change_callback(obj.on_options_change)
  8264. try:
  8265. self.delete_selection_shape()
  8266. except Exception as e:
  8267. log.debug("App.disable_plots() --> %s" % str(e))
  8268. def worker_task(objs):
  8269. with self.proc_container.new(_("Disabling plots ...")):
  8270. for plot_obj in objs:
  8271. # obj.options['plot'] = True
  8272. if isinstance(plot_obj, CNCJobObject):
  8273. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8274. else:
  8275. plot_obj.plot(visible=False)
  8276. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8277. def toggle_plots(self, objects):
  8278. """
  8279. Toggle plots visibility
  8280. :param objects: list of Objects for which to be toggled the visibility
  8281. :return: None
  8282. """
  8283. # if no objects selected then do nothing
  8284. if not self.collection.get_selected():
  8285. return
  8286. log.debug("Toggling plots ...")
  8287. self.inform.emit(_("Working ..."))
  8288. for obj in objects:
  8289. if obj.options['plot'] is False:
  8290. obj.options['plot'] = True
  8291. else:
  8292. obj.options['plot'] = False
  8293. self.app_obj.plots_updated.emit()
  8294. def clear_plots(self):
  8295. """
  8296. Clear the plots
  8297. :return: None
  8298. """
  8299. objects = self.collection.get_list()
  8300. for obj in objects:
  8301. obj.clear(obj == objects[-1])
  8302. # Clear pool to free memory
  8303. self.clear_pool()
  8304. def on_set_color_action_triggered(self):
  8305. """
  8306. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8307. :return:
  8308. """
  8309. new_color = self.defaults['gerber_plot_fill']
  8310. clicked_action = self.sender()
  8311. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8312. act_name = clicked_action.text()
  8313. sel_obj_list = self.collection.get_selected()
  8314. if not sel_obj_list:
  8315. return
  8316. # a default value, I just chose this one
  8317. alpha_level = 'BF'
  8318. for sel_obj in sel_obj_list:
  8319. if sel_obj.kind == 'excellon':
  8320. alpha_level = str(hex(
  8321. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8322. elif sel_obj.kind == 'gerber':
  8323. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8324. elif sel_obj.kind == 'geometry':
  8325. alpha_level = 'FF'
  8326. else:
  8327. log.debug(
  8328. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8329. continue
  8330. sel_obj.alpha_level = alpha_level
  8331. if act_name == _('Red'):
  8332. new_color = '#FF0000' + alpha_level
  8333. if act_name == _('Blue'):
  8334. new_color = '#0000FF' + alpha_level
  8335. if act_name == _('Yellow'):
  8336. new_color = '#FFDF00' + alpha_level
  8337. if act_name == _('Green'):
  8338. new_color = '#00FF00' + alpha_level
  8339. if act_name == _('Purple'):
  8340. new_color = '#FF00FF' + alpha_level
  8341. if act_name == _('Brown'):
  8342. new_color = '#A52A2A' + alpha_level
  8343. if act_name == _('White'):
  8344. new_color = '#FFFFFF' + alpha_level
  8345. if act_name == _('Black'):
  8346. new_color = '#000000' + alpha_level
  8347. if act_name == _('Custom'):
  8348. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8349. c_dialog = QtWidgets.QColorDialog()
  8350. plot_fill_color = c_dialog.getColor(initial=new_color)
  8351. if plot_fill_color.isValid() is False:
  8352. return
  8353. new_color = str(plot_fill_color.name()) + alpha_level
  8354. if act_name == _("Default"):
  8355. for sel_obj in sel_obj_list:
  8356. if sel_obj.kind == 'excellon':
  8357. new_color = self.defaults['excellon_plot_fill']
  8358. new_line_color = self.defaults['excellon_plot_line']
  8359. elif sel_obj.kind == 'gerber':
  8360. new_color = self.defaults['gerber_plot_fill']
  8361. new_line_color = self.defaults['gerber_plot_line']
  8362. elif sel_obj.kind == 'geometry':
  8363. new_color = self.defaults['geometry_plot_line']
  8364. new_line_color = self.defaults['geometry_plot_line']
  8365. else:
  8366. log.debug(
  8367. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8368. continue
  8369. sel_obj.fill_color = new_color
  8370. sel_obj.outline_color = new_line_color
  8371. sel_obj.shapes.redraw(
  8372. update_colors=(new_color, new_line_color)
  8373. )
  8374. return
  8375. if act_name == _("Opacity"):
  8376. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8377. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8378. if ok_button:
  8379. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8380. for sel_obj in sel_obj_list:
  8381. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8382. sel_obj.shapes.redraw(
  8383. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8384. )
  8385. return
  8386. new_line_color = color_variant(new_color[:7], 0.7)
  8387. if act_name == _("White"):
  8388. new_line_color = color_variant("#dedede", 0.7)
  8389. for sel_obj in sel_obj_list:
  8390. sel_obj.fill_color = new_color
  8391. sel_obj.outline_color = new_line_color
  8392. sel_obj.shapes.redraw(
  8393. update_colors=(new_color, new_line_color)
  8394. )
  8395. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8396. group = self.collection.group_items["gerber"]
  8397. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8398. new_c = (new_line_color, new_color)
  8399. for sel_obj in sel_obj_list:
  8400. if sel_obj.kind == 'gerber':
  8401. item = sel_obj.item
  8402. item_index = self.collection.index(item.row(), 0, group_index)
  8403. idx = item_index.row()
  8404. self.defaults["gerber_color_list"][idx] = new_c
  8405. def generate_cnc_job(self, objects):
  8406. """
  8407. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8408. :param objects: Selected objects in the Project Tab
  8409. :return:
  8410. """
  8411. self.defaults.report_usage("generate_cnc_job()")
  8412. # for obj in objects:
  8413. # obj.generatecncjob()
  8414. for obj in objects:
  8415. obj.on_generatecnc_button_click()
  8416. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8417. """
  8418. Saves the current project to the specified file.
  8419. :param filename: Name of the file in which to save.
  8420. :type filename: str
  8421. :param quit_action: if the project saving will be followed by an app quit; boolean
  8422. :param silent: if True will not display status messages
  8423. :param from_tcl True is run from Tcl Shell
  8424. :return: None
  8425. """
  8426. self.log.debug("save_project()")
  8427. self.save_in_progress = True
  8428. with self.proc_container.new(_("Saving FlatCAM Project")):
  8429. # Capture the latest changes
  8430. # Current object
  8431. try:
  8432. current_object = self.collection.get_active()
  8433. if current_object:
  8434. current_object.read_form()
  8435. except Exception as e:
  8436. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8437. pass
  8438. # Serialize the whole project
  8439. d = {
  8440. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8441. "options": self.options,
  8442. "version": self.version
  8443. }
  8444. if self.defaults["global_save_compressed"] is True:
  8445. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8446. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8447. # # Write
  8448. f.write(g)
  8449. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8450. else:
  8451. # Open file
  8452. try:
  8453. f = open(filename, 'w')
  8454. except IOError:
  8455. App.log.error("Failed to open file for saving: %s", filename)
  8456. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8457. return
  8458. # Write
  8459. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8460. f.close()
  8461. # verification of the saved project
  8462. # Open and parse
  8463. try:
  8464. saved_f = open(filename, 'r')
  8465. except IOError:
  8466. if silent is False:
  8467. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8468. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8469. return
  8470. try:
  8471. saved_d = json.load(saved_f, object_hook=dict2obj)
  8472. except Exception:
  8473. if silent is False:
  8474. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8475. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8476. f.close()
  8477. return
  8478. saved_f.close()
  8479. if silent is False:
  8480. if 'version' in saved_d:
  8481. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8482. else:
  8483. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8484. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8485. tb_settings = QSettings("Open Source", "FlatCAM")
  8486. lock_state = self.ui.lock_action.isChecked()
  8487. tb_settings.setValue('toolbar_lock', lock_state)
  8488. # This will write the setting to the platform specific storage.
  8489. del tb_settings
  8490. # if quit:
  8491. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8492. # t.start()
  8493. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8494. def start_delayed_quit(self, delay, filename, should_quit=None):
  8495. """
  8496. :param delay: period of checking if project file size is more than zero; in seconds
  8497. :param filename: the name of the project file to be checked periodically for size more than zero
  8498. :param should_quit: if the task finished will be followed by an app quit; boolean
  8499. :return:
  8500. """
  8501. to_quit = should_quit
  8502. self.save_timer = QtCore.QTimer()
  8503. self.save_timer.setInterval(delay)
  8504. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8505. self.save_timer.start()
  8506. def check_project_file_size(self, filename, should_quit=None):
  8507. """
  8508. :param filename: the name of the project file to be checked periodically for size more than zero
  8509. :param should_quit: will quit the app if True; boolean
  8510. :return:
  8511. """
  8512. try:
  8513. if os.stat(filename).st_size > 0:
  8514. self.save_in_progress = False
  8515. self.save_timer.stop()
  8516. if should_quit:
  8517. self.app_quit.emit()
  8518. except Exception:
  8519. traceback.print_exc()
  8520. def save_project_auto(self):
  8521. """
  8522. Called periodically to save the project.
  8523. 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
  8524. # progress.
  8525. :return:
  8526. """
  8527. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8528. self.on_file_saveproject()
  8529. def save_project_auto_update(self):
  8530. """
  8531. Update the auto save time interval value.
  8532. :return:
  8533. """
  8534. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8535. try:
  8536. if self.autosave_timer.isActive():
  8537. self.autosave_timer.stop()
  8538. except Exception:
  8539. pass
  8540. if self.defaults['global_autosave'] is True:
  8541. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8542. self.autosave_timer.start()
  8543. def on_options_app2project(self):
  8544. """
  8545. Callback for Options->Transfer Options->App=>Project. Copies options
  8546. from application defaults to project defaults.
  8547. :return: None
  8548. """
  8549. self.defaults.report_usage("on_options_app2project")
  8550. self.preferencesUiManager.defaults_read_form()
  8551. self.options.update(self.defaults)
  8552. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  8553. """
  8554. Shows a message on the FlatCAM Shell
  8555. :param msg: Message to display.
  8556. :param show: Opens the shell.
  8557. :param error: Shows the message as an error.
  8558. :param warning: Shows the message as an warning.
  8559. :param success: Shows the message as an success.
  8560. :param selected: Indicate that something was selected on canvas
  8561. :return: None
  8562. """
  8563. end = '\n' if new_line is True else ''
  8564. if show:
  8565. self.ui.shell_dock.show()
  8566. try:
  8567. if error:
  8568. self.shell.append_error(msg + end)
  8569. elif warning:
  8570. self.shell.append_warning(msg + end)
  8571. elif success:
  8572. self.shell.append_success(msg + end)
  8573. elif selected:
  8574. self.shell.append_selected(msg + end)
  8575. else:
  8576. self.shell.append_output(msg + end)
  8577. except AttributeError:
  8578. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8579. def dec_format(self, val, dec=None):
  8580. """
  8581. Returns a formatted float value with a certain number of decimals
  8582. """
  8583. dec_nr = dec if dec is not None else self.decimals
  8584. return float('%.*f' % (dec_nr, val))
  8585. class ArgsThread(QtCore.QObject):
  8586. open_signal = pyqtSignal(list)
  8587. start = pyqtSignal()
  8588. stop = pyqtSignal()
  8589. if sys.platform == 'win32':
  8590. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8591. else:
  8592. address = ('/tmp/testipc', 'AF_UNIX')
  8593. def __init__(self):
  8594. super().__init__()
  8595. self.listener = None
  8596. self.thread_exit = False
  8597. self.start.connect(self.run)
  8598. self.stop.connect(self.close_listener)
  8599. def my_loop(self, address):
  8600. try:
  8601. self.listener = Listener(*address)
  8602. while self.thread_exit is False:
  8603. conn = self.listener.accept()
  8604. self.serve(conn)
  8605. except socket.error:
  8606. try:
  8607. conn = Client(*address)
  8608. conn.send(sys.argv)
  8609. conn.send('close')
  8610. # close the current instance only if there are args
  8611. if len(sys.argv) > 1:
  8612. try:
  8613. self.listener.close()
  8614. except Exception:
  8615. pass
  8616. sys.exit()
  8617. except ConnectionRefusedError:
  8618. if sys.platform == 'win32':
  8619. pass
  8620. else:
  8621. os.system('rm /tmp/testipc')
  8622. self.listener = Listener(*address)
  8623. while True:
  8624. conn = self.listener.accept()
  8625. self.serve(conn)
  8626. def serve(self, conn):
  8627. while self.thread_exit is False:
  8628. msg = conn.recv()
  8629. if msg == 'close':
  8630. break
  8631. self.open_signal.emit(msg)
  8632. conn.close()
  8633. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8634. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8635. @pyqtSlot()
  8636. def run(self):
  8637. self.my_loop(self.address)
  8638. @pyqtSlot()
  8639. def close_listener(self):
  8640. self.thread_exit = True
  8641. self.listener.close()
  8642. # end of file